本文整理汇总了Golang中github.com/stretchr/testify/require.NoError函数的典型用法代码示例。如果您正苦于以下问题:Golang NoError函数的具体用法?Golang NoError怎么用?Golang NoError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NoError函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Test_RpcServiceServesRequests
func Test_RpcServiceServesRequests(t *testing.T) {
f := NewRpcFixture(t)
defer f.Close()
serviceWasCalled := false
svc := MockRpcService{
callback: func(text string, result *string) error {
serviceWasCalled = true
(*result) = strings.ToUpper(text)
return nil
},
}
err := f.rpcServer.Register(&svc)
require.NoError(t, err)
conn, err := f.rpcServer.Connect()
require.NoError(t, err)
defer conn.Close()
client := rpc.NewClient(conn)
defer client.Close()
var reply string
err = client.Call("MockRpcService.Test", "lowercase", &reply)
assert.NoError(t, err)
assert.Equal(t, "LOWERCASE", reply)
assert.True(t, serviceWasCalled)
}
示例2: TestCompletedPieceWrongSize
// We read from a piece which is marked completed, but is missing data.
func TestCompletedPieceWrongSize(t *testing.T) {
cfg := TestingConfig
cfg.DefaultStorage = badStorage{}
cl, err := NewClient(&cfg)
require.NoError(t, err)
defer cl.Close()
ie := metainfo.InfoEx{
Info: metainfo.Info{
PieceLength: 15,
Pieces: make([]byte, 20),
Files: []metainfo.FileInfo{
metainfo.FileInfo{Path: []string{"greeting"}, Length: 13},
},
},
}
ie.UpdateBytes()
tt, new, err := cl.AddTorrentSpec(&TorrentSpec{
Info: &ie,
InfoHash: ie.Hash(),
})
require.NoError(t, err)
defer tt.Drop()
assert.True(t, new)
r := tt.NewReader()
defer r.Close()
b, err := ioutil.ReadAll(r)
assert.Len(t, b, 13)
assert.NoError(t, err)
}
示例3: NewTestServer
// NewTestServer creates a new initialised Laika httptest.Server. The server
// root credentials are "root" as username and password. It contains an
// environment named "test" with an enabled featured named "test_feature",
// and a user whose username is "user" and password is "password".
func NewTestServer(t *testing.T) *httptest.Server {
s, err := store.NewMySQLStore(
os.Getenv("LAIKA_MYSQL_USERNAME"),
os.Getenv("LAIKA_MYSQL_PASSWORD"),
os.Getenv("LAIKA_MYSQL_HOST"),
os.Getenv("LAIKA_MYSQL_PORT"),
os.Getenv("LAIKA_MYSQL_DBNAME"),
)
require.NoError(t, err)
err = s.Ping()
require.NoError(t, err)
err = s.Migrate()
require.NoError(t, err)
user := models.User{
Username: "test_username" + store.Token(),
PasswordHash: "awesome_password",
}
err = s.CreateUser(&user)
require.NoError(t, err)
server, err := NewServer(ServerConfig{
Store: s,
RootUsername: "root",
RootPassword: "root",
})
require.NoError(t, err)
return httptest.NewServer(server)
}
示例4: TestSyncWithExclude
// Test with exclude
func TestSyncWithExclude(t *testing.T) {
r := NewRun(t)
defer r.Finalise()
file1 := r.WriteBoth("potato2", "------------------------------------------------------------", t1)
file2 := r.WriteBoth("empty space", "", t2)
file3 := r.WriteFile("enormous", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", t1) // 100 bytes
fstest.CheckItems(t, r.fremote, file1, file2)
fstest.CheckItems(t, r.flocal, file1, file2, file3)
fs.Config.Filter.MaxSize = 40
defer func() {
fs.Config.Filter.MaxSize = -1
}()
fs.Stats.ResetCounters()
err := fs.Sync(r.fremote, r.flocal)
require.NoError(t, err)
fstest.CheckItems(t, r.fremote, file2, file1)
// Now sync the other way round and check enormous doesn't get
// deleted as it is excluded from the sync
fs.Stats.ResetCounters()
err = fs.Sync(r.flocal, r.fremote)
require.NoError(t, err)
fstest.CheckItems(t, r.flocal, file2, file1, file3)
}
示例5: TestZfsPoolMetrics
func TestZfsPoolMetrics(t *testing.T) {
var acc testutil.Accumulator
z := &Zfs{
KstatMetrics: []string{"vdev_cache_stats"},
sysctl: mock_sysctl,
zpool: mock_zpool,
}
err := z.Gather(&acc)
require.NoError(t, err)
require.False(t, acc.HasMeasurement("zfs_pool"))
acc.Metrics = nil
z = &Zfs{
KstatMetrics: []string{"vdev_cache_stats"},
PoolMetrics: true,
sysctl: mock_sysctl,
zpool: mock_zpool,
}
err = z.Gather(&acc)
require.NoError(t, err)
//one pool, all metrics
tags := map[string]string{
"pool": "freenas-boot",
"health": "ONLINE",
}
poolMetrics := getFreeNasBootPoolMetrics()
acc.AssertContainsTaggedFields(t, "zfs_pool", poolMetrics, tags)
}
示例6: TestSyncBasedOnCheckSum
// Create a file and sync it. Change the last modified date and resync.
// If we're only doing sync by size and checksum, we expect nothing to
// to be transferred on the second sync.
func TestSyncBasedOnCheckSum(t *testing.T) {
r := NewRun(t)
defer r.Finalise()
fs.Config.CheckSum = true
defer func() { fs.Config.CheckSum = false }()
file1 := r.WriteFile("check sum", "", t1)
fstest.CheckItems(t, r.flocal, file1)
fs.Stats.ResetCounters()
err := fs.Sync(r.fremote, r.flocal)
require.NoError(t, err)
// We should have transferred exactly one file.
assert.Equal(t, int64(1), fs.Stats.GetTransfers())
fstest.CheckItems(t, r.fremote, file1)
// Change last modified date only
file2 := r.WriteFile("check sum", "", t2)
fstest.CheckItems(t, r.flocal, file2)
fs.Stats.ResetCounters()
err = fs.Sync(r.fremote, r.flocal)
require.NoError(t, err)
// We should have transferred no files
assert.Equal(t, int64(0), fs.Stats.GetTransfers())
fstest.CheckItems(t, r.flocal, file2)
fstest.CheckItems(t, r.fremote, file1)
}
示例7: TestSyncIgnoreSize
// Create a file and sync it. Keep the last modified date but change
// the size. With --ignore-size we expect nothing to to be
// transferred on the second sync.
func TestSyncIgnoreSize(t *testing.T) {
r := NewRun(t)
defer r.Finalise()
fs.Config.IgnoreSize = true
defer func() { fs.Config.IgnoreSize = false }()
file1 := r.WriteFile("ignore-size", "contents", t1)
fstest.CheckItems(t, r.flocal, file1)
fs.Stats.ResetCounters()
err := fs.Sync(r.fremote, r.flocal)
require.NoError(t, err)
// We should have transferred exactly one file.
assert.Equal(t, int64(1), fs.Stats.GetTransfers())
fstest.CheckItems(t, r.fremote, file1)
// Update size but not date of file
file2 := r.WriteFile("ignore-size", "longer contents but same date", t1)
fstest.CheckItems(t, r.flocal, file2)
fs.Stats.ResetCounters()
err = fs.Sync(r.fremote, r.flocal)
require.NoError(t, err)
// We should have transferred no files
assert.Equal(t, int64(0), fs.Stats.GetTransfers())
fstest.CheckItems(t, r.flocal, file2)
fstest.CheckItems(t, r.fremote, file1)
}
示例8: TestUploadLogChunksAndCloseSuccessfully
func TestUploadLogChunksAndCloseSuccessfully(t *testing.T) {
ts := testserver.NewTestServer(t)
defer ts.CloseAndAssertExpectations()
client := NewArtifactStoreClient(ts.URL)
ts.ExpectAndRespond("POST", "/buckets/", http.StatusOK, `{"Id": "foo"}`)
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts", http.StatusOK, `{"Name": "artifact"}`)
b, _ := client.NewBucket("foo", "bar", 32)
sa, err := b.NewChunkedArtifact("artifact")
require.NotNil(t, sa)
require.NoError(t, err)
{
// Content request might come later, even as late as Flush()
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts/artifact", 200, `{}`)
err := sa.AppendLog("console contents")
require.NoError(t, err)
}
{
// Content request might come later, even as late as Flush()
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts/artifact", 200, `{}`)
err := sa.AppendLog("more console contents")
require.NoError(t, err)
}
{
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts/artifact/close", 200, `{}`)
err := sa.Close()
require.NoError(t, err)
}
}
示例9: TestPushLogChunkServerSucceedOnRetry
func TestPushLogChunkServerSucceedOnRetry(t *testing.T) {
ts := testserver.NewTestServer(t)
defer ts.CloseAndAssertExpectations()
client := NewArtifactStoreClient(ts.URL)
ts.ExpectAndRespond("POST", "/buckets/", http.StatusOK, `{"Id": "foo"}`)
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts", http.StatusOK, `{"Name": "artifact"}`)
b, _ := client.NewBucket("foo", "bar", 32)
sa, err := b.NewChunkedArtifact("artifact")
require.NotNil(t, sa)
require.NoError(t, err)
{
// Fail with a retriable error first
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts/artifact", 500, `{}`)
// Then succeed on retry
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts/artifact", 200, `{}`)
err := sa.AppendLog("console contents")
require.NoError(t, err)
}
{
ts.ExpectAndRespond("POST", "/buckets/foo/artifacts/artifact/close", 200, `{}`)
err := sa.Close()
require.NoError(t, err)
}
}
示例10: BenchmarkInboundParallel
func BenchmarkInboundParallel(b *testing.B) {
var reqCount int32
serverAddr, err := setupBenchServer()
require.NoError(b, err, "setupBenchServer failed")
started := time.Now()
b.RunParallel(func(pb *testing.PB) {
// Start a client for each runner
client, err := startClient(serverAddr)
require.NoError(b, err, "startClient failed")
defer client.Close()
for pb.Next() {
client.CallAndWait()
atomic.AddInt32(&reqCount, int32(1))
}
fmt.Println("Successful requests", client.numTimes, "Mean", client.mean)
for err, count := range client.errors {
fmt.Printf("%v: %v\n", count, err)
}
})
duration := time.Since(started)
fmt.Println("Requests", reqCount, "RPS: ", float64(reqCount)/duration.Seconds())
}
示例11: Test_StepTemplate
func Test_StepTemplate(t *testing.T) {
configPth := "bitrise.yml"
t.Log("step template test")
{
cmd := cmdex.NewCommand(binPath(), "run", "test", "--config", configPth)
cmd.SetDir("step_template")
out, err := cmd.RunAndReturnTrimmedCombinedOutput()
require.NoError(t, err, out)
}
t.Log("bash toolkit step template test")
{
cmd := cmdex.NewCommand(binPath(), "run", "test", "--config", configPth)
cmd.SetDir("bash_toolkit_step_template")
out, err := cmd.RunAndReturnTrimmedCombinedOutput()
require.NoError(t, err, out)
}
t.Log("go toolkit step template test")
{
cmd := cmdex.NewCommand(binPath(), "run", "test", "--config", configPth)
cmd.SetDir("go_toolkit_step_template")
out, err := cmd.RunAndReturnTrimmedCombinedOutput()
require.NoError(t, err, out)
}
}
示例12: TestChangeTargetMetaFailsIfPrefixError
// If applying a change fails due to a prefix error, changeTargetMeta fails outright
func TestChangeTargetMetaFailsIfPrefixError(t *testing.T) {
repo, cs, err := testutils.EmptyRepo("docker.com/notary")
require.NoError(t, err)
newKey, err := cs.Create("targets/level1", "docker.com/notary", data.ED25519Key)
require.NoError(t, err)
err = repo.UpdateDelegationKeys("targets/level1", []data.PublicKey{newKey}, []string{}, 1)
require.NoError(t, err)
err = repo.UpdateDelegationPaths("targets/level1", []string{"pathprefix"}, []string{}, false)
require.NoError(t, err)
hash := sha256.Sum256([]byte{})
f := &data.FileMeta{
Length: 1,
Hashes: map[string][]byte{
"sha256": hash[:],
},
}
fjson, err := json.Marshal(f)
require.NoError(t, err)
err = changeTargetMeta(repo, &changelist.TUFChange{
Actn: changelist.ActionCreate,
Role: "targets/level1",
ChangeType: "target",
ChangePath: "notPathPrefix",
Data: fjson,
})
require.Error(t, err)
// no target in targets or targets/latest
require.Empty(t, repo.Targets[data.CanonicalTargetsRole].Signed.Targets)
require.Empty(t, repo.Targets["targets/level1"].Signed.Targets)
}
示例13: TestApplyTargetsDelegationParentDoesntExist
// Applying a delegation whose parent doesn't exist fails.
func TestApplyTargetsDelegationParentDoesntExist(t *testing.T) {
repo, cs, err := testutils.EmptyRepo("docker.com/notary")
require.NoError(t, err)
// make sure a key exists for the previous level, so it's not a missing
// key error, but we don't care about this key
_, err = cs.Create("targets/level1", "docker.com/notary", data.ED25519Key)
require.NoError(t, err)
newKey, err := cs.Create("targets/level1/level2", "docker.com/notary", data.ED25519Key)
require.NoError(t, err)
// create delegation
kl := data.KeyList{newKey}
td := &changelist.TUFDelegation{
NewThreshold: 1,
AddKeys: kl,
}
tdJSON, err := json.Marshal(td)
require.NoError(t, err)
ch := changelist.NewTUFChange(
changelist.ActionCreate,
"targets/level1/level2",
changelist.TypeTargetsDelegation,
"",
tdJSON,
)
err = applyTargetsChange(repo, nil, ch)
require.Error(t, err)
require.IsType(t, data.ErrInvalidRole{}, err)
}
示例14: TestApplyTargetsDelegationInvalidJSONContent
func TestApplyTargetsDelegationInvalidJSONContent(t *testing.T) {
repo, cs, err := testutils.EmptyRepo("docker.com/notary")
require.NoError(t, err)
newKey, err := cs.Create("targets/level1", "docker.com/notary", data.ED25519Key)
require.NoError(t, err)
// create delegation
kl := data.KeyList{newKey}
td := &changelist.TUFDelegation{
NewThreshold: 1,
AddKeys: kl,
AddPaths: []string{"level1"},
}
tdJSON, err := json.Marshal(td)
require.NoError(t, err)
ch := changelist.NewTUFChange(
changelist.ActionCreate,
"targets/level1",
changelist.TypeTargetsDelegation,
"",
tdJSON[1:],
)
err = applyTargetsChange(repo, nil, ch)
require.Error(t, err)
}
示例15: TestDiskMailboxPush
func TestDiskMailboxPush(t *testing.T) {
dir, err := ioutil.TempDir("", "mailbox")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
r, err := NewDiskStorage(dir)
if err != nil {
panic(err)
}
defer r.Close()
m := r.Mailbox("a")
msg := vega.Msg([]byte("hello"))
err = m.Push(msg)
require.NoError(t, err)
out, err := m.Poll()
require.NoError(t, err)
assert.True(t, out.Equal(msg), "wrong value")
}