當前位置: 首頁>>代碼示例>>Golang>>正文


Golang assert.NoError函數代碼示例

本文整理匯總了Golang中github.com/getlantern/testify/assert.NoError函數的典型用法代碼示例。如果您正苦於以下問題:Golang NoError函數的具體用法?Golang NoError怎麽用?Golang NoError使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NoError函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestNestedField

func TestNestedField(t *testing.T) {
	d := makeData()
	orig := d.B

	p := Parse("B")
	err := p.Set(d, &B{
		S: "10",
		I: 10,
	})

	assert.NoError(t, err, "Setting struct should succeed")
	assert.Equal(t, "10", d.B.S, "string field should reflect value from new struct")
	assert.Equal(t, 10, d.B.I, "int field should reflect value from new struct")
	assert.NotEqual(t, d.B, orig, "struct should change")

	gotten, err := Parse("B/S").Get(d)
	assert.NoError(t, err, "Getting nested string should succeed")
	assert.Equal(t, "10", gotten, "Getting nested string should have gotten right value")

	err = p.Clear(d)
	assert.NoError(t, err, "Clearing struct should succeed")
	assert.Nil(t, d.B, "struct should be nil after clearing")

	zv, err := p.ZeroValue(d)
	assert.NoError(t, err, "Getting zero value of struct should succeed")
	assert.Equal(t, &B{}, zv, "Zero value of struct should match expected")
}
開發者ID:Christeefym,項目名稱:lantern,代碼行數:27,代碼來源:pathreflect_test.go

示例2: TestCreateAndRefresh

func TestCreateAndRefresh(t *testing.T) {
	if true {
		t.Log("We don't currently use peerscanner, so this test is disabled. To reenable, we'll need to delete test distributions to avoid hitting our limit")
		return
	}
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	cfr := getCfr()
	// Deleting cloudfront distributions is actually quite an involved process.
	// Fortunately, distributions per se cost us nothing.  A separate service
	// will be implemented to delete test and otherwise unused distributions.
	name := uuid.NewV4().String()
	dist, err := CreateDistribution(cfr, name, name+"-grey.flashlightproxy.org", COMMENT)
	assert.NoError(t, err, "Should be able to create distribution")
	assert.Equal(t, "InProgress", dist.Status, "New distribution should have Status: \"InProgress\"")
	assert.Equal(t, dist.Comment, COMMENT, "New distribution should have the comment we've set for it")
	assert.Equal(t, name, dist.InstanceId, "New distribution should have the right InstanceId")
	assert.True(t, strings.HasSuffix(dist.Domain, ".cloudfront.net"), "Domain should be a .cloudfront.net subdomain, not '"+dist.Domain+"'")
	dist.Status = "modified to check it really gets overwritten"
	err = RefreshStatus(cfr, dist)
	assert.NoError(t, err, "Should be able to refresh status")
	// Just check that Status stays a valid one.  Checking that it eventually
	// gets refreshed to "Deployed" would take a few minutes, and thus is out
	// of the scope of this unit test.
	assert.Equal(t, "InProgress", dist.Status, "New distribution should have Status: \"InProgress\" even after refreshing right away")
	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
開發者ID:2722,項目名稱:lantern,代碼行數:29,代碼來源:cfr_test.go

示例3: TestTranslate

func TestTranslate(t *testing.T) {
	assertTranslation(t, "", "HELLO")
	UseOSLocale()
	assertTranslation(t, "I speak America English!", "ONLY_IN_EN_US")
	assertTranslation(t, "I speak Generic English!", "ONLY_IN_EN")
	assertTranslation(t, "", "NOT_EXISTED")

	SetMessagesDir("not-existed-dir")
	err := SetLocale("en_US")
	assert.Error(t, err, "should error if dir is not existed")

	SetMessagesDir("locale")
	assert.Error(t, SetLocale("e0"), "should error on malformed locale")
	assert.Error(t, SetLocale("e0-DO"), "should error on malformed locale")
	assert.Error(t, SetLocale("e0-DO.C"), "should error on malformed locale")
	assert.NoError(t, SetLocale("en"), "should change locale")
	if assert.NoError(t, SetLocale("en_US"), "should change locale") {
		// formatting
		assertTranslation(t, "Hello An Argument!", "HELLO", "An Argument")
		assertTranslation(t, "", "NOT_EXISTED", "extra args")
	}
	if assert.NoError(t, SetLocale("zh_CN"), "should change locale") {
		assertTranslation(t, "An Argument你好!", "HELLO", "An Argument")
		// fallbacks
		assertTranslation(t, "I speak Mandarin!", "ONLY_IN_ZH_CN")
		assertTranslation(t, "I speak Chinese!", "ONLY_IN_ZH")
		assertTranslation(t, "I speak America English!", "ONLY_IN_EN_US")
		assertTranslation(t, "I speak Generic English!", "ONLY_IN_EN")
	}
}
開發者ID:shizhh,項目名稱:lantern,代碼行數:30,代碼來源:translate_test.go

示例4: TestIgnoreEmpty

func TestIgnoreEmpty(t *testing.T) {
	tarString := bytes.NewBuffer(nil)
	err := EncodeToTarString("resources", tarString)
	if err != nil {
		t.Fatalf("Unable to encode to tar string: %v", err)
	}

	fs, err := New(tarStringToBytes(t, tarString), "localresources")
	if err != nil {
		t.Fatalf("Unable to open filesystem: %v", err)
	}

	// Test to make sure we get the file if we're not ignoring empty.
	// Note empty on disk actually has a single space to allow us to
	// check it into git, but the method ignores whitespace.
	a, err := fs.Get("empty.txt")
	if assert.NoError(t, err, "empty.txt should have loaded") {
		assert.Equal(t, " \n", string(a), "A should have matched expected")
	}

	// We artificially change the entry for empty byte in the file system
	// to make sure we get the file system and not the local version.
	emptyBytes := []byte("empty")
	fs.files["empty.txt"] = emptyBytes

	a, err = fs.GetIgnoreLocalEmpty("empty.txt")
	if assert.NoError(t, err, "empty.txt should have loaded") {
		assert.Equal(t, string(emptyBytes), string(a), "A should have matched expected")
	}
}
開發者ID:Christeefym,項目名稱:lantern,代碼行數:30,代碼來源:tarfs_test.go

示例5: TestTCP

func TestTCP(t *testing.T) {
	// Lower maxAssertAttempts to keep this test from running too long
	maxAssertAttempts = 2

	l0, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := l0.Close(); err != nil {
			t.Fatalf("Unable to close listener: %v", err)
		}
	}()

	start, fdc, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 1, start, "Starting count should have been 1")

	err = fdc.AssertDelta(0)
	if err != nil {
		t.Fatal(err)
	}
	assert.NoError(t, err, "Initial TCP count should be 0")

	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	_, middle, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.True(t, len(err.Error()) > 100)
	}
	err = fdc.AssertDelta(1)
	assert.NoError(t, err, "Ending TCP count should be 1")

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.Contains(t, err.Error(), "New")
		assert.True(t, len(err.Error()) > 100)
	}

	if err := l.Close(); err != nil {
		t.Fatalf("Unable to close listener: %v", err)
	}
	err = middle.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have -1")
		assert.Contains(t, err.Error(), "Removed")
		assert.True(t, len(err.Error()) > 100)
	}
}
開發者ID:2722,項目名稱:lantern,代碼行數:60,代碼來源:fdcount_test.go

示例6: TestHTTPRedirect

// This test stimulates a connection leak as seen in
// https://github.com/getlantern/lantern/issues/2174.
func TestHTTPRedirect(t *testing.T) {
	startProxy(t, false)

	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				return Dial(addr, &Config{
					DialProxy: func(addr string) (net.Conn, error) {
						return net.Dial("tcp", proxyAddr)
					},
					NewRequest: newRequest,
				})
			},
			DisableKeepAlives: true,
		},
	}

	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get fdcount: %v", err)
	}

	resp, err := client.Head("http://www.facebook.com")
	if assert.NoError(t, err, "Head request to facebook should have succeeded") {
		resp.Body.Close()
	}

	assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed")
}
開發者ID:shizhh,項目名稱:lantern,代碼行數:31,代碼來源:conn_test.go

示例7: TestAuth

func TestAuth(t *testing.T) {
	log.Debugf("TestGET")
	reqTemplate := "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n"
	resp := "HTTP/1.1 404 Not Found\r\n"
	content := "holla!\n"
	defer stopMockServers()
	site, _ := newMockServer(content)
	u, _ := url.Parse(site)
	log.Debugf("Started target site at %s", u)

	addr, s := startServer(t)
	s.Checker = func(req *http.Request) error {
		return errors.New("dsafda")
	}
	log.Debugf("Started proxy server at %s", addr)

	con, err := net.Dial("tcp", addr.String())
	if !assert.NoError(t, err, "should dial proxy server") {
		return
	}
	defer func() {
		assert.NoError(t, con.Close(), "should close connection")
	}()

	req := fmt.Sprintf(reqTemplate, u, u.Host)
	_, err = con.Write([]byte(req))
	if !assert.NoError(t, err, "should write request") {
		return
	}

	var buf [400]byte
	_, err = con.Read(buf[:])
	assert.Contains(t, string(buf[:]), resp, "should get 404 Not Found")
}
開發者ID:Nuos,項目名稱:chained-server,代碼行數:34,代碼來源:main_test.go

示例8: TestNestedMapEntry

func TestNestedMapEntry(t *testing.T) {
	d := makeData()
	orig := d.MapB["3"]

	p := Parse("MapB/3")
	err := p.Set(d, &B{
		S: "10",
		I: 10,
	})

	assert.NoError(t, err, "Setting struct should succeed")
	assert.Equal(t, "10", d.MapB["3"].S, "string field should reflect value from new struct")
	assert.Equal(t, 10, d.MapB["3"].I, "int field should reflect value from new struct")
	assert.NotEqual(t, d.B, orig, "struct should change")

	gotten, err := Parse("MapB/3/S").Get(d)
	assert.NoError(t, err, "Getting nested string should succeed")
	assert.Equal(t, "10", gotten, "Getting nested string should have gotten right value")

	err = p.Clear(d)
	assert.NoError(t, err, "Clearing struct should succeed")
	_, found := d.MapB["3"]
	assert.False(t, found, "struct should be gone from map after clearing")

	zv, err := p.ZeroValue(d)
	assert.NoError(t, err, "Getting zero value of struct should succeed")
	assert.Equal(t, &B{}, zv, "Zero value of struct should match expected")
}
開發者ID:Christeefym,項目名稱:lantern,代碼行數:28,代碼來源:pathreflect_test.go

示例9: doTestConn

func doTestConn(t *testing.T, conn net.Conn) {
	defer func() {
		if err := conn.Close(); err != nil {
			log.Debugf("Unable to close connection: %v", err)
		}
	}()

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		n, err := conn.Write(msg)
		assert.NoError(t, err, "Writing should have succeeded")
		assert.Equal(t, len(msg), n, "Should have written full message")
		wg.Done()
	}()
	go func() {
		b := make([]byte, len(msg))
		n, err := io.ReadFull(conn, b)
		assert.NoError(t, err, "Read should have succeeded")
		assert.Equal(t, len(msg), n, "Should have read full message")
		assert.Equal(t, msg, b[:n], "Read should have matched written")
		wg.Done()
	}()

	wg.Wait()
}
開發者ID:ComeOn-Wuhan,項目名稱:lantern,代碼行數:26,代碼來源:balancer_test.go

示例10: TestLines

func TestLines(t *testing.T) {
	buf := bytes.NewBuffer(nil)
	i := int32(0)
	w := LinePrepender(buf, func(w io.Writer) (int, error) {
		j := atomic.AddInt32(&i, 1)
		return fmt.Fprintf(w, "%d ", j)
	})

	n, err := fmt.Fprint(w, "A")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 1, n, "Wrong bytes written for A")
	}
	n, err = fmt.Fprintln(w, "")
	if assert.NoError(t, err, "Error writing newline after A") {
		assert.Equal(t, 1, n, "Wrong bytes written for newline after A")
	}
	n, err = fmt.Fprintf(w, "B\nC")
	if assert.NoError(t, err, "Error writing BC") {
		assert.Equal(t, 3, n, "Wrong bytes written for BC")
	}
	n, err = fmt.Fprintln(w, "\nD")
	if assert.NoError(t, err, "Error writing D") {
		assert.Equal(t, 3, n, "Wrong bytes written for D")
	}

	assert.Equal(t, expected, string(buf.Bytes()))
}
開發者ID:shizhh,項目名稱:lantern,代碼行數:27,代碼來源:wfilter_test.go

示例11: TestEnsureRegistered

func TestEnsureRegistered(t *testing.T) {
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	u := getUtil()
	// Test with no existing record
	name, ip := "cfl-test-entry", "127.0.0.1"
	rec, proxying, err := u.EnsureRegistered(name, ip, nil)
	if assert.NoError(t, err, "Should be able to register with no record") {
		assert.NotNil(t, rec, "A new record should have been returned")
		assert.True(t, proxying, "Proxying (orange cloud) should be on")
	}

	// Test with existing record, but not passing it in
	rec, proxying, err = u.EnsureRegistered(name, ip, nil)
	if assert.NoError(t, err, "Should be able to register with unspecified existing record") {
		assert.NotNil(t, rec, "Existing record should have been returned")
		assert.True(t, proxying, "Proxying (orange cloud) should be on")

		// Test with existing record, passing it in
		rec, proxying, err = u.EnsureRegistered(name, ip, rec)
		if assert.NoError(t, err, "Should be able to register with specified existing record") {
			assert.NotNil(t, rec, "Existing record should have been returned")
			assert.True(t, proxying, "Proxying (orange cloud) should be on")
		}
	}

	if rec != nil {
		err := u.DestroyRecord(rec)
		assert.NoError(t, err, "Should be able to destroy record")
	}

	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
開發者ID:Christeefym,項目名稱:lantern,代碼行數:35,代碼來源:cfl_test.go

示例12: TestConfigServer

func TestConfigServer(t *testing.T) {
	file, err := ioutil.TempFile("", "yamlconf_test_")
	if err != nil {
		t.Fatalf("Unable to create temp file: %s", err)
	}
	defer os.Remove(file.Name())

	m := &Manager{
		EmptyConfig: func() Config {
			return &TestCfg{}
		},
		FilePath:         file.Name(),
		FilePollInterval: pollInterval,
		ConfigServerAddr: ConfigSrvAddr,
	}

	_, err = m.Init()
	if err != nil {
		t.Fatalf("Unable to init manager: %s", err)
	}
	m.StartPolling()

	newNested := &Nested{
		S: "900",
		I: 900,
	}
	nny, err := yaml.Marshal(newNested)
	if err != nil {
		t.Fatalf("Unable to marshal new nested into yaml: %s", err)
	}

	_, err = http.Post(fmt.Sprintf("http://%s/N", ConfigSrvAddr), "text/yaml", bytes.NewReader(nny))
	assert.NoError(t, err, "POSTing to config server should succeed")

	updated := m.Next()

	assert.Equal(t, &TestCfg{
		Version: 2,
		N:       newNested,
	}, updated, "Nested should have been updated by POST")

	req, err := http.NewRequest("DELETE", fmt.Sprintf("http://%s/N/I", ConfigSrvAddr), bytes.NewReader(nny))
	if err != nil {
		t.Fatalf("Unable to construct DELETE request: %s", err)
	}
	_, err = (&http.Client{}).Do(req)
	assert.NoError(t, err, "DELETEing to config server should succeed")

	updated = m.Next()

	assert.Equal(t, &TestCfg{
		Version: 3,
		N: &Nested{
			S: newNested.S,
			I: FIXED_I,
		},
	}, updated, "Nested I should have reverted to default value after clearing")
}
開發者ID:shizhh,項目名稱:lantern,代碼行數:58,代碼來源:yamlconf_test.go

示例13: TestDialFailure

func TestDialFailure(t *testing.T) {
	fail := int32(1)
	dialAttempts := int32(0)

	addr, err := startTestServer()
	if err != nil {
		t.Fatalf("Unable to start test server: %s", err)
	}

	_, fdc, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	poolSize := 10

	p := New(Config{
		Size: poolSize,
		Dial: func() (net.Conn, error) {
			atomic.AddInt32(&dialAttempts, 1)
			if fail == int32(1) {
				return nil, fmt.Errorf("I'm failing intentionally!")
			}
			return net.DialTimeout("tcp", addr, 15*time.Millisecond)
		},
	})

	// Try to get connection, make sure it fails
	conn, err := p.Get()
	if !assert.Error(t, err, "Dialing should have failed") {
		if err := conn.Close(); err != nil {
			t.Fatalf("Unable to close connection: %v", err)
		}
	}

	// Wait for fill to run for a while with a failing connection
	time.Sleep(1 * time.Second)
	assert.Equal(t, 1, atomic.LoadInt32(&dialAttempts), fmt.Sprintf("There should have been only 1 dial attempt"))
	assert.NoError(t, fdc.AssertDelta(0), "There should be no additional file descriptors open")

	// Now make connection succeed and verify that it works
	atomic.StoreInt32(&fail, 0)
	time.Sleep(100 * time.Millisecond)
	connectAndRead(t, p, 1)

	time.Sleep(fillTime)
	log.Debug("Testing")
	assert.NoError(t, fdc.AssertDelta(10), "Pool should have filled")

	// Now make the connection fail again so that when we stop, we're stopping
	// while failing (tests a different code path for stopping)
	atomic.StoreInt32(&fail, 1)
	time.Sleep(100 * time.Millisecond)

	p.Close()

	assert.NoError(t, fdc.AssertDelta(0), "All connections should be closed")
}
開發者ID:2722,項目名稱:lantern,代碼行數:58,代碼來源:connpool_test.go

示例14: TestReadWriteOK

func TestReadWriteOK(t *testing.T) {
	id1 := Random()
	b := make([]byte, EncodedLength)
	err := id1.Write(b)
	assert.NoError(t, err, "Unable to write")
	id2, err := Read(b)
	assert.NoError(t, err, "Unable to read")
	assert.Equal(t, id1.ToBytes(), id2.ToBytes(), "Read didn't match written")
}
開發者ID:2722,項目名稱:lantern,代碼行數:9,代碼來源:buuid_test.go

示例15: TestRoundTrip

func TestRoundTrip(t *testing.T) {
	defer func() {
		if err := os.Remove(PK_FILE); err != nil {
			log.Debugf("Unable to remove file: %v", err)
		}
	}()
	defer func() {
		if err := os.Remove(CERT_FILE); err != nil {
			log.Debugf("Unable to remove file: %v", err)
		}
	}()

	pk, err := GeneratePK(1024)
	assert.NoError(t, err, "Unable to generate PK")

	err = pk.WriteToFile(PK_FILE)
	assert.NoError(t, err, "Unable to save PK")

	pk2, err := LoadPKFromFile(PK_FILE)
	assert.NoError(t, err, "Unable to load PK")
	assert.Equal(t, pk.PEMEncoded(), pk2.PEMEncoded(), "Loaded PK didn't match saved PK")

	cert, err := pk.TLSCertificateFor("Test Org", "127.0.0.1", time.Now().Add(TWO_WEEKS), true, nil)
	assert.NoError(t, err, "Unable to generate self-signed certificate")

	numberOfIPSANs := len(cert.X509().IPAddresses)
	if numberOfIPSANs != 1 {
		t.Errorf("Wrong number of SANs, expected 1 got %d", numberOfIPSANs)
	} else {
		ip := cert.X509().IPAddresses[0]
		expectedIP := net.ParseIP("127.0.0.1")
		assert.Equal(t, expectedIP.String(), ip.String(), "Wrong IP SAN")
	}

	err = cert.WriteToFile(CERT_FILE)
	assert.NoError(t, err, "Unable to write certificate to file")

	cert2, err := LoadCertificateFromFile(CERT_FILE)
	assert.NoError(t, err, "Unable to load certificate from file")
	assert.Equal(t, cert.PEMEncoded(), cert2.PEMEncoded(), "Loaded certificate didn't match saved certificate")

	_, err = pk.Certificate(cert.X509(), cert)
	assert.NoError(t, err, "Unable to generate certificate signed by original certificate")

	pk3, err := GeneratePK(1024)
	assert.NoError(t, err, "Unable to generate PK 3")

	_, err = pk.CertificateForKey(cert.X509(), cert, &pk3.rsaKey.PublicKey)
	assert.NoError(t, err, "Unable to generate certificate for pk3")

	x509rt, err := LoadCertificateFromX509(cert.X509())
	assert.NoError(t, err, "Unable to load certificate from X509")
	assert.Equal(t, cert, x509rt, "X509 round tripped cert didn't match original")
}
開發者ID:2722,項目名稱:lantern,代碼行數:54,代碼來源:keyman_test.go


注:本文中的github.com/getlantern/testify/assert.NoError函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。