From 2b6c35a6121827e4f0af038f6c0c2895d5c1f729 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Sat, 14 Jun 2025 12:39:52 +0200 Subject: [PATCH 1/2] fix testifylint issues Signed-off-by: Matthieu MOREL --- agent/agent_test.go | 21 +- agent/csi/volume_manager_test.go | 5 +- agent/exec/controller_test.go | 21 +- agent/exec/errors_test.go | 13 +- agent/reporter_test.go | 10 +- agent/secrets/secrets_test.go | 4 +- agent/storage_test.go | 45 +- agent/task_test.go | 9 +- agent/worker_test.go | 47 +- api/equality/equality_test.go | 2 +- api/genericresource/parse_test.go | 31 +- .../resource_management_test.go | 27 +- api/naming/naming_test.go | 2 +- ca/certificates_test.go | 112 ++-- ca/config_test.go | 70 +-- ca/keyreadwriter_test.go | 3 +- ca/renewer_test.go | 12 +- ca/server_test.go | 72 +-- ca/testutils/cautils.go | 19 +- ca/transport_test.go | 22 +- cli/external_ca_test.go | 5 +- identity/combined_id_test.go | 6 +- identity/randomid_test.go | 10 +- integration/integration_test.go | 2 +- internal/idm/idm_test.go | 141 ++--- ioutils/ioutils_test.go | 15 +- log/context_test.go | 20 +- manager/allocator/allocator_test_suite.go | 317 +++++------ .../allocator/allocator_test_suite_linux.go | 8 +- manager/allocator/network_test.go | 6 +- manager/allocator/portallocator_test.go | 15 +- manager/constraint/constraint_test.go | 53 +- manager/controlapi/ca_rotation_test.go | 3 +- manager/controlapi/cluster_test.go | 84 +-- manager/controlapi/common_test.go | 7 +- manager/controlapi/config_test.go | 61 ++- manager/controlapi/extension_test.go | 27 +- manager/controlapi/network_test.go | 71 +-- manager/controlapi/node_test.go | 188 +++---- manager/controlapi/resource_test.go | 24 +- manager/controlapi/secret_test.go | 67 +-- manager/controlapi/server_test.go | 13 +- manager/controlapi/service_test.go | 323 ++++++----- manager/controlapi/task_test.go | 33 +- manager/controlapi/volume_test.go | 50 +- manager/deallocator/deallocator_test.go | 4 +- manager/dirty_test.go | 20 +- manager/dispatcher/assignments_test.go | 18 +- manager/dispatcher/dispatcher_test.go | 401 +++++++------- manager/keymanager/keymanager_test.go | 11 +- manager/logbroker/broker_test.go | 46 +- .../constraint_enforcer_test.go | 22 +- manager/orchestrator/global/global_test.go | 204 ++++--- manager/orchestrator/replicated/drain_test.go | 23 +- .../replicated/replicated_test.go | 186 ++++--- .../orchestrator/replicated/restart_test.go | 270 +++++---- .../orchestrator/replicated/update_test.go | 82 +-- manager/orchestrator/service_test.go | 16 +- .../taskreaper/task_reaper_test.go | 200 +++---- manager/orchestrator/update/updater_test.go | 72 ++- manager/scheduler/nodeinfo_test.go | 2 +- manager/scheduler/nodeset_test.go | 42 +- manager/scheduler/scheduler_test.go | 512 +++++++++--------- manager/scheduler/topology_test.go | 5 +- manager/state/raft/membership/cluster_test.go | 63 +-- manager/state/raft/raft_test.go | 108 ++-- manager/state/raft/storage_test.go | 60 +- manager/state/raft/testutils/testutils.go | 15 +- manager/state/raft/transport/peer_test.go | 2 +- .../state/raft/transport/transport_test.go | 16 +- manager/state/store/combinator_test.go | 19 +- manager/state/store/memory_test.go | 434 +++++++-------- manager/watchapi/server_test.go | 12 +- manager/watchapi/watch_test.go | 48 +- node/node_test.go | 4 +- .../plugin/raftproxy/test/raftproxy_test.go | 2 +- remotes/remotes_test.go | 124 ++--- swarmd/dockerexec/container_test.go | 62 +-- .../dockerexec/controller_integration_test.go | 24 +- swarmd/dockerexec/controller_test.go | 33 +- template/context_test.go | 5 +- template/getter_test.go | 12 +- watch/watch_test.go | 28 +- 83 files changed, 2524 insertions(+), 2779 deletions(-) diff --git a/agent/agent_test.go b/agent/agent_test.go index f514f757d6..661ff8fa8c 100644 --- a/agent/agent_test.go +++ b/agent/agent_test.go @@ -94,13 +94,12 @@ func TestAgentStartStop(t *testing.T) { defer cancel() assert.Equal(t, errAgentNotStarted, agent.Stop(ctx)) - assert.NoError(t, agent.Start(ctx)) + require.NoError(t, agent.Start(ctx)) - if err := agent.Start(ctx); err != errAgentStarted { - t.Fatalf("expected agent started error: %v", err) - } + err = agent.Start(ctx) + require.Equalf(t, err, errAgentStarted, "expected agent started error: %v", err) - assert.NoError(t, agent.Stop(ctx)) + require.NoError(t, agent.Stop(ctx)) } func TestHandleSessionMessageNetworkManagerChanges(t *testing.T) { @@ -429,9 +428,9 @@ func TestAgentExitsBasedOnSessionTracker(t *testing.T) { } establishedSessions, errCounter, closeClounter := tracker.Stats() - require.Equal(t, establishedSessions, 0) - require.Equal(t, errCounter, 3) - require.Equal(t, closeClounter, 3) + require.Equal(t, 0, establishedSessions) + require.Equal(t, 3, errCounter) + require.Equal(t, 3, closeClounter) currSession, closedSessions := tester.dispatcher.GetSessions() require.Nil(t, currSession) require.Len(t, closedSessions, 3) @@ -461,11 +460,11 @@ func TestAgentRegistersSessionsWithSessionTracker(t *testing.T) { } return nil }, 3*time.Millisecond)) - require.Equal(t, errCounter, 0) - require.Equal(t, closeCounter, 0) + require.Equal(t, 0, errCounter) + require.Equal(t, 0, closeCounter) currSession, closedSessions := tester.dispatcher.GetSessions() require.NotNil(t, currSession) - require.Len(t, closedSessions, 0) + require.Empty(t, closedSessions) } type agentTester struct { diff --git a/agent/csi/volume_manager_test.go b/agent/csi/volume_manager_test.go index 0bdf5f31ca..f6ccf0fc5d 100644 --- a/agent/csi/volume_manager_test.go +++ b/agent/csi/volume_manager_test.go @@ -9,6 +9,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/volumequeue" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -84,10 +85,10 @@ func TestTaskRestrictedVolumesProvider(t *testing.T) { volume, err := volumesGetter.Get(testCase.volumeID) if testCase.expectedErr != "" { - assert.Error(t, err, testCase.desc) + require.Error(t, err, testCase.desc) assert.Equal(t, testCase.expectedErr, err.Error()) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, volume) } }) diff --git a/agent/exec/controller_test.go b/agent/exec/controller_test.go index 666514d921..0d783366b4 100644 --- a/agent/exec/controller_test.go +++ b/agent/exec/controller_test.go @@ -11,6 +11,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/log" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestResolve(t *testing.T) { @@ -21,14 +22,14 @@ func TestResolve(t *testing.T) { ) _, status, err := Resolve(ctx, task, executor) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.TaskStateAccepted, status.State) assert.Equal(t, "accepted", status.Message) task.Status = *status // now, we get no status update. _, status, err = Resolve(ctx, task, executor) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, task.Status, *status) // now test an error causing rejection @@ -56,7 +57,7 @@ func TestResolve(t *testing.T) { task.Status = *status executor.err = nil _, status, err = Resolve(ctx, task, executor) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, task.Status, *status) } @@ -138,7 +139,7 @@ func TestPrepareFailure(t *testing.T) { ) defer func() { finish() - assert.Equal(t, ctlr.calls["Prepare"], 1) + assert.Equal(t, 1, ctlr.calls["Prepare"]) }() ctlr.PrepareFn = func(_ context.Context) error { return errors.New("test error") @@ -461,22 +462,20 @@ func checkDo(ctx context.Context, t *testing.T, task *api.Task, ctlr Controller, if len(expectedErr) > 0 { assert.Equal(t, expectedErr[0], err) } else { - assert.NoError(t, err) + require.NoError(t, err) } // if the status and task.Status are different, make sure new timestamp is greater if task.Status.Timestamp != nil { // crazy timestamp validation follows previous, err := gogotypes.TimestampFromProto(task.Status.Timestamp) - assert.Nil(t, err) + require.NoError(t, err) current, err := gogotypes.TimestampFromProto(status.Timestamp) - assert.Nil(t, err) + require.NoError(t, err) - if current.Before(previous) { - // ensure that the timestamp always proceeds forward - t.Fatalf("timestamp must proceed forward: %v < %v", current, previous) - } + // ensure that the timestamp always proceeds forward + require.Falsef(t, current.Before(previous), "timestamp must proceed forward: %v < %v", current, previous) } copy := status.Copy() diff --git a/agent/exec/errors_test.go b/agent/exec/errors_test.go index 45a237fdd4..7d6720886a 100644 --- a/agent/exec/errors_test.go +++ b/agent/exec/errors_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/pkg/errors" + "github.com/stretchr/testify/assert" ) func TestIsTemporary(t *testing.T) { @@ -15,13 +16,7 @@ func TestIsTemporary(t *testing.T) { err4 := fmt.Errorf("err4: %w", err3) err5 := errors.Wrap(err4, "err5") - if IsTemporary(nil) { - t.Error("expected error to not be a temporary error") - } - if IsTemporary(err) { - t.Error("expected error to not be a temporary error") - } - if !IsTemporary(err5) { - t.Error("expected error to be a temporary error") - } + assert.False(t, IsTemporary(nil), "expected error to not be a temporary error") + assert.False(t, IsTemporary(err), "expected error to not be a temporary error") + assert.True(t, IsTemporary(err5), "expected error to be a temporary error") } diff --git a/agent/reporter_test.go b/agent/reporter_test.go index a2440a2688..b97945efb9 100644 --- a/agent/reporter_test.go +++ b/agent/reporter_test.go @@ -10,6 +10,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type uniqueStatus struct { @@ -41,9 +42,8 @@ func TestReporter(t *testing.T) { key := uniqueStatus{taskID, status} // make sure we get the status only once. - if _, ok := unique[key]; ok { - t.Fatal("encountered status twice") - } + _, ok := unique[key] + require.False(t, ok, "encountered status twice") if status.State == api.TaskStateCompleted { wg.Done() @@ -81,7 +81,7 @@ func TestReporter(t *testing.T) { // simulate pounding this with a bunch of goroutines go func() { if err := reporter.UpdateTaskStatus(ctx, taskID, status); err != nil { - assert.NoError(t, err, "sending should not fail") + require.NoError(t, err, "sending should not fail") } }() @@ -89,7 +89,7 @@ func TestReporter(t *testing.T) { } wg.Wait() // wait for the propagation - assert.NoError(t, reporter.Close()) + require.NoError(t, reporter.Close()) mu.Lock() defer mu.Unlock() diff --git a/agent/secrets/secrets_test.go b/agent/secrets/secrets_test.go index 810c136a10..6be3f65b48 100644 --- a/agent/secrets/secrets_test.go +++ b/agent/secrets/secrets_test.go @@ -98,11 +98,11 @@ func TestTaskRestrictedSecretsProvider(t *testing.T) { (secretsGetter.(*taskRestrictedSecretsProvider)).secretIDs = testCase.secretIDs secret, err := secretsGetter.Get(testCase.secretIDToGet) if testCase.expectedErr != "" { - assert.Error(t, err, testCase.desc) + require.Error(t, err, testCase.desc) assert.Equal(t, testCase.expectedErr, err.Error(), testCase.desc) } else { t.Logf("secretIDs=%v", testCase.secretIDs) - assert.NoError(t, err, testCase.desc) + require.NoError(t, err, testCase.desc) require.NotNil(t, secret, testCase.desc) require.NotNil(t, secret.Spec, testCase.desc) require.NotNil(t, secret.Spec.Data, testCase.desc) diff --git a/agent/storage_test.go b/agent/storage_test.go index a0d9025ce4..b496e0e0cf 100644 --- a/agent/storage_test.go +++ b/agent/storage_test.go @@ -10,6 +10,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/identity" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" bolt "go.etcd.io/bbolt" ) @@ -17,8 +18,8 @@ func TestStorageInit(t *testing.T) { db, cleanup := storageTestEnv(t) defer cleanup() - assert.NoError(t, InitDB(db)) // ensure idempotence. - assert.NoError(t, db.View(func(tx *bolt.Tx) error { + require.NoError(t, InitDB(db)) // ensure idempotence. + require.NoError(t, db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket(bucketKeyStorageVersion) assert.NotNil(t, bkt) @@ -35,9 +36,9 @@ func TestStoragePutGet(t *testing.T) { tasks := genTasks(20) - assert.NoError(t, db.Update(func(tx *bolt.Tx) error { + require.NoError(t, db.Update(func(tx *bolt.Tx) error { for i, task := range tasks { - assert.NoError(t, PutTask(tx, task)) + require.NoError(t, PutTask(tx, task)) // remove status to make comparison work tasks[i].Status = api.TaskStatus{} } @@ -45,10 +46,10 @@ func TestStoragePutGet(t *testing.T) { return nil })) - assert.NoError(t, db.View(func(tx *bolt.Tx) error { + require.NoError(t, db.View(func(tx *bolt.Tx) error { for _, task := range tasks { retrieved, err := GetTask(tx, task.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, task, retrieved) } @@ -63,24 +64,24 @@ func TestStoragePutGetStatusAssigned(t *testing.T) { tasks := genTasks(20) // set task, status and assignment for all tasks. - assert.NoError(t, db.Update(func(tx *bolt.Tx) error { + require.NoError(t, db.Update(func(tx *bolt.Tx) error { for _, task := range tasks { - assert.NoError(t, PutTask(tx, task)) - assert.NoError(t, PutTaskStatus(tx, task.ID, &task.Status)) - assert.NoError(t, SetTaskAssignment(tx, task.ID, true)) + require.NoError(t, PutTask(tx, task)) + require.NoError(t, PutTaskStatus(tx, task.ID, &task.Status)) + require.NoError(t, SetTaskAssignment(tx, task.ID, true)) } return nil })) - assert.NoError(t, db.View(func(tx *bolt.Tx) error { + require.NoError(t, db.View(func(tx *bolt.Tx) error { for _, task := range tasks { status, err := GetTaskStatus(tx, task.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &task.Status, status) retrieved, err := GetTask(tx, task.ID) - assert.NoError(t, err) + require.NoError(t, err) task.Status = api.TaskStatus{} assert.Equal(t, task, retrieved) @@ -92,27 +93,27 @@ func TestStoragePutGetStatusAssigned(t *testing.T) { })) // set evens to unassigned and updates all states plus one - assert.NoError(t, db.Update(func(tx *bolt.Tx) error { + require.NoError(t, db.Update(func(tx *bolt.Tx) error { for i, task := range tasks { task.Status.State++ - assert.NoError(t, PutTaskStatus(tx, task.ID, &task.Status)) + require.NoError(t, PutTaskStatus(tx, task.ID, &task.Status)) if i%2 == 0 { - assert.NoError(t, SetTaskAssignment(tx, task.ID, false)) + require.NoError(t, SetTaskAssignment(tx, task.ID, false)) } } return nil })) - assert.NoError(t, db.View(func(tx *bolt.Tx) error { + require.NoError(t, db.View(func(tx *bolt.Tx) error { for i, task := range tasks { status, err := GetTaskStatus(tx, task.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &task.Status, status) retrieved, err := GetTask(tx, task.ID) - assert.NoError(t, err) + require.NoError(t, err) task.Status = api.TaskStatus{} assert.Equal(t, task, retrieved) @@ -178,13 +179,13 @@ func storageTestEnv(t *testing.T) (*bolt.DB, func()) { var cleanup []func() dir := t.TempDir() dbpath := filepath.Join(dir, "tasks.db") - assert.NoError(t, os.MkdirAll(dir, 0o777)) + require.NoError(t, os.MkdirAll(dir, 0o777)) db, err := bolt.Open(dbpath, 0666, nil) - assert.NoError(t, err) + require.NoError(t, err) cleanup = append(cleanup, func() { db.Close() }) - assert.NoError(t, InitDB(db)) + require.NoError(t, InitDB(db)) return db, func() { // iterate in reverse so it works like defer for i := len(cleanup) - 1; i >= 0; i-- { diff --git a/agent/task_test.go b/agent/task_test.go index e735a2db42..9a72a97cb4 100644 --- a/agent/task_test.go +++ b/agent/task_test.go @@ -9,6 +9,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/log" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const debugLevel = 5 @@ -70,22 +71,22 @@ func TestTaskManager(t *testing.T) { select { case <-acceptedWait: task.DesiredState = api.TaskStateReady // proceed to ready - assert.NoError(t, tm.Update(ctx, task)) + require.NoError(t, tm.Update(ctx, task)) acceptedWait = nil case <-readyWait: time.Sleep(time.Second) task.DesiredState = api.TaskStateRunning // proceed to running. - assert.NoError(t, tm.Update(ctx, task)) + require.NoError(t, tm.Update(ctx, task)) readyWait = nil case <-shutdownWait: - assert.NoError(t, tm.Close()) + require.NoError(t, tm.Close()) select { case <-tm.closed: default: t.Fatal("not actually closed") } - assert.NoError(t, tm.Close()) // hit a second time to make sure it behaves + require.NoError(t, tm.Close()) // hit a second time to make sure it behaves assert.Equal(t, tm.Update(ctx, task), ErrClosed) assert.Equal(t, map[string]int{ diff --git a/agent/worker_test.go b/agent/worker_test.go index 40de4adc75..ecf9a47450 100644 --- a/agent/worker_test.go +++ b/agent/worker_test.go @@ -2,7 +2,6 @@ package agent import ( "context" - "errors" "net" "testing" @@ -11,6 +10,7 @@ import ( "github.com/moby/swarmkit/v2/log" "github.com/moby/swarmkit/v2/testutils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" bolt "go.etcd.io/bbolt" ) @@ -224,14 +224,14 @@ func TestWorkerAssign(t *testing.T) { // TODO(stevvooe): There are a few more states here we need to get // covered to ensure correct during code changes. } { - assert.NoError(t, worker.Assign(ctx, testcase.changeSet)) + require.NoError(t, worker.Assign(ctx, testcase.changeSet)) var ( tasks []*api.Task assigned []*api.Task ) - assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error { + require.NoError(t, worker.db.View(func(tx *bolt.Tx) error { return WalkTasks(tx, func(task *api.Task) error { tasks = append(tasks, task) if TaskAssigned(tx, task.ID) { @@ -245,18 +245,18 @@ func TestWorkerAssign(t *testing.T) { assert.Equal(t, testcase.expectedAssigned, assigned) for _, secret := range testcase.expectedSecrets { secret, err := executor.Secrets().Get(secret.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, secret) } for _, config := range testcase.expectedConfigs { config, err := executor.Configs().Get(config.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, config) } for _, volume := range testcase.expectedVolumes { _, err := executor.Volumes().Get(volume.VolumeID) - assert.Error(t, err) - assert.True(t, errors.Is(err, exec.ErrDependencyNotReady)) + require.Error(t, err) + assert.ErrorIs(t, err, exec.ErrDependencyNotReady) } } } @@ -360,9 +360,9 @@ func TestWorkerWait(t *testing.T) { tasks []*api.Task assigned []*api.Task ) - assert.NoError(t, worker.Assign(ctx, changeSet)) + require.NoError(t, worker.Assign(ctx, changeSet)) - assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error { + require.NoError(t, worker.db.View(func(tx *bolt.Tx) error { return WalkTasks(tx, func(task *api.Task) error { tasks = append(tasks, task) if TaskAssigned(tx, task.ID) { @@ -376,29 +376,28 @@ func TestWorkerWait(t *testing.T) { assert.Equal(t, expectedAssigned, assigned) for _, secret := range expectedSecrets { secret, err := executor.Secrets().Get(secret.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, secret) } for _, config := range expectedConfigs { config, err := executor.Configs().Get(config.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, config) } for _, volume := range expectedVolumes { _, err := executor.Volumes().Get(volume.VolumeID) - assert.Error(t, err) - assert.True(t, errors.Is(err, exec.ErrDependencyNotReady)) + require.ErrorIs(t, err, exec.ErrDependencyNotReady) } err := worker.Assign(ctx, nil) - assert.Nil(t, err) + require.NoError(t, err) err = worker.Wait(ctx) - assert.Nil(t, err) + require.NoError(t, err) assigned = assigned[:0] - assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error { + require.NoError(t, worker.db.View(func(tx *bolt.Tx) error { return WalkTasks(tx, func(task *api.Task) error { if TaskAssigned(tx, task.ID) { assigned = append(assigned, task) @@ -406,7 +405,7 @@ func TestWorkerWait(t *testing.T) { return nil }) })) - assert.Equal(t, len(assigned), 0) + assert.Empty(t, assigned) } func TestWorkerUpdate(t *testing.T) { @@ -443,7 +442,7 @@ func TestWorkerUpdate(t *testing.T) { worker.Listen(ctx, reporter) // create existing task/secret/config/volume - assert.NoError(t, worker.Assign(ctx, []*api.AssignmentChange{ + require.NoError(t, worker.Assign(ctx, []*api.AssignmentChange{ { Assignment: &api.Assignment{ Item: &api.Assignment_Task{ @@ -734,13 +733,13 @@ func TestWorkerUpdate(t *testing.T) { }, }, } { - assert.NoError(t, worker.Update(ctx, testcase.changeSet)) + require.NoError(t, worker.Update(ctx, testcase.changeSet)) var ( tasks []*api.Task assigned []*api.Task ) - assert.NoError(t, worker.db.View(func(tx *bolt.Tx) error { + require.NoError(t, worker.db.View(func(tx *bolt.Tx) error { return WalkTasks(tx, func(task *api.Task) error { tasks = append(tasks, task) if TaskAssigned(tx, task.ID) { @@ -754,19 +753,19 @@ func TestWorkerUpdate(t *testing.T) { assert.Equal(t, testcase.expectedAssigned, assigned) for _, secret := range testcase.expectedSecrets { secret, err := executor.Secrets().Get(secret.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, secret) } for _, config := range testcase.expectedConfigs { config, err := executor.Configs().Get(config.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, config) } for _, volume := range testcase.expectedVolumes { _, err := executor.Volumes().Get(volume.VolumeID) // volumes should not be ready yet, so we expect an error. - assert.Error(t, err) - assert.True(t, errors.Is(err, exec.ErrDependencyNotReady), "error: %v", err) + require.Error(t, err) + assert.ErrorIs(t, err, exec.ErrDependencyNotReady, "error: %v", err) } } } diff --git a/api/equality/equality_test.go b/api/equality/equality_test.go index f3e9ee129f..a88266fcfd 100644 --- a/api/equality/equality_test.go +++ b/api/equality/equality_test.go @@ -51,7 +51,7 @@ func TestTasksEqualStable(t *testing.T) { {tasks[4], false, "Tasks with different Spec are not equal"}, } for _, test := range tests { - assert.Equal(t, TasksEqualStable(tasks[0], test.task), test.expected, test.failureText) + assert.Equal(t, test.expected, TasksEqualStable(tasks[0], test.task), test.failureText) } } diff --git a/api/genericresource/parse_test.go b/api/genericresource/parse_test.go index 433226d8a0..867b9f3627 100644 --- a/api/genericresource/parse_test.go +++ b/api/genericresource/parse_test.go @@ -4,34 +4,35 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseDiscrete(t *testing.T) { res, err := ParseCmd("apple=3") - assert.NoError(t, err) - assert.Equal(t, len(res), 1) + require.NoError(t, err) + assert.Len(t, res, 1) apples := GetResource("apple", res) - assert.Equal(t, len(apples), 1) - assert.Equal(t, apples[0].GetDiscreteResourceSpec().Value, int64(3)) + assert.Len(t, apples, 1) + assert.Equal(t, int64(3), apples[0].GetDiscreteResourceSpec().Value) _, err = ParseCmd("apple=3\napple=4") - assert.Error(t, err) + require.Error(t, err) _, err = ParseCmd("apple=3,apple=4") - assert.Error(t, err) + require.Error(t, err) _, err = ParseCmd("apple=-3") - assert.Error(t, err) + require.Error(t, err) } func TestParseStr(t *testing.T) { res, err := ParseCmd("orange=red,orange=green,orange=blue") - assert.NoError(t, err) - assert.Equal(t, len(res), 3) + require.NoError(t, err) + assert.Len(t, res, 3) oranges := GetResource("orange", res) - assert.Equal(t, len(oranges), 3) + assert.Len(t, oranges, 3) for _, k := range []string{"red", "green", "blue"} { assert.True(t, HasResource(NewString("orange", k), oranges)) } @@ -39,16 +40,16 @@ func TestParseStr(t *testing.T) { func TestParseDiscreteAndStr(t *testing.T) { res, err := ParseCmd("orange=red,orange=green,orange=blue,apple=3") - assert.NoError(t, err) - assert.Equal(t, len(res), 4) + require.NoError(t, err) + assert.Len(t, res, 4) oranges := GetResource("orange", res) - assert.Equal(t, len(oranges), 3) + assert.Len(t, oranges, 3) for _, k := range []string{"red", "green", "blue"} { assert.True(t, HasResource(NewString("orange", k), oranges)) } apples := GetResource("apple", res) - assert.Equal(t, len(apples), 1) - assert.Equal(t, apples[0].GetDiscreteResourceSpec().Value, int64(3)) + assert.Len(t, apples, 1) + assert.Equal(t, int64(3), apples[0].GetDiscreteResourceSpec().Value) } diff --git a/api/genericresource/resource_management_test.go b/api/genericresource/resource_management_test.go index d5ea0a32a2..4f08db25c1 100644 --- a/api/genericresource/resource_management_test.go +++ b/api/genericresource/resource_management_test.go @@ -5,6 +5,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestClaimSingleDiscrete(t *testing.T) { @@ -14,7 +15,7 @@ func TestClaimSingleDiscrete(t *testing.T) { taskReservations = append(taskReservations, NewDiscrete("apple", 2)) err := Claim(&nodeRes, &taskAssigned, taskReservations) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 1) assert.Len(t, taskAssigned, 1) @@ -36,7 +37,7 @@ func TestClaimMultipleDiscrete(t *testing.T) { taskReservations = append(taskReservations, NewDiscrete("apple", 2)) err := Claim(&nodeRes, &taskAssigned, taskReservations) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 3) // oranges isn't present anymore assert.Len(t, taskAssigned, 2) @@ -57,7 +58,7 @@ func TestClaimSingleStr(t *testing.T) { taskReservations = append(taskReservations, NewDiscrete("apple", 2)) err := Claim(&nodeRes, &taskAssigned, taskReservations) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 2) assert.Len(t, taskAssigned, 2) @@ -77,7 +78,7 @@ func TestClaimMultipleStr(t *testing.T) { taskReservations = append(taskReservations, NewDiscrete("apple", 2)) err := Claim(&nodeRes, &taskAssigned, taskReservations) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 6) assert.Len(t, taskAssigned, 6) @@ -99,13 +100,13 @@ func TestReclaimSingleDiscrete(t *testing.T) { taskAssigned = append(taskAssigned, NewDiscrete("apple", 2)) err := reclaimResources(&nodeRes, taskAssigned) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 1) assert.Equal(t, int64(2), nodeRes[0].GetDiscreteResourceSpec().Value) err = reclaimResources(&nodeRes, taskAssigned) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 1) assert.Equal(t, int64(4), nodeRes[0].GetDiscreteResourceSpec().Value) @@ -122,7 +123,7 @@ func TestReclaimMultipleDiscrete(t *testing.T) { taskAssigned = append(taskAssigned, NewDiscrete("apple", 2)) err := reclaimResources(&nodeRes, taskAssigned) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 3) @@ -143,7 +144,7 @@ func TestReclaimSingleStr(t *testing.T) { taskAssigned := NewSet("apple", "red", "orange") err := reclaimResources(&nodeRes, taskAssigned) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 2) for _, k := range []string{"red", "orange"} { @@ -153,7 +154,7 @@ func TestReclaimSingleStr(t *testing.T) { taskAssigned = NewSet("apple", "blue", "red") err = reclaimResources(&nodeRes, taskAssigned) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 4) for _, k := range []string{"red", "orange", "blue", "red"} { @@ -167,7 +168,7 @@ func TestReclaimMultipleStr(t *testing.T) { taskAssigned = append(taskAssigned, NewSet("orange", "red", "orange")...) err := reclaimResources(&nodeRes, taskAssigned) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 5) apples := GetResource("apple", nodeRes) @@ -196,7 +197,7 @@ func TestReclaimResources(t *testing.T) { taskAssigned = append(taskAssigned, NewDiscrete("coffe", 2)) err := reclaimResources(&nodeRes, taskAssigned) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, nodeRes, 12) apples := GetResource("apple", nodeRes) @@ -234,7 +235,7 @@ func TestSanitizeDiscrete(t *testing.T) { nodeAvailableResources = append(nodeAvailableResources, NewDiscrete("orange", 4)) sanitize(nodeRes, &nodeAvailableResources) - assert.Len(t, nodeAvailableResources, 0) + assert.Empty(t, nodeAvailableResources) nodeRes = append(nodeRes, NewDiscrete("orange", 6)) nodeAvailableResources = append(nodeAvailableResources, NewDiscrete("orange", 4)) @@ -273,7 +274,7 @@ func TestSanitizeStr(t *testing.T) { nodeAvailableResources := NewSet("apple", "red", "orange", "blue") sanitize(nodeRes, &nodeAvailableResources) - assert.Len(t, nodeAvailableResources, 0) + assert.Empty(t, nodeAvailableResources) nodeAvailableResources = NewSet("apple", "red", "orange", "blue") nodeRes = NewSet("apple", "red", "orange", "blue", "green") diff --git a/api/naming/naming_test.go b/api/naming/naming_test.go index 5549f61f82..a9dc1d6d17 100644 --- a/api/naming/naming_test.go +++ b/api/naming/naming_test.go @@ -54,7 +54,7 @@ func TestTaskNaming(t *testing.T) { t.Run(testcase.Name, func(t *testing.T) { t.Parallel() name := Task(testcase.Task) - assert.Equal(t, name, testcase.Expected) + assert.Equal(t, testcase.Expected, name) }) } } diff --git a/ca/certificates_test.go b/ca/certificates_test.go index 9543578920..2cee895e65 100644 --- a/ca/certificates_test.go +++ b/ca/certificates_test.go @@ -82,13 +82,13 @@ func TestCreateRootCASaveRootCA(t *testing.T) { paths := ca.NewConfigPaths(tempBaseDir) rootCA, err := ca.CreateRootCA("rootCN") - assert.NoError(t, err) + require.NoError(t, err) err = ca.SaveRootCA(rootCA, paths.RootCA) - assert.NoError(t, err) + require.NoError(t, err) perms, err := permbits.Stat(paths.RootCA.Cert) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, perms.GroupWrite()) assert.False(t, perms.OtherWrite()) @@ -97,19 +97,19 @@ func TestCreateRootCASaveRootCA(t *testing.T) { // ensure that the cert that was written is already normalized written, err := os.ReadFile(paths.RootCA.Cert) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, written, ca.NormalizePEMs(written)) } func TestCreateRootCAExpiry(t *testing.T) { rootCA, err := ca.CreateRootCA("rootCN") - assert.NoError(t, err) + require.NoError(t, err) // Convert the certificate into an object to create a RootCA parsedCert, err := helpers.ParseCertificatePEM(rootCA.Certs) - assert.NoError(t, err) + require.NoError(t, err) duration, err := time.ParseDuration(ca.RootCAExpiration) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, time.Now().Add(duration).AddDate(0, -1, 0).Before(parsedCert.NotAfter)) } @@ -123,40 +123,40 @@ func TestGetLocalRootCA(t *testing.T) { // Create the local Root CA to ensure that we can reload it correctly. rootCA, err := ca.CreateRootCA("rootCN") - assert.NoError(t, err) + require.NoError(t, err) s, err := rootCA.Signer() - assert.NoError(t, err) + require.NoError(t, err) err = ca.SaveRootCA(rootCA, paths.RootCA) - assert.NoError(t, err) + require.NoError(t, err) // No private key here rootCA2, err := ca.GetLocalRootCA(paths.RootCA) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, rootCA.Certs, rootCA2.Certs) _, err = rootCA2.Signer() assert.Equal(t, err, ca.ErrNoValidSigner) // write private key and assert we can load it and sign - assert.NoError(t, os.WriteFile(paths.RootCA.Key, s.Key, os.FileMode(0o600))) + require.NoError(t, os.WriteFile(paths.RootCA.Key, s.Key, os.FileMode(0o600))) rootCA3, err := ca.GetLocalRootCA(paths.RootCA) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, rootCA.Certs, rootCA3.Certs) _, err = rootCA3.Signer() - assert.NoError(t, err) + require.NoError(t, err) // Try with a private key that does not match the CA cert public key. privKey, err := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader) - assert.NoError(t, err) + require.NoError(t, err) privKeyBytes, err := x509.MarshalECPrivateKey(privKey) - assert.NoError(t, err) + require.NoError(t, err) privKeyPem := pem.EncodeToMemory(&pem.Block{ Type: "EC PRIVATE KEY", Bytes: privKeyBytes, }) - assert.NoError(t, os.WriteFile(paths.RootCA.Key, privKeyPem, os.FileMode(0o600))) + require.NoError(t, os.WriteFile(paths.RootCA.Key, privKeyPem, os.FileMode(0o600))) _, err = ca.GetLocalRootCA(paths.RootCA) - assert.EqualError(t, err, "certificate key mismatch") + require.EqualError(t, err, "certificate key mismatch") } func TestGetLocalRootCAInvalidCert(t *testing.T) { @@ -191,13 +191,13 @@ some random garbage\n func TestParseValidateAndSignCSR(t *testing.T) { rootCA, err := ca.CreateRootCA("rootCN") - assert.NoError(t, err) + require.NoError(t, err) csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) signedCert, err := rootCA.ParseValidateAndSignCSR(csr, "CN", "OU", "ORG") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, signedCert) assert.Len(t, checkLeafCert(t, signedCert, "rootCN", "CN", "OU", "ORG"), 1) @@ -205,7 +205,7 @@ func TestParseValidateAndSignCSR(t *testing.T) { func TestParseValidateAndSignMaliciousCSR(t *testing.T) { rootCA, err := ca.CreateRootCA("rootCN") - assert.NoError(t, err) + require.NoError(t, err) req := &cfcsr.CertificateRequest{ Names: []cfcsr.Name{ @@ -221,10 +221,10 @@ func TestParseValidateAndSignMaliciousCSR(t *testing.T) { } csr, _, err := cfcsr.ParseRequest(req) - assert.NoError(t, err) + require.NoError(t, err) signedCert, err := rootCA.ParseValidateAndSignCSR(csr, "CN", "OU", "ORG") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, signedCert) assert.Len(t, checkLeafCert(t, signedCert, "rootCN", "CN", "OU", "ORG"), 1) @@ -277,7 +277,7 @@ func TestGetRemoteCA(t *testing.T) { downloadedRootCA, err = ca.GetRemoteCA(tc.Context, d, tc.ConnBroker) require.NoError(t, err) require.Equal(t, comboCertBundle, downloadedRootCA.Certs) - require.Equal(t, 2, len(downloadedRootCA.Pool.Subjects())) + require.Len(t, downloadedRootCA.Pool.Subjects(), 2) for _, rootCA := range []ca.RootCA{tc.RootCA, otherRootCA} { krw := ca.NewKeyReadWriter(paths.Node, nil, nil) @@ -303,7 +303,7 @@ func TestGetRemoteCAInvalidHash(t *testing.T) { defer tc.Stop() _, err := ca.GetRemoteCA(tc.Context, "sha256:2d2f968475269f0dde5299427cf74348ee1d6115b95c6e3f283e5a4de8da445b", tc.ConnBroker) - assert.Error(t, err) + require.Error(t, err) } // returns the issuer as well as all the parsed certs returned from the request @@ -503,23 +503,23 @@ func TestGetRemoteSignedCertificate(t *testing.T) { // Create a new CSR to be signed csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) certs, err := ca.GetRemoteSignedCertificate(tc.Context, csr, tc.RootCA.Pool, ca.CertificateRequestConfig{ Token: tc.ManagerToken, ConnBroker: tc.ConnBroker, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, certs) // Test the expiration for a manager certificate parsedCerts, err := helpers.ParseCertificatesPEM(certs) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, parsedCerts, 1) assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter)) assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter)) - assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.ManagerRole) + assert.Equal(t, ca.ManagerRole, parsedCerts[0].Subject.OrganizationalUnit[0]) // Test the expiration for an worker certificate certs, err = ca.GetRemoteSignedCertificate(tc.Context, csr, tc.RootCA.Pool, @@ -527,14 +527,14 @@ func TestGetRemoteSignedCertificate(t *testing.T) { Token: tc.WorkerToken, ConnBroker: tc.ConnBroker, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, certs) parsedCerts, err = helpers.ParseCertificatesPEM(certs) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, parsedCerts, 1) assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter)) assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter)) - assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.WorkerRole) + assert.Equal(t, ca.WorkerRole, parsedCerts[0].Subject.OrganizationalUnit[0]) } func TestGetRemoteSignedCertificateNodeInfo(t *testing.T) { @@ -543,14 +543,14 @@ func TestGetRemoteSignedCertificateNodeInfo(t *testing.T) { // Create a new CSR to be signed csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) cert, err := ca.GetRemoteSignedCertificate(tc.Context, csr, tc.RootCA.Pool, ca.CertificateRequestConfig{ Token: tc.WorkerToken, ConnBroker: tc.ConnBroker, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cert) } @@ -712,7 +712,7 @@ func TestGetRemoteSignedCertificateWithPending(t *testing.T) { case <-time.After(2500 * time.Millisecond): // good, it's still polling so we can proceed with the test } - require.True(t, atomic.LoadInt64(&fakeCAServer.nodeStatusCalled) > 1, "expected NodeCertificateStatus to have been polled more than once") + require.Greater(t, atomic.LoadInt64(&fakeCAServer.nodeStatusCalled), 1, "expected NodeCertificateStatus to have been polled more than once") // Directly update the status of the store err = tc.MemoryStore.Update(func(tx store.Tx) error { @@ -742,7 +742,7 @@ func TestGetRemoteSignedCertificateWithPending(t *testing.T) { select { case err = <-completed: s, _ := status.FromError(err) - require.Equal(t, s.Code(), codes.DeadlineExceeded) + require.Equal(t, codes.DeadlineExceeded, s.Code()) case <-time.After(3 * time.Second): require.FailNow(t, "GetRemoteSignedCertificate should have been canceled after 1 second, and it has been 3") } @@ -909,51 +909,51 @@ func TestNewRootCABundle(t *testing.T) { // make one rootCA firstRootCA, err := ca.CreateRootCA("rootCN1") - assert.NoError(t, err) + require.NoError(t, err) // make a second root CA secondRootCA, err := ca.CreateRootCA("rootCN2") - assert.NoError(t, err) + require.NoError(t, err) s, err := firstRootCA.Signer() require.NoError(t, err) // Overwrite the bytes of the second Root CA with the bundle, creating a valid 2 cert bundle bundle := append(firstRootCA.Certs, secondRootCA.Certs...) err = os.WriteFile(paths.RootCA.Cert, bundle, 0o644) - assert.NoError(t, err) + require.NoError(t, err) newRootCA, err := ca.NewRootCA(bundle, firstRootCA.Certs, s.Key, ca.DefaultNodeCertExpiration, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, bundle, newRootCA.Certs) - assert.Equal(t, 2, len(newRootCA.Pool.Subjects())) + assert.Len(t, newRootCA.Pool.Subjects(), 2) // If I use newRootCA's IssueAndSaveNewCertificates to sign certs, I'll get the correct CA in the chain kw := ca.NewKeyReadWriter(paths.Node, nil, nil) _, _, err = newRootCA.IssueAndSaveNewCertificates(kw, "CN", "OU", "ORG") - assert.NoError(t, err) + require.NoError(t, err) certBytes, err := os.ReadFile(paths.Node.Cert) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, checkLeafCert(t, certBytes, "rootCN1", "CN", "OU", "ORG"), 1) } func TestNewRootCANonDefaultExpiry(t *testing.T) { rootCA, err := ca.CreateRootCA("rootCN") - assert.NoError(t, err) + require.NoError(t, err) s, err := rootCA.Signer() require.NoError(t, err) newRootCA, err := ca.NewRootCA(rootCA.Certs, rootCA.Certs, s.Key, 1*time.Hour, nil) - assert.NoError(t, err) + require.NoError(t, err) // Create and sign a new CSR csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) cert, err := newRootCA.ParseValidateAndSignCSR(csr, "CN", ca.ManagerRole, "ORG") - assert.NoError(t, err) + require.NoError(t, err) parsedCerts, err := helpers.ParseCertificatesPEM(cert) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, parsedCerts, 1) assert.True(t, time.Now().Add(time.Minute*59).Before(parsedCerts[0].NotAfter)) assert.True(t, time.Now().Add(time.Hour).Add(time.Minute).After(parsedCerts[0].NotAfter)) @@ -961,13 +961,13 @@ func TestNewRootCANonDefaultExpiry(t *testing.T) { // Sign the same CSR again, this time with a 59 Minute expiration RootCA (under the 60 minute minimum). // This should use the default of 3 months newRootCA, err = ca.NewRootCA(rootCA.Certs, rootCA.Certs, s.Key, 59*time.Minute, nil) - assert.NoError(t, err) + require.NoError(t, err) cert, err = newRootCA.ParseValidateAndSignCSR(csr, "CN", ca.ManagerRole, "ORG") - assert.NoError(t, err) + require.NoError(t, err) parsedCerts, err = helpers.ParseCertificatesPEM(cert) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, parsedCerts, 1) assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter)) assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter)) @@ -1158,8 +1158,8 @@ func TestNewRootCAInvalidCertAndKeys(t *testing.T) { for i, invalid := range invalids { _, err := ca.NewRootCA(invalid.roots, invalid.cert, invalid.key, ca.DefaultNodeCertExpiration, invalid.intermediates) - require.Error(t, err, fmt.Sprintf("expected error containing: \"%s\", test case (%d)", invalid.errorStr, i)) - require.Contains(t, err.Error(), invalid.errorStr, fmt.Sprintf("%d", i)) + require.Error(t, err, "expected error containing: \"%s\", test case (%d)", invalid.errorStr, i) + require.Contains(t, err.Error(), invalid.errorStr, "%d", i) } } @@ -1217,7 +1217,7 @@ func TestRootCAWithCrossSignedIntermediates(t *testing.T) { require.NoError(t, err) require.Len(t, parsedCerts, 2) require.Len(t, chains, 1) - require.True(t, len(chains[0]) >= 2) // there are always at least 2 certs at minimum: the leaf and the root + require.GreaterOrEqual(t, len(chains[0]), 2) // there are always at least 2 certs at minimum: the leaf and the root require.Equal(t, parsedCerts[0], chains[0][0]) require.Equal(t, parsedIntermediate.Raw, parsedCerts[1].Raw) @@ -1402,7 +1402,7 @@ func TestValidateCertificateChain(t *testing.T) { require.NotEmpty(t, chain) for _, chain := range chains { require.Equal(t, parsedCerts[0], chain[0]) // the leaf certs are equal - require.True(t, len(chain) >= 2) + require.GreaterOrEqual(t, len(chain), 2) } } } diff --git a/ca/config_test.go b/ca/config_test.go index 728a141f8f..a5453d63e1 100644 --- a/ca/config_test.go +++ b/ca/config_test.go @@ -55,7 +55,7 @@ func testDownloadRootCASuccess(t *testing.T, fips bool) { require.True(t, strings.HasPrefix(token, prefix)) // Remove the CA cert - assert.NoError(t, os.RemoveAll(tc.Paths.RootCA.Cert)) + require.NoError(t, os.RemoveAll(tc.Paths.RootCA.Cert)) rootCA, err := ca.DownloadRootCA(tc.Context, tc.Paths.RootCA, token, tc.ConnBroker) require.NoError(t, err) @@ -66,7 +66,7 @@ func testDownloadRootCASuccess(t *testing.T, fips bool) { require.Equal(t, tc.RootCA.Certs, rootCA.Certs) // Remove the CA cert - assert.NoError(t, os.RemoveAll(tc.Paths.RootCA.Cert)) + require.NoError(t, os.RemoveAll(tc.Paths.RootCA.Cert)) // downloading without a join token also succeeds rootCA, err = ca.DownloadRootCA(tc.Context, tc.Paths.RootCA, "", tc.ConnBroker) @@ -83,7 +83,7 @@ func TestDownloadRootCAWrongCAHash(t *testing.T) { defer tc.Stop() // Remove the CA cert - assert.NoError(t, os.RemoveAll(tc.Paths.RootCA.Cert)) + require.NoError(t, os.RemoveAll(tc.Paths.RootCA.Cert)) // invalid token for _, invalid := range []string{ @@ -114,14 +114,14 @@ func TestCreateSecurityConfigEmptyDir(t *testing.T) { } tc := cautils.NewTestCA(t) defer tc.Stop() - assert.NoError(t, tc.CAServer.Stop()) + require.NoError(t, tc.CAServer.Stop()) // Remove all the contents from the temp dir and try again with a new node for _, org := range []string{ "", "my_org", } { - assert.NoError(t, os.RemoveAll(tc.TempDir)) + require.NoError(t, os.RemoveAll(tc.TempDir)) krw := ca.NewKeyReadWriter(tc.Paths.Node, nil, nil) nodeConfig, cancel, err := tc.RootCA.CreateSecurityConfig(tc.Context, krw, ca.CertificateRequestConfig{ @@ -129,8 +129,8 @@ func TestCreateSecurityConfigEmptyDir(t *testing.T) { ConnBroker: tc.ConnBroker, Organization: org, }) - assert.NoError(t, err) - assert.NoError(t, cancel()) + require.NoError(t, err) + require.NoError(t, cancel()) assert.NotNil(t, nodeConfig) assert.NotNil(t, nodeConfig.ClientTLSCreds) assert.NotNil(t, nodeConfig.ServerTLSCreds) @@ -140,7 +140,7 @@ func TestCreateSecurityConfigEmptyDir(t *testing.T) { } root, err := helpers.ParseCertificatePEM(tc.RootCA.Certs) - assert.NoError(t, err) + require.NoError(t, err) issuerInfo := nodeConfig.IssuerInfo() assert.NotNil(t, issuerInfo) @@ -155,7 +155,7 @@ func TestCreateSecurityConfigNoCerts(t *testing.T) { krw := ca.NewKeyReadWriter(tc.Paths.Node, nil, nil) root, err := helpers.ParseCertificatePEM(tc.RootCA.Certs) - assert.NoError(t, err) + require.NoError(t, err) validateNodeConfig := func(rootCA *ca.RootCA) { nodeConfig, cancel, err := rootCA.CreateSecurityConfig(tc.Context, krw, @@ -163,8 +163,8 @@ func TestCreateSecurityConfigNoCerts(t *testing.T) { Token: tc.WorkerToken, ConnBroker: tc.ConnBroker, }) - assert.NoError(t, err) - assert.NoError(t, cancel()) + require.NoError(t, err) + require.NoError(t, cancel()) assert.NotNil(t, nodeConfig) assert.NotNil(t, nodeConfig.ClientTLSCreds) assert.NotNil(t, nodeConfig.ServerTLSCreds) @@ -181,14 +181,14 @@ func TestCreateSecurityConfigNoCerts(t *testing.T) { // Remove only the node certificates form the directory, and attest that we get // new certificates that are locally signed - assert.NoError(t, os.RemoveAll(tc.Paths.Node.Cert)) + require.NoError(t, os.RemoveAll(tc.Paths.Node.Cert)) validateNodeConfig(&tc.RootCA) // Remove only the node certificates form the directory, get a new rootCA, and attest that we get // new certificates that are issued by the remote CA - assert.NoError(t, os.RemoveAll(tc.Paths.Node.Cert)) + require.NoError(t, os.RemoveAll(tc.Paths.Node.Cert)) rootCA, err := ca.GetLocalRootCA(tc.Paths.RootCA) - assert.NoError(t, err) + require.NoError(t, err) validateNodeConfig(&rootCA) } @@ -210,7 +210,7 @@ func testGRPCConnection(t *testing.T, secConfig *ca.SecurityConfig) { } conn, err := grpc.Dial(l.Addr().String(), dialOpts...) require.NoError(t, err) - assert.NoError(t, conn.Close()) + require.NoError(t, conn.Close()) } func TestLoadSecurityConfigExpiredCert(t *testing.T) { @@ -253,7 +253,7 @@ func TestLoadSecurityConfigExpiredCert(t *testing.T) { // but it is valid if expiry is allowed _, cancel, err := ca.LoadSecurityConfig(tc.Context, tc.RootCA, krw, true) require.NoError(t, err) - assert.NoError(t, cancel()) + require.NoError(t, cancel()) } func TestLoadSecurityConfigInvalidCert(t *testing.T) { @@ -267,12 +267,12 @@ func TestLoadSecurityConfigInvalidCert(t *testing.T) { err := os.WriteFile(tc.Paths.Node.Cert, []byte(`-----BEGIN CERTIFICATE-----\n some random garbage\n -----END CERTIFICATE-----`), 0o644) - assert.NoError(t, err) + require.NoError(t, err) krw := ca.NewKeyReadWriter(tc.Paths.Node, nil, nil) _, _, err = ca.LoadSecurityConfig(tc.Context, tc.RootCA, krw, false) - assert.Error(t, err) + require.Error(t, err) } func TestLoadSecurityConfigInvalidKey(t *testing.T) { @@ -286,12 +286,12 @@ func TestLoadSecurityConfigInvalidKey(t *testing.T) { err := os.WriteFile(tc.Paths.Node.Key, []byte(`-----BEGIN PRIVATE KEY-----\n some random garbage\n -----END PRIVATE KEY-----`), 0o644) - assert.NoError(t, err) + require.NoError(t, err) krw := ca.NewKeyReadWriter(tc.Paths.Node, nil, nil) _, _, err = ca.LoadSecurityConfig(tc.Context, tc.RootCA, krw, false) - assert.Error(t, err) + require.Error(t, err) } func TestLoadSecurityConfigIncorrectPassphrase(t *testing.T) { @@ -442,7 +442,7 @@ func TestSecurityConfigUpdateRootCA(t *testing.T) { secConfig, cancel, err := rootCA.CreateSecurityConfig(tc.Context, ca.NewKeyReadWriter(configPaths.Node, nil, nil), ca.CertificateRequestConfig{}) require.NoError(t, err) - assert.NoError(t, cancel()) + require.NoError(t, cancel()) // update the server TLS to require certificates, otherwise this will all pass // even if the root pools aren't updated secConfig.ServerTLSCreds.Config().ClientAuth = tls.RequireAndVerifyClientCert @@ -497,7 +497,7 @@ func TestSecurityConfigUpdateRootCA(t *testing.T) { grpc.WithTransportCredentials(tcConfig.ClientTLSCreds), ) require.NoError(t, err) - assert.NoError(t, conn.Close()) + require.NoError(t, conn.Close()) conn, err = grpc.Dial( tc.Addr, @@ -506,7 +506,7 @@ func TestSecurityConfigUpdateRootCA(t *testing.T) { grpc.WithTransportCredentials(secConfig.ClientTLSCreds), ) require.NoError(t, err) - assert.NoError(t, conn.Close()) + require.NoError(t, conn.Close()) // make sure any generated certs after updating contain the intermediate krw := ca.NewKeyReadWriter(configPaths.Node, nil, nil) @@ -554,7 +554,7 @@ func TestSecurityConfigUpdateRootCAUpdateConsistentWithTLSCertificates(t *testin secConfig, cancel, err := ca.NewSecurityConfig(&rootCA, krw, tlsKeyPair, issuerInfo) require.NoError(t, err) - assert.NoError(t, cancel()) + require.NoError(t, cancel()) // can't update the root CA to one that doesn't match the tls certs require.Error(t, secConfig.UpdateRootCA(&otherRootCA)) @@ -863,7 +863,7 @@ func writeAlmostExpiringCertToDisk(t *testing.T, tc *cautils.TestCA, cn, ou, org // Because of the default backdate of 5 minutes, this issues certificates // valid for 1 minute. newRootCA, err := ca.NewRootCA(tc.RootCA.Certs, s.Cert, s.Key, ca.DefaultNodeCertExpiration, nil) - assert.NoError(t, err) + require.NoError(t, err) newSigner, err := newRootCA.Signer() require.NoError(t, err) newSigner.SetPolicy(&cfconfig.Signing{ @@ -876,7 +876,7 @@ func writeAlmostExpiringCertToDisk(t *testing.T, tc *cautils.TestCA, cn, ou, org // Issue a new certificate with the same details as the current config, but with 1 min expiration time, and // overwrite the existing cert on disk _, _, err = newRootCA.IssueAndSaveNewCertificates(ca.NewKeyReadWriter(tc.Paths.Node, nil, nil), cn, ou, org) - assert.NoError(t, err) + require.NoError(t, err) } func TestRenewTLSConfigWorker(t *testing.T) { @@ -891,7 +891,7 @@ func TestRenewTLSConfigWorker(t *testing.T) { // Get a new nodeConfig with a TLS cert that has the default Cert duration, but overwrite // the cert on disk with one that expires in 1 minute nodeConfig, err := tc.WriteNewNodeConfig(ca.WorkerRole) - assert.NoError(t, err) + require.NoError(t, err) c := nodeConfig.ClientTLSCreds writeAlmostExpiringCertToDisk(t, tc, c.NodeID(), c.Role(), c.Organization()) @@ -901,13 +901,13 @@ func TestRenewTLSConfigWorker(t *testing.T) { case <-time.After(10 * time.Second): assert.Fail(t, "TestRenewTLSConfig timed-out") case certUpdate := <-updates: - assert.NoError(t, certUpdate.Err) + require.NoError(t, certUpdate.Err) assert.NotNil(t, certUpdate) assert.Equal(t, ca.WorkerRole, certUpdate.Role) } root, err := helpers.ParseCertificatePEM(tc.RootCA.Certs) - assert.NoError(t, err) + require.NoError(t, err) issuerInfo := nodeConfig.IssuerInfo() assert.NotNil(t, issuerInfo) @@ -927,7 +927,7 @@ func TestRenewTLSConfigManager(t *testing.T) { // Get a new nodeConfig with a TLS cert that has the default Cert duration, but overwrite // the cert on disk with one that expires in 1 minute nodeConfig, err := tc.WriteNewNodeConfig(ca.WorkerRole) - assert.NoError(t, err) + require.NoError(t, err) c := nodeConfig.ClientTLSCreds writeAlmostExpiringCertToDisk(t, tc, c.NodeID(), c.Role(), c.Organization()) @@ -937,13 +937,13 @@ func TestRenewTLSConfigManager(t *testing.T) { case <-time.After(10 * time.Second): assert.Fail(t, "TestRenewTLSConfig timed-out") case certUpdate := <-updates: - assert.NoError(t, certUpdate.Err) + require.NoError(t, certUpdate.Err) assert.NotNil(t, certUpdate) assert.Equal(t, ca.WorkerRole, certUpdate.Role) } root, err := helpers.ParseCertificatePEM(tc.RootCA.Certs) - assert.NoError(t, err) + require.NoError(t, err) issuerInfo := nodeConfig.IssuerInfo() assert.NotNil(t, issuerInfo) @@ -963,7 +963,7 @@ func TestRenewTLSConfigWithNoNode(t *testing.T) { // Get a new nodeConfig with a TLS cert that has the default Cert duration, but overwrite // the cert on disk with one that expires in 1 minute nodeConfig, err := tc.WriteNewNodeConfig(ca.WorkerRole) - assert.NoError(t, err) + require.NoError(t, err) c := nodeConfig.ClientTLSCreds writeAlmostExpiringCertToDisk(t, tc, c.NodeID(), c.Role(), c.Organization()) @@ -973,7 +973,7 @@ func TestRenewTLSConfigWithNoNode(t *testing.T) { assert.NotNil(t, node) return store.DeleteNode(tx, nodeConfig.ClientTLSCreds.NodeID()) }) - assert.NoError(t, err) + require.NoError(t, err) renewer := ca.NewTLSRenewer(nodeConfig, tc.ConnBroker, tc.Paths.RootCA) updates := renewer.Start(ctx) @@ -981,7 +981,7 @@ func TestRenewTLSConfigWithNoNode(t *testing.T) { case <-time.After(10 * time.Second): assert.Fail(t, "TestRenewTLSConfig timed-out") case certUpdate := <-updates: - assert.Error(t, certUpdate.Err) + require.Error(t, certUpdate.Err) assert.Contains(t, certUpdate.Err.Error(), "not found when attempting to renew certificate") } } diff --git a/ca/keyreadwriter_test.go b/ca/keyreadwriter_test.go index ff0445909e..92e2634451 100644 --- a/ca/keyreadwriter_test.go +++ b/ca/keyreadwriter_test.go @@ -11,7 +11,6 @@ import ( "github.com/moby/swarmkit/v2/ca/keyutils" "github.com/moby/swarmkit/v2/ca/pkcs8" "github.com/moby/swarmkit/v2/ca/testutils" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -337,7 +336,7 @@ func TestTwoPhaseReadWrite(t *testing.T) { // remove the directory, to simulate it failing to write the first time err = os.RemoveAll(path.Node.Cert) - assert.NoError(t, err) + require.NoError(t, err) readCert, readKey, err := krw.Read() require.NoError(t, err) require.Equal(t, cert2, readCert) diff --git a/ca/renewer_test.go b/ca/renewer_test.go index 02f6e440a4..9139fde798 100644 --- a/ca/renewer_test.go +++ b/ca/renewer_test.go @@ -24,7 +24,7 @@ func TestForceRenewTLSConfig(t *testing.T) { // Get a new managerConfig with a TLS cert that has 15 minutes to live nodeConfig, err := tc.WriteNewNodeConfig(ca.ManagerRole) - assert.NoError(t, err) + require.NoError(t, err) renewer := ca.NewTLSRenewer(nodeConfig, tc.ConnBroker, tc.Paths.RootCA) updates := renewer.Start(ctx) @@ -33,9 +33,9 @@ func TestForceRenewTLSConfig(t *testing.T) { case <-time.After(10 * time.Second): assert.Fail(t, "TestForceRenewTLSConfig timed-out") case certUpdate := <-updates: - assert.NoError(t, certUpdate.Err) + require.NoError(t, certUpdate.Err) assert.NotNil(t, certUpdate) - assert.Equal(t, certUpdate.Role, ca.ManagerRole) + assert.Equal(t, ca.ManagerRole, certUpdate.Role) } } @@ -50,7 +50,7 @@ func TestForceRenewExpectedRole(t *testing.T) { // Get a new managerConfig with a TLS cert that has 15 minutes to live nodeConfig, err := tc.WriteNewNodeConfig(ca.ManagerRole) - assert.NoError(t, err) + require.NoError(t, err) go func() { time.Sleep(750 * time.Millisecond) @@ -64,7 +64,7 @@ func TestForceRenewExpectedRole(t *testing.T) { return store.UpdateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) }() renewer := ca.NewTLSRenewer(nodeConfig, tc.ConnBroker, tc.Paths.RootCA) @@ -76,7 +76,7 @@ func TestForceRenewExpectedRole(t *testing.T) { case <-time.After(10 * time.Second): t.Fatal("timed out") case certUpdate := <-updates: - assert.NoError(t, certUpdate.Err) + require.NoError(t, certUpdate.Err) assert.NotNil(t, certUpdate) if certUpdate.Role == ca.WorkerRole { return diff --git a/ca/server_test.go b/ca/server_test.go index 01a4ed71bd..e7e5ba9f1b 100644 --- a/ca/server_test.go +++ b/ca/server_test.go @@ -34,7 +34,7 @@ func TestGetRootCACertificate(t *testing.T) { defer tc.Stop() resp, err := tc.CAClients[0].GetRootCACertificate(tc.Context, &api.GetRootCACertificateRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.Certificate) } @@ -43,7 +43,7 @@ func TestRestartRootCA(t *testing.T) { defer tc.Stop() _, err := tc.NodeCAClients[0].NodeCertificateStatus(tc.Context, &api.NodeCertificateStatusRequest{NodeID: "foo"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) tc.CAServer.Stop() @@ -52,7 +52,7 @@ func TestRestartRootCA(t *testing.T) { <-tc.CAServer.Ready() _, err = tc.NodeCAClients[0].NodeCertificateStatus(tc.Context, &api.NodeCertificateStatusRequest{NodeID: "foo"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) } @@ -61,11 +61,11 @@ func TestIssueNodeCertificate(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Token: tc.WorkerToken} issueResponse, err := tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, issueResponse.NodeID) assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership) @@ -83,11 +83,11 @@ func TestForceRotationIsNoop(t *testing.T) { // Get a new Certificate issued csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Token: tc.WorkerToken} issueResponse, err := tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, issueResponse.NodeID) assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership) @@ -108,7 +108,7 @@ func TestForceRotationIsNoop(t *testing.T) { node.Certificate.Status.State = api.IssuanceStateRotate return store.UpdateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) // Wait a bit and check that the certificate hasn't changed/been reissued time.Sleep(250 * time.Millisecond) @@ -129,7 +129,7 @@ func TestIssueNodeCertificateBrokenCA(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) tc.ExternalSigningServer.Flake() @@ -139,7 +139,7 @@ func TestIssueNodeCertificateBrokenCA(t *testing.T) { }() issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Token: tc.WorkerToken} issueResponse, err := tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, issueResponse.NodeID) assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership) @@ -158,7 +158,7 @@ func TestIssueNodeCertificateWithInvalidCSR(t *testing.T) { issueRequest := &api.IssueNodeCertificateRequest{CSR: []byte("random garbage"), Token: tc.WorkerToken} issueResponse, err := tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, issueResponse.NodeID) assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership) @@ -175,12 +175,12 @@ func TestIssueNodeCertificateWorkerRenewal(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) role := api.NodeRoleWorker issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Role: role} issueResponse, err := tc.NodeCAClients[1].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, issueResponse.NodeID) assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership) @@ -197,7 +197,7 @@ func TestIssueNodeCertificateManagerRenewal(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, csr) role := api.NodeRoleManager @@ -220,13 +220,13 @@ func TestIssueNodeCertificateWorkerFromDifferentOrgRenewal(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) // Since we're using a client that has a different Organization, this request will be treated // as a new certificate request, not allowing auto-renewal. Therefore, the request will fail. issueRequest := &api.IssueNodeCertificateRequest{CSR: csr} _, err = tc.NodeCAClients[3].IssueNodeCertificate(tc.Context, issueRequest) - assert.Error(t, err) + require.Error(t, err) } func TestNodeCertificateRenewalsDoNotRequireToken(t *testing.T) { @@ -234,18 +234,18 @@ func TestNodeCertificateRenewalsDoNotRequireToken(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) role := api.NodeRoleManager issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Role: role} issueResponse, err := tc.NodeCAClients[2].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, issueResponse.NodeID) assert.Equal(t, api.NodeMembershipAccepted, issueResponse.NodeMembership) statusRequest := &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID} statusResponse, err := tc.NodeCAClients[2].NodeCertificateStatus(tc.Context, statusRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.IssuanceStateIssued, statusResponse.Status.State) assert.NotNil(t, statusResponse.Certificate.Certificate) assert.Equal(t, role, statusResponse.Certificate.Role) @@ -272,47 +272,47 @@ func TestNewNodeCertificateRequiresToken(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) // Issuance fails if no secret is provided role := api.NodeRoleManager issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Role: role} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") role = api.NodeRoleWorker issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") // Issuance fails if wrong secret is provided role = api.NodeRoleManager issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: "invalid-secret"} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") role = api.NodeRoleWorker issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: "invalid-secret"} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") // Issuance succeeds if correct token is provided role = api.NodeRoleManager issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: tc.ManagerToken} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) role = api.NodeRoleWorker issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: tc.WorkerToken} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) // Rotate manager and worker tokens var ( newManagerToken string newWorkerToken string ) - assert.NoError(t, tc.MemoryStore.Update(func(tx store.Tx) error { + require.NoError(t, tc.MemoryStore.Update(func(tx store.Tx) error { clusters, _ := store.FindClusters(tx, store.ByName(store.DefaultClusterName)) newWorkerToken = ca.GenerateJoinToken(&tc.RootCA, false) clusters[0].RootCA.JoinTokens.Worker = newWorkerToken @@ -322,7 +322,7 @@ func TestNewNodeCertificateRequiresToken(t *testing.T) { })) // updating the join token may take a little bit in order to register on the CA server, so poll - assert.NoError(t, testutils.PollFunc(nil, func() error { + require.NoError(t, testutils.PollFunc(nil, func() error { // Old token should fail role = api.NodeRoleManager issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: tc.ManagerToken} @@ -334,23 +334,23 @@ func TestNewNodeCertificateRequiresToken(t *testing.T) { })) // Old token should fail - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") role = api.NodeRoleWorker issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: tc.WorkerToken} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") // New token should succeed role = api.NodeRoleManager issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: newManagerToken} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) role = api.NodeRoleWorker issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: newWorkerToken} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.NoError(t, err) + require.NoError(t, err) } func TestNewNodeCertificateBadToken(t *testing.T) { @@ -358,18 +358,18 @@ func TestNewNodeCertificateBadToken(t *testing.T) { defer tc.Stop() csr, _, err := ca.GenerateNewCSR() - assert.NoError(t, err) + require.NoError(t, err) // Issuance fails if wrong secret is provided role := api.NodeRoleManager issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: "invalid-secret"} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") role = api.NodeRoleWorker issueRequest = &api.IssueNodeCertificateRequest{CSR: csr, Role: role, Token: "invalid-secret"} _, err = tc.NodeCAClients[0].IssueNodeCertificate(tc.Context, issueRequest) - assert.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") + require.EqualError(t, err, "rpc error: code = InvalidArgument desc = A valid join token is necessary to join this cluster") } func TestGetUnlockKey(t *testing.T) { @@ -1147,7 +1147,7 @@ func TestRootRotationReconciliationNoChanges(t *testing.T) { } s, err := rt.tc.CAServer.RootCA().Signer() require.NoError(t, err, testcase.descr) - require.Equal(t, s.Key, expectedKey, testcase.descr) + require.Equal(t, expectedKey, s.Key, testcase.descr) } } diff --git a/ca/testutils/cautils.go b/ca/testutils/cautils.go index 9bd491f03d..987f4fc9a2 100644 --- a/ca/testutils/cautils.go +++ b/ca/testutils/cautils.go @@ -26,7 +26,6 @@ import ( "github.com/moby/swarmkit/v2/manager/state/store" stateutils "github.com/moby/swarmkit/v2/manager/state/testutils" "github.com/moby/swarmkit/v2/remotes" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -217,22 +216,22 @@ func newTestCA(t *testing.T, tempBaseDir string, apiRootCA api.RootCA, krwGenera managerConfig, qClose1, err := genSecurityConfig(s, rootCA, krw, ca.ManagerRole, organization, "", External) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } managerDiffOrgConfig, qClose2, err := genSecurityConfig(s, rootCA, krw, ca.ManagerRole, "swarm-test-org-2", "", External) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } workerConfig, qClose3, err := genSecurityConfig(s, rootCA, krw, ca.WorkerRole, organization, "", External) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } l, err := net.Listen("tcp", "127.0.0.1:0") if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } baseOpts := []grpc.DialOption{grpc.WithTimeout(10 * time.Second)} @@ -243,22 +242,22 @@ func newTestCA(t *testing.T, tempBaseDir string, apiRootCA api.RootCA, krwGenera conn1, err := grpc.Dial(l.Addr().String(), insecureClientOpts...) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } conn2, err := grpc.Dial(l.Addr().String(), clientOpts...) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } conn3, err := grpc.Dial(l.Addr().String(), managerOpts...) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } conn4, err := grpc.Dial(l.Addr().String(), managerDiffOrgOpts...) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } serverOpts := []grpc.ServerOption{grpc.Creds(managerConfig.ServerTLSCreds)} @@ -436,7 +435,7 @@ func createClusterObject(t *testing.T, s *store.MemoryStore, clusterID string, a return nil }) if t != nil { - assert.NoError(t, err) + require.NoError(t, err) } return cluster } diff --git a/ca/transport_test.go b/ca/transport_test.go index 7d963ae39d..72aa90581b 100644 --- a/ca/transport_test.go +++ b/ca/transport_test.go @@ -17,12 +17,12 @@ func TestNewMutableTLS(t *testing.T) { require.NoError(t, err) cert, _, err := rootCA.IssueAndSaveNewCertificates(krw, "CN", ManagerRole, "org") - assert.NoError(t, err) + require.NoError(t, err) tlsConfig, err := NewServerTLSConfig([]tls.Certificate{*cert}, rootCA.Pool) - assert.NoError(t, err) + require.NoError(t, err) creds, err := NewMutableTLS(tlsConfig) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ManagerRole, creds.Role()) assert.Equal(t, "CN", creds.NodeID()) } @@ -36,10 +36,10 @@ func TestGetAndValidateCertificateSubject(t *testing.T) { require.NoError(t, err) cert, _, err := rootCA.IssueAndSaveNewCertificates(krw, "CN", ManagerRole, "org") - assert.NoError(t, err) + require.NoError(t, err) name, err := GetAndValidateCertificateSubject([]tls.Certificate{*cert}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "CN", name.CommonName) assert.Len(t, name.OrganizationalUnit, 1) assert.Equal(t, ManagerRole, name.OrganizationalUnit[0]) @@ -55,23 +55,23 @@ func TestLoadNewTLSConfig(t *testing.T) { // Create two different certs and two different TLS configs cert1, _, err := rootCA.IssueAndSaveNewCertificates(krw, "CN1", ManagerRole, "org") - assert.NoError(t, err) + require.NoError(t, err) cert2, _, err := rootCA.IssueAndSaveNewCertificates(krw, "CN2", WorkerRole, "org") - assert.NoError(t, err) + require.NoError(t, err) tlsConfig1, err := NewServerTLSConfig([]tls.Certificate{*cert1}, rootCA.Pool) - assert.NoError(t, err) + require.NoError(t, err) tlsConfig2, err := NewServerTLSConfig([]tls.Certificate{*cert2}, rootCA.Pool) - assert.NoError(t, err) + require.NoError(t, err) // Load the first TLS config into a MutableTLS creds, err := NewMutableTLS(tlsConfig1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ManagerRole, creds.Role()) assert.Equal(t, "CN1", creds.NodeID()) // Load the new Config and assert it changed err = creds.loadNewTLSConfig(tlsConfig2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, WorkerRole, creds.Role()) assert.Equal(t, "CN2", creds.NodeID()) } diff --git a/cli/external_ca_test.go b/cli/external_ca_test.go index f914c3a44f..da0039d5c8 100644 --- a/cli/external_ca_test.go +++ b/cli/external_ca_test.go @@ -5,6 +5,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseExternalCA(t *testing.T) { @@ -22,7 +23,7 @@ func TestParseExternalCA(t *testing.T) { for _, spec := range invalidSpecs { _, err := parseExternalCA(spec) - assert.Error(t, err) + require.Error(t, err) } validSpecs := []struct { @@ -41,7 +42,7 @@ func TestParseExternalCA(t *testing.T) { for _, spec := range validSpecs { parsed, err := parseExternalCA(spec.input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, spec.expected, parsed) } } diff --git a/identity/combined_id_test.go b/identity/combined_id_test.go index 74ea76d6cf..47273b4e35 100644 --- a/identity/combined_id_test.go +++ b/identity/combined_id_test.go @@ -4,6 +4,8 @@ import ( "fmt" "math/rand" "testing" + + "github.com/stretchr/testify/require" ) func TestCombineTwoIDs(t *testing.T) { @@ -13,7 +15,5 @@ func TestCombineTwoIDs(t *testing.T) { combinedID := CombineTwoIDs(id1, id2) expected := fmt.Sprintf("%s.%s", id1, id2) - if combinedID != expected { - t.Fatalf("%s != %s", combinedID, expected) - } + require.Equalf(t, expected, combinedID, "%s != %s", combinedID, expected) } diff --git a/identity/randomid_test.go b/identity/randomid_test.go index 9688a1108e..53f10319f3 100644 --- a/identity/randomid_test.go +++ b/identity/randomid_test.go @@ -4,6 +4,8 @@ import ( "math/big" "math/rand" "testing" + + "github.com/stretchr/testify/require" ) func TestGenerateGUID(t *testing.T) { @@ -14,9 +16,7 @@ func TestGenerateGUID(t *testing.T) { var i big.Int _, ok := i.SetString(guid, randomIDBase) - if !ok { - t.Fatal("id should be base 36", i, guid) - } + require.True(t, ok, "id should be base 36", i, guid) // To ensure that all identifiers are fixed length, we make sure they // get padded out to 25 characters, which is the maximum for the base36 @@ -26,8 +26,6 @@ func TestGenerateGUID(t *testing.T) { // was calculated from floor(log(2^128-1, 36)) + 1. // // See http://mathworld.wolfram.com/NumberLength.html for more information. - if len(guid) != maxRandomIDLength { - t.Fatalf("len(%s) != %v", guid, maxRandomIDLength) - } + require.Lenf(t, guid, maxRandomIDLength, "len(%s) != %v", guid, maxRandomIDLength) } } diff --git a/integration/integration_test.go b/integration/integration_test.go index 9ee3943a6d..85c39e00a7 100644 --- a/integration/integration_test.go +++ b/integration/integration_test.go @@ -536,7 +536,7 @@ func TestRestartLeader(t *testing.T) { if node.ID == origLeaderID { continue } - require.False(t, node.Status.State == api.NodeStatus_DOWN, "nodes shouldn't go to down") + require.NotEqual(t, api.NodeStatus_DOWN, node.Status.State, "nodes shouldn't go to down") if node.Status.State != api.NodeStatus_READY { return errors.Errorf("node %s is still not ready", node.ID) } diff --git a/internal/idm/idm_test.go b/internal/idm/idm_test.go index 9bf1a779a9..cb881f6df4 100644 --- a/internal/idm/idm_test.go +++ b/internal/idm/idm_test.go @@ -2,157 +2,100 @@ package idm import ( "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNew(t *testing.T) { i, err := New(0, 10) - if err != nil { - t.Errorf("idm.New(0, 10) error = %v", err) - } - if i.set == nil { - t.Error("set is not initialized") - } - if i.start != 0 { - t.Errorf("unexpected start: got %d, want 0", i.start) - } - if i.end != 10 { - t.Errorf("unexpected end: got %d, want 10", i.end) - } + require.NoErrorf(t, err, "idm.New(0, 10) error = %v", err) + assert.NotNil(t, i.set, "set is not initialized") + assert.Equalf(t, 0, i.start, "unexpected start: got %d, want 0", i.start) + assert.Equalf(t, 10, i.end, "unexpected end: got %d, want 10", i.end) } func TestAllocate(t *testing.T) { i, err := New(50, 52) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) - if err = i.GetSpecificID(49); err == nil { - t.Error("i.GetSpecificID(49): expected failure but succeeded") - } + err = i.GetSpecificID(49) + require.Error(t, err, "i.GetSpecificID(49): expected failure but succeeded") - if err = i.GetSpecificID(53); err == nil { - t.Fatal("i.GetSpecificID(53): expected failure but succeeded") - } + err = i.GetSpecificID(53) + require.Error(t, err, "i.GetSpecificID(53): expected failure but succeeded") o, err := i.GetID(false) - if err != nil { - t.Errorf("i.GetID(false) error = %v", err) - } - if o != 50 { - t.Errorf("i.GetID(false) = %v, want 50", o) - } + require.NoErrorf(t, err, "i.GetID(false) error = %v", err) + assert.Equalf(t, 50, o, "i.GetID(false) = %v, want 50", o) err = i.GetSpecificID(50) - if err == nil { - t.Error("i.GetSpecificID(50): allocating already-allocated id should fail") - } + require.Error(t, err, "i.GetSpecificID(50): allocating already-allocated id should fail") o, err = i.GetID(false) - if err != nil { - t.Errorf("i.GetID(false) error = %v", err) - } - if o != 51 { - t.Errorf("i.GetID(false) = %v, want 51", o) - } + require.NoErrorf(t, err, "i.GetID(false) error = %v", err) + assert.Equalf(t, 51, o, "i.GetID(false) = %v, want 51", o) o, err = i.GetID(false) - if err != nil { - t.Errorf("i.GetID(false) error = %v", err) - } - if o != 52 { - t.Errorf("i.GetID(false) = %v, want 52", o) - } + require.NoErrorf(t, err, "i.GetID(false) error = %v", err) + assert.Equalf(t, 52, o, "i.GetID(false) = %v, want 52", o) o, err = i.GetID(false) - if err == nil { - t.Errorf("i.GetID(false) = %v, allocating ID from full set should fail", o) - } + require.Errorf(t, err, "i.GetID(false) = %v, allocating ID from full set should fail", o) i.Release(50) o, err = i.GetID(false) - if err != nil { - t.Errorf("i.GetID(false) error = %v", err) - } - if o != 50 { - t.Errorf("i.GetID(false) = %v, want 50", o) - } + require.NoErrorf(t, err, "i.GetID(false) error = %v", err) + assert.Equalf(t, 50, o, "i.GetID(false) = %v, want 50", o) i.Release(52) err = i.GetSpecificID(52) - if err != nil { - t.Errorf("i.GetSpecificID(52) error = %v, expected success allocating a released ID", err) - } + assert.NoErrorf(t, err, "i.GetSpecificID(52) error = %v, expected success allocating a released ID", err) } func TestUninitialized(t *testing.T) { i := &IDM{} - if _, err := i.GetID(false); err == nil { - t.Error("i.GetID(...) on uninitialized set should fail") - } + _, err := i.GetID(false) + require.Error(t, err, "i.GetID(...) on uninitialized set should fail") - if err := i.GetSpecificID(44); err == nil { - t.Error("i.GetSpecificID(...) on uninitialized set should fail") - } + err = i.GetSpecificID(44) + assert.Error(t, err, "i.GetSpecificID(...) on uninitialized set should fail") } func TestAllocateSerial(t *testing.T) { i, err := New(50, 55) - if err != nil { - t.Fatalf("New(50, 55) error = %v", err) - } + require.NoErrorf(t, err, "New(50, 55) error = %v", err) - if err = i.GetSpecificID(49); err == nil { - t.Errorf("i.GetSpecificID(49): allocating out-of-range id should fail") - } + err = i.GetSpecificID(49) + require.Errorf(t, err, "i.GetSpecificID(49): allocating out-of-range id should fail") - if err = i.GetSpecificID(56); err == nil { - t.Errorf("i.GetSpecificID(56): allocating out-of-range id should fail") - } + err = i.GetSpecificID(56) + require.Errorf(t, err, "i.GetSpecificID(56): allocating out-of-range id should fail") o, err := i.GetID(true) - if err != nil { - t.Errorf("i.GetID(true) error = %v", err) - } - if o != 50 { - t.Errorf("i.GetID(true) = %v, want 50", o) - } + require.NoErrorf(t, err, "i.GetID(true) error = %v", err) + assert.Equalf(t, 50, o, "i.GetID(true) = %v, want 50", o) err = i.GetSpecificID(50) - if err == nil { - t.Errorf("i.GetSpecificID(50): allocating already-allocated id should fail") - } + require.Errorf(t, err, "i.GetSpecificID(50): allocating already-allocated id should fail") o, err = i.GetID(true) - if err != nil { - t.Errorf("i.GetID(true) error = %v", err) - } - if o != 51 { - t.Errorf("i.GetID(true) = %v, want 51", o) - } + require.NoErrorf(t, err, "i.GetID(true) error = %v", err) + assert.Equalf(t, 51, o, "i.GetID(true) = %v, want 51", o) o, err = i.GetID(true) - if err != nil { - t.Errorf("i.GetID(true) error = %v", err) - } - if o != 52 { - t.Errorf("i.GetID(true) = %v, want 52", o) - } + require.NoErrorf(t, err, "i.GetID(true) error = %v", err) + assert.Equalf(t, 52, o, "i.GetID(true) = %v, want 52", o) i.Release(50) o, err = i.GetID(true) - if err != nil { - t.Errorf("i.GetID(true) error = %v", err) - } - if o != 53 { - t.Errorf("i.GetID(true) = %v, want 53", o) - } + require.NoErrorf(t, err, "i.GetID(true) error = %v", err) + assert.Equalf(t, 53, o, "i.GetID(true) = %v, want 53", o) i.Release(52) err = i.GetSpecificID(52) - if err != nil { - t.Errorf("i.GetSpecificID(52) error = %v, expected success allocating a released ID", err) - } + assert.NoErrorf(t, err, "i.GetSpecificID(52) error = %v, expected success allocating a released ID", err) } diff --git a/ioutils/ioutils_test.go b/ioutils/ioutils_test.go index 9e7618ac87..7cde50930a 100644 --- a/ioutils/ioutils_test.go +++ b/ioutils/ioutils_test.go @@ -5,21 +5,18 @@ import ( "os" "path/filepath" "testing" + + "github.com/stretchr/testify/require" ) func TestAtomicWriteToFile(t *testing.T) { tmpDir := t.TempDir() expected := []byte("barbaz") - if err := AtomicWriteFile(filepath.Join(tmpDir, "foo"), expected, 0o600); err != nil { - t.Fatalf("Error writing to file: %v", err) - } + err := AtomicWriteFile(filepath.Join(tmpDir, "foo"), expected, 0o600) + require.NoErrorf(t, err, "Error writing to file: %v", err) actual, err := os.ReadFile(filepath.Join(tmpDir, "foo")) - if err != nil { - t.Fatalf("Error reading from file: %v", err) - } + require.NoErrorf(t, err, "Error reading from file: %v", err) - if !bytes.Equal(actual, expected) { - t.Fatalf("Data mismatch, expected %q, got %q", expected, actual) - } + require.Truef(t, bytes.Equal(actual, expected), "Data mismatch, expected %q, got %q", expected, actual) } diff --git a/log/context_test.go b/log/context_test.go index 6c59874c0a..ddb73b6d02 100644 --- a/log/context_test.go +++ b/log/context_test.go @@ -13,29 +13,29 @@ func TestLoggerContext(t *testing.T) { assert.Equal(t, G(ctx), GetLogger(ctx)) // these should be the same. ctx = WithLogger(ctx, G(ctx).WithField("test", "one")) - assert.Equal(t, GetLogger(ctx).Data["test"], "one") + assert.Equal(t, "one", GetLogger(ctx).Data["test"]) assert.Equal(t, G(ctx), GetLogger(ctx)) // these should be the same. } func TestModuleContext(t *testing.T) { ctx := context.Background() - assert.Equal(t, GetModulePath(ctx), "") + assert.Empty(t, GetModulePath(ctx)) ctx = WithModule(ctx, "a") // basic behavior - assert.Equal(t, GetModulePath(ctx), "a") + assert.Equal(t, "a", GetModulePath(ctx)) logger := GetLogger(ctx) - assert.Equal(t, logger.Data["module"], "a") + assert.Equal(t, "a", logger.Data["module"]) parent, ctx := ctx, WithModule(ctx, "a") assert.Equal(t, ctx, parent) // should be a no-op - assert.Equal(t, GetModulePath(ctx), "a") - assert.Equal(t, GetLogger(ctx).Data["module"], "a") + assert.Equal(t, "a", GetModulePath(ctx)) + assert.Equal(t, "a", GetLogger(ctx).Data["module"]) ctx = WithModule(ctx, "b") // new module - assert.Equal(t, GetModulePath(ctx), "a/b") - assert.Equal(t, GetLogger(ctx).Data["module"], "a/b") + assert.Equal(t, "a/b", GetModulePath(ctx)) + assert.Equal(t, "a/b", GetLogger(ctx).Data["module"]) ctx = WithModule(ctx, "c") // new module - assert.Equal(t, GetModulePath(ctx), "a/b/c") - assert.Equal(t, GetLogger(ctx).Data["module"], "a/b/c") + assert.Equal(t, "a/b/c", GetModulePath(ctx)) + assert.Equal(t, "a/b/c", GetLogger(ctx).Data["module"]) } diff --git a/manager/allocator/allocator_test_suite.go b/manager/allocator/allocator_test_suite.go index f37cc426f2..41a57f9333 100644 --- a/manager/allocator/allocator_test_suite.go +++ b/manager/allocator/allocator_test_suite.go @@ -14,7 +14,6 @@ import ( "github.com/moby/swarmkit/v2/manager/state" "github.com/moby/swarmkit/v2/manager/state/store" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -30,8 +29,10 @@ type testSuite struct { } func (suite *testSuite) newAllocator(store *store.MemoryStore) *Allocator { + suite.T().Helper() + na, err := suite.np.NewAllocator(nil) - suite.NoError(err) + suite.Require().NoError(err) a := New(store, na) suite.NotNil(a) return a @@ -48,7 +49,7 @@ func (suite *testSuite) startAllocator(a *Allocator) func() { a.Stop() // Prevent data races with suite.T() by checking the error // return value synchronously, before the test function returns. - suite.NoError(<-done) + suite.Require().NoError(<-done) } } @@ -84,7 +85,7 @@ func (suite *testSuite) TestAllocator() { } // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -95,7 +96,7 @@ func (suite *testSuite) TestAllocator() { Ingress: true, }, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) n1 := &api.Network{ ID: "testID1", @@ -105,7 +106,7 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateNetwork(tx, n1)) + suite.Require().NoError(store.CreateNetwork(tx, n1)) s1 := &api.Service{ ID: "testServiceID1", @@ -149,7 +150,7 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateService(tx, s1)) + suite.Require().NoError(store.CreateService(tx, s1)) t1 := &api.Task{ ID: "testTaskID1", @@ -162,7 +163,7 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateTask(tx, t1)) + suite.Require().NoError(store.CreateTask(tx, t1)) t2 := &api.Task{ ID: "testTaskIDPreInit", @@ -172,10 +173,10 @@ func (suite *testSuite) TestAllocator() { ServiceID: "testServiceID1", DesiredState: api.TaskStateRunning, } - suite.NoError(store.CreateTask(tx, t2)) + suite.Require().NoError(store.CreateTask(tx, t2)) // Create the predefined node-local network with one service - suite.NoError(store.CreateNetwork(tx, p)) + suite.Require().NoError(store.CreateNetwork(tx, p)) sp1 := &api.Service{ ID: "predServiceID1", @@ -193,7 +194,7 @@ func (suite *testSuite) TestAllocator() { Endpoint: &api.EndpointSpec{Mode: api.ResolutionModeDNSRoundRobin}, }, } - suite.NoError(store.CreateService(tx, sp1)) + suite.Require().NoError(store.CreateService(tx, sp1)) tp1 := &api.Task{ ID: "predTaskID1", @@ -206,10 +207,10 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateTask(tx, tp1)) + suite.Require().NoError(store.CreateTask(tx, tp1)) // Create the the swarm level node-local network with one service - suite.NoError(store.CreateNetwork(tx, nln)) + suite.Require().NoError(store.CreateNetwork(tx, nln)) sp2 := &api.Service{ ID: "predServiceID2", @@ -227,7 +228,7 @@ func (suite *testSuite) TestAllocator() { Endpoint: &api.EndpointSpec{Mode: api.ResolutionModeDNSRoundRobin}, }, } - suite.NoError(store.CreateService(tx, sp2)) + suite.Require().NoError(store.CreateService(tx, sp2)) tp2 := &api.Task{ ID: "predTaskID2", @@ -240,7 +241,7 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateTask(tx, tp2)) + suite.Require().NoError(store.CreateTask(tx, tp2)) return nil })) @@ -305,7 +306,7 @@ func (suite *testSuite) TestAllocator() { }) // Add new networks/tasks/services after allocator is started. - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { n2 := &api.Network{ ID: "testID2", Spec: api.NetworkSpec{ @@ -314,13 +315,13 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateNetwork(tx, n2)) + suite.Require().NoError(store.CreateNetwork(tx, n2)) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { s2 := &api.Service{ ID: "testServiceID2", Spec: api.ServiceSpec{ @@ -335,13 +336,13 @@ func (suite *testSuite) TestAllocator() { Endpoint: &api.EndpointSpec{}, }, } - suite.NoError(store.CreateService(tx, s2)) + suite.Require().NoError(store.CreateService(tx, s2)) return nil })) watchService(suite.T(), serviceWatch, false, nil) - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t2 := &api.Task{ ID: "testTaskID2", Status: api.TaskStatus{ @@ -350,7 +351,7 @@ func (suite *testSuite) TestAllocator() { ServiceID: "testServiceID2", DesiredState: api.TaskStateRunning, } - suite.NoError(store.CreateTask(tx, t2)) + suite.Require().NoError(store.CreateTask(tx, t2)) return nil })) @@ -366,7 +367,7 @@ func (suite *testSuite) TestAllocator() { }, } - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t3 := &api.Task{ ID: "testTaskID3", Status: api.TaskStatus{ @@ -379,7 +380,7 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateTask(tx, t3)) + suite.Require().NoError(store.CreateTask(tx, t3)) return nil })) @@ -388,21 +389,21 @@ func (suite *testSuite) TestAllocator() { // going through time.Sleep(10 * time.Millisecond) - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateNetwork(tx, n3)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateNetwork(tx, n3)) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) watchTask(suite.T(), s, taskWatch, false, isValidTask) - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteTask(tx, "testTaskID3")) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteTask(tx, "testTaskID3")) return nil })) watchTask(suite.T(), s, taskWatch, false, isValidTask) - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t5 := &api.Task{ ID: "testTaskID5", Spec: api.TaskSpec{ @@ -418,26 +419,26 @@ func (suite *testSuite) TestAllocator() { DesiredState: api.TaskStateRunning, ServiceID: "testServiceID2", } - suite.NoError(store.CreateTask(tx, t5)) + suite.Require().NoError(store.CreateTask(tx, t5)) return nil })) watchTask(suite.T(), s, taskWatch, false, isValidTask) - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteNetwork(tx, "testID3")) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteNetwork(tx, "testID3")) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteService(tx, "testServiceID2")) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteService(tx, "testServiceID2")) return nil })) watchService(suite.T(), serviceWatch, false, nil) // Try to create a task with no network attachments and test // that it moves to ALLOCATED state. - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t4 := &api.Task{ ID: "testTaskID4", Status: api.TaskStatus{ @@ -445,35 +446,35 @@ func (suite *testSuite) TestAllocator() { }, DesiredState: api.TaskStateRunning, } - suite.NoError(store.CreateTask(tx, t4)) + suite.Require().NoError(store.CreateTask(tx, t4)) return nil })) watchTask(suite.T(), s, taskWatch, false, isValidTask) - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { n2 := store.GetNetwork(tx, "testID2") - require.NotEqual(suite.T(), nil, n2) - suite.NoError(store.UpdateNetwork(tx, n2)) + suite.Require().NotNil(n2) + suite.Require().NoError(store.UpdateNetwork(tx, n2)) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) watchNetwork(suite.T(), netWatch, true, nil) // Try updating service which is already allocated with no endpointSpec - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { s := store.GetService(tx, "testServiceID1") s.Spec.Endpoint = nil - suite.NoError(store.UpdateService(tx, s)) + suite.Require().NoError(store.UpdateService(tx, s)) return nil })) watchService(suite.T(), serviceWatch, false, nil) // Try updating task which is already allocated - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t2 := store.GetTask(tx, "testTaskID2") - require.NotEqual(suite.T(), nil, t2) - suite.NoError(store.UpdateTask(tx, t2)) + suite.Require().NotNil(t2) + suite.Require().NoError(store.UpdateTask(tx, t2)) return nil })) watchTask(suite.T(), s, taskWatch, false, isValidTask) @@ -500,19 +501,19 @@ func (suite *testSuite) TestAllocator() { n5 := n4.Copy() n5.ID = "testID5" n5.Spec.Annotations.Name = "test5" - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateNetwork(tx, n4)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateNetwork(tx, n4)) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateNetwork(tx, n5)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateNetwork(tx, n5)) return nil })) watchNetwork(suite.T(), netWatch, true, nil) - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t6 := &api.Task{ ID: "testTaskID6", Status: api.TaskStatus{ @@ -525,14 +526,14 @@ func (suite *testSuite) TestAllocator() { }, }, } - suite.NoError(store.CreateTask(tx, t6)) + suite.Require().NoError(store.CreateTask(tx, t6)) return nil })) watchTask(suite.T(), s, taskWatch, true, nil) // Now remove the conflicting network. - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteNetwork(tx, n4.ID)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteNetwork(tx, n4.ID)) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) @@ -568,18 +569,18 @@ func (suite *testSuite) TestAllocator() { s4 := s3.Copy() s4.ID = "testServiceID4" s4.Spec.Annotations.Name = "service4" - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateService(tx, s3)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateService(tx, s3)) return nil })) watchService(suite.T(), serviceWatch, false, nil) - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateService(tx, s4)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateService(tx, s4)) return nil })) watchService(suite.T(), serviceWatch, true, nil) - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t7 := &api.Task{ ID: "testTaskID7", Status: api.TaskStatus{ @@ -588,14 +589,14 @@ func (suite *testSuite) TestAllocator() { ServiceID: "testServiceID4", DesiredState: api.TaskStateRunning, } - suite.NoError(store.CreateTask(tx, t7)) + suite.Require().NoError(store.CreateTask(tx, t7)) return nil })) watchTask(suite.T(), s, taskWatch, true, nil) // Now remove the conflicting service. - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteService(tx, s3.ID)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteService(tx, s3.ID)) return nil })) watchService(suite.T(), serviceWatch, false, nil) @@ -608,7 +609,7 @@ func (suite *testSuite) TestNoDuplicateIPs() { defer s.Close() // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -629,7 +630,7 @@ func (suite *testSuite) TestNoDuplicateIPs() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) n1 := &api.Network{ ID: "testID1", Spec: api.NetworkSpec{ @@ -648,7 +649,7 @@ func (suite *testSuite) TestNoDuplicateIPs() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, n1)) + suite.Require().NoError(store.CreateNetwork(tx, n1)) s1 := &api.Service{ ID: "testServiceID1", @@ -676,7 +677,7 @@ func (suite *testSuite) TestNoDuplicateIPs() { }, }, } - suite.NoError(store.CreateService(tx, s1)) + suite.Require().NoError(store.CreateService(tx, s1)) return nil })) @@ -704,7 +705,7 @@ func (suite *testSuite) TestNoDuplicateIPs() { reps := 100 for i := 0; i != reps; i++ { - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { t2 := &api.Task{ // The allocator iterates over the tasks in // lexical order, so number tasks in descending @@ -719,7 +720,7 @@ func (suite *testSuite) TestNoDuplicateIPs() { ServiceID: "testServiceID1", DesiredState: api.TaskStateRunning, } - suite.NoError(store.CreateTask(tx, t2)) + suite.Require().NoError(store.CreateTask(tx, t2)) return nil })) @@ -738,7 +739,7 @@ func (suite *testSuite) TestAllocatorRestoreForDuplicateIPs() { defer s.Close() // Create 3 services with 1 task each numsvcstsks := 3 - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -758,7 +759,7 @@ func (suite *testSuite) TestAllocatorRestoreForDuplicateIPs() { }, }, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) for i := 0; i != numsvcstsks; i++ { svc := &api.Service{ @@ -797,13 +798,13 @@ func (suite *testSuite) TestAllocatorRestoreForDuplicateIPs() { }, }, } - suite.NoError(store.CreateService(tx, svc)) + suite.Require().NoError(store.CreateService(tx, svc)) } return nil })) for i := 0; i != numsvcstsks; i++ { - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { tsk := &api.Task{ ID: "testTaskID" + strconv.Itoa(i), Status: api.TaskStatus{ @@ -812,7 +813,7 @@ func (suite *testSuite) TestAllocatorRestoreForDuplicateIPs() { ServiceID: "testServiceID" + strconv.Itoa(i), DesiredState: api.TaskStateRunning, } - suite.NoError(store.CreateTask(tx, tsk)) + suite.Require().NoError(store.CreateTask(tx, tsk)) return nil })) } @@ -820,8 +821,8 @@ func (suite *testSuite) TestAllocatorRestoreForDuplicateIPs() { assignedVIPs := make(map[string]bool) assignedIPs := make(map[string]bool) hasNoIPOverlapServices := func(fakeT assert.TestingT, service *api.Service) bool { - assert.NotEqual(fakeT, len(service.Endpoint.VirtualIPs), 0) - assert.NotEqual(fakeT, len(service.Endpoint.VirtualIPs[0].Addr), 0) + assert.NotEmpty(fakeT, service.Endpoint.VirtualIPs) + assert.NotEmpty(fakeT, service.Endpoint.VirtualIPs[0].Addr) assignedVIP := service.Endpoint.VirtualIPs[0].Addr if assignedVIPs[assignedVIP] { @@ -835,8 +836,8 @@ func (suite *testSuite) TestAllocatorRestoreForDuplicateIPs() { } hasNoIPOverlapTasks := func(fakeT assert.TestingT, s *store.MemoryStore, task *api.Task) bool { - assert.NotEqual(fakeT, len(task.Networks), 0) - assert.NotEqual(fakeT, len(task.Networks[0].Addresses), 0) + assert.NotEmpty(fakeT, task.Networks) + assert.NotEmpty(fakeT, task.Networks[0].Addresses) assignedIP := task.Networks[0].Addresses[0] if assignedIPs[assignedIP] { @@ -875,7 +876,7 @@ func (suite *testSuite) TestAllocatorRestartNoEndpointSpec() { defer s.Close() // Create 3 services with 1 task each numsvcstsks := 3 - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "overlay1", @@ -895,7 +896,7 @@ func (suite *testSuite) TestAllocatorRestartNoEndpointSpec() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) for i := 0; i != numsvcstsks; i++ { svc := &api.Service{ @@ -927,13 +928,13 @@ func (suite *testSuite) TestAllocatorRestartNoEndpointSpec() { }, }, } - suite.NoError(store.CreateService(tx, svc)) + suite.Require().NoError(store.CreateService(tx, svc)) } return nil })) for i := 0; i != numsvcstsks; i++ { - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { tsk := &api.Task{ ID: "testTaskID" + strconv.Itoa(i), Status: api.TaskStatus{ @@ -949,7 +950,7 @@ func (suite *testSuite) TestAllocatorRestartNoEndpointSpec() { }, }, } - suite.NoError(store.CreateTask(tx, tsk)) + suite.Require().NoError(store.CreateTask(tx, tsk)) return nil })) } @@ -964,8 +965,8 @@ func (suite *testSuite) TestAllocatorRestartNoEndpointSpec() { } assignedIPs := make(map[string]bool) hasNoIPOverlapServices := func(fakeT assert.TestingT, service *api.Service) bool { - assert.NotEqual(fakeT, len(service.Endpoint.VirtualIPs), 0) - assert.NotEqual(fakeT, len(service.Endpoint.VirtualIPs[0].Addr), 0) + assert.NotEmpty(fakeT, service.Endpoint.VirtualIPs) + assert.NotEmpty(fakeT, service.Endpoint.VirtualIPs[0].Addr) assignedVIP := service.Endpoint.VirtualIPs[0].Addr if assignedIPs[assignedVIP] { suite.T().Fatalf("service %s assigned duplicate IP %s", service.ID, assignedVIP) @@ -979,8 +980,8 @@ func (suite *testSuite) TestAllocatorRestartNoEndpointSpec() { } hasNoIPOverlapTasks := func(fakeT assert.TestingT, s *store.MemoryStore, task *api.Task) bool { - assert.NotEqual(fakeT, len(task.Networks), 0) - assert.NotEqual(fakeT, len(task.Networks[0].Addresses), 0) + assert.NotEmpty(fakeT, task.Networks) + assert.NotEmpty(fakeT, task.Networks[0].Addresses) assignedIP := task.Networks[0].Addresses[0] if assignedIPs[assignedIP] { suite.T().Fatalf("task %s assigned duplicate IP %s", task.ID, assignedIP) @@ -1007,7 +1008,7 @@ func (suite *testSuite) TestAllocatorRestartNoEndpointSpec() { watchTask(suite.T(), s, taskWatch, false, hasNoIPOverlapTasks) watchService(suite.T(), serviceWatch, false, hasNoIPOverlapServices) } - suite.Len(expectedIPs, 0) + suite.Empty(expectedIPs) } // TestAllocatorRestoreForUnallocatedNetwork tests allocator restart @@ -1024,7 +1025,7 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { numsvcstsks := 3 var n1 *api.Network var n2 *api.Network - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -1044,7 +1045,7 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { }, }, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) n1 = &api.Network{ ID: "testID1", @@ -1064,7 +1065,7 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, n1)) + suite.Require().NoError(store.CreateNetwork(tx, n1)) n2 = &api.Network{ // Intentionally named testID0 so that in restore this network @@ -1076,7 +1077,7 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { }, }, } - suite.NoError(store.CreateNetwork(tx, n2)) + suite.Require().NoError(store.CreateNetwork(tx, n2)) for i := 0; i != numsvcstsks; i++ { svc := &api.Service{ @@ -1125,13 +1126,13 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { }, }, } - suite.NoError(store.CreateService(tx, svc)) + suite.Require().NoError(store.CreateService(tx, svc)) } return nil })) for i := 0; i != numsvcstsks; i++ { - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { tsk := &api.Task{ ID: "testTaskID" + strconv.Itoa(i), Status: api.TaskStatus{ @@ -1147,7 +1148,7 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { ServiceID: "testServiceID" + strconv.Itoa(i), DesiredState: api.TaskStateRunning, } - suite.NoError(store.CreateTask(tx, tsk)) + suite.Require().NoError(store.CreateTask(tx, tsk)) return nil })) } @@ -1162,8 +1163,8 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { "testTaskID2": "10.1.0.7/24", } hasNoIPOverlapServices := func(fakeT assert.TestingT, service *api.Service) bool { - assert.NotEqual(fakeT, len(service.Endpoint.VirtualIPs), 0) - assert.NotEqual(fakeT, len(service.Endpoint.VirtualIPs[0].Addr), 0) + assert.NotEmpty(fakeT, service.Endpoint.VirtualIPs) + assert.NotEmpty(fakeT, service.Endpoint.VirtualIPs[0].Addr) assignedVIP := service.Endpoint.VirtualIPs[1].Addr if assignedIPs[assignedVIP] { suite.T().Fatalf("service %s assigned duplicate IP %s", service.ID, assignedVIP) @@ -1177,8 +1178,8 @@ func (suite *testSuite) TestAllocatorRestoreForUnallocatedNetwork() { } hasNoIPOverlapTasks := func(fakeT assert.TestingT, s *store.MemoryStore, task *api.Task) bool { - assert.NotEqual(fakeT, len(task.Networks), 0) - assert.NotEqual(fakeT, len(task.Networks[0].Addresses), 0) + assert.NotEmpty(fakeT, task.Networks) + assert.NotEmpty(fakeT, task.Networks[0].Addresses) assignedIP := task.Networks[1].Addresses[0] if assignedIPs[assignedIP] { suite.T().Fatalf("task %s assigned duplicate IP %s", task.ID, assignedIP) @@ -1220,7 +1221,7 @@ func (suite *testSuite) TestNodeAllocator() { } // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress", @@ -1231,7 +1232,7 @@ func (suite *testSuite) TestNodeAllocator() { Ingress: true, }, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) n1 := &api.Network{ ID: "overlayID1", @@ -1241,7 +1242,7 @@ func (suite *testSuite) TestNodeAllocator() { }, }, } - suite.NoError(store.CreateNetwork(tx, n1)) + suite.Require().NoError(store.CreateNetwork(tx, n1)) // this network will never be used for any task nUnused := &api.Network{ @@ -1252,9 +1253,9 @@ func (suite *testSuite) TestNodeAllocator() { }, }, } - suite.NoError(store.CreateNetwork(tx, nUnused)) + suite.Require().NoError(store.CreateNetwork(tx, nUnused)) - suite.NoError(store.CreateNode(tx, node1)) + suite.Require().NoError(store.CreateNode(tx, node1)) return nil })) @@ -1268,7 +1269,7 @@ func (suite *testSuite) TestNodeAllocator() { defer suite.startAllocator(a)() - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // create a task assigned to this node that has a network attachment on // n1 t1 := &api.Task{ @@ -1301,8 +1302,8 @@ func (suite *testSuite) TestNodeAllocator() { node2 := &api.Node{ ID: "nodeID2", } - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateNode(tx, node2)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateNode(tx, node2)) return nil })) watchNode(suite.T(), nodeWatch, false, isValidNode, node2, []string{"ingress"}) // node2 @@ -1316,8 +1317,8 @@ func (suite *testSuite) TestNodeAllocator() { }, }, } - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateNetwork(tx, n2)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateNetwork(tx, n2)) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) // overlayID2 @@ -1326,7 +1327,7 @@ func (suite *testSuite) TestNodeAllocator() { watchNode(suite.T(), nodeWatch, true, isValidNode, node2, []string{"ingress"}) // node2 // add a task and validate that the node gets the network for the task - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // create a task assigned to this node that has a network attachment on // n1 t2 := &api.Task{ @@ -1353,7 +1354,7 @@ func (suite *testSuite) TestNodeAllocator() { // add another task with the same network to a node and validate that it // still only has 1 attachment for that network - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // create a task assigned to this node that has a network attachment on // n1 t3 := &api.Task{ @@ -1382,8 +1383,8 @@ func (suite *testSuite) TestNodeAllocator() { // now remove that task we just created, and validate that the node still // has an attachment for the other task // Remove a node and validate remaining node has 2 LB IP addresses - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteTask(tx, "task1")) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteTask(tx, "task1")) return nil })) @@ -1393,8 +1394,8 @@ func (suite *testSuite) TestNodeAllocator() { // now remove another task. this time the attachment on the node should be // removed as well - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteTask(tx, "task2")) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteTask(tx, "task2")) return nil })) @@ -1402,8 +1403,8 @@ func (suite *testSuite) TestNodeAllocator() { watchNode(suite.T(), nodeWatch, true, isValidNode, node1, []string{"ingress", "overlayID1"}) // node1 // Remove a node and validate remaining node has 2 LB IP addresses - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteNode(tx, node2.ID)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteNode(tx, node2.ID)) return nil })) watchNode(suite.T(), nodeWatch, false, nil, nil, nil) // node2 @@ -1426,8 +1427,8 @@ func (suite *testSuite) TestNodeAllocator() { DriverConfig: &api.Driver{Name: "bridge"}, }, } - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.CreateNetwork(tx, p)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateNetwork(tx, p)) return nil })) watchNetwork(suite.T(), netWatch, false, isValidNetwork) // bridge @@ -1494,12 +1495,12 @@ func (suite *testSuite) TestNodeAttachmentOnLeadershipChange() { } // before starting the allocator, populate with these - suite.NoError(s.Update(func(tx store.Tx) error { - require.NoError(suite.T(), store.CreateNetwork(tx, net1)) - require.NoError(suite.T(), store.CreateNetwork(tx, net2)) - require.NoError(suite.T(), store.CreateNode(tx, node1)) - require.NoError(suite.T(), store.CreateTask(tx, task1)) - require.NoError(suite.T(), store.CreateTask(tx, task2)) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.CreateNetwork(tx, net1)) + suite.Require().NoError(store.CreateNetwork(tx, net2)) + suite.Require().NoError(store.CreateNode(tx, node1)) + suite.Require().NoError(store.CreateTask(tx, task1)) + suite.Require().NoError(store.CreateTask(tx, task2)) return nil })) @@ -1528,11 +1529,11 @@ func (suite *testSuite) TestNodeAttachmentOnLeadershipChange() { // now update task2 to assign it to node1 s.Update(func(tx store.Tx) error { task := store.GetTask(tx, task2.ID) - require.NotNil(suite.T(), task) + suite.Require().NotNil(task) // make sure it has 1 network attachment suite.Len(task.Networks, 1) task.NodeID = node1.ID - require.NoError(suite.T(), store.UpdateTask(tx, task)) + suite.Require().NoError(store.UpdateTask(tx, task)) return nil }) @@ -1552,7 +1553,7 @@ func (suite *testSuite) TestAllocateServiceConflictingUserDefinedPorts() { const svcID = "testID1" // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -1573,7 +1574,7 @@ func (suite *testSuite) TestAllocateServiceConflictingUserDefinedPorts() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) s1 := &api.Service{ ID: svcID, @@ -1597,7 +1598,7 @@ func (suite *testSuite) TestAllocateServiceConflictingUserDefinedPorts() { }, }, } - suite.NoError(store.CreateService(tx, s1)) + suite.Require().NoError(store.CreateService(tx, s1)) return nil })) @@ -1615,12 +1616,12 @@ func (suite *testSuite) TestAllocateServiceConflictingUserDefinedPorts() { }) // Update the service to remove the conflicting port - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { s1 := store.GetService(tx, svcID) if suite.NotNil(s1) { s1.Spec.Endpoint.Ports[1].TargetPort = 1235 s1.Spec.Endpoint.Ports[1].PublishedPort = 1235 - suite.NoError(store.UpdateService(tx, s1)) + suite.Require().NoError(store.UpdateService(tx, s1)) } return nil })) @@ -1658,7 +1659,7 @@ func (suite *testSuite) TestDeallocateServiceAllocate() { } // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -1679,8 +1680,8 @@ func (suite *testSuite) TestDeallocateServiceAllocate() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, in)) - suite.NoError(store.CreateService(tx, newSvc("testID1"))) + suite.Require().NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateService(tx, newSvc("testID1"))) return nil })) @@ -1702,9 +1703,9 @@ func (suite *testSuite) TestDeallocateServiceAllocate() { watchService(suite.T(), serviceWatch, false, isTestService("testID1")) // Deallocate the service and allocate a new one with the same port spec - suite.NoError(s.Update(func(tx store.Tx) error { - suite.NoError(store.DeleteService(tx, "testID1")) - suite.NoError(store.CreateService(tx, newSvc("testID2"))) + suite.Require().NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(store.DeleteService(tx, "testID1")) + suite.Require().NoError(store.CreateService(tx, newSvc("testID2"))) return nil })) // Confirm new service is allocated @@ -1718,7 +1719,7 @@ func (suite *testSuite) TestServiceAddRemovePorts() { const svcID = "testID1" // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -1739,7 +1740,7 @@ func (suite *testSuite) TestServiceAddRemovePorts() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) s1 := &api.Service{ ID: svcID, @@ -1758,7 +1759,7 @@ func (suite *testSuite) TestServiceAddRemovePorts() { }, }, } - suite.NoError(store.CreateService(tx, s1)) + suite.Require().NoError(store.CreateService(tx, s1)) return nil })) @@ -1797,11 +1798,11 @@ func (suite *testSuite) TestServiceAddRemovePorts() { allocatedVIP := probedVIP // Unpublish port - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { s1 := store.GetService(tx, svcID) if suite.NotNil(s1) { s1.Spec.Endpoint.Ports = nil - suite.NoError(store.UpdateService(tx, s1)) + suite.Require().NoError(store.UpdateService(tx, s1)) } return nil })) @@ -1810,14 +1811,14 @@ func (suite *testSuite) TestServiceAddRemovePorts() { // Publish port again and ensure VIP is not the same that was deallocated. // Since IP allocation is serial we should receive the next available IP. - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { s1 := store.GetService(tx, svcID) if suite.NotNil(s1) { s1.Spec.Endpoint.Ports = append(s1.Spec.Endpoint.Ports, &api.PortConfig{Name: "some_tcp", TargetPort: 1234, PublishedPort: 1234, }) - suite.NoError(store.UpdateService(tx, s1)) + suite.Require().NoError(store.UpdateService(tx, s1)) } return nil })) @@ -1832,7 +1833,7 @@ func (suite *testSuite) TestServiceUpdatePort() { const svcID = "testID1" // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -1853,7 +1854,7 @@ func (suite *testSuite) TestServiceUpdatePort() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) s1 := &api.Service{ ID: svcID, @@ -1876,7 +1877,7 @@ func (suite *testSuite) TestServiceUpdatePort() { }, }, } - suite.NoError(store.CreateService(tx, s1)) + suite.Require().NoError(store.CreateService(tx, s1)) return nil })) @@ -1891,11 +1892,11 @@ func (suite *testSuite) TestServiceUpdatePort() { return assert.Equal(t, svcID, service.ID) && assert.Len(t, service.Endpoint.Ports, 2) }) - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { s1 := store.GetService(tx, svcID) if suite.NotNil(s1) { s1.Spec.Endpoint.Ports[1].PublishedPort = 1235 - suite.NoError(store.UpdateService(tx, s1)) + suite.Require().NoError(store.UpdateService(tx, s1)) } return nil })) @@ -1915,7 +1916,7 @@ func (suite *testSuite) TestServicePortAllocationIsRepeatable() { const svcID = "testID1" // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -1936,7 +1937,7 @@ func (suite *testSuite) TestServicePortAllocationIsRepeatable() { }, DriverState: &api.Driver{}, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) s1 := &api.Service{ ID: svcID, @@ -1959,7 +1960,7 @@ func (suite *testSuite) TestServicePortAllocationIsRepeatable() { }, }, } - suite.NoError(store.CreateService(tx, s1)) + suite.Require().NoError(store.CreateService(tx, s1)) return nil })) @@ -1991,12 +1992,12 @@ func isValidNode(t assert.TestingT, originalNode, updatedNode *api.Node, network return false } - if !assert.Equal(t, len(updatedNode.Attachments), len(networks)) { + if !assert.Len(t, networks, len(updatedNode.Attachments)) { return false } for _, na := range updatedNode.Attachments { - if !assert.Equal(t, len(na.Addresses), 1) { + if !assert.Len(t, na.Addresses, 1) { return false } } @@ -2008,23 +2009,23 @@ func isValidNetwork(t assert.TestingT, n *api.Network) bool { if _, ok := n.Spec.Annotations.Labels["com.docker.swarm.predefined"]; ok { return true } - return assert.NotEqual(t, n.IPAM.Configs, nil) && - assert.Equal(t, len(n.IPAM.Configs), 1) && - assert.Equal(t, n.IPAM.Configs[0].Range, "") && - assert.Equal(t, len(n.IPAM.Configs[0].Reserved), 0) && + return assert.NotNil(t, n.IPAM.Configs) && + assert.Len(t, n.IPAM.Configs, 1) && + assert.Empty(t, n.IPAM.Configs[0].Range) && + assert.Empty(t, n.IPAM.Configs[0].Reserved) && isValidSubnet(t, n.IPAM.Configs[0].Subnet) && - assert.NotEqual(t, net.ParseIP(n.IPAM.Configs[0].Gateway), nil) + assert.NotNil(t, net.ParseIP(n.IPAM.Configs[0].Gateway)) } func isValidTask(t assert.TestingT, s *store.MemoryStore, task *api.Task) bool { return isValidNetworkAttachment(t, task) && isValidEndpoint(t, s, task) && - assert.Equal(t, task.Status.State, api.TaskStatePending) + assert.Equal(t, api.TaskStatePending, task.Status.State) } func isValidNetworkAttachment(t assert.TestingT, task *api.Task) bool { if len(task.Networks) != 0 { - return assert.Equal(t, len(task.Networks[0].Addresses), 1) && + return assert.Len(t, task.Networks[0].Addresses, 1) && isValidSubnet(t, task.Networks[0].Addresses[0]) } diff --git a/manager/allocator/allocator_test_suite_linux.go b/manager/allocator/allocator_test_suite_linux.go index 2150db3bd7..935dd0382d 100644 --- a/manager/allocator/allocator_test_suite_linux.go +++ b/manager/allocator/allocator_test_suite_linux.go @@ -40,7 +40,7 @@ func (suite *testSuite) TestIPAMNotNil() { } // Try adding some objects to store before allocator is started - suite.NoError(s.Update(func(tx store.Tx) error { + suite.Require().NoError(s.Update(func(tx store.Tx) error { // populate ingress network in := &api.Network{ ID: "ingress-nw-id", @@ -51,13 +51,13 @@ func (suite *testSuite) TestIPAMNotNil() { Ingress: true, }, } - suite.NoError(store.CreateNetwork(tx, in)) + suite.Require().NoError(store.CreateNetwork(tx, in)) // Create the predefined node-local network with one service - suite.NoError(store.CreateNetwork(tx, p)) + suite.Require().NoError(store.CreateNetwork(tx, p)) // Create the the swarm level node-local network with one service - suite.NoError(store.CreateNetwork(tx, nln)) + suite.Require().NoError(store.CreateNetwork(tx, nln)) return nil })) diff --git a/manager/allocator/network_test.go b/manager/allocator/network_test.go index e768de2410..7e50c271db 100644 --- a/manager/allocator/network_test.go +++ b/manager/allocator/network_test.go @@ -34,7 +34,7 @@ func TestUpdatePortsInHostPublishMode(t *testing.T) { } updatePortsInHostPublishMode(&service) - assert.Equal(t, len(service.Endpoint.Ports), 1) - assert.Equal(t, service.Endpoint.Ports[0].PublishedPort, uint32(10000)) - assert.Equal(t, service.Endpoint.Spec.Ports[0].PublishedPort, uint32(10000)) + assert.Len(t, service.Endpoint.Ports, 1) + assert.Equal(t, uint32(10000), service.Endpoint.Ports[0].PublishedPort) + assert.Equal(t, uint32(10000), service.Endpoint.Spec.Ports[0].PublishedPort) } diff --git a/manager/allocator/portallocator_test.go b/manager/allocator/portallocator_test.go index e85ffbe79d..2b91d7de22 100644 --- a/manager/allocator/portallocator_test.go +++ b/manager/allocator/portallocator_test.go @@ -5,6 +5,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReconcilePortConfigs(t *testing.T) { @@ -200,7 +201,7 @@ func TestAllocateServicePorts(t *testing.T) { } err := pa.serviceAllocatePorts(s) - assert.NoError(t, err) + require.NoError(t, err) // Service has a published port 10001 in ServiceSpec s = &api.Service{ @@ -229,7 +230,7 @@ func TestAllocateServicePorts(t *testing.T) { } err = pa.serviceAllocatePorts(s) - assert.NoError(t, err) + require.NoError(t, err) // Service has a published port 10001 in ServiceSpec // which is already allocated on host @@ -260,7 +261,7 @@ func TestAllocateServicePorts(t *testing.T) { // port allocated already, got an error err = pa.serviceAllocatePorts(s) - assert.Error(t, err) + require.Error(t, err) } func TestHostPublishPortsNeedUpdate(t *testing.T) { @@ -894,7 +895,7 @@ func TestAllocate(t *testing.T) { // first consume 30000 in dynamicPortSpace err := pSpace.allocate(pConfig) - assert.NoError(t, err) + require.NoError(t, err) pConfig = &api.PortConfig{ Name: "test1", @@ -905,7 +906,7 @@ func TestAllocate(t *testing.T) { // consume 30000 again in dynamicPortSpace, got an error err = pSpace.allocate(pConfig) - assert.Error(t, err) + require.Error(t, err) pConfig = &api.PortConfig{ Name: "test2", @@ -916,7 +917,7 @@ func TestAllocate(t *testing.T) { // consume 10000 in masterPortSpace, got no error err = pSpace.allocate(pConfig) - assert.NoError(t, err) + require.NoError(t, err) pConfig = &api.PortConfig{ Name: "test3", @@ -927,5 +928,5 @@ func TestAllocate(t *testing.T) { // consume 10000 again in masterPortSpace, got an error err = pSpace.allocate(pConfig) - assert.Error(t, err) + require.Error(t, err) } diff --git a/manager/constraint/constraint_test.go b/manager/constraint/constraint_test.go index 6efd005588..4bf57d378a 100644 --- a/manager/constraint/constraint_test.go +++ b/manager/constraint/constraint_test.go @@ -4,94 +4,95 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParse(t *testing.T) { // empty string _, err := Parse([]string{""}) - assert.Error(t, err) + require.Error(t, err) _, err = Parse([]string{" "}) - assert.Error(t, err) + require.Error(t, err) // no operator _, err = Parse([]string{"nodeabc"}) - assert.Error(t, err) + require.Error(t, err) // incorrect operator _, err = Parse([]string{"node ~ abc"}) - assert.Error(t, err) + require.Error(t, err) // Cannot use the leading digit for key _, err = Parse([]string{"1node==a2"}) - assert.Error(t, err) + require.Error(t, err) // leading and trailing white space are ignored _, err = Parse([]string{" node == node1"}) - assert.NoError(t, err) + require.NoError(t, err) // key cannot container white space in the middle _, err = Parse([]string{"no de== node1"}) - assert.Error(t, err) + require.Error(t, err) // Cannot use * in key _, err = Parse([]string{"no*de==node1"}) - assert.Error(t, err) + require.Error(t, err) // key cannot be empty _, err = Parse([]string{"==node1"}) - assert.Error(t, err) + require.Error(t, err) // value cannot be empty _, err = Parse([]string{"node=="}) - assert.Error(t, err) + require.Error(t, err) // value cannot be an empty space _, err = Parse([]string{"node== "}) - assert.Error(t, err) + require.Error(t, err) // Cannot use $ in key _, err = Parse([]string{"no$de==node1"}) - assert.Error(t, err) + require.Error(t, err) // Allow CAPS in key exprs, err := Parse([]string{"NoDe==node1"}) - assert.NoError(t, err) - assert.Equal(t, exprs[0].key, "NoDe") + require.NoError(t, err) + assert.Equal(t, "NoDe", exprs[0].key) // Allow dot in key exprs, err = Parse([]string{"no.de==node1"}) - assert.NoError(t, err) - assert.Equal(t, exprs[0].key, "no.de") + require.NoError(t, err) + assert.Equal(t, "no.de", exprs[0].key) // Allow leading underscore exprs, err = Parse([]string{"_node==_node1"}) - assert.NoError(t, err) - assert.Equal(t, exprs[0].key, "_node") + require.NoError(t, err) + assert.Equal(t, "_node", exprs[0].key) // Allow special characters in exp exprs, err = Parse([]string{"node==[a-b]+c*(n|b)/"}) - assert.NoError(t, err) - assert.Equal(t, exprs[0].key, "node") + require.NoError(t, err) + assert.Equal(t, "node", exprs[0].key) assert.Equal(t, exprs[0].exp, "[a-b]+c*(n|b)/") // Allow space in Exp exprs, err = Parse([]string{"node==node 1"}) - assert.NoError(t, err) - assert.Equal(t, exprs[0].key, "node") + require.NoError(t, err) + assert.Equal(t, "node", exprs[0].key) assert.Equal(t, exprs[0].exp, "node 1") } func TestMatch(t *testing.T) { exprs, err := Parse([]string{"node.name==foo"}) - assert.NoError(t, err) + require.NoError(t, err) e := exprs[0] assert.True(t, e.Match("foo")) assert.False(t, e.Match("fo")) assert.False(t, e.Match("fooE")) exprs, err = Parse([]string{"node.name!=foo"}) - assert.NoError(t, err) + require.NoError(t, err) e = exprs[0] assert.False(t, e.Match("foo")) assert.True(t, e.Match("bar")) @@ -99,7 +100,7 @@ func TestMatch(t *testing.T) { assert.True(t, e.Match("fooExtra")) exprs, err = Parse([]string{"node.name==f*o"}) - assert.NoError(t, err) + require.NoError(t, err) e = exprs[0] assert.False(t, e.Match("fo")) assert.True(t, e.Match("f*o")) @@ -110,7 +111,7 @@ func TestMatch(t *testing.T) { // test special characters exprs, err = Parse([]string{"node.name==f.-$o"}) - assert.NoError(t, err) + require.NoError(t, err) e = exprs[0] assert.False(t, e.Match("fa-$o")) assert.True(t, e.Match("f.-$o")) diff --git a/manager/controlapi/ca_rotation_test.go b/manager/controlapi/ca_rotation_test.go index e339a5d92d..9b977ce0ce 100644 --- a/manager/controlapi/ca_rotation_test.go +++ b/manager/controlapi/ca_rotation_test.go @@ -12,7 +12,6 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/ca" "github.com/moby/swarmkit/v2/ca/testutils" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -61,7 +60,7 @@ func getSecurityConfig(t *testing.T, localRootCA *ca.RootCA, cluster *api.Cluste paths := ca.NewConfigPaths(tempdir) secConfig, cancel, err := localRootCA.CreateSecurityConfig(context.Background(), ca.NewKeyReadWriter(paths.Node, nil, nil), ca.CertificateRequestConfig{}) require.NoError(t, err) - assert.NoError(t, cancel()) + require.NoError(t, cancel()) return secConfig } diff --git a/manager/controlapi/cluster_test.go b/manager/controlapi/cluster_test.go index 56cfb34f96..31194b776f 100644 --- a/manager/controlapi/cluster_test.go +++ b/manager/controlapi/cluster_test.go @@ -55,7 +55,7 @@ func createClusterObj(id, name string, policy api.AcceptancePolicy, rootCA *ca.R func createCluster(t *testing.T, ts *testServer, id, name string, policy api.AcceptancePolicy, rootCA *ca.RootCA) *api.Cluster { cluster := createClusterObj(id, name, policy, rootCA) - assert.NoError(t, ts.Store.Update(func(tx store.Tx) error { + require.NoError(t, ts.Store.Update(func(tx store.Tx) error { return store.CreateCluster(tx, cluster) })) return cluster @@ -112,7 +112,7 @@ func TestValidateClusterSpec(t *testing.T) { }, } { err := validateClusterSpec(bad.spec) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, bad.c, grpcutils.ErrorCode(err)) } @@ -120,7 +120,7 @@ func TestValidateClusterSpec(t *testing.T) { createClusterSpec(store.DefaultClusterName), } { err := validateClusterSpec(good) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -129,16 +129,16 @@ func TestGetCluster(t *testing.T) { ts := newTestServer(t) defer ts.Stop() _, err := ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, grpcutils.ErrorCode(err)) _, err = ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{ClusterID: "invalid"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, grpcutils.ErrorCode(err)) cluster := createCluster(t, ts, "name", "name", api.AcceptancePolicy{}, ts.Server.securityConfig.RootCA()) r, err := ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{ClusterID: cluster.ID}) - assert.NoError(t, err) + require.NoError(t, err) cluster.Meta.Version = r.Cluster.Meta.Version // Only public fields should be available assert.Equal(t, cluster.ID, r.Cluster.ID) @@ -155,17 +155,17 @@ func TestGetClusterWithSecret(t *testing.T) { ts := newTestServer(t) defer ts.Stop() _, err := ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, grpcutils.ErrorCode(err)) _, err = ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{ClusterID: "invalid"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, grpcutils.ErrorCode(err)) policy := api.AcceptancePolicy{Policies: []*api.AcceptancePolicy_RoleAdmissionPolicy{{Secret: &api.AcceptancePolicy_RoleAdmissionPolicy_Secret{Data: []byte("secret")}}}} cluster := createCluster(t, ts, "name", "name", policy, ts.Server.securityConfig.RootCA()) r, err := ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{ClusterID: cluster.ID}) - assert.NoError(t, err) + require.NoError(t, err) cluster.Meta.Version = r.Cluster.Meta.Version assert.NotEqual(t, cluster, r.Cluster) assert.NotContains(t, r.Cluster.String(), "secret") @@ -179,30 +179,30 @@ func TestUpdateCluster(t *testing.T) { cluster := createCluster(t, ts, "name", store.DefaultClusterName, api.AcceptancePolicy{}, ts.Server.securityConfig.RootCA()) _, err := ts.Client.UpdateCluster(context.Background(), &api.UpdateClusterRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, grpcutils.ErrorCode(err)) _, err = ts.Client.UpdateCluster(context.Background(), &api.UpdateClusterRequest{ClusterID: "invalid", Spec: &cluster.Spec, ClusterVersion: &api.Version{}}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, grpcutils.ErrorCode(err)) // No update options. _, err = ts.Client.UpdateCluster(context.Background(), &api.UpdateClusterRequest{ClusterID: cluster.ID, Spec: &cluster.Spec}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, grpcutils.ErrorCode(err)) _, err = ts.Client.UpdateCluster(context.Background(), &api.UpdateClusterRequest{ClusterID: cluster.ID, Spec: &cluster.Spec, ClusterVersion: &cluster.Meta.Version}) - assert.NoError(t, err) + require.NoError(t, err) r, err := ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{ Filters: &api.ListClustersRequest_Filters{ NamePrefixes: []string{store.DefaultClusterName}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Clusters, 1) assert.Equal(t, cluster.Spec.Annotations.Name, r.Clusters[0].Spec.Annotations.Name) - assert.Len(t, r.Clusters[0].Spec.AcceptancePolicy.Policies, 0) + assert.Empty(t, r.Clusters[0].Spec.AcceptancePolicy.Policies) r.Clusters[0].Spec.AcceptancePolicy = api.AcceptancePolicy{Policies: []*api.AcceptancePolicy_RoleAdmissionPolicy{{Secret: &api.AcceptancePolicy_RoleAdmissionPolicy_Secret{Alg: "bcrypt", Data: []byte("secret")}}}} _, err = ts.Client.UpdateCluster(context.Background(), &api.UpdateClusterRequest{ @@ -210,14 +210,14 @@ func TestUpdateCluster(t *testing.T) { Spec: &r.Clusters[0].Spec, ClusterVersion: &r.Clusters[0].Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{ Filters: &api.ListClustersRequest_Filters{ NamePrefixes: []string{store.DefaultClusterName}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Clusters, 1) assert.Equal(t, cluster.Spec.Annotations.Name, r.Clusters[0].Spec.Annotations.Name) assert.Len(t, r.Clusters[0].Spec.AcceptancePolicy.Policies, 1) @@ -228,13 +228,13 @@ func TestUpdateCluster(t *testing.T) { Spec: &r.Clusters[0].Spec, ClusterVersion: &r.Clusters[0].Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotContains(t, returnedCluster.String(), "secret") assert.NotContains(t, returnedCluster.String(), "PRIVATE") assert.NotNil(t, returnedCluster.Cluster.Spec.AcceptancePolicy.Policies[0].Secret.Data) // Versioning. - assert.NoError(t, err) + require.NoError(t, err) version := &returnedCluster.Cluster.Meta.Version _, err = ts.Client.UpdateCluster(context.Background(), &api.UpdateClusterRequest{ @@ -242,7 +242,7 @@ func TestUpdateCluster(t *testing.T) { Spec: &r.Clusters[0].Spec, ClusterVersion: version, }) - assert.NoError(t, err) + require.NoError(t, err) // Perform an update with the "old" version. _, err = ts.Client.UpdateCluster(context.Background(), &api.UpdateClusterRequest{ @@ -250,7 +250,7 @@ func TestUpdateCluster(t *testing.T) { Spec: &r.Clusters[0].Spec, ClusterVersion: version, }) - assert.Error(t, err) + require.Error(t, err) } func TestUpdateClusterRotateToken(t *testing.T) { @@ -264,7 +264,7 @@ func TestUpdateClusterRotateToken(t *testing.T) { }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Clusters, 1) workerToken := r.Clusters[0].RootCA.JoinTokens.Worker managerToken := r.Clusters[0].RootCA.JoinTokens.Manager @@ -278,14 +278,14 @@ func TestUpdateClusterRotateToken(t *testing.T) { WorkerJoinToken: true, }, }) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{ Filters: &api.ListClustersRequest_Filters{ NamePrefixes: []string{store.DefaultClusterName}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Clusters, 1) assert.NotEqual(t, workerToken, r.Clusters[0].RootCA.JoinTokens.Worker) assert.Equal(t, managerToken, r.Clusters[0].RootCA.JoinTokens.Manager) @@ -300,14 +300,14 @@ func TestUpdateClusterRotateToken(t *testing.T) { ManagerJoinToken: true, }, }) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{ Filters: &api.ListClustersRequest_Filters{ NamePrefixes: []string{store.DefaultClusterName}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Clusters, 1) assert.Equal(t, workerToken, r.Clusters[0].RootCA.JoinTokens.Worker) assert.NotEqual(t, managerToken, r.Clusters[0].RootCA.JoinTokens.Manager) @@ -323,14 +323,14 @@ func TestUpdateClusterRotateToken(t *testing.T) { ManagerJoinToken: true, }, }) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{ Filters: &api.ListClustersRequest_Filters{ NamePrefixes: []string{store.DefaultClusterName}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Clusters, 1) assert.NotEqual(t, workerToken, r.Clusters[0].RootCA.JoinTokens.Worker) assert.NotEqual(t, managerToken, r.Clusters[0].RootCA.JoinTokens.Manager) @@ -497,10 +497,10 @@ func TestUpdateClusterRootRotation(t *testing.T) { // check that all keys are redacted, and that the spec signing cert is also redacted (not because // the cert is a secret, but because that makes it easier to get-and-update) - require.Len(t, c.RootCA.CAKey, 0) - require.Len(t, c.RootCA.RootRotation.CAKey, 0) - require.Len(t, c.Spec.CAConfig.SigningCAKey, 0) - require.Len(t, c.Spec.CAConfig.SigningCACert, 0) + require.Empty(t, c.RootCA.CAKey) + require.Empty(t, c.RootCA.RootRotation.CAKey) + require.Empty(t, c.Spec.CAConfig.SigningCAKey) + require.Empty(t, c.Spec.CAConfig.SigningCACert) return c } @@ -538,40 +538,40 @@ func TestListClusters(t *testing.T) { ts := newTestServer(t) defer ts.Stop() r, err := ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Clusters) createCluster(t, ts, "id1", "name1", api.AcceptancePolicy{}, ts.Server.securityConfig.RootCA()) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Clusters)) + require.NoError(t, err) + assert.Len(t, r.Clusters, 1) createCluster(t, ts, "id2", "name2", api.AcceptancePolicy{}, ts.Server.securityConfig.RootCA()) createCluster(t, ts, "id3", "name3", api.AcceptancePolicy{}, ts.Server.securityConfig.RootCA()) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Clusters)) + require.NoError(t, err) + assert.Len(t, r.Clusters, 3) } func TestListClustersWithSecrets(t *testing.T) { ts := newTestServer(t) defer ts.Stop() r, err := ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Clusters) policy := api.AcceptancePolicy{Policies: []*api.AcceptancePolicy_RoleAdmissionPolicy{{Secret: &api.AcceptancePolicy_RoleAdmissionPolicy_Secret{Alg: "bcrypt", Data: []byte("secret")}}}} createCluster(t, ts, "id1", "name1", policy, ts.Server.securityConfig.RootCA()) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Clusters)) + require.NoError(t, err) + assert.Len(t, r.Clusters, 1) createCluster(t, ts, "id2", "name2", policy, ts.Server.securityConfig.RootCA()) createCluster(t, ts, "id3", "name3", policy, ts.Server.securityConfig.RootCA()) r, err = ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Clusters)) + require.NoError(t, err) + assert.Len(t, r.Clusters, 3) for _, cluster := range r.Clusters { assert.NotContains(t, cluster.String(), policy.Policies[0].Secret) assert.NotContains(t, cluster.String(), "PRIVATE") diff --git a/manager/controlapi/common_test.go b/manager/controlapi/common_test.go index 153dc52ab0..b667b888eb 100644 --- a/manager/controlapi/common_test.go +++ b/manager/controlapi/common_test.go @@ -6,12 +6,13 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/testutils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" ) func TestValidateAnnotations(t *testing.T) { err := validateAnnotations(api.Annotations{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) for _, good := range []api.Annotations{ @@ -22,7 +23,7 @@ func TestValidateAnnotations(t *testing.T) { {Name: "n--d"}, } { err := validateAnnotations(good) - assert.NoError(t, err, "string: "+good.Name) + require.NoError(t, err, "string: "+good.Name) } for _, bad := range []api.Annotations{ @@ -35,6 +36,6 @@ func TestValidateAnnotations(t *testing.T) { {Name: "////"}, } { err := validateAnnotations(bad) - assert.Error(t, err, "string: "+bad.Name) + require.Error(t, err, "string: "+bad.Name) } } diff --git a/manager/controlapi/config_test.go b/manager/controlapi/config_test.go index 148d7d2763..1bab28eddc 100644 --- a/manager/controlapi/config_test.go +++ b/manager/controlapi/config_test.go @@ -10,6 +10,7 @@ import ( "github.com/moby/swarmkit/v2/manager/state/store" "github.com/moby/swarmkit/v2/testutils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" ) @@ -53,7 +54,7 @@ func TestValidateConfigSpec(t *testing.T) { strings.Repeat("a", 65), } { err := validateConfigSpec(createConfigSpec(badName, []byte("valid config"), nil)) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -62,7 +63,7 @@ func TestValidateConfigSpec(t *testing.T) { createConfigSpec("validName", nil, nil), } { err := validateConfigSpec(badSpec) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -78,7 +79,7 @@ func TestValidateConfigSpec(t *testing.T) { strings.Repeat("a", 64), } { err := validateConfigSpec(createConfigSpec(goodName, []byte("valid config"), nil)) - assert.NoError(t, err) + require.NoError(t, err) } for _, good := range []*api.ConfigSpec{ @@ -87,7 +88,7 @@ func TestValidateConfigSpec(t *testing.T) { createConfigSpec("createName", make([]byte, 1), nil), // 1 byte } { err := validateConfigSpec(good) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -97,7 +98,7 @@ func TestCreateConfig(t *testing.T) { // ---- creating a config with an invalid spec fails, thus checking that CreateConfig validates the spec ---- _, err := ts.Client.CreateConfig(context.Background(), &api.CreateConfigRequest{Spec: createConfigSpec("", nil, nil)}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- creating a config with a valid spec succeeds, and returns a config that reflects the config in the store @@ -107,7 +108,7 @@ func TestCreateConfig(t *testing.T) { validSpecRequest := api.CreateConfigRequest{Spec: creationSpec} resp, err := ts.Client.CreateConfig(context.Background(), &validSpecRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Config) assert.Equal(t, *creationSpec, resp.Config.Spec) @@ -122,7 +123,7 @@ func TestCreateConfig(t *testing.T) { // ---- creating a config with the same name, even if it's the exact same spec, fails due to a name conflict ---- _, err = ts.Client.CreateConfig(context.Background(), &validSpecRequest) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.AlreadyExists, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -132,12 +133,12 @@ func TestGetConfig(t *testing.T) { // ---- getting a config without providing an ID results in an InvalidArgument ---- _, err := ts.Client.GetConfig(context.Background(), &api.GetConfigRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- getting a non-existent config fails with NotFound ---- _, err = ts.Client.GetConfig(context.Background(), &api.GetConfigRequest{ConfigID: "12345"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- getting an existing config returns the config ---- @@ -145,10 +146,10 @@ func TestGetConfig(t *testing.T) { err = ts.Store.Update(func(tx store.Tx) error { return store.CreateConfig(tx, config) }) - assert.NoError(t, err) + require.NoError(t, err) resp, err := ts.Client.GetConfig(context.Background(), &api.GetConfigRequest{ConfigID: config.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Config) assert.Equal(t, config, resp.Config) @@ -163,16 +164,16 @@ func TestUpdateConfig(t *testing.T) { err := ts.Store.Update(func(tx store.Tx) error { return store.CreateConfig(tx, config) }) - assert.NoError(t, err) + require.NoError(t, err) // updating a config without providing an ID results in an InvalidArgument _, err = ts.Client.UpdateConfig(context.Background(), &api.UpdateConfigRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // getting a non-existent config fails with NotFound _, err = ts.Client.UpdateConfig(context.Background(), &api.UpdateConfigRequest{ConfigID: "1234adsaa", ConfigVersion: &api.Version{Index: 1}}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // updating an existing config's data returns an error @@ -203,7 +204,7 @@ func TestUpdateConfig(t *testing.T) { Spec: &config.Spec, ConfigVersion: &config.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Config) @@ -216,7 +217,7 @@ func TestUpdateConfig(t *testing.T) { Spec: &config.Spec, ConfigVersion: &resp.Config.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Config) assert.Equal(t, []byte("data"), resp.Config.Spec.Data) @@ -230,7 +231,7 @@ func TestUpdateConfig(t *testing.T) { Spec: &config.Spec, ConfigVersion: &resp.Config.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Config) assert.Equal(t, []byte("data"), resp.Config.Spec.Data) @@ -243,7 +244,7 @@ func TestRemoveUnusedConfig(t *testing.T) { // removing a config without providing an ID results in an InvalidArgument _, err := ts.Client.RemoveConfig(context.Background(), &api.RemoveConfigRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // removing a config that exists succeeds @@ -251,15 +252,15 @@ func TestRemoveUnusedConfig(t *testing.T) { err = ts.Store.Update(func(tx store.Tx) error { return store.CreateConfig(tx, config) }) - assert.NoError(t, err) + require.NoError(t, err) resp, err := ts.Client.RemoveConfig(context.Background(), &api.RemoveConfigRequest{ConfigID: config.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.RemoveConfigResponse{}, *resp) // ---- it was really removed because attempting to remove it again fails with a NotFound ---- _, err = ts.Client.RemoveConfig(context.Background(), &api.RemoveConfigRequest{ConfigID: config.ID}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -272,10 +273,10 @@ func TestRemoveUsedConfig(t *testing.T) { data := []byte("config") creationSpec := createConfigSpec("configID1", data, nil) resp, err := ts.Client.CreateConfig(context.Background(), &api.CreateConfigRequest{Spec: creationSpec}) - assert.NoError(t, err) + require.NoError(t, err) creationSpec2 := createConfigSpec("configID2", data, nil) resp2, err := ts.Client.CreateConfig(context.Background(), &api.CreateConfigRequest{Spec: creationSpec2}) - assert.NoError(t, err) + require.NoError(t, err) // Create a service that uses a config service := createSpec("service1", "image", 1) @@ -292,12 +293,12 @@ func TestRemoveUsedConfig(t *testing.T) { } service.Task.GetContainer().Configs = configRefs _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: service}) - assert.NoError(t, err) + require.NoError(t, err) service2 := createSpec("service2", "image", 1) service2.Task.GetContainer().Configs = configRefs _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: service2}) - assert.NoError(t, err) + require.NoError(t, err) // removing a config that exists but is in use fails _, err = ts.Client.RemoveConfig(context.Background(), &api.RemoveConfigRequest{ConfigID: resp.Config.ID}) @@ -306,11 +307,11 @@ func TestRemoveUsedConfig(t *testing.T) { // removing a config that exists but is not in use succeeds _, err = ts.Client.RemoveConfig(context.Background(), &api.RemoveConfigRequest{ConfigID: resp2.Config.ID}) - assert.NoError(t, err) + require.NoError(t, err) // it was really removed because attempting to remove it again fails with a NotFound _, err = ts.Client.RemoveConfig(context.Background(), &api.RemoveConfigRequest{ConfigID: resp2.Config.ID}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -319,7 +320,7 @@ func TestListConfigs(t *testing.T) { listConfigs := func(req *api.ListConfigsRequest) map[string]*api.Config { resp, err := s.Client.ListConfigs(context.Background(), req) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) byName := make(map[string]*api.Config) @@ -331,7 +332,7 @@ func TestListConfigs(t *testing.T) { // ---- Listing configs when there are no configs returns an empty list but no error ---- result := listConfigs(&api.ListConfigsRequest{}) - assert.Len(t, result, 0) + assert.Empty(t, result) // ---- Create a bunch of configs in the store so we can test filtering ---- allListableNames := []string{"aaa", "aab", "abc", "bbb", "bac", "bbc", "ccc", "cac", "cbc", "ddd"} @@ -344,7 +345,7 @@ func TestListConfigs(t *testing.T) { err := s.Store.Update(func(tx store.Tx) error { return store.CreateConfig(tx, config) }) - assert.NoError(t, err) + require.NoError(t, err) configNamesToID[configName] = config.ID } diff --git a/manager/controlapi/extension_test.go b/manager/controlapi/extension_test.go index 7da1a8e41d..4912cbec96 100644 --- a/manager/controlapi/extension_test.go +++ b/manager/controlapi/extension_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "github.com/moby/swarmkit/v2/api" @@ -18,7 +19,7 @@ func TestCreateExtension(t *testing.T) { // ---- CreateExtensionRequest with no Annotations fails ---- _, err := ts.Client.CreateExtension(context.Background(), &api.CreateExtensionRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // --- With no name also fails @@ -30,7 +31,7 @@ func TestCreateExtension(t *testing.T) { }, }, ) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) extensionName := "extension1" @@ -38,7 +39,7 @@ func TestCreateExtension(t *testing.T) { validRequest := api.CreateExtensionRequest{Annotations: &api.Annotations{Name: extensionName}} resp, err := ts.Client.CreateExtension(context.Background(), &validRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) // for sanity, check that the stored extension still has the extension data @@ -51,7 +52,7 @@ func TestCreateExtension(t *testing.T) { // ---- creating an extension with the same name, even if it's the exact same spec, fails due to a name conflict ---- _, err = ts.Client.CreateExtension(context.Background(), &validRequest) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.AlreadyExists, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // creating an extension with an empty string as a name fails @@ -64,7 +65,7 @@ func TestCreateExtension(t *testing.T) { _, err = ts.Client.CreateExtension( context.Background(), &hasNoName, ) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -74,23 +75,23 @@ func TestGetExtension(t *testing.T) { // ---- getting an extension without providing an ID results in an InvalidArgument ---- _, err := ts.Client.GetExtension(context.Background(), &api.GetExtensionRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- getting a non-existent extension fails with NotFound ---- _, err = ts.Client.GetExtension(context.Background(), &api.GetExtensionRequest{ExtensionID: "12345"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- getting an existing extension returns the extension ---- extensionName := "extension1" validRequest := api.CreateExtensionRequest{Annotations: &api.Annotations{Name: extensionName}} resp, err := ts.Client.CreateExtension(context.Background(), &validRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) resp1, err := ts.Client.GetExtension(context.Background(), &api.GetExtensionRequest{ExtensionID: resp.Extension.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp1) assert.NotNil(t, resp1) assert.Equal(t, validRequest.Annotations.Name, resp1.Extension.Annotations.Name) @@ -103,23 +104,23 @@ func TestRemoveUnreferencedExtension(t *testing.T) { // removing an extension without providing an ID results in an InvalidArgument _, err := ts.Client.RemoveExtension(context.Background(), &api.RemoveExtensionRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // removing an extension that exists succeeds extensionName := "extension1" validRequest := api.CreateExtensionRequest{Annotations: &api.Annotations{Name: extensionName}} resp, err := ts.Client.CreateExtension(context.Background(), &validRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) resp1, err := ts.Client.RemoveExtension(context.Background(), &api.RemoveExtensionRequest{ExtensionID: resp.Extension.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.RemoveExtensionResponse{}, *resp1) // ---- verify the extension was really removed because attempting to remove it again fails with a NotFound ---- _, err = ts.Client.RemoveExtension(context.Background(), &api.RemoveExtensionRequest{ExtensionID: resp.Extension.ID}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } diff --git a/manager/controlapi/network_test.go b/manager/controlapi/network_test.go index aa427533e0..8db2778ab9 100644 --- a/manager/controlapi/network_test.go +++ b/manager/controlapi/network_test.go @@ -12,6 +12,7 @@ import ( "github.com/moby/swarmkit/v2/identity" "github.com/moby/swarmkit/v2/manager/state/store" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createNetworkSpec(name string) *api.NetworkSpec { @@ -80,13 +81,13 @@ func createServiceInNetworkSpec(name, image string, nwid string, instances uint6 func createServiceInNetwork(t *testing.T, ts *testServer, name, image string, nwid string, instances uint64) *api.Service { spec := createServiceInNetworkSpec(name, image, nwid, instances) r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) return r.Service } func TestValidateIPAMConfiguration(t *testing.T) { err := validateIPAMConfiguration(nil) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) IPAMConf := &api.IPAMConfig{ @@ -94,45 +95,45 @@ func TestValidateIPAMConfiguration(t *testing.T) { } err = validateIPAMConfiguration(IPAMConf) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) IPAMConf.Subnet = "bad" err = validateIPAMConfiguration(IPAMConf) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) IPAMConf.Subnet = "192.168.0.0/16" err = validateIPAMConfiguration(IPAMConf) - assert.NoError(t, err) + require.NoError(t, err) IPAMConf.Range = "bad" err = validateIPAMConfiguration(IPAMConf) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) IPAMConf.Range = "192.169.1.0/24" err = validateIPAMConfiguration(IPAMConf) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) IPAMConf.Range = "192.168.1.0/24" err = validateIPAMConfiguration(IPAMConf) - assert.NoError(t, err) + require.NoError(t, err) IPAMConf.Gateway = "bad" err = validateIPAMConfiguration(IPAMConf) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) IPAMConf.Gateway = "192.169.1.1" err = validateIPAMConfiguration(IPAMConf) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) IPAMConf.Gateway = "192.168.1.1" err = validateIPAMConfiguration(IPAMConf) - assert.NoError(t, err) + require.NoError(t, err) } func TestCreateNetwork(t *testing.T) { @@ -141,9 +142,9 @@ func TestCreateNetwork(t *testing.T) { nr, err := ts.Client.CreateNetwork(context.Background(), &api.CreateNetworkRequest{ Spec: createNetworkSpec("testnet1"), }) - assert.NoError(t, err) - assert.NotEqual(t, nr.Network, nil) - assert.NotEqual(t, nr.Network.ID, "") + require.NoError(t, err) + assert.NotNil(t, nr.Network) + assert.NotEmpty(t, nr.Network.ID) } func TestGetNetwork(t *testing.T) { @@ -152,12 +153,12 @@ func TestGetNetwork(t *testing.T) { nr, err := ts.Client.CreateNetwork(context.Background(), &api.CreateNetworkRequest{ Spec: createNetworkSpec("testnet2"), }) - assert.NoError(t, err) - assert.NotEqual(t, nr.Network, nil) - assert.NotEqual(t, nr.Network.ID, "") + require.NoError(t, err) + assert.NotNil(t, nr.Network) + assert.NotEmpty(t, nr.Network.ID) _, err = ts.Client.GetNetwork(context.Background(), &api.GetNetworkRequest{NetworkID: nr.Network.ID}) - assert.NoError(t, err) + require.NoError(t, err) } func TestRemoveNetwork(t *testing.T) { @@ -166,12 +167,12 @@ func TestRemoveNetwork(t *testing.T) { nr, err := ts.Client.CreateNetwork(context.Background(), &api.CreateNetworkRequest{ Spec: createNetworkSpec("testnet3"), }) - assert.NoError(t, err) - assert.NotEqual(t, nr.Network, nil) - assert.NotEqual(t, nr.Network.ID, "") + require.NoError(t, err) + assert.NotNil(t, nr.Network) + assert.NotEmpty(t, nr.Network.ID) _, err = ts.Client.RemoveNetwork(context.Background(), &api.RemoveNetworkRequest{NetworkID: nr.Network.ID}) - assert.NoError(t, err) + require.NoError(t, err) } func TestRemoveNetworkWithAttachedService(t *testing.T) { @@ -180,12 +181,12 @@ func TestRemoveNetworkWithAttachedService(t *testing.T) { nr, err := ts.Client.CreateNetwork(context.Background(), &api.CreateNetworkRequest{ Spec: createNetworkSpec("testnet4"), }) - assert.NoError(t, err) - assert.NotEqual(t, nr.Network, nil) - assert.NotEqual(t, nr.Network.ID, "") + require.NoError(t, err) + assert.NotNil(t, nr.Network) + assert.NotEmpty(t, nr.Network.ID) createServiceInNetwork(t, ts, "name", "image", nr.Network.ID, 1) _, err = ts.Client.RemoveNetwork(context.Background(), &api.RemoveNetworkRequest{NetworkID: nr.Network.ID}) - assert.Error(t, err) + require.Error(t, err) } func TestCreateNetworkInvalidDriver(t *testing.T) { @@ -198,7 +199,7 @@ func TestCreateNetworkInvalidDriver(t *testing.T) { _, err := ts.Client.CreateNetwork(context.Background(), &api.CreateNetworkRequest{ Spec: spec, }) - assert.Error(t, err) + require.Error(t, err) } func TestListNetworks(t *testing.T) { @@ -208,20 +209,20 @@ func TestListNetworks(t *testing.T) { nr1, err := ts.Client.CreateNetwork(context.Background(), &api.CreateNetworkRequest{ Spec: createNetworkSpec("listtestnet1"), }) - assert.NoError(t, err) - assert.NotEqual(t, nr1.Network, nil) - assert.NotEqual(t, nr1.Network.ID, "") + require.NoError(t, err) + assert.NotNil(t, nr1.Network) + assert.NotEmpty(t, nr1.Network.ID) nr2, err := ts.Client.CreateNetwork(context.Background(), &api.CreateNetworkRequest{ Spec: createNetworkSpec("listtestnet2"), }) - assert.NoError(t, err) - assert.NotEqual(t, nr2.Network, nil) - assert.NotEqual(t, nr2.Network.ID, "") + require.NoError(t, err) + assert.NotNil(t, nr2.Network) + assert.NotEmpty(t, nr2.Network.ID) r, err := ts.Client.ListNetworks(context.Background(), &api.ListNetworksRequest{}) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Networks)) // Account ingress network + require.NoError(t, err) + assert.Len(t, r.Networks, 3) // Account ingress network for _, nw := range r.Networks { if nw.Spec.Ingress { continue diff --git a/manager/controlapi/node_test.go b/manager/controlapi/node_test.go index 795e3d8d76..52c5540124 100644 --- a/manager/controlapi/node_test.go +++ b/manager/controlapi/node_test.go @@ -33,7 +33,7 @@ func createNode(t *testing.T, ts *testServer, id string, role api.NodeRole, memb err := ts.Store.Update(func(tx store.Tx) error { return store.CreateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) return node } @@ -42,16 +42,16 @@ func TestGetNode(t *testing.T) { defer ts.Stop() _, err := ts.Client.GetNode(context.Background(), &api.GetNodeRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) _, err = ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: "invalid"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) node := createNode(t, ts, "id", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) r, err := ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: node.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, node.ID, r.Node.ID) } @@ -60,19 +60,19 @@ func TestListNodes(t *testing.T) { ts := newTestServer(t) defer ts.Stop() r, err := ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Nodes) createNode(t, ts, "id1", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 1) createNode(t, ts, "id2", api.NodeRoleWorker, api.NodeMembershipAccepted, api.NodeStatus_READY) createNode(t, ts, "id3", api.NodeRoleWorker, api.NodeMembershipPending, api.NodeStatus_READY) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 3) // List by role. r, err = ts.Client.ListNodes(context.Background(), @@ -82,8 +82,8 @@ func TestListNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 1) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ Filters: &api.ListNodesRequest_Filters{ @@ -91,8 +91,8 @@ func TestListNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 2, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 2) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ Filters: &api.ListNodesRequest_Filters{ @@ -100,8 +100,8 @@ func TestListNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 3) // List by membership. r, err = ts.Client.ListNodes(context.Background(), @@ -111,8 +111,8 @@ func TestListNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 2, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 2) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ Filters: &api.ListNodesRequest_Filters{ @@ -120,8 +120,8 @@ func TestListNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 1) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ Filters: &api.ListNodesRequest_Filters{ @@ -129,8 +129,8 @@ func TestListNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 3) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ Filters: &api.ListNodesRequest_Filters{ @@ -139,8 +139,8 @@ func TestListNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Nodes)) + require.NoError(t, err) + assert.Len(t, r.Nodes, 1) } func TestListNodesWithLabelFilter(t *testing.T) { @@ -243,7 +243,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { r, err := ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ Filters: &api.ListNodesRequest_Filters{}, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 3) t.Log("list nodes with allcommon=engine engine label filter") @@ -252,7 +252,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { Labels: map[string]string{"allcommon": "engine"}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 3) t.Log("list nodes with allcommon=node engine label filter") @@ -262,8 +262,8 @@ func TestListNodesWithLabelFilter(t *testing.T) { }, }) // nothing should be returned; allcommon=engine on engine labels - assert.NoError(t, err) - assert.Len(t, r.Nodes, 0) + require.NoError(t, err) + assert.Empty(t, r.Nodes) t.Log("list nodes with allcommon=node node filter") r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ @@ -271,7 +271,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { NodeLabels: map[string]string{"allcommon": "node"}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 3) t.Log("list nodes with allcommon=engine node filter") @@ -280,8 +280,8 @@ func TestListNodesWithLabelFilter(t *testing.T) { NodeLabels: map[string]string{"allcommon": "engine"}, }, }) - assert.NoError(t, err) - assert.Len(t, r.Nodes, 0) + require.NoError(t, err) + assert.Empty(t, r.Nodes) t.Log("list nodes with nodelabel1=shouldmatch node filter") r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ @@ -290,7 +290,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { }, }) // should only return the first 2 nodes - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 2) assert.Contains(t, r.Nodes, nodes[0]) assert.Contains(t, r.Nodes, nodes[1]) @@ -302,7 +302,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { }, }) // should only return the first 2 nodes - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 2) assert.Contains(t, r.Nodes, nodes[0]) assert.Contains(t, r.Nodes, nodes[1]) @@ -317,7 +317,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { }, }) // should only return the first node - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 1) assert.Contains(t, r.Nodes, nodes[0]) @@ -331,7 +331,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { }, }) // should only return the first node - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 1) assert.Contains(t, r.Nodes, nodes[0]) @@ -348,7 +348,7 @@ func TestListNodesWithLabelFilter(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 2) assert.Contains(t, r.Nodes, nodes[0]) assert.Contains(t, r.Nodes, nodes[2]) @@ -371,18 +371,18 @@ func TestRemoveNodes(t *testing.T) { }) r, err := ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Nodes) createNode(t, ts, "id1", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 1) createNode(t, ts, "id2", api.NodeRoleWorker, api.NodeMembershipAccepted, api.NodeStatus_READY) createNode(t, ts, "id3", api.NodeRoleWorker, api.NodeMembershipPending, api.NodeStatus_UNKNOWN) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 3) // Attempt to remove a ready node without force @@ -392,7 +392,7 @@ func TestRemoveNodes(t *testing.T) { Force: false, }, ) - assert.Error(t, err) + require.Error(t, err) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ @@ -401,7 +401,7 @@ func TestRemoveNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 3) // Attempt to remove a ready node with force @@ -411,7 +411,7 @@ func TestRemoveNodes(t *testing.T) { Force: true, }, ) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ @@ -420,11 +420,11 @@ func TestRemoveNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 2) clusterResp, err := ts.Client.ListClusters(context.Background(), &api.ListClustersRequest{}) - assert.NoError(t, err) + require.NoError(t, err) require.Len(t, clusterResp.Clusters, 1) require.Len(t, clusterResp.Clusters[0].BlacklistedCertificates, 1) _, ok := clusterResp.Clusters[0].BlacklistedCertificates["id2"] @@ -437,7 +437,7 @@ func TestRemoveNodes(t *testing.T) { Force: false, }, ) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{ @@ -446,7 +446,7 @@ func TestRemoveNodes(t *testing.T) { }, }, ) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 1) } @@ -477,10 +477,10 @@ func TestListManagerNodes(t *testing.T) { defer raftutils.TeardownCluster(nodes) // Create a node object for each of the managers - assert.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[1].SecurityConfig.ClientTLSCreds.NodeID()})) - assert.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[2].SecurityConfig.ClientTLSCreds.NodeID()})) - assert.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[3].SecurityConfig.ClientTLSCreds.NodeID()})) + require.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { + require.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[1].SecurityConfig.ClientTLSCreds.NodeID()})) + require.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[2].SecurityConfig.ClientTLSCreds.NodeID()})) + require.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[3].SecurityConfig.ClientTLSCreds.NodeID()})) return nil })) @@ -490,7 +490,7 @@ func TestListManagerNodes(t *testing.T) { // There should be 3 reachable managers listed r, err := ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, r) managers := getMap(t, r.Nodes) assert.Len(t, ts.Server.raft.GetMemberlist(), 3) @@ -516,15 +516,15 @@ func TestListManagerNodes(t *testing.T) { raftutils.WaitForCluster(t, clockSource, nodes) // Add node entries for these - assert.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[4].SecurityConfig.ClientTLSCreds.NodeID()})) - assert.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[5].SecurityConfig.ClientTLSCreds.NodeID()})) + require.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { + require.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[4].SecurityConfig.ClientTLSCreds.NodeID()})) + require.NoError(t, store.CreateNode(tx, &api.Node{ID: nodes[5].SecurityConfig.ClientTLSCreds.NodeID()})) return nil })) // There should be 5 reachable managers listed r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, r) managers = getMap(t, r.Nodes) assert.Len(t, ts.Server.raft.GetMemberlist(), 5) @@ -540,7 +540,7 @@ func TestListManagerNodes(t *testing.T) { nodes[5].ShutdownRaft() // Node 4 and Node 5 should be listed as Unreachable - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) if err != nil { return err @@ -570,7 +570,7 @@ func TestListManagerNodes(t *testing.T) { assert.Len(t, ts.Server.raft.GetMemberlist(), 5) // All the nodes should be reachable again - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) if err != nil { return err @@ -609,7 +609,7 @@ func TestListManagerNodes(t *testing.T) { ts.Server.raft = leaderNode.Node // Node 1 should not be the leader anymore - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) if err != nil { return err @@ -675,12 +675,12 @@ func TestUpdateNode(t *testing.T) { }, NodeVersion: &api.Version{}, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) // Create a node object for the manager - assert.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, &api.Node{ + require.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { + require.NoError(t, store.CreateNode(tx, &api.Node{ ID: nodes[1].SecurityConfig.ClientTLSCreds.NodeID(), Spec: api.NodeSpec{ Membership: api.NodeMembershipAccepted, @@ -691,22 +691,22 @@ func TestUpdateNode(t *testing.T) { })) _, err = ts.Client.UpdateNode(context.Background(), &api.UpdateNodeRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) _, err = ts.Client.UpdateNode(context.Background(), &api.UpdateNodeRequest{NodeID: "invalid", Spec: &api.NodeSpec{}, NodeVersion: &api.Version{}}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) r, err := ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: nodeID}) - assert.NoError(t, err) + require.NoError(t, err) if !assert.NotNil(t, r) { assert.FailNow(t, "got unexpected nil response from GetNode") } assert.NotNil(t, r.Node) _, err = ts.Client.UpdateNode(context.Background(), &api.UpdateNodeRequest{NodeID: nodeID}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) spec := r.Node.Spec.Copy() @@ -715,7 +715,7 @@ func TestUpdateNode(t *testing.T) { NodeID: nodeID, Spec: spec, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) _, err = ts.Client.UpdateNode(context.Background(), &api.UpdateNodeRequest{ @@ -723,10 +723,10 @@ func TestUpdateNode(t *testing.T) { Spec: spec, NodeVersion: &r.Node.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: nodeID}) - assert.NoError(t, err) + require.NoError(t, err) if !assert.NotNil(t, r) { assert.FailNow(t, "got unexpected nil response from GetNode") } @@ -736,11 +736,11 @@ func TestUpdateNode(t *testing.T) { version := &r.Node.Meta.Version _, err = ts.Client.UpdateNode(context.Background(), &api.UpdateNodeRequest{NodeID: nodeID, Spec: &r.Node.Spec, NodeVersion: version}) - assert.NoError(t, err) + require.NoError(t, err) // Perform an update with the "old" version. _, err = ts.Client.UpdateNode(context.Background(), &api.UpdateNodeRequest{NodeID: nodeID, Spec: &r.Node.Spec, NodeVersion: version}) - assert.Error(t, err) + require.Error(t, err) } func testUpdateNodeDemote(t *testing.T) { @@ -757,8 +757,8 @@ func testUpdateNodeDemote(t *testing.T) { ts.Server.store = nodes[1].MemoryStore() // Create a node object for each of the managers - assert.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, &api.Node{ + require.NoError(t, nodes[1].MemoryStore().Update(func(tx store.Tx) error { + require.NoError(t, store.CreateNode(tx, &api.Node{ ID: nodes[1].SecurityConfig.ClientTLSCreds.NodeID(), Spec: api.NodeSpec{ DesiredRole: api.NodeRoleManager, @@ -766,7 +766,7 @@ func testUpdateNodeDemote(t *testing.T) { }, Role: api.NodeRoleManager, })) - assert.NoError(t, store.CreateNode(tx, &api.Node{ + require.NoError(t, store.CreateNode(tx, &api.Node{ ID: nodes[2].SecurityConfig.ClientTLSCreds.NodeID(), Spec: api.NodeSpec{ DesiredRole: api.NodeRoleManager, @@ -774,7 +774,7 @@ func testUpdateNodeDemote(t *testing.T) { }, Role: api.NodeRoleManager, })) - assert.NoError(t, store.CreateNode(tx, &api.Node{ + require.NoError(t, store.CreateNode(tx, &api.Node{ ID: nodes[3].SecurityConfig.ClientTLSCreds.NodeID(), Spec: api.NodeSpec{ DesiredRole: api.NodeRoleManager, @@ -790,7 +790,7 @@ func testUpdateNodeDemote(t *testing.T) { nodes[3].ShutdownRaft() // Node 3 should be listed as Unreachable - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { members := nodes[1].GetMemberlist() if len(members) != 3 { return fmt.Errorf("expected 3 nodes, got %d", len(members)) @@ -803,7 +803,7 @@ func testUpdateNodeDemote(t *testing.T) { // Try to demote Node 2, this should fail because of the quorum safeguard r, err := ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: nodes[2].SecurityConfig.ClientTLSCreds.NodeID()}) - assert.NoError(t, err) + require.NoError(t, err) spec := r.Node.Spec.Copy() spec.DesiredRole = api.NodeRoleWorker version := &r.Node.Meta.Version @@ -812,7 +812,7 @@ func testUpdateNodeDemote(t *testing.T) { Spec: spec, NodeVersion: version, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.FailedPrecondition, testutils.ErrorCode(err)) // Restart Node 3 @@ -820,7 +820,7 @@ func testUpdateNodeDemote(t *testing.T) { raftutils.WaitForCluster(t, clockSource, nodes) // Node 3 should be listed as Reachable - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { members := nodes[1].GetMemberlist() if len(members) != 3 { return fmt.Errorf("expected 3 nodes, got %d", len(members)) @@ -836,7 +836,7 @@ func testUpdateNodeDemote(t *testing.T) { // Try to demote Node 3, this should succeed r, err = ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: nodes[3].SecurityConfig.ClientTLSCreds.NodeID()}) - assert.NoError(t, err) + require.NoError(t, err) spec = r.Node.Spec.Copy() spec.DesiredRole = api.NodeRoleWorker version = &r.Node.Meta.Version @@ -845,7 +845,7 @@ func testUpdateNodeDemote(t *testing.T) { Spec: spec, NodeVersion: version, }) - assert.NoError(t, err) + require.NoError(t, err) newCluster := map[uint64]*raftutils.TestNode{ 1: nodes[1], @@ -857,7 +857,7 @@ func testUpdateNodeDemote(t *testing.T) { raftutils.WaitForCluster(t, clockSource, newCluster) // Server should list 2 members - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { members := nodes[1].GetMemberlist() if len(members) != 2 { return fmt.Errorf("expected 2 nodes, got %d", len(members)) @@ -873,7 +873,7 @@ func testUpdateNodeDemote(t *testing.T) { // Try to demote a Node and scale down to 1 r, err = ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: demoteNode.SecurityConfig.ClientTLSCreds.NodeID()}) - assert.NoError(t, err) + require.NoError(t, err) spec = r.Node.Spec.Copy() spec.DesiredRole = api.NodeRoleWorker version = &r.Node.Meta.Version @@ -882,7 +882,7 @@ func testUpdateNodeDemote(t *testing.T) { Spec: spec, NodeVersion: version, }) - assert.NoError(t, err) + require.NoError(t, err) ts.Server.raft.RemoveMember(context.Background(), raftMember.RaftID) @@ -896,7 +896,7 @@ func testUpdateNodeDemote(t *testing.T) { raftutils.WaitForCluster(t, clockSource, newCluster) - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { members := lastNode.GetMemberlist() if len(members) != 1 { return fmt.Errorf("expected 1 node, got %d", len(members)) @@ -906,7 +906,7 @@ func testUpdateNodeDemote(t *testing.T) { // Make sure we can't demote the last manager. r, err = ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: lastNode.SecurityConfig.ClientTLSCreds.NodeID()}) - assert.NoError(t, err) + require.NoError(t, err) spec = r.Node.Spec.Copy() spec.DesiredRole = api.NodeRoleWorker version = &r.Node.Meta.Version @@ -915,12 +915,12 @@ func testUpdateNodeDemote(t *testing.T) { Spec: spec, NodeVersion: version, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.FailedPrecondition, testutils.ErrorCode(err)) // Propose a change in the spec and check if the remaining node can still process updates r, err = ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: lastNode.SecurityConfig.ClientTLSCreds.NodeID()}) - assert.NoError(t, err) + require.NoError(t, err) spec = r.Node.Spec.Copy() spec.Availability = api.NodeAvailabilityDrain version = &r.Node.Meta.Version @@ -929,12 +929,12 @@ func testUpdateNodeDemote(t *testing.T) { Spec: spec, NodeVersion: version, }) - assert.NoError(t, err) + require.NoError(t, err) // Get node information and check that the availability is set to drain r, err = ts.Client.GetNode(context.Background(), &api.GetNodeRequest{NodeID: lastNode.SecurityConfig.ClientTLSCreds.NodeID()}) - assert.NoError(t, err) - assert.Equal(t, r.Node.Spec.Availability, api.NodeAvailabilityDrain) + require.NoError(t, err) + assert.Equal(t, api.NodeAvailabilityDrain, r.Node.Spec.Availability) } func TestUpdateNodeDemote(t *testing.T) { @@ -962,20 +962,20 @@ func TestOrphanNodeTasks(t *testing.T) { // make sure before we start that our server is in a good (empty) state r, err := ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Nodes) // create a manager createNode(t, ts, "id1", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 1) // create a worker. put it in the DOWN state, which is the state it will be // in to remove it anyway createNode(t, ts, "id2", api.NodeRoleWorker, api.NodeMembershipAccepted, api.NodeStatus_DOWN) r, err = ts.Client.ListNodes(context.Background(), &api.ListNodesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, r.Nodes, 2) // create a network we can "attach" to @@ -1122,9 +1122,9 @@ func TestOrphanNodeTasks(t *testing.T) { for _, task := range tasks { require.NotNil(t, task) if task.ID == "task1" || task.ID == "task3" { - require.Equal(t, task.Status.State, api.TaskStateOrphaned) + require.Equal(t, api.TaskStateOrphaned, task.Status.State) } else { - require.NotEqual(t, task.Status.State, api.TaskStateOrphaned) + require.NotEqual(t, api.TaskStateOrphaned, task.Status.State) } } }) diff --git a/manager/controlapi/resource_test.go b/manager/controlapi/resource_test.go index 0ea74f08ae..021c528a01 100644 --- a/manager/controlapi/resource_test.go +++ b/manager/controlapi/resource_test.go @@ -25,7 +25,7 @@ func prepResource(t *testing.T, ts *testServer) *api.Resource { } // create an extension so we can create valid requests extResp, err := ts.Client.CreateExtension(context.Background(), extensionReq) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, extResp) assert.NotNil(t, extResp.Extension) @@ -66,7 +66,7 @@ func TestCreateResource(t *testing.T) { // create an extension so we can create valid requests resp, err := ts.Client.CreateExtension(context.Background(), extensionReq) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Extension) @@ -81,7 +81,7 @@ func TestCreateResource(t *testing.T) { } resp, err := ts.Client.CreateResource(context.Background(), req) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Resource) assert.NotEmpty(t, resp.Resource.ID) @@ -139,7 +139,7 @@ func TestCreateResource(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { _, err := ts.Client.CreateResource(context.Background(), tc.req) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tc.code, testutils.ErrorCode(err), testutils.ErrorDesc(err)) }) } @@ -220,7 +220,7 @@ func TestUpdateResourceValid(t *testing.T) { require.NotNil(t, resp.Resource) assert.Equal(t, resp.Resource.Payload, r.Payload) assert.Equal(t, resp.Resource.Annotations, r.Annotations) - assert.Equal(t, resp.Resource.Kind, testExtName) + assert.Equal(t, testExtName, resp.Resource.Kind) }) } } @@ -277,7 +277,7 @@ func TestUpdateResourceInvalid(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { _, err := ts.Client.UpdateResource(context.Background(), tc.req) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tc.code, testutils.ErrorCode(err), testutils.ErrorDesc(err)) }) } @@ -291,7 +291,7 @@ func TestGetResource(t *testing.T) { // empty resource ID should fail with invalid argument resp, err := ts.Client.GetResource(context.Background(), &api.GetResourceRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // id which does not exist should return NotFound @@ -299,7 +299,7 @@ func TestGetResource(t *testing.T) { context.Background(), &api.GetResourceRequest{ResourceID: "notreal"}, ) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ID which exists should return the resource @@ -321,7 +321,7 @@ func TestRemoveResource(t *testing.T) { // empty resource ID should fail with invalid argument resp, err := ts.Client.RemoveResource(context.Background(), &api.RemoveResourceRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) assert.Nil(t, resp) @@ -330,7 +330,7 @@ func TestRemoveResource(t *testing.T) { context.Background(), &api.RemoveResourceRequest{ResourceID: "notreal"}, ) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) assert.Nil(t, resp) @@ -347,7 +347,7 @@ func TestRemoveResource(t *testing.T) { context.Background(), &api.RemoveResourceRequest{ResourceID: resource.ID}, ) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) assert.Nil(t, resp) } @@ -384,7 +384,7 @@ func TestListResources(t *testing.T) { // listing when there is nothing returns an empty list but no error result := listResources(&api.ListResourcesRequest{}) - assert.Len(t, result, 0) + assert.Empty(t, result) // create a bunch of resources to test filtering allListableNames := []string{"aaa", "aab", "abc", "bbb", "bac", "bbc", "ccc", "cac", "cbc", "ddd"} diff --git a/manager/controlapi/secret_test.go b/manager/controlapi/secret_test.go index 12d927fe33..f2d040f5b3 100644 --- a/manager/controlapi/secret_test.go +++ b/manager/controlapi/secret_test.go @@ -10,6 +10,7 @@ import ( "github.com/moby/swarmkit/v2/manager/state/store" "github.com/moby/swarmkit/v2/testutils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" ) @@ -53,7 +54,7 @@ func TestValidateSecretSpec(t *testing.T) { strings.Repeat("a", 65), } { err := validateSecretSpec(createSecretSpec(badName, []byte("valid secret"), nil)) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -62,7 +63,7 @@ func TestValidateSecretSpec(t *testing.T) { createSecretSpec("validName", nil, nil), } { err := validateSecretSpec(badSpec) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -78,7 +79,7 @@ func TestValidateSecretSpec(t *testing.T) { strings.Repeat("a", 64), } { err := validateSecretSpec(createSecretSpec(goodName, []byte("valid secret"), nil)) - assert.NoError(t, err) + require.NoError(t, err) } for _, good := range []*api.SecretSpec{ @@ -87,18 +88,18 @@ func TestValidateSecretSpec(t *testing.T) { createSecretSpec("createName", make([]byte, 1), nil), // 1 byte } { err := validateSecretSpec(good) - assert.NoError(t, err) + require.NoError(t, err) } // Ensure secret driver has a name spec := createSecretSpec("secret-driver", make([]byte, 1), nil) spec.Driver = &api.Driver{} err := validateSecretSpec(spec) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) spec.Driver.Name = "secret-driver" err = validateSecretSpec(spec) - assert.NoError(t, err) + require.NoError(t, err) } func TestCreateSecret(t *testing.T) { @@ -107,7 +108,7 @@ func TestCreateSecret(t *testing.T) { // ---- creating a secret with an invalid spec fails, thus checking that CreateSecret validates the spec ---- _, err := ts.Client.CreateSecret(context.Background(), &api.CreateSecretRequest{Spec: createSecretSpec("", nil, nil)}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- creating a secret with a valid spec succeeds, and returns a secret that reflects the secret in the store @@ -117,7 +118,7 @@ func TestCreateSecret(t *testing.T) { validSpecRequest := api.CreateSecretRequest{Spec: creationSpec} resp, err := ts.Client.CreateSecret(context.Background(), &validSpecRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Secret) @@ -134,7 +135,7 @@ func TestCreateSecret(t *testing.T) { // ---- creating a secret with the same name, even if it's the exact same spec, fails due to a name conflict ---- _, err = ts.Client.CreateSecret(context.Background(), &validSpecRequest) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.AlreadyExists, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -144,12 +145,12 @@ func TestGetSecret(t *testing.T) { // ---- getting a secret without providing an ID results in an InvalidArgument ---- _, err := ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- getting a non-existent secret fails with NotFound ---- _, err = ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{SecretID: "12345"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // ---- getting an existing secret returns the secret with all the private data cleaned ---- @@ -157,10 +158,10 @@ func TestGetSecret(t *testing.T) { err = ts.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, secret) }) - assert.NoError(t, err) + require.NoError(t, err) resp, err := ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{SecretID: secret.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Secret) @@ -179,16 +180,16 @@ func TestUpdateSecret(t *testing.T) { err := ts.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, secret) }) - assert.NoError(t, err) + require.NoError(t, err) // updating a secret without providing an ID results in an InvalidArgument _, err = ts.Client.UpdateSecret(context.Background(), &api.UpdateSecretRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // getting a non-existent secret fails with NotFound _, err = ts.Client.UpdateSecret(context.Background(), &api.UpdateSecretRequest{SecretID: "1234adsaa", SecretVersion: &api.Version{Index: 1}}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // updating an existing secret's data returns an error @@ -219,7 +220,7 @@ func TestUpdateSecret(t *testing.T) { Spec: &secret.Spec, SecretVersion: &secret.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Secret) @@ -232,7 +233,7 @@ func TestUpdateSecret(t *testing.T) { Spec: &secret.Spec, SecretVersion: &resp.Secret.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Secret) assert.Nil(t, resp.Secret.Spec.Data) @@ -246,7 +247,7 @@ func TestUpdateSecret(t *testing.T) { Spec: &secret.Spec, SecretVersion: &resp.Secret.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) assert.NotNil(t, resp.Secret) assert.Nil(t, resp.Secret.Spec.Data) @@ -259,7 +260,7 @@ func TestRemoveUnusedSecret(t *testing.T) { // removing a secret without providing an ID results in an InvalidArgument _, err := ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err), testutils.ErrorDesc(err)) // removing a secret that exists succeeds @@ -267,15 +268,15 @@ func TestRemoveUnusedSecret(t *testing.T) { err = ts.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, secret) }) - assert.NoError(t, err) + require.NoError(t, err) resp, err := ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: secret.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.RemoveSecretResponse{}, *resp) // ---- it was really removed because attempting to remove it again fails with a NotFound ---- _, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: secret.ID}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -288,10 +289,10 @@ func TestRemoveUsedSecret(t *testing.T) { data := []byte("secret") creationSpec := createSecretSpec("secretID1", data, nil) resp, err := ts.Client.CreateSecret(context.Background(), &api.CreateSecretRequest{Spec: creationSpec}) - assert.NoError(t, err) + require.NoError(t, err) creationSpec2 := createSecretSpec("secretID2", data, nil) resp2, err := ts.Client.CreateSecret(context.Background(), &api.CreateSecretRequest{Spec: creationSpec2}) - assert.NoError(t, err) + require.NoError(t, err) // Create a service that uses a secret service := createSpec("service1", "image", 1) @@ -308,12 +309,12 @@ func TestRemoveUsedSecret(t *testing.T) { } service.Task.GetContainer().Secrets = secretRefs _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: service}) - assert.NoError(t, err) + require.NoError(t, err) service2 := createSpec("service2", "image", 1) service2.Task.GetContainer().Secrets = secretRefs _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: service2}) - assert.NoError(t, err) + require.NoError(t, err) // removing a secret that exists but is in use fails _, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: resp.Secret.ID}) @@ -322,11 +323,11 @@ func TestRemoveUsedSecret(t *testing.T) { // removing a secret that exists but is not in use succeeds _, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: resp2.Secret.ID}) - assert.NoError(t, err) + require.NoError(t, err) // it was really removed because attempting to remove it again fails with a NotFound _, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: resp2.Secret.ID}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -335,7 +336,7 @@ func TestListSecrets(t *testing.T) { listSecrets := func(req *api.ListSecretsRequest) map[string]*api.Secret { resp, err := s.Client.ListSecrets(context.Background(), req) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) byName := make(map[string]*api.Secret) @@ -347,7 +348,7 @@ func TestListSecrets(t *testing.T) { // ---- Listing secrets when there are no secrets returns an empty list but no error ---- result := listSecrets(&api.ListSecretsRequest{}) - assert.Len(t, result, 0) + assert.Empty(t, result) // ---- Create a bunch of secrets in the store so we can test filtering ---- allListableNames := []string{"aaa", "aab", "abc", "bbb", "bac", "bbc", "ccc", "cac", "cbc", "ddd"} @@ -360,7 +361,7 @@ func TestListSecrets(t *testing.T) { err := s.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, secret) }) - assert.NoError(t, err) + require.NoError(t, err) secretNamesToID[secretName] = secret.ID } // also add an internal secret to show that it's never returned @@ -372,7 +373,7 @@ func TestListSecrets(t *testing.T) { err := s.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, internalSecret) }) - assert.NoError(t, err) + require.NoError(t, err) secretNamesToID["internal"] = internalSecret.ID // ---- build up our list of expectations for what secrets get filtered ---- diff --git a/manager/controlapi/server_test.go b/manager/controlapi/server_test.go index 0d0cd26c7e..115a2b07ed 100644 --- a/manager/controlapi/server_test.go +++ b/manager/controlapi/server_test.go @@ -15,6 +15,7 @@ import ( "github.com/moby/swarmkit/v2/manager/state/store" stateutils "github.com/moby/swarmkit/v2/manager/state/testutils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testServer struct { @@ -42,7 +43,7 @@ func newTestServer(t *testing.T) *testServer { tc := cautils.NewTestCA(t) securityConfig, err := tc.NewNodeConfig(ca.ManagerRole) tc.Stop() - assert.NoError(t, err) + require.NoError(t, err) ts.Store = store.NewMemoryStore(&stateutils.MockProposer{}) assert.NotNil(t, ts.Store) @@ -51,14 +52,14 @@ func newTestServer(t *testing.T) *testServer { assert.NotNil(t, ts.Server) temp, err := os.CreateTemp("", "test-socket") - assert.NoError(t, err) - assert.NoError(t, temp.Close()) - assert.NoError(t, os.Remove(temp.Name())) + require.NoError(t, err) + require.NoError(t, temp.Close()) + require.NoError(t, os.Remove(temp.Name())) ts.tempUnixSocket = temp.Name() lis, err := net.Listen("unix", temp.Name()) - assert.NoError(t, err) + require.NoError(t, err) ts.grpcServer = grpc.NewServer() api.RegisterControlServer(ts.grpcServer, ts.Server) @@ -72,7 +73,7 @@ func newTestServer(t *testing.T) *testServer { grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("unix", addr, timeout) })) - assert.NoError(t, err) + require.NoError(t, err) ts.clientConn = conn ts.Client = api.NewControlClient(conn) diff --git a/manager/controlapi/service_test.go b/manager/controlapi/service_test.go index b3b92ddb8a..91ff8a124c 100644 --- a/manager/controlapi/service_test.go +++ b/manager/controlapi/service_test.go @@ -89,7 +89,7 @@ func createSecret(t *testing.T, ts *testServer, secretName, target string) *api. err := ts.Store.Update(func(tx store.Tx) error { return store.CreateSecret(tx, secret) }) - assert.NoError(t, err) + require.NoError(t, err) return &api.SecretReference{ SecretName: secret.Spec.Annotations.Name, @@ -121,7 +121,7 @@ func createConfig(t *testing.T, ts *testServer, configName, target string) *api. err := ts.Store.Update(func(tx store.Tx) error { return store.CreateConfig(tx, config) }) - assert.NoError(t, err) + require.NoError(t, err) return &api.ConfigReference{ ConfigName: config.Spec.Annotations.Name, @@ -147,20 +147,20 @@ func createServiceSpecWithConfigs(serviceName string, configRefs ...*api.ConfigR func createService(t *testing.T, ts *testServer, name, image string, instances uint64) *api.Service { spec := createSpec(name, image, instances) r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) return r.Service } func createGenericService(t *testing.T, ts *testServer, name, runtime string) *api.Service { spec := createGenericSpec(name, runtime) r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) return r.Service } func getIngressTargetID(t *testing.T, ts *testServer) string { rsp, err := ts.Client.ListNetworks(context.Background(), &api.ListNetworksRequest{}) - assert.NoError(t, err) + require.NoError(t, err) for _, n := range rsp.Networks { if n.Spec.Ingress { return n.ID @@ -183,12 +183,12 @@ func TestValidateResources(t *testing.T) { for _, b := range bad { err := validateResources(b) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } for _, g := range good { - assert.NoError(t, validateResources(g)) + require.NoError(t, validateResources(g)) } } @@ -203,12 +203,12 @@ func TestValidateResourceRequirements(t *testing.T) { } for _, b := range bad { err := validateResourceRequirements(b) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } for _, g := range good { - assert.NoError(t, validateResourceRequirements(g)) + require.NoError(t, validateResourceRequirements(g)) } } @@ -237,13 +237,13 @@ func TestValidateMode(t *testing.T) { for _, b := range bad { err := validateMode(b) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } for _, g := range good { err := validateMode(g) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -296,7 +296,7 @@ func TestValidateTaskSpec(t *testing.T) { }, } { err := validateTaskSpec(bad.s) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, bad.c, testutils.ErrorCode(err)) } @@ -306,7 +306,7 @@ func TestValidateTaskSpec(t *testing.T) { createSpecWithHostnameTemplate("service", "{{.Service.Name}}-{{.Task.Slot}}").Task, } { err := validateTaskSpec(good) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -375,7 +375,7 @@ func TestValidateContainerSpec(t *testing.T) { }, } { err := validateContainerSpec(bad.spec) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, bad.c, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -409,7 +409,7 @@ func TestValidateContainerSpec(t *testing.T) { for _, good := range []api.TaskSpec{good1} { err := validateContainerSpec(good) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -446,7 +446,7 @@ func TestValidateServiceSpec(t *testing.T) { }, } { err := validateServiceSpec(bad.spec) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, bad.c, testutils.ErrorCode(err), testutils.ErrorDesc(err)) } @@ -454,7 +454,7 @@ func TestValidateServiceSpec(t *testing.T) { createSpec("name", "image", 1), } { err := validateServiceSpec(good) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -465,7 +465,7 @@ func TestValidateServiceSpecJobsDifference(t *testing.T) { // correctly formed spec should be valid cannedSpec := createSpec("name", "image", 1) err := validateServiceSpec(cannedSpec) - assert.NoError(t, err) + require.NoError(t, err) // Replicated job should not be allowed to have update config specReplicatedJobUpdate := cannedSpec.Copy() @@ -474,12 +474,12 @@ func TestValidateServiceSpecJobsDifference(t *testing.T) { } specReplicatedJobUpdate.Update = &api.UpdateConfig{} err = validateServiceSpec(specReplicatedJobUpdate) - assert.Error(t, err) + require.Error(t, err) specReplicatedJobNoUpdate := specReplicatedJobUpdate.Copy() specReplicatedJobNoUpdate.Update = nil err = validateServiceSpec(specReplicatedJobNoUpdate) - assert.NoError(t, err) + require.NoError(t, err) // Global job should not be allowed to have update config specGlobalJobUpdate := cannedSpec.Copy() @@ -488,12 +488,12 @@ func TestValidateServiceSpecJobsDifference(t *testing.T) { } specGlobalJobUpdate.Update = &api.UpdateConfig{} err = validateServiceSpec(specGlobalJobUpdate) - assert.Error(t, err) + require.Error(t, err) specGlobalJobNoUpdate := specGlobalJobUpdate.Copy() specGlobalJobNoUpdate.Update = nil err = validateServiceSpec(specReplicatedJobNoUpdate) - assert.NoError(t, err) + require.NoError(t, err) // Replicated service should be allowed to have update config, which should // be verified for correctness @@ -502,12 +502,12 @@ func TestValidateServiceSpecJobsDifference(t *testing.T) { Delay: -1 * time.Second, } err = validateServiceSpec(replicatedServiceBrokenUpdate) - assert.Error(t, err) + require.Error(t, err) replicatedServiceCorrectUpdate := replicatedServiceBrokenUpdate.Copy() replicatedServiceCorrectUpdate.Update.Delay = time.Second err = validateServiceSpec(replicatedServiceCorrectUpdate) - assert.NoError(t, err) + require.NoError(t, err) // Global service should be allowed to have update config, which should be // verified for correctness @@ -516,7 +516,7 @@ func TestValidateServiceSpecJobsDifference(t *testing.T) { Global: &api.GlobalService{}, } err = validateServiceSpec(globalServiceBrokenUpdate) - assert.Error(t, err) + require.Error(t, err) globalServiceCorrectUpdate := globalServiceBrokenUpdate.Copy() globalServiceCorrectUpdate.Update.Delay = time.Second @@ -544,12 +544,12 @@ func TestValidateRestartPolicy(t *testing.T) { for _, b := range bad { err := validateRestartPolicy(b) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } for _, g := range good { - assert.NoError(t, validateRestartPolicy(g)) + require.NoError(t, validateRestartPolicy(g)) } } @@ -571,12 +571,12 @@ func TestValidateUpdate(t *testing.T) { for _, b := range bad { err := validateUpdate(b) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } for _, g := range good { - assert.NoError(t, validateUpdate(g)) + require.NoError(t, validateUpdate(g)) } } @@ -584,12 +584,12 @@ func TestCreateService(t *testing.T) { ts := newTestServer(t) defer ts.Stop() _, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) spec := createSpec("name", "image", 1) r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Service.ID) // test port conflicts @@ -598,7 +598,7 @@ func TestCreateService(t *testing.T) { {PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Service.ID) spec2 := createSpec("name3", "image", 1) @@ -606,7 +606,7 @@ func TestCreateService(t *testing.T) { {PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) // test no port conflicts when no publish port is specified @@ -615,14 +615,14 @@ func TestCreateService(t *testing.T) { {TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec3}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Service.ID) spec4 := createSpec("name5", "image", 1) spec4.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{ {TargetPort: uint32(9001), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec4}) - assert.NoError(t, err) + require.NoError(t, err) // ensure no port conflict when different protocols are used spec = createSpec("name6", "image", 1) @@ -630,7 +630,7 @@ func TestCreateService(t *testing.T) { {PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Service.ID) spec2 = createSpec("name7", "image", 1) @@ -638,7 +638,7 @@ func TestCreateService(t *testing.T) { {PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolUDP)}, }} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2}) - assert.NoError(t, err) + require.NoError(t, err) // ensure no port conflict when host ports overlap spec = createSpec("name8", "image", 1) @@ -646,7 +646,7 @@ func TestCreateService(t *testing.T) { {PublishMode: api.PublishModeHost, PublishedPort: uint32(9101), TargetPort: uint32(9101), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Service.ID) spec2 = createSpec("name9", "image", 1) @@ -654,7 +654,7 @@ func TestCreateService(t *testing.T) { {PublishMode: api.PublishModeHost, PublishedPort: uint32(9101), TargetPort: uint32(9101), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2}) - assert.NoError(t, err) + require.NoError(t, err) // ensure port conflict when host ports overlaps with ingress port (host port first) spec = createSpec("name10", "image", 1) @@ -662,7 +662,7 @@ func TestCreateService(t *testing.T) { {PublishMode: api.PublishModeHost, PublishedPort: uint32(9102), TargetPort: uint32(9102), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Service.ID) spec2 = createSpec("name11", "image", 1) @@ -670,7 +670,7 @@ func TestCreateService(t *testing.T) { {PublishMode: api.PublishModeIngress, PublishedPort: uint32(9102), TargetPort: uint32(9102), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) // ensure port conflict when host ports overlaps with ingress port (ingress port first) @@ -679,7 +679,7 @@ func TestCreateService(t *testing.T) { {PublishMode: api.PublishModeIngress, PublishedPort: uint32(9103), TargetPort: uint32(9103), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Service.ID) spec2 = createSpec("name13", "image", 1) @@ -687,22 +687,22 @@ func TestCreateService(t *testing.T) { {PublishMode: api.PublishModeHost, PublishedPort: uint32(9103), TargetPort: uint32(9103), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) // ingress network cannot be attached explicitly spec = createSpec("name14", "image", 1) spec.Task.Networks = []*api.NetworkAttachmentConfig{{Target: getIngressTargetID(t, ts)}} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) spec = createSpec("notunique", "image", 1) _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.AlreadyExists, testutils.ErrorCode(err)) // Make sure the error contains "name conflicts with an existing object" for @@ -754,7 +754,7 @@ func TestSecretValidation(t *testing.T) { serviceSpec = createServiceSpecWithSecrets("service4", secretRef2, secretRef5) _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: serviceSpec}) - assert.NoError(t, err) + require.NoError(t, err) // test secret References with invalid filenames secretRefBlank := createSecret(t, ts, "", "") @@ -773,7 +773,7 @@ func TestSecretValidation(t *testing.T) { serviceSpec = createServiceSpecWithSecrets(fmt.Sprintf("valid%v", i), secretRef) _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: serviceSpec}) - assert.NoError(t, err) + require.NoError(t, err) } // test secret target conflicts on update @@ -782,7 +782,7 @@ func TestSecretValidation(t *testing.T) { serviceSpec2 := serviceSpec1.Copy() serviceSpec2.Task.GetContainer().Secrets = nil rs, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: serviceSpec2}) - assert.NoError(t, err) + require.NoError(t, err) // Attempt to update to the originally intended (conflicting) spec _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ @@ -837,7 +837,7 @@ func TestConfigValidation(t *testing.T) { serviceSpec = createServiceSpecWithConfigs("service4", configRef2, configRef5) _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: serviceSpec}) - assert.NoError(t, err) + require.NoError(t, err) // Test config References with valid filenames // TODO(aaronl): Should some of these be disallowed? How can we deal @@ -848,7 +848,7 @@ func TestConfigValidation(t *testing.T) { serviceSpec = createServiceSpecWithConfigs(fmt.Sprintf("valid%v", i), configRef) _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: serviceSpec}) - assert.NoError(t, err) + require.NoError(t, err) } // test config references with RuntimeTarget @@ -867,7 +867,7 @@ func TestConfigValidation(t *testing.T) { _, err = ts.Client.CreateService( context.Background(), &api.CreateServiceRequest{Spec: serviceSpec}, ) - assert.NoError(t, err) + require.NoError(t, err) // test CredentialSpec without ConfigReference serviceSpec = createSpec("missingruntimetarget", "imagemissingruntimetarget", 1) @@ -882,7 +882,7 @@ func TestConfigValidation(t *testing.T) { context.Background(), &api.CreateServiceRequest{Spec: serviceSpec}, ) t.Logf("error when missing configreference: %v", err) - assert.Error(t, err) + require.Error(t, err) // test config target conflicts on update serviceSpec1 := createServiceSpecWithConfigs("service5", configRef2, configRef3) @@ -890,7 +890,7 @@ func TestConfigValidation(t *testing.T) { serviceSpec2 := serviceSpec1.Copy() serviceSpec2.Task.GetContainer().Configs = nil rs, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: serviceSpec2}) - assert.NoError(t, err) + require.NoError(t, err) // Attempt to update to the originally intended (conflicting) spec _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ @@ -905,16 +905,16 @@ func TestGetService(t *testing.T) { ts := newTestServer(t) defer ts.Stop() _, err := ts.Client.GetService(context.Background(), &api.GetServiceRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) _, err = ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: "invalid"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) service := createService(t, ts, "name", "image", 1) r, err := ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: service.ID}) - assert.NoError(t, err) + require.NoError(t, err) service.Meta.Version = r.Service.Meta.Version assert.Equal(t, service, r.Service) } @@ -925,27 +925,27 @@ func TestUpdateService(t *testing.T) { service := createService(t, ts, "name", "image", 1) _, err := ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ServiceID: "invalid", Spec: &service.Spec, ServiceVersion: &api.Version{}}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) // No update options. _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ServiceID: service.ID, Spec: &service.Spec}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ServiceID: service.ID, Spec: &service.Spec, ServiceVersion: &service.Meta.Version}) - assert.NoError(t, err) + require.NoError(t, err) r, err := ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: service.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, service.Spec.Annotations.Name, r.Service.Spec.Annotations.Name) mode, ok := r.Service.Spec.GetMode().(*api.ServiceSpec_Replicated) - assert.Equal(t, ok, true) - assert.True(t, mode.Replicated.Replicas == 1) + assert.True(t, ok) + assert.Equal(t, 1, mode.Replicated.Replicas) mode.Replicated.Replicas = 42 _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ @@ -953,18 +953,18 @@ func TestUpdateService(t *testing.T) { Spec: &r.Service.Spec, ServiceVersion: &r.Service.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) r, err = ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: service.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, service.Spec.Annotations.Name, r.Service.Spec.Annotations.Name) mode, ok = r.Service.Spec.GetMode().(*api.ServiceSpec_Replicated) - assert.Equal(t, ok, true) - assert.True(t, mode.Replicated.Replicas == 42) + assert.True(t, ok) + assert.Equal(t, 42, mode.Replicated.Replicas) // mode change not allowed r, err = ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: service.ID}) - assert.NoError(t, err) + require.NoError(t, err) r.Service.Spec.Mode = &api.ServiceSpec_Global{ Global: &api.GlobalService{}, } @@ -973,12 +973,12 @@ func TestUpdateService(t *testing.T) { Spec: &r.Service.Spec, ServiceVersion: &r.Service.Meta.Version, }) - assert.Error(t, err) - assert.True(t, strings.Contains(err.Error(), errModeChangeNotAllowed.Error())) + require.Error(t, err) + assert.Contains(t, err.Error(), errModeChangeNotAllowed.Error()) // Versioning. r, err = ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: service.ID}) - assert.NoError(t, err) + require.NoError(t, err) version := &r.Service.Meta.Version _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ @@ -986,7 +986,7 @@ func TestUpdateService(t *testing.T) { Spec: &r.Service.Spec, ServiceVersion: version, }) - assert.NoError(t, err) + require.NoError(t, err) // Perform an update with the "old" version. _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ @@ -994,7 +994,7 @@ func TestUpdateService(t *testing.T) { Spec: &r.Service.Spec, ServiceVersion: version, }) - assert.Error(t, err) + require.Error(t, err) // Attempt to update service name; renaming is not implemented r.Service.Spec.Annotations.Name = "newname" @@ -1003,7 +1003,7 @@ func TestUpdateService(t *testing.T) { Spec: &r.Service.Spec, ServiceVersion: version, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.Unimplemented, testutils.ErrorCode(err)) // test port conflicts @@ -1012,11 +1012,11 @@ func TestUpdateService(t *testing.T) { {PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, }} _, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2}) - assert.NoError(t, err) + require.NoError(t, err) spec3 := createSpec("name3", "image", 1) rs, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec3}) - assert.NoError(t, err) + require.NoError(t, err) spec3.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{ {PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, @@ -1026,7 +1026,7 @@ func TestUpdateService(t *testing.T) { Spec: spec3, ServiceVersion: &rs.Service.Meta.Version, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) spec3.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{ {PublishedPort: uint32(9001), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)}, @@ -1036,19 +1036,19 @@ func TestUpdateService(t *testing.T) { Spec: spec3, ServiceVersion: &rs.Service.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) // ingress network cannot be attached explicitly spec4 := createSpec("name4", "image", 1) rs, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec4}) - assert.NoError(t, err) + require.NoError(t, err) spec4.Task.Networks = []*api.NetworkAttachmentConfig{{Target: getIngressTargetID(t, ts)}} _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{ ServiceID: rs.Service.ID, Spec: spec4, ServiceVersion: &rs.Service.Meta.Version, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } @@ -1062,10 +1062,10 @@ func TestServiceUpdateRejectNetworkChange(t *testing.T) { }, } cr, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) ur, err := ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: cr.Service.ID}) - assert.NoError(t, err) + require.NoError(t, err) service := ur.Service service.Spec.Networks[0].Target = "net30" @@ -1075,8 +1075,8 @@ func TestServiceUpdateRejectNetworkChange(t *testing.T) { Spec: &service.Spec, ServiceVersion: &service.Meta.Version, }) - assert.Error(t, err) - assert.True(t, strings.Contains(err.Error(), errNetworkUpdateNotSupported.Error())) + require.Error(t, err) + assert.Contains(t, err.Error(), errNetworkUpdateNotSupported.Error()) // Changes to TaskSpec.Networks are allowed spec = createSpec("name2", "image", 1) @@ -1086,10 +1086,10 @@ func TestServiceUpdateRejectNetworkChange(t *testing.T) { }, } cr, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) ur, err = ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: cr.Service.ID}) - assert.NoError(t, err) + require.NoError(t, err) service = ur.Service service.Spec.Task.Networks[0].Target = "net30" @@ -1099,7 +1099,7 @@ func TestServiceUpdateRejectNetworkChange(t *testing.T) { Spec: &service.Spec, ServiceVersion: &service.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) // Migrate networks from ServiceSpec.Networks to TaskSpec.Networks spec = createSpec("name3", "image", 1) @@ -1109,10 +1109,10 @@ func TestServiceUpdateRejectNetworkChange(t *testing.T) { }, } cr, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) ur, err = ts.Client.GetService(context.Background(), &api.GetServiceRequest{ServiceID: cr.Service.ID}) - assert.NoError(t, err) + require.NoError(t, err) service = ur.Service service.Spec.Task.Networks = spec.Networks @@ -1123,19 +1123,19 @@ func TestServiceUpdateRejectNetworkChange(t *testing.T) { Spec: &service.Spec, ServiceVersion: &service.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) } func TestRemoveService(t *testing.T) { ts := newTestServer(t) defer ts.Stop() _, err := ts.Client.RemoveService(context.Background(), &api.RemoveServiceRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) service := createService(t, ts, "name", "image", 1) r, err := ts.Client.RemoveService(context.Background(), &api.RemoveServiceRequest{ServiceID: service.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, r) } @@ -1225,21 +1225,21 @@ func TestValidateEndpointSpec(t *testing.T) { } err := validateEndpointSpec(endPointSpec1) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) err = validateEndpointSpec(endPointSpec2) - assert.NoError(t, err) + require.NoError(t, err) err = validateEndpointSpec(endPointSpec3) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) err = validateEndpointSpec(endPointSpec4) - assert.NoError(t, err) + require.NoError(t, err) err = validateEndpointSpec(endPointSpec5) - assert.NoError(t, err) + require.NoError(t, err) } func TestServiceEndpointSpecUpdate(t *testing.T) { @@ -1273,7 +1273,7 @@ func TestServiceEndpointSpecUpdate(t *testing.T) { r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, r) // Update the service with duplicate ports @@ -1283,7 +1283,7 @@ func TestServiceEndpointSpecUpdate(t *testing.T) { }) _, err = ts.Client.UpdateService(context.Background(), &api.UpdateServiceRequest{Spec: spec}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } @@ -1291,21 +1291,21 @@ func TestListServices(t *testing.T) { ts := newTestServer(t) defer ts.Stop() r, err := ts.Client.ListServices(context.Background(), &api.ListServicesRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Services) s1 := createService(t, ts, "name1", "image", 1) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{}) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 1) createService(t, ts, "name2", "image", 1) s3 := createGenericService(t, ts, "name3", "my-runtime") // List all. r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{}) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 3) // List by runtime. r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ @@ -1313,16 +1313,16 @@ func TestListServices(t *testing.T) { Runtimes: []string{"container"}, }, }) - assert.NoError(t, err) - assert.Equal(t, 2, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 2) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ Filters: &api.ListServicesRequest_Filters{ Runtimes: []string{"my-runtime"}, }, }) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 1) assert.Equal(t, s3.ID, r.Services[0].ID) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ @@ -1330,7 +1330,7 @@ func TestListServices(t *testing.T) { Runtimes: []string{"invalid"}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Services) // List with an ID prefix. @@ -1339,8 +1339,8 @@ func TestListServices(t *testing.T) { IDPrefixes: []string{s1.ID[0:4]}, }, }) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 1) assert.Equal(t, s1.ID, r.Services[0].ID) // List with simple filter. @@ -1349,8 +1349,8 @@ func TestListServices(t *testing.T) { NamePrefixes: []string{"name1"}, }, }) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 1) // List with union filter. r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ @@ -1358,24 +1358,24 @@ func TestListServices(t *testing.T) { NamePrefixes: []string{"name1", "name2"}, }, }) - assert.NoError(t, err) - assert.Equal(t, 2, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 2) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ Filters: &api.ListServicesRequest_Filters{ NamePrefixes: []string{"name1", "name2", "name4"}, }, }) - assert.NoError(t, err) - assert.Equal(t, 2, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 2) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ Filters: &api.ListServicesRequest_Filters{ NamePrefixes: []string{"name4"}, }, }) - assert.NoError(t, err) - assert.Equal(t, 0, len(r.Services)) + require.NoError(t, err) + assert.Empty(t, r.Services) // List with filter intersection. r, err = ts.Client.ListServices(context.Background(), @@ -1386,8 +1386,8 @@ func TestListServices(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 1) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ @@ -1397,8 +1397,8 @@ func TestListServices(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 0, len(r.Services)) + require.NoError(t, err) + assert.Empty(t, r.Services) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ @@ -1408,8 +1408,8 @@ func TestListServices(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 1) // List filter by label. r, err = ts.Client.ListServices(context.Background(), @@ -1421,8 +1421,8 @@ func TestListServices(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 3) // Value-less label. r, err = ts.Client.ListServices(context.Background(), @@ -1434,8 +1434,8 @@ func TestListServices(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 3) // Label intersection. r, err = ts.Client.ListServices(context.Background(), @@ -1448,8 +1448,8 @@ func TestListServices(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Services)) + require.NoError(t, err) + assert.Len(t, r.Services, 1) r, err = ts.Client.ListServices(context.Background(), &api.ListServicesRequest{ @@ -1461,8 +1461,8 @@ func TestListServices(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 0, len(r.Services)) + require.NoError(t, err) + assert.Empty(t, r.Services) } func TestListServiceStatuses(t *testing.T) { @@ -1474,7 +1474,7 @@ func TestListServiceStatuses(t *testing.T) { context.Background(), &api.ListServiceStatusesRequest{}, ) - assert.NoError(t, err, "error when listing no services against an empty store") + require.NoError(t, err, "error when listing no services against an empty store") assert.NotNil(t, r, "response against an empty store was nil") assert.Empty(t, r.Statuses, "response statuses was not empty") @@ -1484,12 +1484,11 @@ func TestListServiceStatuses(t *testing.T) { context.Background(), &api.ListServiceStatusesRequest{Services: []string{"foo"}}, ) - assert.NoError(t, err, "error listing services that do not exist") + require.NoError(t, err, "error listing services that do not exist") assert.NotNil(t, r, "response for nonexistant services was nil") assert.Len(t, r.Statuses, 1, "expected 1 status") assert.Equal( - t, r.Statuses[0], - &api.ListServiceStatusesResponse_ServiceStatus{ServiceID: "foo"}, + t, &api.ListServiceStatusesResponse_ServiceStatus{ServiceID: "foo"}, r.Statuses[0], ) // now test that listing service statuses actually works. @@ -1506,7 +1505,7 @@ func TestListServiceStatuses(t *testing.T) { svcResp, svcErr := ts.Client.CreateService( context.Background(), &api.CreateServiceRequest{Spec: globalSpec}, ) - assert.NoError(t, svcErr) + require.NoError(t, svcErr) // global will have the right number of tasks global := svcResp.Service @@ -1517,7 +1516,7 @@ func TestListServiceStatuses(t *testing.T) { svcResp, svcErr = ts.Client.CreateService( context.Background(), &api.CreateServiceRequest{Spec: global2Spec}, ) - assert.NoError(t, svcErr) + require.NoError(t, svcErr) // global2 will not have enough tasks global2 := svcResp.Service @@ -1537,7 +1536,7 @@ func TestListServiceStatuses(t *testing.T) { svcResp, svcErr = ts.Client.CreateService( context.Background(), &api.CreateServiceRequest{Spec: replicatedJob1Spec}, ) - assert.NoError(t, svcErr) + require.NoError(t, svcErr) assert.NotNil(t, svcResp) replicatedJob1 := svcResp.Service @@ -1548,7 +1547,7 @@ func TestListServiceStatuses(t *testing.T) { svcResp, svcErr = ts.Client.CreateService( context.Background(), &api.CreateServiceRequest{Spec: replicatedJob2Spec}, ) - assert.NoError(t, svcErr) + require.NoError(t, svcErr) assert.NotNil(t, svcResp) replicatedJob2 := svcResp.Service @@ -1560,7 +1559,7 @@ func TestListServiceStatuses(t *testing.T) { svcResp, svcErr = ts.Client.CreateService( context.Background(), &api.CreateServiceRequest{Spec: globalJobSpec}, ) - assert.NoError(t, svcErr) + require.NoError(t, svcErr) assert.NotNil(t, svcResp) globalJob := svcResp.Service @@ -1583,7 +1582,7 @@ func TestListServiceStatuses(t *testing.T) { err := ts.Store.Update(func(tx store.Tx) error { return store.CreateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) return task } @@ -1674,7 +1673,7 @@ func TestListServiceStatuses(t *testing.T) { Spec: replicatedJob2Spec, }, ) - assert.NoError(t, updateErr) + require.NoError(t, updateErr) assert.NotNil(t, updateResp) replicatedJob2 = updateResp.Service @@ -1715,7 +1714,7 @@ func TestListServiceStatuses(t *testing.T) { replicatedJob1.ID, replicatedJob2.ID, globalJob.ID, over.ID, gone.ID, }}, ) - assert.NoError(t, err, "error getting service statuses") + require.NoError(t, err, "error getting service statuses") assert.NotNil(t, r, "service status response is nil") assert.Len(t, r.Statuses, 9) @@ -1786,9 +1785,7 @@ func TestListServiceStatuses(t *testing.T) { break } } - if !found { - t.Errorf("did not find status for %v in response", name) - } + assert.Truef(t, found, "did not find status for %v in response", name) } } @@ -1837,14 +1834,14 @@ func TestJobService(t *testing.T) { require.NotNil(t, resp.Service.JobStatus, "expected JobStatus to not be nil") // and ensure that JobStatus.JobIteration is set to 0, which is the default require.Equal( - t, resp.Service.JobStatus.JobIteration.Index, uint64(0), + t, uint64(0), resp.Service.JobStatus.JobIteration.Index, "expected JobIteration for new replicated job to be 0", ) require.NotNil(t, resp.Service.JobStatus.LastExecution) - assert.True(t, resp.Service.JobStatus.LastExecution.Compare(before) >= 0, + assert.GreaterOrEqual(t, resp.Service.JobStatus.LastExecution.Compare(before), 0, "expected %v to be after %v", resp.Service.JobStatus.LastExecution, before, ) - assert.True(t, resp.Service.JobStatus.LastExecution.Compare(after) <= 0, + assert.LessOrEqual(t, resp.Service.JobStatus.LastExecution.Compare(after), 0, "expected %v to be before %v", resp.Service.JobStatus.LastExecution, after, ) @@ -1867,14 +1864,14 @@ func TestJobService(t *testing.T) { require.NotNil(t, gresp.Service) require.NotNil(t, gresp.Service.JobStatus) require.Equal( - t, gresp.Service.JobStatus.JobIteration.Index, uint64(0), + t, uint64(0), gresp.Service.JobStatus.JobIteration.Index, "expected JobIteration for new global job to be 0", ) require.NotNil(t, gresp.Service.JobStatus.LastExecution) - assert.True(t, gresp.Service.JobStatus.LastExecution.Compare(before) >= 0, + assert.GreaterOrEqual(t, gresp.Service.JobStatus.LastExecution.Compare(before), 0, "expected %v to be after %v", gresp.Service.JobStatus.LastExecution, before, ) - assert.True(t, gresp.Service.JobStatus.LastExecution.Compare(after) <= 0, + assert.LessOrEqual(t, gresp.Service.JobStatus.LastExecution.Compare(after), 0, "expected %v to be before %v", gresp.Service.JobStatus.LastExecution, after, ) @@ -1896,14 +1893,14 @@ func TestJobService(t *testing.T) { require.NotNil(t, uresp.Service.JobStatus) // updating the service should bump the JobStatus.JobIteration.Index by 1 require.Equal( - t, uresp.Service.JobStatus.JobIteration.Index, uint64(1), + t, uint64(1), uresp.Service.JobStatus.JobIteration.Index, "expected JobIteration for updated replicated job to be 1", ) require.NotNil(t, uresp.Service.JobStatus.LastExecution) - assert.True(t, uresp.Service.JobStatus.LastExecution.Compare(before) >= 0, + assert.GreaterOrEqual(t, uresp.Service.JobStatus.LastExecution.Compare(before), 0, "expected %v to be after %v", uresp.Service.JobStatus.LastExecution, before, ) - assert.True(t, uresp.Service.JobStatus.LastExecution.Compare(after) <= 0, + assert.LessOrEqual(t, uresp.Service.JobStatus.LastExecution.Compare(after), 0, "expected %v to be before %v", uresp.Service.JobStatus.LastExecution, after, ) @@ -1924,14 +1921,14 @@ func TestJobService(t *testing.T) { require.NotNil(t, guresp.Service) require.NotNil(t, guresp.Service.JobStatus) require.Equal( - t, guresp.Service.JobStatus.JobIteration.Index, uint64(1), + t, uint64(1), guresp.Service.JobStatus.JobIteration.Index, "expected JobIteration for updated replicated job to be 1", ) require.NotNil(t, guresp.Service.JobStatus.LastExecution) - assert.True(t, guresp.Service.JobStatus.LastExecution.Compare(before) >= 0, + assert.GreaterOrEqual(t, guresp.Service.JobStatus.LastExecution.Compare(before), 0, "expected %v to be after %v", guresp.Service.JobStatus.LastExecution, before, ) - assert.True(t, guresp.Service.JobStatus.LastExecution.Compare(after) <= 0, + assert.LessOrEqual(t, guresp.Service.JobStatus.LastExecution.Compare(after), 0, "expected %v to be before %v", guresp.Service.JobStatus.LastExecution, after, ) } @@ -1946,7 +1943,7 @@ func TestServiceValidateJob(t *testing.T) { } err := validateJob(bad) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) good := []*api.ServiceSpec{ @@ -1962,6 +1959,6 @@ func TestServiceValidateJob(t *testing.T) { for _, g := range good { err := validateJob(g) - assert.NoError(t, err) + require.NoError(t, err) } } diff --git a/manager/controlapi/task_test.go b/manager/controlapi/task_test.go index 894b533d26..a335a47a5e 100644 --- a/manager/controlapi/task_test.go +++ b/manager/controlapi/task_test.go @@ -12,6 +12,7 @@ import ( "github.com/moby/swarmkit/v2/identity" "github.com/moby/swarmkit/v2/manager/state/store" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createTask(t *testing.T, ts *testServer, desiredState api.TaskState) *api.Task { @@ -27,7 +28,7 @@ func createTask(t *testing.T, ts *testServer, desiredState api.TaskState) *api.T err := ts.Store.Update(func(tx store.Tx) error { return store.CreateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) return task } @@ -36,16 +37,16 @@ func TestGetTask(t *testing.T) { defer ts.Stop() _, err := ts.Client.GetTask(context.Background(), &api.GetTaskRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) _, err = ts.Client.GetTask(context.Background(), &api.GetTaskRequest{TaskID: "invalid"}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) task := createTask(t, ts, api.TaskStateRunning) r, err := ts.Client.GetTask(context.Background(), &api.GetTaskRequest{TaskID: task.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, task.ID, r.Task.ID) } @@ -57,19 +58,19 @@ func TestListTasks(t *testing.T) { ts := newTestServer(t) defer ts.Stop() r, err := ts.Client.ListTasks(context.Background(), &api.ListTasksRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, r.Tasks) t1 := createTask(t, ts, api.TaskStateRunning) r, err = ts.Client.ListTasks(context.Background(), &api.ListTasksRequest{}) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Tasks)) + require.NoError(t, err) + assert.Len(t, r.Tasks, 1) createTask(t, ts, api.TaskStateRunning) createTask(t, ts, api.TaskStateShutdown) r, err = ts.Client.ListTasks(context.Background(), &api.ListTasksRequest{}) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Tasks)) + require.NoError(t, err) + assert.Len(t, r.Tasks, 3) // List with an ID prefix. r, err = ts.Client.ListTasks(context.Background(), &api.ListTasksRequest{ @@ -77,7 +78,7 @@ func TestListTasks(t *testing.T) { IDPrefixes: []string{t1.ID[0:4]}, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, r.Tasks) for _, task := range r.Tasks { assert.True(t, strings.HasPrefix(task.ID, t1.ID[0:4])) @@ -91,8 +92,8 @@ func TestListTasks(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 2, len(r.Tasks)) + require.NoError(t, err) + assert.Len(t, r.Tasks, 2) r, err = ts.Client.ListTasks(context.Background(), &api.ListTasksRequest{ Filters: &api.ListTasksRequest_Filters{ @@ -100,8 +101,8 @@ func TestListTasks(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 1, len(r.Tasks)) + require.NoError(t, err) + assert.Len(t, r.Tasks, 1) r, err = ts.Client.ListTasks(context.Background(), &api.ListTasksRequest{ Filters: &api.ListTasksRequest_Filters{ @@ -109,6 +110,6 @@ func TestListTasks(t *testing.T) { }, }, ) - assert.NoError(t, err) - assert.Equal(t, 3, len(r.Tasks)) + require.NoError(t, err) + assert.Len(t, r.Tasks, 3) } diff --git a/manager/controlapi/volume_test.go b/manager/controlapi/volume_test.go index 6c897e9513..1e72288e24 100644 --- a/manager/controlapi/volume_test.go +++ b/manager/controlapi/volume_test.go @@ -46,7 +46,7 @@ func TestCreateVolumeEmptyRequest(t *testing.T) { defer ts.Stop() _, err := ts.Client.CreateVolume(context.Background(), &api.CreateVolumeRequest{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } @@ -62,7 +62,7 @@ func TestCreateVolumeNoName(t *testing.T) { Spec: &v.Spec, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) assert.Contains(t, err.Error(), "name") } @@ -79,7 +79,7 @@ func TestCreateVolumeNoDriver(t *testing.T) { Spec: &v.Spec, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) assert.Contains(t, err.Error(), "driver") } @@ -96,7 +96,7 @@ func TestCreateVolumeValid(t *testing.T) { Spec: &v.Spec, }) - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(t, resp) require.NotNil(t, resp.Volume, "volume in response should not be nil") assert.NotEmpty(t, resp.Volume.ID, "volume ID should not be empty") @@ -150,7 +150,7 @@ func TestCreateVolumeValidateSecrets(t *testing.T) { _, err := ts.Client.CreateVolume(context.Background(), &api.CreateVolumeRequest{ Spec: &v.Spec, }) - assert.Error(t, err, "expected creating a volume when a secret doesn't exist to fail") + require.Error(t, err, "expected creating a volume when a secret doesn't exist to fail") assert.Contains(t, err.Error(), "secret") assert.Contains(t, err.Error(), "someIDnotReal") assert.Contains(t, err.Error(), "someOtherNotRealID") @@ -165,7 +165,7 @@ func TestCreateVolumeValidateSecrets(t *testing.T) { _, err = ts.Client.CreateVolume(context.Background(), &api.CreateVolumeRequest{ Spec: &v.Spec, }) - assert.NoError(t, err) + require.NoError(t, err) } // TestCreateVolumeInvalidAccessMode tests that CreateVolume enforces the @@ -181,7 +181,7 @@ func TestCreateVolumeInvalidAccessMode(t *testing.T) { _, err := ts.Client.CreateVolume(context.Background(), &api.CreateVolumeRequest{ Spec: &volume.Spec, }) - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), "AccessMode must not be nil") volume.Spec.AccessMode = &api.VolumeAccessMode{} @@ -189,7 +189,7 @@ func TestCreateVolumeInvalidAccessMode(t *testing.T) { _, err = ts.Client.CreateVolume(context.Background(), &api.CreateVolumeRequest{ Spec: &volume.Spec, }) - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), "either Mount or Block") } @@ -205,7 +205,7 @@ func TestUpdateVolume(t *testing.T) { err := ts.Store.Update(func(tx store.Tx) error { return store.CreateVolume(tx, volume) }) - assert.NoError(t, err, "creating volume in store returned an error") + require.NoError(t, err, "creating volume in store returned an error") // we need to read the volume back out so we can get the current version // just reuse the volume variable and store the latest copy in it. @@ -225,7 +225,7 @@ func TestUpdateVolume(t *testing.T) { Spec: spec, }) - assert.NoError(t, err, "expected updating volume to return no error") + require.NoError(t, err, "expected updating volume to return no error") require.NotNil(t, resp, "response was nil") require.NotNil(t, resp.Volume, "response.Volume was nil") require.Equal(t, resp.Volume.ID, volume.ID) @@ -251,7 +251,7 @@ func TestUpdateVolumeMissingRequestComponents(t *testing.T) { Spec: &cannedVolume.Spec, VolumeVersion: &api.Version{}, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) assert.Contains(t, err.Error(), "ID") @@ -260,7 +260,7 @@ func TestUpdateVolumeMissingRequestComponents(t *testing.T) { VolumeID: cannedVolume.ID, VolumeVersion: &api.Version{}, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) assert.Contains(t, err.Error(), "Spec") @@ -269,7 +269,7 @@ func TestUpdateVolumeMissingRequestComponents(t *testing.T) { VolumeID: cannedVolume.ID, Spec: &cannedVolume.Spec, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) assert.Contains(t, err.Error(), "VolumeVersion") } @@ -286,7 +286,7 @@ func TestUpdateVolumeNotFound(t *testing.T) { VolumeVersion: &api.Version{}, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.NotFound, testutils.ErrorCode(err)) } @@ -303,7 +303,7 @@ func TestUpdateVolumeOutOfSequence(t *testing.T) { err := ts.Store.Update(func(tx store.Tx) error { return store.CreateVolume(tx, volume) }) - assert.NoError(t, err, "creating volume in store returned an error") + require.NoError(t, err, "creating volume in store returned an error") spec := volume.Spec.Copy() spec.Annotations.Labels = map[string]string{"foo": "bar"} @@ -394,7 +394,7 @@ func TestUpdateVolumeInvalidFields(t *testing.T) { err := ts.Store.Update(func(tx store.Tx) error { return store.CreateVolume(tx, volume) }) - assert.NoError(t, err, "creating volume in store returned an error") + require.NoError(t, err, "creating volume in store returned an error") // we need to read the volume back out so we can get the current version // just reuse the volume variable and store the latest copy in it. @@ -427,12 +427,12 @@ func TestGetVolume(t *testing.T) { err := ts.Store.Update(func(tx store.Tx) error { return store.CreateVolume(tx, volume) }) - assert.NoError(t, err) + require.NoError(t, err) resp, err := ts.Client.GetVolume(context.Background(), &api.GetVolumeRequest{ VolumeID: volume.ID, }) - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(t, resp) require.NotNil(t, resp.Volume) require.Equal(t, resp.Volume, volume) @@ -541,7 +541,7 @@ func TestListVolumesByGroup(t *testing.T) { return nil }) - assert.NoError(t, err) + require.NoError(t, err) for _, tc := range []struct { name string @@ -623,7 +623,7 @@ func TestListVolumesByGroup(t *testing.T) { resp, err := ts.Client.ListVolumes(context.Background(), &api.ListVolumesRequest{ Filters: tc.filters, }) - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(t, resp) assert.ElementsMatch(t, resp.Volumes, tc.expected) }) @@ -644,7 +644,7 @@ func TestRemoveVolume(t *testing.T) { VolumeID: cannedVolume.ID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) var v *api.Volume @@ -676,7 +676,7 @@ func TestRemoveVolumeCreatedButNotInUse(t *testing.T) { VolumeID: volume.ID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resp) var v *api.Volume @@ -711,7 +711,7 @@ func TestRemoveVolumeInUse(t *testing.T) { VolumeID: volume.ID, }) - assert.Error(t, err) + require.Error(t, err) assert.Equal( t, codes.FailedPrecondition, testutils.ErrorCode(err), "expected code FailedPrecondition", @@ -735,7 +735,7 @@ func TestRemoveVolumeNotFound(t *testing.T) { VolumeID: "notReal", }) - assert.Error(t, err) + require.Error(t, err) assert.Equal( t, codes.NotFound, testutils.ErrorCode(err), "expected code NotFound", @@ -767,7 +767,7 @@ func TestRemoveVolumeForce(t *testing.T) { Force: true, }) - assert.NoError(t, err) + require.NoError(t, err) ts.Store.View(func(tx store.ReadTx) { v := store.GetVolume(tx, volume.ID) diff --git a/manager/deallocator/deallocator_test.go b/manager/deallocator/deallocator_test.go index a2ed082f72..12cd9ef454 100644 --- a/manager/deallocator/deallocator_test.go +++ b/manager/deallocator/deallocator_test.go @@ -312,9 +312,7 @@ func stopDeallocator(t *testing.T, deallocator *Deallocator, ran chan error) { func waitForDeallocatorEvent(t *testing.T, deallocator *Deallocator, expectedUpdates bool) { select { case updates := <-deallocator.eventChan: - if updates != expectedUpdates { - t.Errorf("Expected updates %v VS actual %v", expectedUpdates, updates) - } + assert.Equalf(t, expectedUpdates, updates, "Expected updates %v VS actual %v", expectedUpdates, updates) ensureNoDeallocatorEvent(t, deallocator) case <-time.After(time.Second): t.Fatal("Waited for too long for the deallocator to process new events") diff --git a/manager/dirty_test.go b/manager/dirty_test.go index a8894d530a..e694f07ce9 100644 --- a/manager/dirty_test.go +++ b/manager/dirty_test.go @@ -18,9 +18,9 @@ func TestIsStateDirty(t *testing.T) { ctx := context.Background() temp, err := os.CreateTemp("", "test-socket") - assert.NoError(t, err) - assert.NoError(t, temp.Close()) - assert.NoError(t, os.Remove(temp.Name())) + require.NoError(t, err) + require.NoError(t, temp.Close()) + require.NoError(t, os.Remove(temp.Name())) defer os.RemoveAll(temp.Name()) @@ -30,7 +30,7 @@ func TestIsStateDirty(t *testing.T) { defer tc.Stop() managerSecurityConfig, err := tc.NewNodeConfig(ca.ManagerRole) - assert.NoError(t, err) + require.NoError(t, err) stateDir := t.TempDir() m, err := New(&Config{ @@ -42,7 +42,7 @@ func TestIsStateDirty(t *testing.T) { UnlockKey: []byte("kek"), RootCAPaths: tc.Paths.RootCA, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, m) go m.Run(ctx) @@ -50,7 +50,7 @@ func TestIsStateDirty(t *testing.T) { // State should never be dirty just after creating the manager isDirty, err := m.IsStateDirty() - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isDirty) // Wait for cluster and node to be created. @@ -60,21 +60,21 @@ func TestIsStateDirty(t *testing.T) { <-watch // Updating the node should not cause the state to become dirty - assert.NoError(t, m.raftNode.MemoryStore().Update(func(tx store.Tx) error { + require.NoError(t, m.raftNode.MemoryStore().Update(func(tx store.Tx) error { node := store.GetNode(tx, m.config.SecurityConfig.ClientTLSCreds.NodeID()) require.NotNil(t, node) node.Spec.Availability = api.NodeAvailabilityPause return store.UpdateNode(tx, node) })) isDirty, err = m.IsStateDirty() - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isDirty) // Adding a service should cause the state to become dirty - assert.NoError(t, m.raftNode.MemoryStore().Update(func(tx store.Tx) error { + require.NoError(t, m.raftNode.MemoryStore().Update(func(tx store.Tx) error { return store.CreateService(tx, &api.Service{ID: "foo"}) })) isDirty, err = m.IsStateDirty() - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isDirty) } diff --git a/manager/dispatcher/assignments_test.go b/manager/dispatcher/assignments_test.go index 7b65a0b7db..421fc755f9 100644 --- a/manager/dispatcher/assignments_test.go +++ b/manager/dispatcher/assignments_test.go @@ -104,7 +104,7 @@ func TestAssignVolume(t *testing.T) { m := as.message() // the Volume will not yet be assigned, because it is not ready. - assert.Len(t, m.Changes, 0) + assert.Empty(t, m.Changes) var ( nv *api.Volume @@ -138,8 +138,8 @@ func TestAssignVolume(t *testing.T) { var foundSecret1, foundSecret2 bool for _, change := range m.Changes { if vol, ok := change.Assignment.Item.(*api.Assignment_Volume); ok { - assert.Equal(t, change.Action, api.AssignmentChange_AssignmentActionUpdate) - assert.Equal(t, vol.Volume, &api.VolumeAssignment{ + assert.Equal(t, api.AssignmentChange_AssignmentActionUpdate, change.Action) + assert.Equal(t, &api.VolumeAssignment{ ID: "volume1", VolumeID: "volumeID1", Driver: &api.Driver{ @@ -151,7 +151,7 @@ func TestAssignVolume(t *testing.T) { {Key: "secretKey1", Secret: "secret1"}, {Key: "secretKey2", Secret: "secret2"}, }, - }) + }, vol.Volume) } else { secretAssignment := change.Assignment.Item.(*api.Assignment_Secret) // we don't need to test correctness of the assignment content, @@ -167,7 +167,7 @@ func TestAssignVolume(t *testing.T) { } // every one of these should be an Update change - assert.Equal(t, change.Action, api.AssignmentChange_AssignmentActionUpdate) + assert.Equal(t, api.AssignmentChange_AssignmentActionUpdate, change.Action) } assert.True(t, foundSecret1) @@ -194,10 +194,10 @@ func TestAssignVolume(t *testing.T) { m = as.message() assert.Len(t, m.Changes, 1) - assert.Equal(t, m.Changes[0].Action, api.AssignmentChange_AssignmentActionRemove) + assert.Equal(t, api.AssignmentChange_AssignmentActionRemove, m.Changes[0].Action) v, ok := m.Changes[0].Assignment.Item.(*api.Assignment_Volume) assert.True(t, ok) - assert.Equal(t, v.Volume, &api.VolumeAssignment{ + assert.Equal(t, &api.VolumeAssignment{ ID: "volume1", VolumeID: "volumeID1", Driver: &api.Driver{ @@ -209,7 +209,7 @@ func TestAssignVolume(t *testing.T) { {Key: "secretKey1", Secret: "secret1"}, {Key: "secretKey2", Secret: "secret2"}, }, - }) + }, v.Volume) // now update the volume again, this time, to acknowledge its removal on // the node. @@ -234,7 +234,7 @@ func TestAssignVolume(t *testing.T) { foundSecret2 = false for _, change := range m.Changes { - assert.Equal(t, change.Action, api.AssignmentChange_AssignmentActionRemove) + assert.Equal(t, api.AssignmentChange_AssignmentActionRemove, change.Action) s, ok := change.Assignment.Item.(*api.Assignment_Secret) assert.True(t, ok) switch s.Secret.ID { diff --git a/manager/dispatcher/dispatcher_test.go b/manager/dispatcher/dispatcher_test.go index b5e4311e07..7827e2e7c9 100644 --- a/manager/dispatcher/dispatcher_test.go +++ b/manager/dispatcher/dispatcher_test.go @@ -127,18 +127,18 @@ func startDispatcher(t *testing.T, c *Config) *grpcDispatcher { t.Helper() l, err := net.Listen("tcp", "127.0.0.1:0") - assert.NoError(t, err) + require.NoError(t, err) tca := cautils.NewTestCA(t) tca.CAServer.Stop() // there is no need for the CA server to be running agentSecurityConfig1, err := tca.NewNodeConfig(ca.WorkerRole) - assert.NoError(t, err) + require.NoError(t, err) agentSecurityConfig2, err := tca.NewNodeConfig(ca.WorkerRole) - assert.NoError(t, err) + require.NoError(t, err) managerSecurityConfig, err := tca.NewNodeConfig(ca.ManagerRole) - assert.NoError(t, err) + require.NoError(t, err) serverOpts := []grpc.ServerOption{grpc.Creds(managerSecurityConfig.ServerTLSCreds)} @@ -168,7 +168,7 @@ func startDispatcher(t *testing.T, c *Config) *grpcDispatcher { } return nil }, 5*time.Second) - assert.NoError(t, err) + require.NoError(t, err) clientOpts := []grpc.DialOption{grpc.WithTimeout(10 * time.Second)} clientOpts1 := append(clientOpts, grpc.WithTransportCredentials(agentSecurityConfig1.ClientTLSCreds)) @@ -176,13 +176,13 @@ func startDispatcher(t *testing.T, c *Config) *grpcDispatcher { clientOpts3 := append(clientOpts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) conn1, err := grpc.Dial(l.Addr().String(), clientOpts1...) - assert.NoError(t, err) + require.NoError(t, err) conn2, err := grpc.Dial(l.Addr().String(), clientOpts2...) - assert.NoError(t, err) + require.NoError(t, err) conn3, err := grpc.Dial(l.Addr().String(), clientOpts3...) - assert.NoError(t, err) + require.NoError(t, err) clients := []api.DispatcherClient{api.NewDispatcherClient(conn1), api.NewDispatcherClient(conn2), api.NewDispatcherClient(conn3)} securityConfigs := []*ca.SecurityConfig{agentSecurityConfig1, agentSecurityConfig2, managerSecurityConfig} @@ -209,21 +209,21 @@ func TestRegisterTwice(t *testing.T) { var expectedSessionID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) msg, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, msg.SessionID) expectedSessionID = msg.SessionID stream.CloseSend() } { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) msg, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // session should be different! - assert.NotEqual(t, msg.SessionID, expectedSessionID) + assert.NotEqual(t, expectedSessionID, msg.SessionID) stream.CloseSend() } } @@ -236,18 +236,18 @@ func TestRegisterExceedRateLimit(t *testing.T) { for i := 0; i < 3; i++ { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) msg, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, msg.SessionID) stream.CloseSend() } { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) defer stream.CloseSend() - assert.NoError(t, err) + require.NoError(t, err) _, err = stream.Recv() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, codes.Unavailable, testutils.ErrorCode(err), err.Error()) } } @@ -258,11 +258,11 @@ func TestRegisterNoCert(t *testing.T) { // This client has no certificates, this should fail stream, err := gd.Clients[2].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() assert.Nil(t, resp) - assert.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") + require.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") } func TestHeartbeat(t *testing.T) { @@ -275,11 +275,11 @@ func TestHeartbeat(t *testing.T) { var expectedSessionID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID } @@ -289,18 +289,18 @@ func TestHeartbeat(t *testing.T) { // heartbeat without correct SessionID should fail resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{}) assert.Nil(t, resp) - assert.Error(t, err) - assert.Equal(t, testutils.ErrorCode(err), codes.InvalidArgument) + require.Error(t, err) + assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotZero(t, resp.Period) time.Sleep(300 * time.Millisecond) gd.Store.View(func(readTx store.ReadTx) { storeNodes, err := store.FindNodes(readTx, store.All) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, storeNodes) found := false for _, node := range storeNodes { @@ -320,7 +320,7 @@ func TestHeartbeatNoCert(t *testing.T) { // heartbeat without correct SessionID should fail resp, err := gd.Clients[2].Heartbeat(context.Background(), &api.HeartbeatRequest{}) assert.Nil(t, resp) - assert.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") + require.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") } func TestHeartbeatTimeout(t *testing.T) { @@ -335,15 +335,15 @@ func TestHeartbeatTimeout(t *testing.T) { var expectedSessionID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID } - assert.NoError(t, testutils.PollFunc(nil, func() error { + require.NoError(t, testutils.PollFunc(nil, func() error { var storeNode *api.Node gd.Store.View(func(readTx store.ReadTx) { storeNode = store.GetNode(readTx, gd.SecurityConfigs[0].ClientTLSCreds.NodeID()) @@ -360,7 +360,7 @@ func TestHeartbeatTimeout(t *testing.T) { // check that node is deregistered resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{SessionID: expectedSessionID}) assert.Nil(t, resp) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, testutils.ErrorDesc(err), ErrNodeNotRegistered.Error()) } @@ -369,7 +369,7 @@ func TestHeartbeatUnregistered(t *testing.T) { defer gd.Close() resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{}) assert.Nil(t, resp) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, ErrSessionInvalid.Error(), testutils.ErrorDesc(err)) } @@ -382,14 +382,14 @@ func TestAssignmentsErrorsIfNoSessionID(t *testing.T) { // without correct SessionID should fail stream, err := gd.Clients[0].Assignments(context.Background(), &api.AssignmentsRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, stream) defer stream.CloseSend() resp, err := stream.Recv() assert.Nil(t, resp) - assert.Error(t, err) - assert.Equal(t, testutils.ErrorCode(err), codes.InvalidArgument) + require.Error(t, err) + assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } func TestAssignmentsSecretDriver(t *testing.T) { @@ -421,21 +421,21 @@ func TestAssignmentsSecretDriver(t *testing.T) { var mux MockPluginClient mux.HandleFunc(drivers.SecretsProviderAPI, func(body []byte) (interface{}, error) { var request drivers.SecretsProviderRequest - assert.NoError(t, json.Unmarshal(body, &request)) + require.NoError(t, json.Unmarshal(body, &request)) response := responses[request.SecretName] assert.Equal(t, serviceName, request.ServiceName) assert.Equal(t, serviceHostname, request.ServiceHostname) assert.Equal(t, int32(serviceEndpointMode), request.ServiceEndpointSpec.Mode) assert.Len(t, request.ServiceEndpointSpec.Ports, 1) - assert.EqualValues(t, portConfig, request.ServiceEndpointSpec.Ports[0]) - assert.EqualValues(t, serviceLabels, request.ServiceLabels) + assert.Equal(t, portConfig, request.ServiceEndpointSpec.Ports[0]) + assert.Equal(t, serviceLabels, request.ServiceLabels) assert.NotNil(t, response) return response, nil }) gd := startDispatcher(t, DefaultConfig()) defer gd.Close() - assert.NoError(t, gd.PluginGetter.SetupPlugin(secretDriver, &mux)) + require.NoError(t, gd.PluginGetter.SetupPlugin(secretDriver, &mux)) expectedSessionID, nodeID := getSessionAndNodeID(t, gd.Clients[0]) @@ -495,21 +495,21 @@ func TestAssignmentsSecretDriver(t *testing.T) { } err := gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateSecret(tx, secret)) - assert.NoError(t, store.CreateSecret(tx, doNotReuseSecret)) - assert.NoError(t, store.CreateSecret(tx, errSecret)) - assert.NoError(t, store.CreateConfig(tx, config)) - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateSecret(tx, secret)) + require.NoError(t, store.CreateSecret(tx, doNotReuseSecret)) + require.NoError(t, store.CreateSecret(tx, errSecret)) + require.NoError(t, store.CreateConfig(tx, config)) + require.NoError(t, store.CreateTask(tx, task)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) stream, err := gd.Clients[0].Assignments(context.Background(), &api.AssignmentsRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) _, _, secretChanges, _ := splitChanges(resp.Changes) assert.Len(t, secretChanges, 2) @@ -702,19 +702,19 @@ func TestAssignmentsWithVolume(t *testing.T) { return store.CreateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) stream, err := gd.Clients[0].Assignments( context.Background(), &api.AssignmentsRequest{SessionID: expectedSessionID}, ) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() time.Sleep(100 * time.Millisecond) resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) verifyChanges(t, resp.Changes, []changeExpectations{ { @@ -750,7 +750,7 @@ func TestAssignmentsWithVolume(t *testing.T) { }) // now update the volume to be published - assert.NoError(t, gd.Store.Update(func(tx store.Tx) error { + require.NoError(t, gd.Store.Update(func(tx store.Tx) error { v := store.GetVolume(tx, "volumeID0") v.PublishStatus[0].State = api.VolumePublishStatus_PUBLISHED v.PublishStatus[0].PublishContext = map[string]string{ @@ -762,15 +762,11 @@ func TestAssignmentsWithVolume(t *testing.T) { // now see if we get a volume assignment resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) _, _, _, volumeChanges := splitChanges(resp.Changes) assert.Len(t, volumeChanges, 1) assert.Equal(t, - volumeChanges[idAndAction{ - id: "volumeID0", - action: api.AssignmentChange_AssignmentActionUpdate, - }], &api.VolumeAssignment{ ID: "volumeID0", VolumeID: "csiID0", @@ -793,7 +789,10 @@ func TestAssignmentsWithVolume(t *testing.T) { Secret: "secret1", }, }, - }, + }, volumeChanges[idAndAction{ + id: "volumeID0", + action: api.AssignmentChange_AssignmentActionUpdate, + }], ) } @@ -823,32 +822,32 @@ func testAssignmentsInitialNodeTasksWithGivenTasks(t *testing.T, genTasks taskGe secrets, configs, resourceRefs, tasks := genTasks(t, nodeID) err := gd.Store.Update(func(tx store.Tx) error { for _, secret := range secrets { - assert.NoError(t, store.CreateSecret(tx, secret)) + require.NoError(t, store.CreateSecret(tx, secret)) } for _, config := range configs { - assert.NoError(t, store.CreateConfig(tx, config)) + require.NoError(t, store.CreateConfig(tx, config)) } // make dummy secrets and configs for resourceRefs for _, resourceRef := range resourceRefs { - assert.NoError(t, makeMockResource(tx, resourceRef)) + require.NoError(t, makeMockResource(tx, resourceRef)) } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) stream, err := gd.Clients[0].Assignments(context.Background(), &api.AssignmentsRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() time.Sleep(100 * time.Millisecond) // check the initial task and secret stream resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assignedToRunningTasks := filterTasks(tasks, func(s api.TaskState) bool { return s >= api.TaskStateAssigned && s <= api.TaskStateRunning @@ -877,15 +876,15 @@ func testAssignmentsInitialNodeTasksWithGivenTasks(t *testing.T, genTasks taskGe // updating all the tasks will attempt to remove all the secrets for the tasks that are in state > running err = gd.Store.Update(func(tx store.Tx) error { for _, task := range tasks { - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // dependencies for tasks > RUNNING are removed, but only if they are not currently being used // by a task >= ASSIGNED and <= RUNNING @@ -907,14 +906,14 @@ func testAssignmentsInitialNodeTasksWithGivenTasks(t *testing.T, genTasks taskGe // what state it's in err = gd.Store.Update(func(tx store.Tx) error { for _, task := range tasks { - assert.NoError(t, store.DeleteTask(tx, task.ID)) + require.NoError(t, store.DeleteTask(tx, task.ID)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // tasks >= ASSIGNED and their dependencies have all been removed; // task < ASSIGNED and their dependencies were never sent in the first place, so don't need to be removed @@ -1023,14 +1022,14 @@ func testAssignmentsAddingTasksWithGivenTasks(t *testing.T, genTasks taskGenerat expectedSessionID, nodeID := getSessionAndNodeID(t, gd.Clients[0]) stream, err := gd.Clients[0].Assignments(context.Background(), &api.AssignmentsRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() time.Sleep(100 * time.Millisecond) // There are no initial tasks or secrets resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, resp.Changes) // create the relevant secrets, configs, and tasks and update the tasks @@ -1046,39 +1045,39 @@ func testAssignmentsAddingTasksWithGivenTasks(t *testing.T, genTasks taskGenerat err = gd.Store.Update(func(tx store.Tx) error { for _, secret := range createdSecrets { if store.GetSecret(tx, secret.ID) == nil { - assert.NoError(t, store.CreateSecret(tx, secret)) + require.NoError(t, store.CreateSecret(tx, secret)) } } for _, config := range createdConfigs { if store.GetConfig(tx, config.ID) == nil { - assert.NoError(t, store.CreateConfig(tx, config)) + require.NoError(t, store.CreateConfig(tx, config)) } } // make dummy secrets and configs for resourceRefs for _, resourceRef := range resourceRefs { - assert.NoError(t, makeMockResource(tx, resourceRef)) + require.NoError(t, makeMockResource(tx, resourceRef)) } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Nothing happens until we update. Updating all the tasks will send updates for all the tasks >= ASSIGNED, // and secrets for all the tasks >= ASSIGNED and <= RUNNING. err = gd.Store.Update(func(tx store.Tx) error { for _, task := range tasks { - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assignedToRunningTasks := filterTasks(tasks, func(s api.TaskState) bool { return s >= api.TaskStateAssigned && s <= api.TaskStateRunning @@ -1107,15 +1106,15 @@ func testAssignmentsAddingTasksWithGivenTasks(t *testing.T, genTasks taskGenerat // what state it's in err = gd.Store.Update(func(tx store.Tx) error { for _, task := range tasks { - assert.NoError(t, store.DeleteTask(tx, task.ID)) + require.NoError(t, store.DeleteTask(tx, task.ID)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // tasks >= ASSIGNED and their dependencies have all been removed, even if they don't exist in the store; // task < ASSIGNED and their dependencies were never sent in the first place, so don't need to be removed @@ -1157,35 +1156,35 @@ func testAssignmentsDependencyUpdateAndDeletionWithGivenTasks(t *testing.T, genT err := gd.Store.Update(func(tx store.Tx) error { for _, secret := range secrets { if store.GetSecret(tx, secret.ID) == nil { - assert.NoError(t, store.CreateSecret(tx, secret)) + require.NoError(t, store.CreateSecret(tx, secret)) } } for _, config := range configs { if store.GetConfig(tx, config.ID) == nil { - assert.NoError(t, store.CreateConfig(tx, config)) + require.NoError(t, store.CreateConfig(tx, config)) } } // make dummy secrets and configs for resourceRefs for _, resourceRef := range resourceRefs { - assert.NoError(t, makeMockResource(tx, resourceRef)) + require.NoError(t, makeMockResource(tx, resourceRef)) } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) stream, err := gd.Clients[0].Assignments(context.Background(), &api.AssignmentsRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() time.Sleep(100 * time.Millisecond) // check the initial task and secret stream resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assignedToRunningTasks := filterTasks(tasks, func(s api.TaskState) bool { return s >= api.TaskStateAssigned && s <= api.TaskStateRunning @@ -1211,7 +1210,7 @@ func testAssignmentsDependencyUpdateAndDeletionWithGivenTasks(t *testing.T, genT // updating secrets and configs, used by tasks or not, do not cause any changes uniqueSecrets := uniquifySecrets(secrets) uniqueConfigs := uniquifyConfigs(configs) - assert.NoError(t, gd.Store.Update(func(tx store.Tx) error { + require.NoError(t, gd.Store.Update(func(tx store.Tx) error { for _, s := range uniqueSecrets { s.Spec.Data = []byte("new secret data") if err := store.UpdateSecret(tx, s); err != nil { @@ -1242,14 +1241,14 @@ func testAssignmentsDependencyUpdateAndDeletionWithGivenTasks(t *testing.T, genT // deleting secrets and configs, used by tasks or not, do not cause any changes err = gd.Store.Update(func(tx store.Tx) error { for _, secret := range uniqueSecrets { - assert.NoError(t, store.DeleteSecret(tx, secret.ID)) + require.NoError(t, store.DeleteSecret(tx, secret.ID)) } for _, config := range uniqueConfigs { - assert.NoError(t, store.DeleteConfig(tx, config.ID)) + require.NoError(t, store.DeleteConfig(tx, config.ID)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) select { case <-recvChan: @@ -1268,10 +1267,10 @@ func TestTasksStatusChange(t *testing.T) { var nodeID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID nodeID = resp.Node.ID @@ -1291,31 +1290,31 @@ func TestTasksStatusChange(t *testing.T) { } stream, err := gd.Clients[0].Assignments(context.Background(), &api.AssignmentsRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) time.Sleep(100 * time.Millisecond) resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // initially no tasks - assert.Equal(t, 0, len(resp.Changes)) + assert.Empty(t, resp.Changes) // Creating the tasks will not create an event for assignments err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, testTask1)) - assert.NoError(t, store.CreateTask(tx, testTask2)) + require.NoError(t, store.CreateTask(tx, testTask1)) + require.NoError(t, store.CreateTask(tx, testTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, testTask1)) - assert.NoError(t, store.UpdateTask(tx, testTask2)) + require.NoError(t, store.UpdateTask(tx, testTask1)) + require.NoError(t, store.UpdateTask(tx, testTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) verifyChanges(t, resp.Changes, []changeExpectations{ { @@ -1324,7 +1323,7 @@ func TestTasksStatusChange(t *testing.T) { }, }) - assert.NoError(t, gd.Store.Update(func(tx store.Tx) error { + require.NoError(t, gd.Store.Update(func(tx store.Tx) error { task := store.GetTask(tx, testTask1.ID) if task == nil { return errors.New("no task") @@ -1358,10 +1357,10 @@ func TestTasksBatch(t *testing.T) { var nodeID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID nodeID = resp.Node.ID @@ -1379,36 +1378,36 @@ func TestTasksBatch(t *testing.T) { } stream, err := gd.Clients[0].Assignments(context.Background(), &api.AssignmentsRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // initially no tasks - assert.Equal(t, 0, len(resp.Changes)) + assert.Empty(t, resp.Changes) // Create, Update and Delete tasks. err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, testTask1)) - assert.NoError(t, store.CreateTask(tx, testTask2)) + require.NoError(t, store.CreateTask(tx, testTask1)) + require.NoError(t, store.CreateTask(tx, testTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, testTask1)) - assert.NoError(t, store.UpdateTask(tx, testTask2)) + require.NoError(t, store.UpdateTask(tx, testTask1)) + require.NoError(t, store.UpdateTask(tx, testTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteTask(tx, testTask1.ID)) - assert.NoError(t, store.DeleteTask(tx, testTask2.ID)) + require.NoError(t, store.DeleteTask(tx, testTask1.ID)) + require.NoError(t, store.DeleteTask(tx, testTask2.ID)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // all tasks have been deleted verifyChanges(t, resp.Changes, []changeExpectations{ @@ -1424,11 +1423,11 @@ func TestTasksNoCert(t *testing.T) { defer gd.Close() stream, err := gd.Clients[2].Assignments(context.Background(), &api.AssignmentsRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, stream) resp, err := stream.Recv() assert.Nil(t, resp) - assert.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") + require.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") } func TestTaskUpdate(t *testing.T) { @@ -1441,10 +1440,10 @@ func TestTaskUpdate(t *testing.T) { ) { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID nodeID = resp.Node.ID @@ -1475,13 +1474,13 @@ func TestTaskUpdate(t *testing.T) { }, } err := gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, testTask1)) - assert.NoError(t, store.CreateTask(tx, testTask2)) - assert.NoError(t, store.CreateTask(tx, testTask3)) - assert.NoError(t, store.CreateTask(tx, testTask4)) + require.NoError(t, store.CreateTask(tx, testTask1)) + require.NoError(t, store.CreateTask(tx, testTask2)) + require.NoError(t, store.CreateTask(tx, testTask3)) + require.NoError(t, store.CreateTask(tx, testTask4)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testTask1.Status = api.TaskStatus{State: api.TaskStateAssigned} testTask2.Status = api.TaskStatus{State: api.TaskStateAssigned} @@ -1508,13 +1507,13 @@ func TestTaskUpdate(t *testing.T) { // without correct SessionID should fail resp, err := gd.Clients[0].UpdateTaskStatus(context.Background(), updReq) assert.Nil(t, resp) - assert.Error(t, err) - assert.Equal(t, testutils.ErrorCode(err), codes.InvalidArgument) + require.Error(t, err) + assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } updReq.SessionID = expectedSessionID _, err = gd.Clients[0].UpdateTaskStatus(context.Background(), updReq) - assert.NoError(t, err) + require.NoError(t, err) { // updating a task not assigned to us should fail @@ -1527,8 +1526,8 @@ func TestTaskUpdate(t *testing.T) { resp, err := gd.Clients[0].UpdateTaskStatus(context.Background(), updReq) assert.Nil(t, resp) - assert.Error(t, err) - assert.Equal(t, testutils.ErrorCode(err), codes.PermissionDenied) + require.Error(t, err) + assert.Equal(t, codes.PermissionDenied, testutils.ErrorCode(err)) } gd.dispatcherServer.processUpdates(context.Background()) @@ -1538,18 +1537,18 @@ func TestTaskUpdate(t *testing.T) { assert.NotNil(t, storeTask1) storeTask2 := store.GetTask(readTx, testTask2.ID) assert.NotNil(t, storeTask2) - assert.Equal(t, storeTask1.Status.State, api.TaskStateAssigned) - assert.Equal(t, storeTask2.Status.State, api.TaskStateAssigned) + assert.Equal(t, api.TaskStateAssigned, storeTask1.Status.State) + assert.Equal(t, api.TaskStateAssigned, storeTask2.Status.State) storeTask3 := store.GetTask(readTx, testTask3.ID) assert.NotNil(t, storeTask3) - assert.Equal(t, storeTask3.Status.State, api.TaskStateNew) + assert.Equal(t, api.TaskStateNew, storeTask3.Status.State) // The update to task4's state should be ignored because it // would have moved backwards. storeTask4 := store.GetTask(readTx, testTask4.ID) assert.NotNil(t, storeTask4) - assert.Equal(t, storeTask4.Status.State, api.TaskStateShutdown) + assert.Equal(t, api.TaskStateShutdown, storeTask4.Status.State) }) } @@ -1562,10 +1561,10 @@ func TestTaskUpdateNoCert(t *testing.T) { ID: "testTask1", } err := gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, testTask1)) + require.NoError(t, store.CreateTask(tx, testTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testTask1.Status = api.TaskStatus{State: api.TaskStateAssigned} updReq := &api.UpdateTaskStatusRequest{ @@ -1579,8 +1578,8 @@ func TestTaskUpdateNoCert(t *testing.T) { // without correct SessionID should fail resp, err := gd.Clients[2].UpdateTaskStatus(context.Background(), updReq) assert.Nil(t, resp) - assert.Error(t, err) - assert.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") + require.Error(t, err) + require.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") } func TestSession(t *testing.T) { @@ -1598,12 +1597,12 @@ func TestSession(t *testing.T) { require.NoError(t, err) stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) - assert.Equal(t, 1, len(resp.Managers)) + assert.Len(t, resp.Managers, 1) } func TestSessionNoCert(t *testing.T) { @@ -1611,18 +1610,18 @@ func TestSessionNoCert(t *testing.T) { defer gd.Close() stream, err := gd.Clients[2].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) msg, err := stream.Recv() assert.Nil(t, msg) - assert.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") + require.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") } func getSessionAndNodeID(t *testing.T, c api.DispatcherClient) (string, string) { stream, err := c.Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) return resp.SessionID, resp.Node.ID } @@ -2002,10 +2001,10 @@ func TestOldTasks(t *testing.T) { var nodeID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID nodeID = resp.Node.ID @@ -2027,37 +2026,37 @@ func TestOldTasks(t *testing.T) { { // without correct SessionID should fail stream, err := gd.Clients[0].Tasks(context.Background(), &api.TasksRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, stream) resp, err := stream.Recv() assert.Nil(t, resp) - assert.Error(t, err) - assert.Equal(t, testutils.ErrorCode(err), codes.InvalidArgument) + require.Error(t, err) + assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } stream, err := gd.Clients[0].Tasks(context.Background(), &api.TasksRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) time.Sleep(100 * time.Millisecond) resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // initially no tasks - assert.Equal(t, 0, len(resp.Tasks)) + assert.Empty(t, resp.Tasks) err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, testTask1)) - assert.NoError(t, store.CreateTask(tx, testTask2)) + require.NoError(t, store.CreateTask(tx, testTask1)) + require.NoError(t, store.CreateTask(tx, testTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) - assert.Equal(t, len(resp.Tasks), 2) + require.NoError(t, err) + assert.Len(t, resp.Tasks, 2) assert.True(t, resp.Tasks[0].ID == "testTask1" && resp.Tasks[1].ID == "testTask2" || resp.Tasks[0].ID == "testTask2" && resp.Tasks[1].ID == "testTask1") - assert.NoError(t, gd.Store.Update(func(tx store.Tx) error { + require.NoError(t, gd.Store.Update(func(tx store.Tx) error { task := store.GetTask(tx, testTask1.ID) if task == nil { return errors.New("no task") @@ -2069,24 +2068,24 @@ func TestOldTasks(t *testing.T) { })) resp, err = stream.Recv() - assert.NoError(t, err) - assert.Equal(t, len(resp.Tasks), 2) + require.NoError(t, err) + assert.Len(t, resp.Tasks, 2) for _, task := range resp.Tasks { if task.ID == "testTask1" { - assert.Equal(t, task.DesiredState, api.TaskStateRunning) + assert.Equal(t, api.TaskStateRunning, task.DesiredState) } } err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteTask(tx, testTask1.ID)) - assert.NoError(t, store.DeleteTask(tx, testTask2.ID)) + require.NoError(t, store.DeleteTask(tx, testTask1.ID)) + require.NoError(t, store.DeleteTask(tx, testTask2.ID)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) - assert.Equal(t, len(resp.Tasks), 0) + require.NoError(t, err) + assert.Empty(t, resp.Tasks) } func TestOldTasksStatusChange(t *testing.T) { @@ -2099,10 +2098,10 @@ func TestOldTasksStatusChange(t *testing.T) { var nodeID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID nodeID = resp.Node.ID @@ -2124,37 +2123,37 @@ func TestOldTasksStatusChange(t *testing.T) { { // without correct SessionID should fail stream, err := gd.Clients[0].Tasks(context.Background(), &api.TasksRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, stream) resp, err := stream.Recv() assert.Nil(t, resp) - assert.Error(t, err) - assert.Equal(t, testutils.ErrorCode(err), codes.InvalidArgument) + require.Error(t, err) + assert.Equal(t, codes.InvalidArgument, testutils.ErrorCode(err)) } stream, err := gd.Clients[0].Tasks(context.Background(), &api.TasksRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) time.Sleep(100 * time.Millisecond) resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // initially no tasks - assert.Equal(t, 0, len(resp.Tasks)) + assert.Empty(t, resp.Tasks) err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, testTask1)) - assert.NoError(t, store.CreateTask(tx, testTask2)) + require.NoError(t, store.CreateTask(tx, testTask1)) + require.NoError(t, store.CreateTask(tx, testTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) - assert.Equal(t, len(resp.Tasks), 2) + require.NoError(t, err) + assert.Len(t, resp.Tasks, 2) assert.True(t, resp.Tasks[0].ID == "testTask1" && resp.Tasks[1].ID == "testTask2" || resp.Tasks[0].ID == "testTask2" && resp.Tasks[1].ID == "testTask1") - assert.NoError(t, gd.Store.Update(func(tx store.Tx) error { + require.NoError(t, gd.Store.Update(func(tx store.Tx) error { task := store.GetTask(tx, testTask1.ID) if task == nil { return errors.New("no task") @@ -2188,10 +2187,10 @@ func TestOldTasksBatch(t *testing.T) { var nodeID string { stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{}) - assert.NoError(t, err) + require.NoError(t, err) defer stream.CloseSend() resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp.SessionID) expectedSessionID = resp.SessionID nodeID = resp.Node.ID @@ -2209,31 +2208,31 @@ func TestOldTasksBatch(t *testing.T) { } stream, err := gd.Clients[0].Tasks(context.Background(), &api.TasksRequest{SessionID: expectedSessionID}) - assert.NoError(t, err) + require.NoError(t, err) resp, err := stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // initially no tasks - assert.Equal(t, 0, len(resp.Tasks)) + assert.Empty(t, resp.Tasks) err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, testTask1)) - assert.NoError(t, store.CreateTask(tx, testTask2)) + require.NoError(t, store.CreateTask(tx, testTask1)) + require.NoError(t, store.CreateTask(tx, testTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) err = gd.Store.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteTask(tx, testTask1.ID)) - assert.NoError(t, store.DeleteTask(tx, testTask2.ID)) + require.NoError(t, store.DeleteTask(tx, testTask1.ID)) + require.NoError(t, store.DeleteTask(tx, testTask2.ID)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) resp, err = stream.Recv() - assert.NoError(t, err) + require.NoError(t, err) // all tasks have been deleted - assert.Equal(t, len(resp.Tasks), 0) + assert.Empty(t, resp.Tasks) } func TestOldTasksNoCert(t *testing.T) { @@ -2241,11 +2240,11 @@ func TestOldTasksNoCert(t *testing.T) { defer gd.Close() stream, err := gd.Clients[2].Tasks(context.Background(), &api.TasksRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, stream) resp, err := stream.Recv() assert.Nil(t, resp) - assert.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") + require.EqualError(t, err, "rpc error: code = PermissionDenied desc = Permission denied: unauthorized peer role: rpc error: code = PermissionDenied desc = no client certificates in request") } func TestClusterUpdatesSendMessages(t *testing.T) { diff --git a/manager/keymanager/keymanager_test.go b/manager/keymanager/keymanager_test.go index c957d74f55..037945daf0 100644 --- a/manager/keymanager/keymanager_test.go +++ b/manager/keymanager/keymanager_test.go @@ -9,6 +9,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/manager/state/store" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createClusterSpec(name string) *api.ClusterSpec { @@ -26,7 +27,7 @@ func createCluster(t *testing.T, s *store.MemoryStore, id, name string) *api.Clu ID: id, Spec: *spec, } - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { return store.CreateCluster(tx, cluster) })) return cluster @@ -53,7 +54,7 @@ func TestKeyManagerDefaultSubsystem(t *testing.T) { clusters, err = store.FindClusters(readTx, store.ByName(k.config.ClusterName)) }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, len(clusters[0].NetworkBootstrapKeys), len(k.config.Subsystems)*keyringSize) key1 := clusters[0].NetworkBootstrapKeys[0].Key @@ -95,8 +96,8 @@ func TestKeyManagerCustomSubsystem(t *testing.T) { clusters, err = store.FindClusters(readTx, store.ByName(k.config.ClusterName)) }) - assert.NoError(t, err) - assert.Equal(t, len(clusters[0].NetworkBootstrapKeys), keyringSize) + require.NoError(t, err) + assert.Len(t, clusters[0].NetworkBootstrapKeys, keyringSize) key1 := clusters[0].NetworkBootstrapKeys[0].Key @@ -104,7 +105,7 @@ func TestKeyManagerCustomSubsystem(t *testing.T) { // verify that after a rotation oldest key has been removed from the keyring // also verify that all keys are for the right subsystem - assert.Equal(t, len(k.keyRing.keys), keyringSize) + assert.Len(t, k.keyRing.keys, keyringSize) for _, key := range k.keyRing.keys { match := bytes.Equal(key.Key, key1) assert.False(t, match) diff --git a/manager/logbroker/broker_test.go b/manager/logbroker/broker_test.go index cf84f16dae..361e53b025 100644 --- a/manager/logbroker/broker_test.go +++ b/manager/logbroker/broker_test.go @@ -36,9 +36,7 @@ func TestLogBrokerLogs(t *testing.T) { ) subStream, err := brokerClient.ListenSubscriptions(ctx, &api.ListenSubscriptionsRequest{}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) stream, err := client.SubscribeLogs(ctx, &api.SubscribeLogsRequest{ Options: &api.LogSubscriptionOptions{ @@ -48,14 +46,10 @@ func TestLogBrokerLogs(t *testing.T) { NodeIDs: []string{agentSecurity.ServerTLSCreds.NodeID()}, }, }) - if err != nil { - t.Fatalf("error subscribing: %v", err) - } + require.NoErrorf(t, err, "error subscribing: %v", err) subscription, err := subStream.Recv() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) // spread some services across nodes with a bunch of tasks. const ( @@ -435,9 +429,9 @@ func TestLogBrokerNoFollow(t *testing.T) { // Get the subscriptions from the agents. subscription1 := ensureSubscription(t, agent1subscriptions) - require.Equal(t, subscription1.Selector.ServiceIDs[0], "service") + require.Equal(t, "service", subscription1.Selector.ServiceIDs[0]) subscription2 := ensureSubscription(t, agent2subscriptions) - require.Equal(t, subscription2.Selector.ServiceIDs[0], "service") + require.Equal(t, "service", subscription2.Selector.ServiceIDs[0]) require.Equal(t, subscription1.ID, subscription2.ID) @@ -553,7 +547,7 @@ func TestLogBrokerNoFollowMissingNode(t *testing.T) { // Grab the subscription and publish a log message from the connected agent. subscription := ensureSubscription(t, agentSubscriptions) - require.Equal(t, subscription.Selector.ServiceIDs[0], "service") + require.Equal(t, "service", subscription.Selector.ServiceIDs[0]) publisher, err := agent.PublishLogs(ctx) require.NoError(t, err) require.NoError(t, @@ -680,9 +674,9 @@ func TestLogBrokerNoFollowDisconnect(t *testing.T) { // Get the subscriptions from the agents. subscription1 := ensureSubscription(t, agent1subscriptions) - require.Equal(t, subscription1.Selector.ServiceIDs[0], "service") + require.Equal(t, "service", subscription1.Selector.ServiceIDs[0]) subscription2 := ensureSubscription(t, agent2subscriptions) - require.Equal(t, subscription2.Selector.ServiceIDs[0], "service") + require.Equal(t, "service", subscription2.Selector.ServiceIDs[0]) require.Equal(t, subscription1.ID, subscription2.ID) @@ -726,9 +720,7 @@ func testLogBrokerEnv(t *testing.T) (context.Context, *testutils.TestCA, *LogBro // Log Server logListener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("error setting up listener: %v", err) - } + require.NoErrorf(t, err, "error setting up listener: %v", err) logServer := grpc.NewServer() api.RegisterLogsServer(logServer, broker) @@ -742,14 +734,10 @@ func testLogBrokerEnv(t *testing.T) (context.Context, *testutils.TestCA, *LogBro // Log Broker brokerListener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("error setting up listener: %v", err) - } + require.NoErrorf(t, err, "error setting up listener: %v", err) securityConfig, err := tca.NewNodeConfig(ca.ManagerRole) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) serverOpts := []grpc.ServerOption{grpc.Creds(securityConfig.ServerTLSCreds)} brokerServer := grpc.NewServer(serverOpts...) @@ -786,9 +774,7 @@ func testLogBrokerEnv(t *testing.T) (context.Context, *testutils.TestCA, *LogBro func testLogClient(t *testing.T, addr string) (api.LogsClient, func()) { // Log client logCc, err := grpc.Dial(addr, grpc.WithInsecure()) - if err != nil { - t.Fatalf("error dialing local server: %v", err) - } + require.NoErrorf(t, err, "error dialing local server: %v", err) return api.NewLogsClient(logCc), func() { logCc.Close() } @@ -796,15 +782,11 @@ func testLogClient(t *testing.T, addr string) (api.LogsClient, func()) { func testBrokerClient(t *testing.T, tca *testutils.TestCA, addr string) (api.LogBrokerClient, *ca.SecurityConfig, func()) { securityConfig, err := tca.NewNodeConfig(ca.WorkerRole) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) opts := []grpc.DialOption{grpc.WithTimeout(10 * time.Second), grpc.WithTransportCredentials(securityConfig.ClientTLSCreds)} cc, err := grpc.Dial(addr, opts...) - if err != nil { - t.Fatalf("error dialing local server: %v", err) - } + require.NoErrorf(t, err, "error dialing local server: %v", err) return api.NewLogBrokerClient(cc), securityConfig, func() { cc.Close() diff --git a/manager/orchestrator/constraintenforcer/constraint_enforcer_test.go b/manager/orchestrator/constraintenforcer/constraint_enforcer_test.go index f63518b1aa..90219e3097 100644 --- a/manager/orchestrator/constraintenforcer/constraint_enforcer_test.go +++ b/manager/orchestrator/constraintenforcer/constraint_enforcer_test.go @@ -129,16 +129,16 @@ func TestConstraintEnforcer(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Prepoulate nodes for _, n := range nodes { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) watch, cancel := state.Watch(s.WatchQueue(), api.EventUpdateTask{}) defer cancel() @@ -156,14 +156,12 @@ func TestConstraintEnforcer(t *testing.T) { // Change node id1 to a manager err = s.Update(func(tx store.Tx) error { node := store.GetNode(tx, "id1") - if node == nil { - t.Fatal("could not get node id1") - } + require.NotNil(t, node, "could not get node id1") node.Role = api.NodeRoleManager - assert.NoError(t, store.UpdateNode(tx, node)) + require.NoError(t, store.UpdateNode(tx, node)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // since we've changed the node from a worker to a manager, this task // should now shut down @@ -174,14 +172,12 @@ func TestConstraintEnforcer(t *testing.T) { // Change resources on node id2 err = s.Update(func(tx store.Tx) error { node := store.GetNode(tx, "id2") - if node == nil { - t.Fatal("could not get node id2") - } + require.NotNil(t, node, "could not get node id2") node.Description.Resources.MemoryBytes = 5e8 - assert.NoError(t, store.UpdateNode(tx, node)) + require.NoError(t, store.UpdateNode(tx, node)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) shutdown3 := testutils.WatchTaskUpdate(t, watch) assert.Equal(t, "id4", shutdown3.ID) diff --git a/manager/orchestrator/global/global_test.go b/manager/orchestrator/global/global_test.go index b6d96b44a0..ac6aa39d63 100644 --- a/manager/orchestrator/global/global_test.go +++ b/manager/orchestrator/global/global_test.go @@ -116,7 +116,7 @@ func setup(t *testing.T, store *store.MemoryStore, watch chan events.Event) *Orc // Start the global orchestrator. global := NewGlobalOrchestrator(store) testutils.EnsureRuns(func() { - assert.NoError(t, global.Run(ctx)) + require.NoError(t, global.Run(ctx)) }) addService(t, store, service1) @@ -143,9 +143,9 @@ func TestSetup(t *testing.T) { observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask1.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask1.NodeID) } func TestAddNode(t *testing.T) { @@ -163,9 +163,9 @@ func TestAddNode(t *testing.T) { addNode(t, store, node2) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask2.NodeID, "nodeid2") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) + assert.Equal(t, "nodeid2", observedTask2.NodeID) } func TestDeleteNode(t *testing.T) { @@ -184,8 +184,8 @@ func TestDeleteNode(t *testing.T) { deleteNode(t, store, node1) // task should be set to dead observedTask := testutils.WatchTaskDelete(t, watch) - assert.Equal(t, observedTask.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask.NodeID, "nodeid1") + assert.Equal(t, "name1", observedTask.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask.NodeID) } func TestNodeAvailability(t *testing.T) { @@ -208,8 +208,8 @@ func TestNodeAvailability(t *testing.T) { // task should be set to dead observedTask1 := testutils.WatchShutdownTask(t, watch) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask1.NodeID, "nodeid1") + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask1.NodeID) testutils.Expect(t, watch, state.EventCommit{}) // updating the service shouldn't restart the task @@ -226,9 +226,9 @@ func TestNodeAvailability(t *testing.T) { updateNodeAvailability(t, store, node1, api.NodeAvailabilityActive) // task should be added back observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask2.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask2.NodeID) testutils.Expect(t, watch, state.EventCommit{}) // set node1 to pause @@ -236,8 +236,8 @@ func TestNodeAvailability(t *testing.T) { failTask(t, store, observedTask2) observedTask3 := testutils.WatchShutdownTask(t, watch) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask3.NodeID, "nodeid1") + assert.Equal(t, "name1", observedTask3.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask3.NodeID) testutils.Expect(t, watch, state.EventCommit{}) // updating the service shouldn't restart the task @@ -272,8 +272,8 @@ func TestNodeState(t *testing.T) { // task should be set to dead observedTask1 := testutils.WatchShutdownTask(t, watch) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask1.NodeID, "nodeid1") + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask1.NodeID) testutils.Expect(t, watch, state.EventCommit{}) // updating the service shouldn't restart the task @@ -290,9 +290,9 @@ func TestNodeState(t *testing.T) { updateNodeState(t, store, node1, api.NodeStatus_READY) // task should be added back observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask2.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask2.NodeID) } func TestAddService(t *testing.T) { @@ -310,9 +310,9 @@ func TestAddService(t *testing.T) { addService(t, store, service2) observedTask := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.ServiceAnnotations.Name, "name2") - assert.True(t, observedTask.NodeID == "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "name2", observedTask.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask.NodeID) } func TestDeleteService(t *testing.T) { @@ -331,8 +331,8 @@ func TestDeleteService(t *testing.T) { deleteService(t, store, service1) // task should be deleted observedTask := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask.NodeID, "nodeid1") + assert.Equal(t, "name1", observedTask.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask.NodeID) } func TestRemoveTask(t *testing.T) { @@ -351,9 +351,9 @@ func TestRemoveTask(t *testing.T) { observedTask1 := testutils.WatchTaskCreate(t, watch) testutils.Expect(t, watch, state.EventCommit{}) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask1.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask1.NodeID) deleteTask(t, store, observedTask1) testutils.Expect(t, watch, api.EventDeleteTask{}) @@ -383,9 +383,9 @@ func TestTaskFailure(t *testing.T) { observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask1.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask1.NodeID) failTask(t, store, observedTask1) @@ -393,9 +393,9 @@ func TestTaskFailure(t *testing.T) { // the task should be recreated observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") - assert.Equal(t, observedTask2.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask2.NodeID) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) // ready->running testutils.Expect(t, watch, state.EventCommit{}) @@ -406,16 +406,16 @@ func TestTaskFailure(t *testing.T) { testutils.Expect(t, watch, state.EventCommit{}) observedTask3 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask3.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "norestart") - assert.Equal(t, observedTask3.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask3.Status.State) + assert.Equal(t, "norestart", observedTask3.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask3.NodeID) testutils.Expect(t, watch, state.EventCommit{}) failTask(t, store, observedTask3) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) observedTask4 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask4.DesiredState, api.TaskStateShutdown) + assert.Equal(t, api.TaskStateShutdown, observedTask4.DesiredState) testutils.Expect(t, watch, state.EventCommit{}) // the task should not be recreated @@ -443,15 +443,15 @@ func TestTaskFailure(t *testing.T) { testutils.Expect(t, watch, state.EventCommit{}) observedTask5 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask5.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask5.ServiceAnnotations.Name, "norestart") - assert.Equal(t, observedTask5.NodeID, "nodeid1") + assert.Equal(t, api.TaskStateNew, observedTask5.Status.State) + assert.Equal(t, "norestart", observedTask5.ServiceAnnotations.Name) + assert.Equal(t, "nodeid1", observedTask5.NodeID) testutils.Expect(t, watch, state.EventCommit{}) } func addService(t *testing.T, s *store.MemoryStore, service *api.Service) { s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service.Copy())) + require.NoError(t, store.CreateService(tx, service.Copy())) return nil }) } @@ -463,21 +463,21 @@ func updateService(t *testing.T, s *store.MemoryStore, service *api.Service, for if force { service.Spec.Task.ForceUpdate++ } - assert.NoError(t, store.UpdateService(tx, service)) + require.NoError(t, store.UpdateService(tx, service)) return nil }) } func deleteService(t *testing.T, s *store.MemoryStore, service *api.Service) { s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteService(tx, service.ID)) + require.NoError(t, store.DeleteService(tx, service.ID)) return nil }) } func addNode(t *testing.T, s *store.MemoryStore, node *api.Node) { s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, node.Copy())) + require.NoError(t, store.CreateNode(tx, node.Copy())) return nil }) } @@ -487,7 +487,7 @@ func updateNodeAvailability(t *testing.T, s *store.MemoryStore, node *api.Node, node := store.GetNode(tx, node.ID) require.NotNil(t, node) node.Spec.Availability = avail - assert.NoError(t, store.UpdateNode(tx, node)) + require.NoError(t, store.UpdateNode(tx, node)) return nil }) } @@ -497,28 +497,28 @@ func updateNodeState(t *testing.T, s *store.MemoryStore, node *api.Node, state a node := store.GetNode(tx, node.ID) require.NotNil(t, node) node.Status.State = state - assert.NoError(t, store.UpdateNode(tx, node)) + require.NoError(t, store.UpdateNode(tx, node)) return nil }) } func deleteNode(t *testing.T, s *store.MemoryStore, node *api.Node) { s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteNode(tx, node.ID)) + require.NoError(t, store.DeleteNode(tx, node.ID)) return nil }) } func addTask(t *testing.T, s *store.MemoryStore, task *api.Task) { s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) return nil }) } func deleteTask(t *testing.T, s *store.MemoryStore, task *api.Task) { s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteTask(tx, task.ID)) + require.NoError(t, store.DeleteTask(tx, task.ID)) return nil }) } @@ -528,7 +528,7 @@ func failTask(t *testing.T, s *store.MemoryStore, task *api.Task) { task := store.GetTask(tx, task.ID) require.NotNil(t, task) task.Status.State = api.TaskStateFailed - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) return nil }) } @@ -580,18 +580,18 @@ func TestInitializationRejectedTasks(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) observedTask1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateRejected) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateRejected, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.NodeID, "nodeid1") - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.DesiredState, api.TaskStateReady) + assert.Equal(t, "nodeid1", observedTask2.NodeID) + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask2.DesiredState) } func TestInitializationFailedTasks(t *testing.T) { @@ -643,27 +643,25 @@ func TestInitializationFailedTasks(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) observedTask1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateFailed) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateFailed, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.NodeID, "nodeid1") - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.DesiredState, api.TaskStateReady) + assert.Equal(t, "nodeid1", observedTask2.NodeID) + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask2.DesiredState) observedTask3 := testutils.WatchTaskUpdate(t, watch) after := time.Now() - assert.Equal(t, observedTask3.NodeID, "nodeid1") - assert.Equal(t, observedTask3.DesiredState, api.TaskStateRunning) + assert.Equal(t, "nodeid1", observedTask3.NodeID) + assert.Equal(t, api.TaskStateRunning, observedTask3.DesiredState) - if after.Sub(before) < restartDelay { - t.Fatalf("restart delay should have elapsed. Got: %v", after.Sub(before)) - } + require.GreaterOrEqualf(t, after.Sub(before), restartDelay, "restart delay should have elapsed. Got: %v", after.Sub(before)) } func TestInitializationExtraTask(t *testing.T) { @@ -735,13 +733,13 @@ func TestInitializationExtraTask(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) observedTask1 := testutils.WatchTaskUpdate(t, watch) assert.True(t, observedTask1.ID == "task1" || observedTask1.ID == "task2") - assert.Equal(t, observedTask1.Status.State, api.TaskStateRunning) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, api.TaskStateRunning, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) var deadCnt, liveCnt int var err error @@ -753,14 +751,14 @@ func TestInitializationExtraTask(t *testing.T) { assert.Equal(t, task.ID, observedTask1.ID) deadCnt++ } else { - assert.Equal(t, task.DesiredState, api.TaskStateRunning) + assert.Equal(t, api.TaskStateRunning, task.DesiredState) liveCnt++ } } }) - assert.NoError(t, err) - assert.Equal(t, deadCnt, 1) - assert.Equal(t, liveCnt, 1) + require.NoError(t, err) + assert.Equal(t, 1, deadCnt) + assert.Equal(t, 1, liveCnt) } func TestInitializationMultipleServices(t *testing.T) { @@ -815,7 +813,7 @@ func TestInitializationMultipleServices(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) // Nothing should happen because both tasks are up to date. @@ -833,7 +831,7 @@ func TestInitializationMultipleServices(t *testing.T) { s1.Spec.Task.Restart.Delay = gogotypes.DurationProto(70 * time.Millisecond) - assert.NoError(t, store.UpdateService(tx, s1)) + require.NoError(t, store.UpdateService(tx, s1)) return nil }) @@ -862,7 +860,7 @@ func TestInitializationMultipleServices(t *testing.T) { t2.Status.State = api.TaskStateFailed - assert.NoError(t, store.UpdateTask(tx, t2)) + require.NoError(t, store.UpdateTask(tx, t2)) return nil }) @@ -956,13 +954,13 @@ func TestInitializationTaskWithoutService(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) observedTask1 := testutils.WatchTaskDelete(t, watch) - assert.Equal(t, observedTask1.ID, "task2") - assert.Equal(t, observedTask1.Status.State, api.TaskStateRunning) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateRunning) + assert.Equal(t, "task2", observedTask1.ID) + assert.Equal(t, api.TaskStateRunning, observedTask1.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask1.DesiredState) } func TestInitializationTaskOnDrainedNode(t *testing.T) { @@ -1014,13 +1012,13 @@ func TestInitializationTaskOnDrainedNode(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) observedTask1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateRunning) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateRunning, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) var deadCnt, liveCnt int var err error @@ -1035,9 +1033,9 @@ func TestInitializationTaskOnDrainedNode(t *testing.T) { } } }) - assert.NoError(t, err) - assert.Equal(t, deadCnt, 1) - assert.Equal(t, liveCnt, 0) + require.NoError(t, err) + assert.Equal(t, 1, deadCnt) + assert.Equal(t, 0, liveCnt) } func TestInitializationTaskOnNonexistentNode(t *testing.T) { @@ -1086,13 +1084,13 @@ func TestInitializationTaskOnNonexistentNode(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) observedTask1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateRunning) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateRunning, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) var deadCnt, liveCnt int var err error @@ -1107,9 +1105,9 @@ func TestInitializationTaskOnNonexistentNode(t *testing.T) { } } }) - assert.NoError(t, err) - assert.Equal(t, deadCnt, 1) - assert.Equal(t, liveCnt, 0) + require.NoError(t, err) + assert.Equal(t, 1, deadCnt) + assert.Equal(t, 0, liveCnt) } func TestInitializationRestartHistory(t *testing.T) { @@ -1255,7 +1253,7 @@ func TestInitializationRestartHistory(t *testing.T) { defer orchestrator.Stop() testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) // Fail the running task @@ -1264,7 +1262,7 @@ func TestInitializationRestartHistory(t *testing.T) { require.NotNil(t, task) task.Status.State = api.TaskStateFailed task.Status.Timestamp = ptypes.MustTimestampProto(time.Now()) - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) return nil }) testutils.Expect(t, watch, api.EventUpdateTask{}) @@ -1276,7 +1274,7 @@ func TestInitializationRestartHistory(t *testing.T) { assert.Equal(t, api.TaskStateFailed, observedTask1.Status.State) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.NodeID, "nodeid1") + assert.Equal(t, "nodeid1", observedTask2.NodeID) assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) assert.Equal(t, api.TaskStateReady, observedTask2.DesiredState) @@ -1290,7 +1288,7 @@ func TestInitializationRestartHistory(t *testing.T) { require.NotNil(t, task) task.Status.State = api.TaskStateRejected task.Status.Timestamp = ptypes.MustTimestampProto(time.Now()) - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) return nil }) testutils.Expect(t, watch, api.EventUpdateTask{}) // our update diff --git a/manager/orchestrator/replicated/drain_test.go b/manager/orchestrator/replicated/drain_test.go index 1e185b8260..69eb98bad6 100644 --- a/manager/orchestrator/replicated/drain_test.go +++ b/manager/orchestrator/replicated/drain_test.go @@ -9,6 +9,7 @@ import ( "github.com/moby/swarmkit/v2/manager/state" "github.com/moby/swarmkit/v2/manager/state/store" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDrain(t *testing.T) { @@ -192,19 +193,19 @@ func TestDrain(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Prepopulate service - assert.NoError(t, store.CreateService(tx, initialService)) + require.NoError(t, store.CreateService(tx, initialService)) // Prepoulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks for _, task := range initialTaskSet { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) watch, cancel := state.Watch(s.WatchQueue(), api.EventUpdateTask{}) defer cancel() @@ -213,7 +214,7 @@ func TestDrain(t *testing.T) { defer orchestrator.Stop() go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() // id2 and id5 should be killed immediately @@ -230,10 +231,10 @@ func TestDrain(t *testing.T) { task := initialTaskSet[2].Copy() task.ID = "newtask" task.NodeID = "id2" - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) deletion3 := testutils.WatchShutdownTask(t, watch) assert.Equal(t, "newtask", deletion3.ID) @@ -243,10 +244,10 @@ func TestDrain(t *testing.T) { err = s.Update(func(tx store.Tx) error { n := initialNodeSet[3].Copy() n.Spec.Availability = api.NodeAvailabilityDrain - assert.NoError(t, store.UpdateNode(tx, n)) + require.NoError(t, store.UpdateNode(tx, n)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) deletion4 := testutils.WatchShutdownTask(t, watch) assert.Equal(t, "id4", deletion4.ID) @@ -254,10 +255,10 @@ func TestDrain(t *testing.T) { // Delete node id1 err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteNode(tx, "id1")) + require.NoError(t, store.DeleteNode(tx, "id1")) return nil }) - assert.NoError(t, err) + require.NoError(t, err) deletion5 := testutils.WatchShutdownTask(t, watch) assert.Equal(t, "id1", deletion5.ID) diff --git a/manager/orchestrator/replicated/replicated_test.go b/manager/orchestrator/replicated/replicated_test.go index 2c8aa8c5ba..4c14b009c3 100644 --- a/manager/orchestrator/replicated/replicated_test.go +++ b/manager/orchestrator/replicated/replicated_test.go @@ -49,23 +49,23 @@ func TestReplicatedOrchestrator(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, s1)) + require.NoError(t, store.CreateService(tx, s1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Create a second service. err = s.Update(func(tx store.Tx) error { @@ -87,14 +87,14 @@ func TestReplicatedOrchestrator(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, s2)) + require.NoError(t, store.CreateService(tx, s2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) observedTask3 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask3.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "name2") + assert.Equal(t, api.TaskStateNew, observedTask3.Status.State) + assert.Equal(t, "name2", observedTask3.ServiceAnnotations.Name) // Update a service to scale it out to 3 instances err = s.Update(func(tx store.Tx) error { @@ -116,18 +116,18 @@ func TestReplicatedOrchestrator(t *testing.T) { }, }, } - assert.NoError(t, store.UpdateService(tx, s2)) + require.NoError(t, store.UpdateService(tx, s2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) observedTask4 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask4.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "name2") + assert.Equal(t, api.TaskStateNew, observedTask4.Status.State) + assert.Equal(t, "name2", observedTask4.ServiceAnnotations.Name) observedTask5 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask5.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask5.ServiceAnnotations.Name, "name2") + assert.Equal(t, api.TaskStateNew, observedTask5.Status.State) + assert.Equal(t, "name2", observedTask5.ServiceAnnotations.Name) // Now scale it back down to 1 instance err = s.Update(func(tx store.Tx) error { @@ -149,18 +149,18 @@ func TestReplicatedOrchestrator(t *testing.T) { }, }, } - assert.NoError(t, store.UpdateService(tx, s2)) + require.NoError(t, store.UpdateService(tx, s2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) observedUpdateRemove1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedUpdateRemove1.DesiredState, api.TaskStateRemove) - assert.Equal(t, observedUpdateRemove1.ServiceAnnotations.Name, "name2") + assert.Equal(t, api.TaskStateRemove, observedUpdateRemove1.DesiredState) + assert.Equal(t, "name2", observedUpdateRemove1.ServiceAnnotations.Name) observedUpdateRemove2 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedUpdateRemove2.DesiredState, api.TaskStateRemove) - assert.Equal(t, observedUpdateRemove2.ServiceAnnotations.Name, "name2") + assert.Equal(t, api.TaskStateRemove, observedUpdateRemove2.DesiredState) + assert.Equal(t, "name2", observedUpdateRemove2.ServiceAnnotations.Name) // There should be one remaining task attached to service id2/name2. var liveTasks []*api.Task @@ -173,31 +173,31 @@ func TestReplicatedOrchestrator(t *testing.T) { } } }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, liveTasks, 1) // Delete the remaining task directly. It should be recreated by the // orchestrator. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteTask(tx, liveTasks[0].ID)) + require.NoError(t, store.DeleteTask(tx, liveTasks[0].ID)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) observedTask6 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask6.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask6.ServiceAnnotations.Name, "name2") + assert.Equal(t, api.TaskStateNew, observedTask6.Status.State) + assert.Equal(t, "name2", observedTask6.ServiceAnnotations.Name) // Delete the service. Its remaining task should go away. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteService(tx, "id2")) + require.NoError(t, store.DeleteService(tx, "id2")) return nil }) - assert.NoError(t, err) + require.NoError(t, err) deletedTask := testutils.WatchTaskDelete(t, watch) - assert.Equal(t, deletedTask.Status.State, api.TaskStateNew) - assert.Equal(t, deletedTask.ServiceAnnotations.Name, "name2") + assert.Equal(t, api.TaskStateNew, deletedTask.Status.State) + assert.Equal(t, "name2", deletedTask.ServiceAnnotations.Name) } func TestReplicatedScaleDown(t *testing.T) { @@ -227,7 +227,7 @@ func TestReplicatedScaleDown(t *testing.T) { } err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, s1)) + require.NoError(t, store.CreateService(tx, s1)) nodes := []*api.Node{ { @@ -268,7 +268,7 @@ func TestReplicatedScaleDown(t *testing.T) { }, } for _, node := range nodes { - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateNode(tx, node)) } // task1 is assigned to node1 @@ -369,16 +369,16 @@ func TestReplicatedScaleDown(t *testing.T) { }, } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() // Replicas was set to 6, but we started with 7 tasks. task7 should @@ -396,10 +396,10 @@ func TestReplicatedScaleDown(t *testing.T) { Replicas: 4, }, } - assert.NoError(t, store.UpdateService(tx, s1)) + require.NoError(t, store.UpdateService(tx, s1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Tasks should be shut down in a way that balances the remaining tasks. // node2 should be preferred over node3 because node2's tasks have @@ -434,10 +434,10 @@ func TestReplicatedScaleDown(t *testing.T) { Replicas: 2, }, } - assert.NoError(t, store.UpdateService(tx, s1)) + require.NoError(t, store.UpdateService(tx, s1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Tasks should be shut down in a way that balances the remaining tasks. // node2 and node3 should be preferred over node1 because node1's task @@ -497,7 +497,7 @@ func TestInitializationRejectedTasks(t *testing.T) { } err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) nodes := []*api.Node{ { @@ -514,7 +514,7 @@ func TestInitializationRejectedTasks(t *testing.T) { }, } for _, node := range nodes { - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateNode(tx, node)) } // 1 rejected task is in store before orchestrator starts @@ -539,12 +539,12 @@ func TestInitializationRejectedTasks(t *testing.T) { }, } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) // watch orchestration events watch, cancel := state.Watch(s.WatchQueue(), api.EventCreateTask{}, api.EventUpdateTask{}, api.EventDeleteTask{}) @@ -554,22 +554,22 @@ func TestInitializationRejectedTasks(t *testing.T) { defer orchestrator.Stop() go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() // initTask triggers an update event observedTask1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateRejected) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateRejected, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) // a new task is created observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.ServiceID, "serviceid1") + assert.Equal(t, "serviceid1", observedTask2.ServiceID) // it has not been scheduled - assert.Equal(t, observedTask2.NodeID, "") - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.DesiredState, api.TaskStateReady) + assert.Empty(t, observedTask2.NodeID) + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask2.DesiredState) var deadCnt, liveCnt int s.View(func(readTx store.ReadTx) { @@ -577,16 +577,16 @@ func TestInitializationRejectedTasks(t *testing.T) { tasks, err = store.FindTasks(readTx, store.ByServiceID("serviceid1")) for _, task := range tasks { if task.DesiredState == api.TaskStateShutdown { - assert.Equal(t, task.ID, "task1") + assert.Equal(t, "task1", task.ID) deadCnt++ } else { liveCnt++ } } }) - assert.NoError(t, err) - assert.Equal(t, deadCnt, 1) - assert.Equal(t, liveCnt, 1) + require.NoError(t, err) + assert.Equal(t, 1, deadCnt) + assert.Equal(t, 1, liveCnt) } func TestInitializationFailedTasks(t *testing.T) { @@ -615,7 +615,7 @@ func TestInitializationFailedTasks(t *testing.T) { } err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) nodes := []*api.Node{ { @@ -632,7 +632,7 @@ func TestInitializationFailedTasks(t *testing.T) { }, } for _, node := range nodes { - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateNode(tx, node)) } // 1 failed task is in store before orchestrator starts @@ -675,12 +675,12 @@ func TestInitializationFailedTasks(t *testing.T) { }, } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) // watch orchestration events watch, cancel := state.Watch(s.WatchQueue(), api.EventCreateTask{}, api.EventUpdateTask{}, api.EventDeleteTask{}) @@ -690,20 +690,20 @@ func TestInitializationFailedTasks(t *testing.T) { defer orchestrator.Stop() go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() // initTask triggers an update observedTask1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateFailed) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateFailed, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) // a new task is created observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.ServiceID, "serviceid1") - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.DesiredState, api.TaskStateReady) + assert.Equal(t, "serviceid1", observedTask2.ServiceID) + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask2.DesiredState) var deadCnt, liveCnt int s.View(func(readTx store.ReadTx) { @@ -711,16 +711,16 @@ func TestInitializationFailedTasks(t *testing.T) { tasks, err = store.FindTasks(readTx, store.ByServiceID("serviceid1")) for _, task := range tasks { if task.DesiredState == api.TaskStateShutdown { - assert.Equal(t, task.ID, "task1") + assert.Equal(t, "task1", task.ID) deadCnt++ } else { liveCnt++ } } }) - assert.NoError(t, err) - assert.Equal(t, deadCnt, 1) - assert.Equal(t, liveCnt, 2) + require.NoError(t, err) + assert.Equal(t, 1, deadCnt) + assert.Equal(t, 2, liveCnt) } func TestInitializationNodeDown(t *testing.T) { @@ -749,7 +749,7 @@ func TestInitializationNodeDown(t *testing.T) { } err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) nodes := []*api.Node{ { @@ -766,7 +766,7 @@ func TestInitializationNodeDown(t *testing.T) { }, } for _, node := range nodes { - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateNode(tx, node)) } // 1 failed task is in store before orchestrator starts @@ -791,12 +791,12 @@ func TestInitializationNodeDown(t *testing.T) { }, } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) // watch orchestration events watch, cancel := state.Watch(s.WatchQueue(), api.EventCreateTask{}, api.EventUpdateTask{}, api.EventDeleteTask{}) @@ -806,20 +806,20 @@ func TestInitializationNodeDown(t *testing.T) { defer orchestrator.Stop() go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() // initTask triggers an update observedTask1 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateRunning) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateShutdown) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateRunning, observedTask1.Status.State) + assert.Equal(t, api.TaskStateShutdown, observedTask1.DesiredState) // a new task is created observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.ServiceID, "serviceid1") - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.DesiredState, api.TaskStateReady) + assert.Equal(t, "serviceid1", observedTask2.ServiceID) + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask2.DesiredState) } func TestInitializationDelayStart(t *testing.T) { @@ -853,7 +853,7 @@ func TestInitializationDelayStart(t *testing.T) { before := time.Now() err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) nodes := []*api.Node{ { @@ -870,7 +870,7 @@ func TestInitializationDelayStart(t *testing.T) { }, } for _, node := range nodes { - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateNode(tx, node)) } // 1 failed task is in store before orchestrator starts @@ -900,12 +900,12 @@ func TestInitializationDelayStart(t *testing.T) { }, } for _, task := range tasks { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) // watch orchestration events watch, cancel := state.Watch(s.WatchQueue(), api.EventCreateTask{}, api.EventUpdateTask{}, api.EventDeleteTask{}) @@ -915,18 +915,16 @@ func TestInitializationDelayStart(t *testing.T) { defer orchestrator.Stop() go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() // initTask triggers an update observedTask1 := testutils.WatchTaskUpdate(t, watch) after := time.Now() - assert.Equal(t, observedTask1.ID, "task1") - assert.Equal(t, observedTask1.Status.State, api.TaskStateReady) - assert.Equal(t, observedTask1.DesiredState, api.TaskStateRunning) + assert.Equal(t, "task1", observedTask1.ID) + assert.Equal(t, api.TaskStateReady, observedTask1.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask1.DesiredState) // At least 100 ms should have elapsed - if after.Sub(before) < 100*time.Millisecond { - t.Fatalf("restart delay should have elapsed. Got: %v", after.Sub(before)) - } + require.GreaterOrEqualf(t, after.Sub(before), 100*time.Millisecond, "restart delay should have elapsed. Got: %v", after.Sub(before)) } diff --git a/manager/orchestrator/replicated/restart_test.go b/manager/orchestrator/replicated/restart_test.go index a7589bd375..ad57eb95d6 100644 --- a/manager/orchestrator/replicated/restart_test.go +++ b/manager/orchestrator/replicated/restart_test.go @@ -53,69 +53,69 @@ func TestOrchestratorRestartOnAny(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, j1)) + require.NoError(t, store.CreateService(tx, j1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Fail the first task. Confirm that it gets restarted. updatedTask1 := observedTask1.Copy() updatedTask1.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) observedTask3 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask3.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask3.Status.State) + assert.Equal(t, "name1", observedTask3.ServiceAnnotations.Name) testutils.Expect(t, watch, state.EventCommit{}) observedTask4 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask4.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateRunning, observedTask4.DesiredState) + assert.Equal(t, "name1", observedTask4.ServiceAnnotations.Name) // Mark the second task as completed. Confirm that it gets restarted. updatedTask2 := observedTask2.Copy() updatedTask2.Status = api.TaskStatus{State: api.TaskStateCompleted, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) observedTask5 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask5.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask5.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask5.Status.State) + assert.Equal(t, "name1", observedTask5.ServiceAnnotations.Name) testutils.Expect(t, watch, state.EventCommit{}) observedTask6 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask6.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask6.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateRunning, observedTask6.DesiredState) + assert.Equal(t, "name1", observedTask6.ServiceAnnotations.Name) } func TestOrchestratorRestartOnFailure(t *testing.T) { @@ -158,52 +158,52 @@ func TestOrchestratorRestartOnFailure(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, j1)) + require.NoError(t, store.CreateService(tx, j1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Fail the first task. Confirm that it gets restarted. updatedTask1 := observedTask1.Copy() updatedTask1.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, api.EventUpdateTask{}) observedTask3 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask3.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask3.DesiredState, api.TaskStateReady) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask3.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask3.DesiredState) + assert.Equal(t, "name1", observedTask3.ServiceAnnotations.Name) observedTask4 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask4.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateRunning, observedTask4.DesiredState) + assert.Equal(t, "name1", observedTask4.ServiceAnnotations.Name) // Mark the second task as completed. Confirm that it does not get restarted. updatedTask2 := observedTask2.Copy() updatedTask2.Status = api.TaskStatus{State: api.TaskStateCompleted, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, api.EventUpdateTask{}) @@ -218,10 +218,10 @@ func TestOrchestratorRestartOnFailure(t *testing.T) { err = s.Update(func(tx store.Tx) error { service := store.GetService(tx, "id1") require.NotNil(t, service) - assert.NoError(t, store.UpdateService(tx, service)) + require.NoError(t, store.UpdateService(tx, service)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) select { case <-watch: @@ -235,10 +235,10 @@ func TestOrchestratorRestartOnFailure(t *testing.T) { service := store.GetService(tx, "id1") require.NotNil(t, service) service.Spec.Task.ForceUpdate++ - assert.NoError(t, store.UpdateService(tx, service)) + require.NoError(t, store.UpdateService(tx, service)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventCreateTask{}) } @@ -281,32 +281,32 @@ func TestOrchestratorRestartOnNone(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, j1)) + require.NoError(t, store.CreateService(tx, j1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Fail the first task. Confirm that it does not get restarted. updatedTask1 := observedTask1.Copy() updatedTask1.Status.State = api.TaskStateFailed err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, api.EventUpdateTask{}) @@ -320,10 +320,10 @@ func TestOrchestratorRestartOnNone(t *testing.T) { updatedTask2 := observedTask2.Copy() updatedTask2.Status = api.TaskStatus{State: api.TaskStateCompleted, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, api.EventUpdateTask{}) @@ -338,10 +338,10 @@ func TestOrchestratorRestartOnNone(t *testing.T) { err = s.Update(func(tx store.Tx) error { service := store.GetService(tx, "id1") require.NotNil(t, service) - assert.NoError(t, store.UpdateService(tx, service)) + require.NoError(t, store.UpdateService(tx, service)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) select { case <-watch: @@ -355,10 +355,10 @@ func TestOrchestratorRestartOnNone(t *testing.T) { service := store.GetService(tx, "id1") require.NotNil(t, service) service.Spec.Task.ForceUpdate++ - assert.NoError(t, store.UpdateService(tx, service)) + require.NoError(t, store.UpdateService(tx, service)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventCreateTask{}) newTask := testutils.WatchTaskUpdate(t, watch) assert.Equal(t, api.TaskStateRunning, newTask.DesiredState) @@ -366,10 +366,10 @@ func TestOrchestratorRestartOnNone(t *testing.T) { newTask := store.GetTask(tx, newTask.ID) require.NotNil(t, newTask) newTask.Status.State = api.TaskStateRunning - assert.NoError(t, store.UpdateTask(tx, newTask)) + require.NoError(t, store.UpdateTask(tx, newTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, api.EventCreateTask{}) @@ -415,33 +415,33 @@ func TestOrchestratorRestartDelay(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, j1)) + require.NoError(t, store.CreateService(tx, j1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Fail the first task. Confirm that it gets restarted. updatedTask1 := observedTask1.Copy() updatedTask1.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} before := time.Now() err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) @@ -449,22 +449,20 @@ func TestOrchestratorRestartDelay(t *testing.T) { observedTask3 := testutils.WatchTaskCreate(t, watch) testutils.Expect(t, watch, state.EventCommit{}) - assert.Equal(t, observedTask3.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask3.DesiredState, api.TaskStateReady) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask3.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask3.DesiredState) + assert.Equal(t, "name1", observedTask3.ServiceAnnotations.Name) observedTask4 := testutils.WatchTaskUpdate(t, watch) after := time.Now() // At least 100 ms should have elapsed. Only check the lower bound, // because the system may be slow and it could have taken longer. - if after.Sub(before) < 100*time.Millisecond { - t.Fatalf("restart delay should have elapsed. Got: %v", after.Sub(before)) - } + require.GreaterOrEqualf(t, after.Sub(before), 100*time.Millisecond, "restart delay should have elapsed. Got: %v", after.Sub(before)) - assert.Equal(t, observedTask4.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask4.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask4.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask4.DesiredState) + assert.Equal(t, "name1", observedTask4.ServiceAnnotations.Name) } func TestOrchestratorRestartMaxAttempts(t *testing.T) { @@ -511,46 +509,46 @@ func TestOrchestratorRestartMaxAttempts(t *testing.T) { Index: 1, }, } - assert.NoError(t, store.CreateService(tx, j1)) + require.NoError(t, store.CreateService(tx, j1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() failTask := func(task *api.Task, expectRestart bool) { task = task.Copy() task.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) task = testutils.WatchShutdownTask(t, watch) if expectRestart { createdTask := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, createdTask.Status.State, api.TaskStateNew) - assert.Equal(t, createdTask.DesiredState, api.TaskStateReady) - assert.Equal(t, createdTask.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, createdTask.Status.State) + assert.Equal(t, api.TaskStateReady, createdTask.DesiredState) + assert.Equal(t, "name1", createdTask.ServiceAnnotations.Name) } err = s.Update(func(tx store.Tx) error { task := task.Copy() task.Status.State = api.TaskStateShutdown - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) } testRestart := func(serviceUpdated bool) { observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) if serviceUpdated { runnableTask := testutils.WatchTaskUpdate(t, watch) @@ -559,17 +557,17 @@ func TestOrchestratorRestartMaxAttempts(t *testing.T) { err = s.Update(func(tx store.Tx) error { task := runnableTask.Copy() task.Status.State = api.TaskStateRunning - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) } observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) if serviceUpdated { testutils.Expect(t, watch, api.EventUpdateTask{}) @@ -584,21 +582,19 @@ func TestOrchestratorRestartMaxAttempts(t *testing.T) { // At least 100 ms should have elapsed. Only check the lower bound, // because the system may be slow and it could have taken longer. - if after.Sub(before) < 100*time.Millisecond { - t.Fatal("restart delay should have elapsed") - } + require.GreaterOrEqual(t, after.Sub(before), 100*time.Millisecond, "restart delay should have elapsed") - assert.Equal(t, observedTask4.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask4.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask4.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask4.DesiredState) + assert.Equal(t, "name1", observedTask4.ServiceAnnotations.Name) // Fail the second task. Confirm that it gets restarted. failTask(observedTask2, true) observedTask6 := testutils.WatchTaskUpdate(t, watch) // task gets started after a delay - assert.Equal(t, observedTask6.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask6.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask6.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask6.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask6.DesiredState) + assert.Equal(t, "name1", observedTask6.ServiceAnnotations.Name) // Fail the first instance again. It should not be restarted. failTask(observedTask4, false) @@ -627,10 +623,10 @@ func TestOrchestratorRestartMaxAttempts(t *testing.T) { require.NotNil(t, s) s.Spec.Task.GetContainer().Image = "newimage" s.SpecVersion.Index = 2 - assert.NoError(t, store.UpdateService(tx, s)) + require.NoError(t, store.UpdateService(tx, s)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testRestart(true) } @@ -674,33 +670,33 @@ func TestOrchestratorRestartWindow(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, j1)) + require.NoError(t, store.CreateService(tx, j1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. go func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }() observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Fail the first task. Confirm that it gets restarted. updatedTask1 := observedTask1.Copy() updatedTask1.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} before := time.Now() err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) @@ -708,31 +704,29 @@ func TestOrchestratorRestartWindow(t *testing.T) { observedTask3 := testutils.WatchTaskCreate(t, watch) testutils.Expect(t, watch, state.EventCommit{}) - assert.Equal(t, observedTask3.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask3.DesiredState, api.TaskStateReady) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask3.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask3.DesiredState) + assert.Equal(t, "name1", observedTask3.ServiceAnnotations.Name) observedTask4 := testutils.WatchTaskUpdate(t, watch) after := time.Now() // At least 100 ms should have elapsed. Only check the lower bound, // because the system may be slow and it could have taken longer. - if after.Sub(before) < 100*time.Millisecond { - t.Fatal("restart delay should have elapsed") - } + require.GreaterOrEqual(t, after.Sub(before), 100*time.Millisecond, "restart delay should have elapsed") - assert.Equal(t, observedTask4.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask4.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask4.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask4.DesiredState) + assert.Equal(t, "name1", observedTask4.ServiceAnnotations.Name) // Fail the second task. Confirm that it gets restarted. updatedTask2 := observedTask2.Copy() updatedTask2.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) @@ -740,24 +734,24 @@ func TestOrchestratorRestartWindow(t *testing.T) { observedTask5 := testutils.WatchTaskCreate(t, watch) testutils.Expect(t, watch, state.EventCommit{}) - assert.Equal(t, observedTask5.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask5.DesiredState, api.TaskStateReady) - assert.Equal(t, observedTask5.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask5.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask5.DesiredState) + assert.Equal(t, "name1", observedTask5.ServiceAnnotations.Name) observedTask6 := testutils.WatchTaskUpdate(t, watch) // task gets started after a delay testutils.Expect(t, watch, state.EventCommit{}) - assert.Equal(t, observedTask6.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask6.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask6.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask6.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask6.DesiredState) + assert.Equal(t, "name1", observedTask6.ServiceAnnotations.Name) // Fail the first instance again. It should not be restarted. updatedTask1 = observedTask3.Copy() updatedTask1.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) @@ -777,29 +771,27 @@ func TestOrchestratorRestartWindow(t *testing.T) { updatedTask2.Status = api.TaskStatus{State: api.TaskStateFailed, Timestamp: ptypes.MustTimestampProto(time.Now())} before = time.Now() err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) testutils.Expect(t, watch, api.EventUpdateTask{}) testutils.Expect(t, watch, state.EventCommit{}) testutils.Expect(t, watch, api.EventUpdateTask{}) observedTask7 := testutils.WatchTaskCreate(t, watch) testutils.Expect(t, watch, state.EventCommit{}) - assert.Equal(t, observedTask7.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask7.DesiredState, api.TaskStateReady) + assert.Equal(t, api.TaskStateNew, observedTask7.Status.State) + assert.Equal(t, api.TaskStateReady, observedTask7.DesiredState) observedTask8 := testutils.WatchTaskUpdate(t, watch) after = time.Now() // At least 100 ms should have elapsed. Only check the lower bound, // because the system may be slow and it could have taken longer. - if after.Sub(before) < 100*time.Millisecond { - t.Fatal("restart delay should have elapsed") - } + require.GreaterOrEqual(t, after.Sub(before), 100*time.Millisecond, "restart delay should have elapsed") - assert.Equal(t, observedTask8.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask8.DesiredState, api.TaskStateRunning) - assert.Equal(t, observedTask8.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask8.Status.State) + assert.Equal(t, api.TaskStateRunning, observedTask8.DesiredState) + assert.Equal(t, "name1", observedTask8.ServiceAnnotations.Name) } diff --git a/manager/orchestrator/replicated/update_test.go b/manager/orchestrator/replicated/update_test.go index a44b86ad38..34ddb5278f 100644 --- a/manager/orchestrator/replicated/update_test.go +++ b/manager/orchestrator/replicated/update_test.go @@ -101,14 +101,14 @@ func testUpdaterRollback(t *testing.T, rollbackFailureAction api.UpdateConfig_Fa } return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } else if task.DesiredState > api.TaskStateRunning { err := s.Update(func(tx store.Tx) error { task = store.GetTask(tx, task.ID) task.Status.State = task.DesiredState return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } } }) @@ -163,10 +163,10 @@ func testUpdaterRollback(t *testing.T, rollbackFailureAction api.UpdateConfig_Fa } } - assert.NoError(t, store.CreateService(tx, s1)) + require.NoError(t, store.CreateService(tx, s1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. var orchestratorError error @@ -179,25 +179,25 @@ func testUpdaterRollback(t *testing.T, rollbackFailureAction api.UpdateConfig_Fa select { case <-ctx.Done(): case <-orchestratorDone: - assert.NoError(t, orchestratorError) + require.NoError(t, orchestratorError) } }() observedTask := testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) // Start a rolling update err = s.Update(func(tx store.Tx) error { @@ -210,24 +210,24 @@ func testUpdaterRollback(t *testing.T, rollbackFailureAction api.UpdateConfig_Fa if s1.SpecVersion != nil { s1.SpecVersion.Index = 2 } - assert.NoError(t, store.UpdateService(tx, s1)) + require.NoError(t, store.UpdateService(tx, s1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Should see three tasks started, then a rollback observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image2") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image2", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image2") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image2", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image2") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image2", observedTask.Spec.GetContainer().Image) // Should get to the ROLLBACK_STARTED state for { @@ -247,16 +247,16 @@ func testUpdaterRollback(t *testing.T, rollbackFailureAction api.UpdateConfig_Fa } observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) if !setMonitor { // Exit early in this case, since it would take a long time for @@ -296,24 +296,24 @@ func testUpdaterRollback(t *testing.T, rollbackFailureAction api.UpdateConfig_Fa if s1.SpecVersion != nil { s1.SpecVersion.Index = 2 } - assert.NoError(t, store.UpdateService(tx, s1)) + require.NoError(t, store.UpdateService(tx, s1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Should see three tasks started, then a rollback observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image2") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image2", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image2") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image2", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image2") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image2", observedTask.Spec.GetContainer().Image) // Should get to the ROLLBACK_STARTED state for { @@ -333,16 +333,16 @@ func testUpdaterRollback(t *testing.T, rollbackFailureAction api.UpdateConfig_Fa } observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) observedTask = testutils.WatchTaskCreate(t, watchCreate) - assert.Equal(t, observedTask.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask.Spec.GetContainer().Image, "image1") + assert.Equal(t, api.TaskStateNew, observedTask.Status.State) + assert.Equal(t, "image1", observedTask.Spec.GetContainer().Image) switch rollbackFailureAction { case api.UpdateConfig_PAUSE: diff --git a/manager/orchestrator/service_test.go b/manager/orchestrator/service_test.go index e103436f6c..ab1d60c812 100644 --- a/manager/orchestrator/service_test.go +++ b/manager/orchestrator/service_test.go @@ -20,16 +20,16 @@ func TestIsReplicatedJob(t *testing.T) { // cannot be easily assigned to the same type service.Spec.Mode = &api.ServiceSpec_ReplicatedJob{} - assert.Equal(t, IsReplicatedJob(service), true) + assert.True(t, IsReplicatedJob(service)) service.Spec.Mode = &api.ServiceSpec_GlobalJob{} - assert.Equal(t, IsReplicatedJob(service), false) + assert.False(t, IsReplicatedJob(service)) service.Spec.Mode = &api.ServiceSpec_Replicated{} - assert.Equal(t, IsReplicatedJob(service), false) + assert.False(t, IsReplicatedJob(service)) service.Spec.Mode = &api.ServiceSpec_Global{} - assert.Equal(t, IsReplicatedJob(service), false) + assert.False(t, IsReplicatedJob(service)) } // TestIsGlobalJob tests that IsGlobalJob only returns true when the @@ -48,14 +48,14 @@ func TestIsGlobalJob(t *testing.T) { // cannot be easily assigned to the same type service.Spec.Mode = &api.ServiceSpec_ReplicatedJob{} - assert.Equal(t, IsGlobalJob(service), false) + assert.False(t, IsGlobalJob(service)) service.Spec.Mode = &api.ServiceSpec_GlobalJob{} - assert.Equal(t, IsGlobalJob(service), true) + assert.True(t, IsGlobalJob(service)) service.Spec.Mode = &api.ServiceSpec_Replicated{} - assert.Equal(t, IsGlobalJob(service), false) + assert.False(t, IsGlobalJob(service)) service.Spec.Mode = &api.ServiceSpec_Global{} - assert.Equal(t, IsGlobalJob(service), false) + assert.False(t, IsGlobalJob(service)) } diff --git a/manager/orchestrator/taskreaper/task_reaper_test.go b/manager/orchestrator/taskreaper/task_reaper_test.go index e4e53bde29..1071c1c5ef 100644 --- a/manager/orchestrator/taskreaper/task_reaper_test.go +++ b/manager/orchestrator/taskreaper/task_reaper_test.go @@ -207,7 +207,7 @@ func TestTaskHistory(t *testing.T) { assert.NotNil(t, s) defer s.Close() - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ @@ -253,24 +253,24 @@ func TestTaskHistory(t *testing.T) { }, }, } - assert.NoError(t, store.CreateService(tx, j1)) + require.NoError(t, store.CreateService(tx, j1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) testutils.EnsureRuns(func() { taskReaper.Run(ctx) }) observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Fail both tasks. They should both get restarted. updatedTask1 := observedTask1.Copy() @@ -280,8 +280,8 @@ func TestTaskHistory(t *testing.T) { updatedTask2.Status.State = api.TaskStateFailed updatedTask2.ServiceAnnotations = api.Annotations{Name: "original"} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) @@ -292,13 +292,13 @@ func TestTaskHistory(t *testing.T) { testutils.Expect(t, watch, api.EventUpdateTask{}) observedTask3 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask3.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask3.Status.State) + assert.Equal(t, "name1", observedTask3.ServiceAnnotations.Name) testutils.Expect(t, watch, api.EventUpdateTask{}) observedTask4 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask4.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask4.Status.State) + assert.Equal(t, "name1", observedTask4.ServiceAnnotations.Name) // Fail these replacement tasks. Since TaskHistory is set to 2, this // should cause the oldest tasks for each instance to get deleted. @@ -307,8 +307,8 @@ func TestTaskHistory(t *testing.T) { updatedTask4 := observedTask4.Copy() updatedTask4.Status.State = api.TaskStateFailed err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask3)) - assert.NoError(t, store.UpdateTask(tx, updatedTask4)) + require.NoError(t, store.UpdateTask(tx, updatedTask3)) + require.NoError(t, store.UpdateTask(tx, updatedTask4)) return nil }) @@ -324,7 +324,7 @@ func TestTaskHistory(t *testing.T) { s.View(func(tx store.ReadTx) { foundTasks, err = store.FindTasks(tx, store.All) }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 4) } @@ -338,7 +338,7 @@ func TestTaskStateRemoveOnScaledown(t *testing.T) { assert.NotNil(t, s) defer s.Close() - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ @@ -388,22 +388,22 @@ func TestTaskStateRemoveOnScaledown(t *testing.T) { // started. This should result in two tasks when the orchestrator // starts up. err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. - testutils.EnsureRuns(func() { assert.NoError(t, orchestrator.Run(ctx)) }) + testutils.EnsureRuns(func() { require.NoError(t, orchestrator.Run(ctx)) }) testutils.EnsureRuns(func() { taskReaper.Run(ctx) }) observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Set both tasks to RUNNING, so the service is successfully running updatedTask1 := observedTask1.Copy() @@ -413,8 +413,8 @@ func TestTaskStateRemoveOnScaledown(t *testing.T) { updatedTask2.Status.State = api.TaskStateRunning updatedTask2.ServiceAnnotations = api.Annotations{Name: "original"} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) @@ -427,13 +427,13 @@ func TestTaskStateRemoveOnScaledown(t *testing.T) { // statuses to be set to REMOVE. service1.Spec.GetReplicated().Replicas = 1 err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateService(tx, service1)) + require.NoError(t, store.UpdateService(tx, service1)) return nil }) observedTask3 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask3.DesiredState, api.TaskStateRemove) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "original") + assert.Equal(t, api.TaskStateRemove, observedTask3.DesiredState) + assert.Equal(t, "original", observedTask3.ServiceAnnotations.Name) testutils.Expect(t, watch, state.EventCommit{}) @@ -442,7 +442,7 @@ func TestTaskStateRemoveOnScaledown(t *testing.T) { updatedTask3 := observedTask3.Copy() updatedTask3.Status.State = api.TaskStateShutdown err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask3)) + require.NoError(t, store.UpdateTask(tx, updatedTask3)) return nil }) @@ -455,7 +455,7 @@ func TestTaskStateRemoveOnScaledown(t *testing.T) { s.View(func(tx store.ReadTx) { foundTasks, err = store.FindTasks(tx, store.All) }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) } @@ -469,7 +469,7 @@ func TestTaskStateRemoveOnServiceRemoval(t *testing.T) { assert.NotNil(t, s) defer s.Close() - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ @@ -518,24 +518,24 @@ func TestTaskStateRemoveOnServiceRemoval(t *testing.T) { // started. This should result in two tasks when the orchestrator // starts up. err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) testutils.EnsureRuns(func() { taskReaper.Run(ctx) }) observedTask1 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask1.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) - assert.Equal(t, observedTask2.Status.State, api.TaskStateNew) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Set both tasks to RUNNING, so the service is successfully running updatedTask1 := observedTask1.Copy() @@ -545,8 +545,8 @@ func TestTaskStateRemoveOnServiceRemoval(t *testing.T) { updatedTask2.Status.State = api.TaskStateRunning updatedTask2.ServiceAnnotations = api.Annotations{Name: "original"} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) @@ -557,16 +557,16 @@ func TestTaskStateRemoveOnServiceRemoval(t *testing.T) { // Delete the service. This should trigger both the task desired statuses to be set to REMOVE. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteService(tx, service1.ID)) + require.NoError(t, store.DeleteService(tx, service1.ID)) return nil }) observedTask3 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask3.DesiredState, api.TaskStateRemove) - assert.Equal(t, observedTask3.ServiceAnnotations.Name, "original") + assert.Equal(t, api.TaskStateRemove, observedTask3.DesiredState) + assert.Equal(t, "original", observedTask3.ServiceAnnotations.Name) observedTask4 := testutils.WatchTaskUpdate(t, watch) - assert.Equal(t, observedTask4.DesiredState, api.TaskStateRemove) - assert.Equal(t, observedTask4.ServiceAnnotations.Name, "original") + assert.Equal(t, api.TaskStateRemove, observedTask4.DesiredState) + assert.Equal(t, "original", observedTask4.ServiceAnnotations.Name) testutils.Expect(t, watch, state.EventCommit{}) @@ -577,8 +577,8 @@ func TestTaskStateRemoveOnServiceRemoval(t *testing.T) { updatedTask4 := observedTask4.Copy() updatedTask4.Status.State = api.TaskStateShutdown err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask3)) - assert.NoError(t, store.UpdateTask(tx, updatedTask4)) + require.NoError(t, store.UpdateTask(tx, updatedTask3)) + require.NoError(t, store.UpdateTask(tx, updatedTask4)) return nil }) @@ -594,8 +594,8 @@ func TestTaskStateRemoveOnServiceRemoval(t *testing.T) { s.View(func(tx store.ReadTx) { foundTasks, err = store.FindTasks(tx, store.All) }) - assert.NoError(t, err) - assert.Len(t, foundTasks, 0) + require.NoError(t, err) + assert.Empty(t, foundTasks) } // TestServiceRemoveDeadTasks tests removal of dead tasks @@ -606,7 +606,7 @@ func TestServiceRemoveDeadTasks(t *testing.T) { assert.NotNil(t, s) defer s.Close() - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ @@ -656,24 +656,24 @@ func TestServiceRemoveDeadTasks(t *testing.T) { // started. This should result in two tasks when the orchestrator // starts up. err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator and the reaper. testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) testutils.EnsureRuns(func() { taskReaper.Run(ctx) }) observedTask1 := testutils.WatchTaskCreate(t, watch) assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask2 := testutils.WatchTaskCreate(t, watch) assert.Equal(t, api.TaskStateNew, observedTask2.Status.State) - assert.Equal(t, observedTask2.ServiceAnnotations.Name, "name1") + assert.Equal(t, "name1", observedTask2.ServiceAnnotations.Name) // Set both task states to RUNNING. updatedTask1 := observedTask1.Copy() @@ -683,8 +683,8 @@ func TestServiceRemoveDeadTasks(t *testing.T) { updatedTask2.Status.State = api.TaskStateRunning updatedTask2.ServiceAnnotations = api.Annotations{Name: "original"} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) - assert.NoError(t, store.UpdateTask(tx, updatedTask2)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask2)) return nil }) require.NoError(t, err) @@ -704,8 +704,8 @@ func TestServiceRemoveDeadTasks(t *testing.T) { updatedTask4.Status.State = api.TaskStateCompleted updatedTask4.ServiceAnnotations = api.Annotations{Name: "original"} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask3)) - assert.NoError(t, store.UpdateTask(tx, updatedTask4)) + require.NoError(t, store.UpdateTask(tx, updatedTask3)) + require.NoError(t, store.UpdateTask(tx, updatedTask4)) return nil }) require.NoError(t, err) @@ -720,7 +720,7 @@ func TestServiceRemoveDeadTasks(t *testing.T) { // Delete the service. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteService(tx, service1.ID)) + require.NoError(t, store.DeleteService(tx, service1.ID)) return nil }) @@ -748,8 +748,8 @@ func TestServiceRemoveDeadTasks(t *testing.T) { s.View(func(tx store.ReadTx) { foundTasks, err = store.FindTasks(tx, store.All) }) - assert.NoError(t, err) - assert.Len(t, foundTasks, 0) + require.NoError(t, err) + assert.Empty(t, foundTasks) } // TestTaskReaperBatching tests that the batching logic for the task reaper @@ -767,10 +767,10 @@ func TestTaskReaperBatching(t *testing.T) { ) // set up all of the test fixtures - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { // we need a cluster object, because we need to set the retention limit // to a low value - assert.NoError(t, store.CreateCluster(tx, &api.Cluster{ + require.NoError(t, store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ Annotations: api.Annotations{ @@ -793,7 +793,7 @@ func TestTaskReaperBatching(t *testing.T) { } // we need to create all of the tasks used in this test, because we'll // be using task update events to trigger reaper behavior. - assert.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task1)) task2 = &api.Task{ ID: "foo2", @@ -804,7 +804,7 @@ func TestTaskReaperBatching(t *testing.T) { State: api.TaskStateShutdown, }, } - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateTask(tx, task2)) tasks = make([]*api.Task, maxDirty+1) for i := 0; i < maxDirty+1; i++ { @@ -833,7 +833,7 @@ func TestTaskReaperBatching(t *testing.T) { State: api.TaskStateShutdown, }, } - assert.NoError(t, store.CreateTask(tx, task3)) + require.NoError(t, store.CreateTask(tx, task3)) return nil })) @@ -854,7 +854,7 @@ func TestTaskReaperBatching(t *testing.T) { } // update task1 to die - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { task1.DesiredState = api.TaskStateRemove return store.UpdateTask(tx, task1) })) @@ -875,7 +875,7 @@ func TestTaskReaperBatching(t *testing.T) { } // now make sure we'll tick again if we update another task to die - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { task2.DesiredState = api.TaskStateRemove return store.UpdateTask(tx, task2) })) @@ -897,10 +897,10 @@ func TestTaskReaperBatching(t *testing.T) { // waiting. we should easily within the batching interval be able to // process all of these events, and should expect 1 tick immediately after // and no more - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { for _, task := range tasks { task.DesiredState = api.TaskStateRemove - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) } return nil })) @@ -925,7 +925,7 @@ func TestTaskReaperBatching(t *testing.T) { // now before we wrap up, make sure the task reaper still works off the // timer - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { task3.DesiredState = api.TaskStateRemove return store.UpdateTask(tx, task3) })) @@ -952,7 +952,7 @@ func TestServiceRemoveUnassignedTasks(t *testing.T) { assert.NotNil(t, s) defer s.Close() - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ @@ -1002,27 +1002,27 @@ func TestServiceRemoveUnassignedTasks(t *testing.T) { // started. This should result in one tasks when the orchestrator // starts up. err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Start the orchestrator. testutils.EnsureRuns(func() { - assert.NoError(t, orchestrator.Run(ctx)) + require.NoError(t, orchestrator.Run(ctx)) }) testutils.EnsureRuns(func() { taskReaper.Run(ctx) }) observedTask1 := testutils.WatchTaskCreate(t, watch) assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) // Set the task state to PENDING to simulate allocation. updatedTask1 := observedTask1.Copy() updatedTask1.Status.State = api.TaskStatePending updatedTask1.ServiceAnnotations = api.Annotations{Name: "original"} err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, updatedTask1)) + require.NoError(t, store.UpdateTask(tx, updatedTask1)) return nil }) require.NoError(t, err) @@ -1034,7 +1034,7 @@ func TestServiceRemoveUnassignedTasks(t *testing.T) { service1.Spec.Task.ForceUpdate++ // This should shutdown the previous task and create a new one. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateService(tx, service1)) + require.NoError(t, store.UpdateService(tx, service1)) return nil }) testutils.Expect(t, watch, api.EventUpdateService{}) @@ -1043,7 +1043,7 @@ func TestServiceRemoveUnassignedTasks(t *testing.T) { // New task should be created and old task marked for SHUTDOWN. observedTask1 = testutils.WatchTaskCreate(t, watch) assert.Equal(t, api.TaskStateNew, observedTask1.Status.State) - assert.Equal(t, observedTask1.ServiceAnnotations.Name, "name1") + assert.Equal(t, "name1", observedTask1.ServiceAnnotations.Name) observedTask3 := testutils.WatchTaskUpdate(t, watch) assert.Equal(t, api.TaskStateShutdown, observedTask3.DesiredState) @@ -1062,7 +1062,7 @@ func TestServiceRemoveUnassignedTasks(t *testing.T) { s.View(func(tx store.ReadTx) { foundTasks, err = store.FindTasks(tx, store.All) }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) } @@ -1101,7 +1101,7 @@ func TestTick(t *testing.T) { setupTaskReaperDirty(taskReaper) // call tick directly and verify dirty set was cleaned up. taskReaper.tick() - assert.Zero(t, len(taskReaper.dirty)) + assert.Empty(t, taskReaper.dirty) // Test # 2 // Verify that the dirty set it cleaned up @@ -1153,11 +1153,11 @@ func TestTick(t *testing.T) { // Create a service. err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) - assert.NoError(t, store.CreateService(tx, service2)) + require.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Setup the dirty set with entries to // verify that the dirty set it cleaned up @@ -1166,7 +1166,7 @@ func TestTick(t *testing.T) { taskReaper.taskHistory = 0 // call tick directly and verify dirty set was cleaned up. taskReaper.tick() - assert.Zero(t, len(taskReaper.dirty)) + assert.Empty(t, taskReaper.dirty) // Test # 3 // Test that the tasks are cleanup when the total number of tasks @@ -1201,11 +1201,11 @@ func TestTick(t *testing.T) { // Create Tasks. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task1)) - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Set history to 1 to ensure that the tasks are not cleaned up yet. // At the same time, we should be able to test that the dirty set was @@ -1214,7 +1214,7 @@ func TestTick(t *testing.T) { setupTaskReaperDirty(taskReaper) // call tick directly and verify dirty set was cleaned up. taskReaper.tick() - assert.Zero(t, len(taskReaper.dirty)) + assert.Empty(t, taskReaper.dirty) // Now test that tick() function cleans up the old tasks from the store. @@ -1226,11 +1226,11 @@ func TestTick(t *testing.T) { task2.DesiredState = api.TaskStateRunning task2.ID = "id2task2" err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task1)) - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) watch, cancel := state.Watch(s.WatchQueue() /*api.EventCreateTask{}, api.EventUpdateTask{}*/) defer cancel() @@ -1239,7 +1239,7 @@ func TestTick(t *testing.T) { setupTaskReaperDirty(taskReaper) // Call tick directly and verify dirty set was cleaned up. taskReaper.tick() - assert.Zero(t, len(taskReaper.dirty)) + assert.Empty(t, taskReaper.dirty) // Task reaper should delete the task previously marked for SHUTDOWN. deletedTask1 := testutils.WatchTaskDelete(t, watch) assert.Equal(t, api.TaskStateShutdown, deletedTask1.Status.State) @@ -1285,7 +1285,7 @@ func TestTickHistoryCleanup(t *testing.T) { } s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateService(tx, service1)) return nil }) @@ -1317,14 +1317,14 @@ func TestTickHistoryCleanup(t *testing.T) { }, } s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task3)) + require.NoError(t, store.CreateTask(tx, task3)) return nil }) } else { task.DesiredState = desiredState task.Status.State = actualState s.Update(func(tx store.Tx) error { - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) return nil }) } @@ -1378,7 +1378,7 @@ func TestTickHistoryCleanup(t *testing.T) { {desired: api.TaskStateShutdown, actual: api.TaskStateOrphaned, cleanedUp: true}, } { testfunc(testcase.desired, testcase.actual) - assert.Zero(t, len(taskReaper.dirty)) + assert.Empty(t, taskReaper.dirty) if testcase.cleanedUp { waitForTaskDelete(testcase.desired, testcase.actual) } diff --git a/manager/orchestrator/update/updater_test.go b/manager/orchestrator/update/updater_test.go index 6d16cb5fe4..70e4e00ca8 100644 --- a/manager/orchestrator/update/updater_test.go +++ b/manager/orchestrator/update/updater_test.go @@ -48,7 +48,7 @@ func getRunningServiceTasks(t *testing.T, s *store.MemoryStore, service *api.Ser s.View(func(tx store.ReadTx) { tasks, err = store.FindTasks(tx, store.ByServiceID(service.ID)) }) - assert.NoError(t, err) + require.NoError(t, err) running := []*api.Task{} for _, task := range tasks { @@ -79,7 +79,7 @@ func TestUpdater(t *testing.T) { task.Status.State = task.DesiredState return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } }() @@ -120,14 +120,14 @@ func TestUpdater(t *testing.T) { // Create the cluster, service, and tasks for the service. err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateCluster(tx, cluster)) - assert.NoError(t, store.CreateService(tx, service)) + require.NoError(t, store.CreateCluster(tx, cluster)) + require.NoError(t, store.CreateService(tx, service)) for i := 0; i < instances; i++ { - assert.NoError(t, store.CreateTask(tx, orchestrator.NewTask(cluster, service, uint64(i), ""))) + require.NoError(t, store.CreateTask(tx, orchestrator.NewTask(cluster, service, uint64(i), ""))) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) originalTasks := getRunnableSlotSlice(t, s, service) for _, slot := range originalTasks { @@ -194,7 +194,7 @@ func TestUpdater(t *testing.T) { updater = NewUpdater(s, restart.NewSupervisor(s), cluster, service) updater.Run(ctx, getRunnableSlotSlice(t, s, service)) updatedTasks = getRunnableSlotSlice(t, s, service) - assert.Equal(t, instances, len(updatedTasks)) + assert.Len(t, updatedTasks, instances) for _, instance := range updatedTasks { for _, task := range instance { assert.Equal(t, "v:5", task.Spec.GetContainer().Image) @@ -228,14 +228,14 @@ func TestUpdater(t *testing.T) { // Update the desired state of the tasks to SHUTDOWN to simulate the // case where images failed to pull due to bad registry auth. taskSlots := make([]orchestrator.Slot, len(updatedTasks)) - assert.NoError(t, s.Update(func(tx store.Tx) error { + require.NoError(t, s.Update(func(tx store.Tx) error { for i, slot := range updatedTasks { taskSlots[i] = make(orchestrator.Slot, len(slot)) for j, task := range slot { task = store.GetTask(tx, task.ID) task.DesiredState = api.TaskStateShutdown task.Status.State = task.DesiredState - assert.NoError(t, store.UpdateTask(tx, task)) + require.NoError(t, store.UpdateTask(tx, task)) taskSlots[i][j] = task } } @@ -272,7 +272,7 @@ func TestUpdaterPlacement(t *testing.T) { task.Status.State = task.DesiredState return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } }() @@ -316,15 +316,15 @@ func TestUpdaterPlacement(t *testing.T) { // Create the cluster, service, and tasks for the service. err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateCluster(tx, cluster)) - assert.NoError(t, store.CreateService(tx, service)) + require.NoError(t, store.CreateCluster(tx, cluster)) + require.NoError(t, store.CreateService(tx, service)) store.CreateNode(tx, node) for i := 0; i < instances; i++ { - assert.NoError(t, store.CreateTask(tx, orchestrator.NewTask(cluster, service, uint64(i), "node1"))) + require.NoError(t, store.CreateTask(tx, orchestrator.NewTask(cluster, service, uint64(i), "node1"))) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) originalTasks := getRunnableSlotSlice(t, s, service) originalTasksMaps := make([]map[string]*api.Task, len(originalTasks)) @@ -382,14 +382,14 @@ func TestUpdaterFailureAction(t *testing.T) { task.Status.State = api.TaskStateFailed return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } else if task.DesiredState > api.TaskStateRunning { err := s.Update(func(tx store.Tx) error { task = store.GetTask(tx, task.ID) task.Status.State = task.DesiredState return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } } }() @@ -431,14 +431,14 @@ func TestUpdaterFailureAction(t *testing.T) { } err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateCluster(tx, cluster)) - assert.NoError(t, store.CreateService(tx, service)) + require.NoError(t, store.CreateCluster(tx, cluster)) + require.NoError(t, store.CreateService(tx, service)) for i := 0; i < instances; i++ { - assert.NoError(t, store.CreateTask(tx, orchestrator.NewTask(cluster, service, uint64(i), ""))) + require.NoError(t, store.CreateTask(tx, orchestrator.NewTask(cluster, service, uint64(i), ""))) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) originalTasks := getRunnableSlotSlice(t, s, service) for _, slot := range originalTasks { @@ -493,10 +493,10 @@ func TestUpdaterFailureAction(t *testing.T) { service = store.GetService(tx, service.ID) service.Spec.Update.FailureAction = api.UpdateConfig_CONTINUE service.UpdateStatus = nil - assert.NoError(t, store.UpdateService(tx, service)) + require.NoError(t, store.UpdateService(tx, service)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) service.Spec.Task.GetContainer().Image = "v:3" updater = NewUpdater(s, restart.NewSupervisor(s), cluster, service) @@ -540,7 +540,7 @@ func TestUpdaterTaskTimeout(t *testing.T) { } return nil }) - assert.NoError(t, err) + require.NoError(t, err) } }() @@ -571,15 +571,15 @@ func TestUpdaterTaskTimeout(t *testing.T) { } err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service)) + require.NoError(t, store.CreateService(tx, service)) for i := uint64(0); i < instances; i++ { task := orchestrator.NewTask(nil, service, uint64(i), "") task.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) originalTasks := getRunnableSlotSlice(t, s, service) for _, slot := range originalTasks { @@ -606,9 +606,7 @@ func TestUpdaterTaskTimeout(t *testing.T) { // At least 100 ms should have elapsed. Only check the lower bound, // because the system may be slow and it could have taken longer. - if after.Sub(before) < 100*time.Millisecond { - t.Fatal("stop timeout should have elapsed") - } + require.GreaterOrEqual(t, after.Sub(before), 100*time.Millisecond, "stop timeout should have elapsed") } func TestUpdaterOrder(t *testing.T) { @@ -634,7 +632,7 @@ func TestUpdaterOrder(t *testing.T) { task.Status.State = task.DesiredState return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } }() @@ -662,13 +660,13 @@ func TestUpdaterOrder(t *testing.T) { } err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service)) + require.NoError(t, store.CreateService(tx, service)) for i := 0; i < instances; i++ { - assert.NoError(t, store.CreateTask(tx, orchestrator.NewTask(nil, service, uint64(i), ""))) + require.NoError(t, store.CreateTask(tx, orchestrator.NewTask(nil, service, uint64(i), ""))) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) originalTasks := getRunnableSlotSlice(t, s, service) for _, instance := range originalTasks { @@ -680,7 +678,7 @@ func TestUpdaterOrder(t *testing.T) { task.Status.State = task.DesiredState return store.UpdateTask(tx, task) }) - assert.NoError(t, err) + require.NoError(t, err) } } service.Spec.Task.GetContainer().Image = "v:2" @@ -693,12 +691,12 @@ func TestUpdaterOrder(t *testing.T) { updater := NewUpdater(s, restart.NewSupervisor(s), nil, service) updater.Run(ctx, getRunnableSlotSlice(t, s, service)) allTasks := getRunningServiceTasks(t, s, service) - assert.Equal(t, instances*2, len(allTasks)) + assert.Len(t, allTasks, instances*2) for _, task := range allTasks { if task.Spec.GetContainer().Image == "v:1" { - assert.Equal(t, task.DesiredState, api.TaskStateShutdown) + assert.Equal(t, api.TaskStateShutdown, task.DesiredState) } else if task.Spec.GetContainer().Image == "v:2" { - assert.Equal(t, task.DesiredState, api.TaskStateRunning) + assert.Equal(t, api.TaskStateRunning, task.DesiredState) } } } diff --git a/manager/scheduler/nodeinfo_test.go b/manager/scheduler/nodeinfo_test.go index 5494d4c81c..e9b0d895e4 100644 --- a/manager/scheduler/nodeinfo_test.go +++ b/manager/scheduler/nodeinfo_test.go @@ -83,7 +83,7 @@ func TestRemoveTask(t *testing.T) { assert.Equal(t, cpuLeft, nodeAvailableResources.NanoCPUs) assert.Equal(t, memoryLeft, nodeAvailableResources.MemoryBytes) - assert.Equal(t, 4, len(nodeAvailableResources.Generic)) + assert.Len(t, nodeAvailableResources.Generic, 4) apples := genericresource.GetResource("apple", nodeAvailableResources.Generic) oranges := genericresource.GetResource("orange", nodeAvailableResources.Generic) diff --git a/manager/scheduler/nodeset_test.go b/manager/scheduler/nodeset_test.go index b5ed4ba2b8..35096f9413 100644 --- a/manager/scheduler/nodeset_test.go +++ b/manager/scheduler/nodeset_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/moby/swarmkit/v2/api" + "github.com/stretchr/testify/assert" ) func TestTreeTaskCountConsistency(t *testing.T) { @@ -113,10 +114,8 @@ func TestTreeTaskCountConsistency(t *testing.T) { } // Verify parent's task count equals sum of children - if dt.tasks != childrenSum { - t.Errorf("Parent task count (%d) does not equal sum of children (%d)", - dt.tasks, childrenSum) - } + assert.Equalf(t, dt.tasks, childrenSum, "Parent task count (%d) does not equal sum of children (%d)", + dt.tasks, childrenSum) return dt.tasks } @@ -125,39 +124,26 @@ func TestTreeTaskCountConsistency(t *testing.T) { verifyTaskCounts(t, &tree) // Verify specific expected values - if tree.tasks != 12 { // Total tasks: 3 + 2 + 4 + 2 + 1 = 12 - t.Errorf("Expected root to have 12 tasks, got %d", tree.tasks) - } + // Total tasks: 3 + 2 + 4 + 2 + 1 = 12 + assert.Equalf(t, 12, tree.tasks, "Expected root to have 12 tasks, got %d", tree.tasks) dc1Tasks := tree.next["dc1"].tasks - if dc1Tasks != 5 { // dc1 tasks: 3 + 2 = 5 - t.Errorf("Expected dc1 to have 5 tasks, got %d", dc1Tasks) - } + // dc1 tasks: 3 + 2 = 5 + assert.Equalf(t, 5, dc1Tasks, "Expected dc1 to have 5 tasks, got %d", dc1Tasks) dc1r1Tasks := tree.next["dc1"].next["r1"].tasks - if dc1r1Tasks != 3 { - t.Errorf("Expected dc1 r1 to have 3 tasks, got %d", dc1r1Tasks) - } + assert.Equalf(t, 3, dc1r1Tasks, "Expected dc1 r1 to have 3 tasks, got %d", dc1r1Tasks) dc1r2Tasks := tree.next["dc1"].next["r2"].tasks - if dc1r2Tasks != 2 { - t.Errorf("Expected dc1 r1 to have 2 tasks, got %d", dc1r2Tasks) - } + assert.Equalf(t, 2, dc1r2Tasks, "Expected dc1 r1 to have 2 tasks, got %d", dc1r2Tasks) dc2Tasks := tree.next["dc2"].tasks - if dc2Tasks != 4 { // dc2 tasks: 4 - t.Errorf("Expected dc2 to have 4 tasks, got %d", dc2Tasks) - } + // dc2 tasks: 4 + assert.Equalf(t, 4, dc2Tasks, "Expected dc2 to have 4 tasks, got %d", dc2Tasks) dc2r2Tasks := tree.next["dc2"].next["r2"].tasks - if dc2r2Tasks != 4 { - t.Errorf("Expected dc1 r1 to have 4 tasks, got %d", dc1r2Tasks) - } + assert.Equalf(t, 4, dc2r2Tasks, "Expected dc1 r1 to have 4 tasks, got %d", dc1r2Tasks) otherTasks := tree.next[""].tasks - if otherTasks != 3 { - t.Errorf("Expected others to have 3 tasks, got %d", otherTasks) - } + assert.Equalf(t, 3, otherTasks, "Expected others to have 3 tasks, got %d", otherTasks) subOtherTasks := tree.next[""].next[""].tasks - if subOtherTasks != 3 { - t.Errorf("Expected sub-others to have 3 tasks, got %d", subOtherTasks) - } + assert.Equalf(t, 3, subOtherTasks, "Expected sub-others to have 3 tasks, got %d", subOtherTasks) } diff --git a/manager/scheduler/scheduler_test.go b/manager/scheduler/scheduler_test.go index 27053c01cd..cbd4ee47bb 100644 --- a/manager/scheduler/scheduler_test.go +++ b/manager/scheduler/scheduler_test.go @@ -99,16 +99,16 @@ func TestScheduler(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Prepopulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks for _, task := range initialTaskSet { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -116,7 +116,7 @@ func TestScheduler(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -136,16 +136,16 @@ func TestScheduler(t *testing.T) { // Update each node to make sure this doesn't mess up the // scheduler's state. for _, n := range initialNodeSet { - assert.NoError(t, store.UpdateNode(tx, n)) + require.NoError(t, store.UpdateNode(tx, n)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) err = s.Update(func(tx store.Tx) error { // Delete the task associated with node 1 so it's now the most lightly // loaded node. - assert.NoError(t, store.DeleteTask(tx, "id1")) + require.NoError(t, store.DeleteTask(tx, "id1")) // Create a new task. It should get assigned to id1. t4 := &api.Task{ @@ -158,10 +158,10 @@ func TestScheduler(t *testing.T) { State: api.TaskStatePending, }, } - assert.NoError(t, store.CreateTask(tx, t4)) + require.NoError(t, store.CreateTask(tx, t4)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment3 := watchAssignment(t, watch) assert.Equal(t, "id1", assignment3.NodeID) @@ -181,10 +181,10 @@ func TestScheduler(t *testing.T) { State: api.TaskStatePending, }, } - assert.NoError(t, store.UpdateTask(tx, t4)) + require.NoError(t, store.UpdateTask(tx, t4)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment4 := watchAssignment(t, watch) assert.Equal(t, "id1", assignment4.NodeID) @@ -203,8 +203,8 @@ func TestScheduler(t *testing.T) { State: api.NodeStatus_DOWN, }, } - assert.NoError(t, store.CreateNode(tx, node)) - assert.NoError(t, store.DeleteNode(tx, node.ID)) + require.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.DeleteNode(tx, node.ID)) // Create an unassigned task. task := &api.Task{ @@ -217,10 +217,10 @@ func TestScheduler(t *testing.T) { State: api.TaskStatePending, }, } - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignmentRemovedNode := watchAssignment(t, watch) assert.NotEqual(t, "removednode", assignmentRemovedNode.NodeID) @@ -239,7 +239,7 @@ func TestScheduler(t *testing.T) { State: api.NodeStatus_READY, }, } - assert.NoError(t, store.CreateNode(tx, n4)) + require.NoError(t, store.CreateNode(tx, n4)) // Create an unassigned task. t5 := &api.Task{ @@ -252,10 +252,10 @@ func TestScheduler(t *testing.T) { State: api.TaskStatePending, }, } - assert.NoError(t, store.CreateTask(tx, t5)) + require.NoError(t, store.CreateTask(tx, t5)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment5 := watchAssignment(t, watch) assert.Equal(t, "id4", assignment5.NodeID) @@ -274,7 +274,7 @@ func TestScheduler(t *testing.T) { State: api.NodeStatus_DOWN, }, } - assert.NoError(t, store.CreateNode(tx, n5)) + require.NoError(t, store.CreateNode(tx, n5)) // Create an unassigned task. t6 := &api.Task{ @@ -287,10 +287,10 @@ func TestScheduler(t *testing.T) { State: api.TaskStatePending, }, } - assert.NoError(t, store.CreateTask(tx, t6)) + require.NoError(t, store.CreateTask(tx, t6)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment6 := watchAssignment(t, watch) assert.NotEqual(t, "id5", assignment6.NodeID) @@ -308,7 +308,7 @@ func TestScheduler(t *testing.T) { State: api.NodeStatus_READY, }, } - assert.NoError(t, store.UpdateNode(tx, n5)) + require.NoError(t, store.UpdateNode(tx, n5)) // Create an unassigned task. Should be assigned to the // now-ready node. @@ -322,10 +322,10 @@ func TestScheduler(t *testing.T) { State: api.TaskStatePending, }, } - assert.NoError(t, store.CreateTask(tx, t7)) + require.NoError(t, store.CreateTask(tx, t7)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment7 := watchAssignment(t, watch) assert.Equal(t, "id5", assignment7.NodeID) @@ -344,9 +344,9 @@ func TestScheduler(t *testing.T) { State: api.NodeStatus_READY, }, } - assert.NoError(t, store.CreateNode(tx, n6)) + require.NoError(t, store.CreateNode(tx, n6)) n6.Status.State = api.NodeStatus_DOWN - assert.NoError(t, store.UpdateNode(tx, n6)) + require.NoError(t, store.UpdateNode(tx, n6)) // Create an unassigned task. t8 := &api.Task{ @@ -359,10 +359,10 @@ func TestScheduler(t *testing.T) { State: api.TaskStatePending, }, } - assert.NoError(t, store.CreateTask(tx, t8)) + require.NoError(t, store.CreateTask(tx, t8)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment8 := watchAssignment(t, watch) assert.NotEqual(t, "id6", assignment8.NodeID) @@ -447,17 +447,17 @@ func testHA(t *testing.T, useSpecVersion bool) { err := s.Update(func(tx store.Tx) error { // Prepopulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks from template 1 for i := 0; i != t1Instances; i++ { taskTemplate1.ID = fmt.Sprintf("t1id%d", i) - assert.NoError(t, store.CreateTask(tx, taskTemplate1)) + require.NoError(t, store.CreateTask(tx, taskTemplate1)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -465,16 +465,14 @@ func testHA(t *testing.T, useSpecVersion bool) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() t1Assignments := make(map[string]int) for i := 0; i != t1Instances; i++ { assignment := watchAssignment(t, watch) - if !strings.HasPrefix(assignment.ID, "t1") { - t.Fatal("got assignment for different kind of task") - } + require.True(t, strings.HasPrefix(assignment.ID, "t1"), "got assignment for different kind of task") t1Assignments[assignment.NodeID]++ } @@ -502,18 +500,16 @@ func testHA(t *testing.T, useSpecVersion bool) { err = s.Update(func(tx store.Tx) error { for i := 0; i != t2Instances; i++ { taskTemplate2.ID = fmt.Sprintf("t2id%d", i) - assert.NoError(t, store.CreateTask(tx, taskTemplate2)) + require.NoError(t, store.CreateTask(tx, taskTemplate2)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) t2Assignments := make(map[string]int) for i := 0; i != t2Instances; i++ { assignment := watchAssignment(t, watch) - if !strings.HasPrefix(assignment.ID, "t2") { - t.Fatal("got assignment for different kind of task") - } + require.True(t, strings.HasPrefix(assignment.ID, "t2"), "got assignment for different kind of task") t2Assignments[assignment.NodeID]++ } @@ -528,22 +524,18 @@ func testHA(t *testing.T, useSpecVersion bool) { err = s.Update(func(tx store.Tx) error { for i := t1Instances; i != t1Instances+3; i++ { taskTemplate1.ID = fmt.Sprintf("t1id%d", i) - assert.NoError(t, store.CreateTask(tx, taskTemplate1)) + require.NoError(t, store.CreateTask(tx, taskTemplate1)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) var sharedNodes [2]string for i := 0; i != 3; i++ { assignment := watchAssignment(t, watch) - if !strings.HasPrefix(assignment.ID, "t1") { - t.Fatal("got assignment for different kind of task") - } - if t1Assignments[assignment.NodeID] == 5 { - t.Fatal("more than one new task assigned to the same node") - } + require.True(t, strings.HasPrefix(assignment.ID, "t1"), "got assignment for different kind of task") + require.NotEqual(t, 5, t1Assignments[assignment.NodeID], "more than one new task assigned to the same node") t1Assignments[assignment.NodeID]++ if t2Assignments[assignment.NodeID] != 0 { @@ -580,34 +572,28 @@ func testHA(t *testing.T, useSpecVersion bool) { // has 5 service1 tasks. err = s.Update(func(tx store.Tx) error { taskTemplate2.ID = "t2id4" - assert.NoError(t, store.CreateTask(tx, taskTemplate2)) + require.NoError(t, store.CreateTask(tx, taskTemplate2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment := watchAssignment(t, watch) - if assignment.ID != "t2id4" { - t.Fatal("got assignment for different task") - } + require.Equal(t, "t2id4", assignment.ID, "got assignment for different task") - if t2Assignments[assignment.NodeID] != 0 { - t.Fatal("was scheduled on a node that already has a service2 task") - } - if t1Assignments[assignment.NodeID] == 5 { - t.Fatal("was scheduled on the node that has the most service1 tasks") - } + require.Equal(t, 0, t2Assignments[assignment.NodeID], "was scheduled on a node that already has a service2 task") + require.NotEqual(t, 5, t1Assignments[assignment.NodeID], "was scheduled on the node that has the most service1 tasks") t2Assignments[assignment.NodeID]++ // Remove all tasks on node id1. err = s.Update(func(tx store.Tx) error { tasks, err := store.FindTasks(tx, store.ByNodeID("id1")) - assert.NoError(t, err) + require.NoError(t, err) for _, task := range tasks { - assert.NoError(t, store.DeleteTask(tx, task.ID)) + require.NoError(t, store.DeleteTask(tx, task.ID)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) t1Assignments["id1"] = 0 t2Assignments["id1"] = 0 @@ -628,11 +614,11 @@ func testHA(t *testing.T, useSpecVersion bool) { tasksMap[taskTemplate2.ID] = taskTemplate2.Copy() } for _, task := range tasksMap { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) for i := 0; i != 4+2; i++ { assignment := watchAssignment(t, watch) @@ -761,17 +747,17 @@ func testPreferences(t *testing.T, useSpecVersion bool) { err := s.Update(func(tx store.Tx) error { // Prepoulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks from template 1 for i := 0; i != t1Instances; i++ { taskTemplate1.ID = fmt.Sprintf("t1id%d", i) - assert.NoError(t, store.CreateTask(tx, taskTemplate1)) + require.NoError(t, store.CreateTask(tx, taskTemplate1)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -779,16 +765,14 @@ func testPreferences(t *testing.T, useSpecVersion bool) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() t1Assignments := make(map[string]int) for i := 0; i != t1Instances; i++ { assignment := watchAssignment(t, watch) - if !strings.HasPrefix(assignment.ID, "t1") { - t.Fatal("got assignment for different kind of task") - } + require.True(t, strings.HasPrefix(assignment.ID, "t1"), "got assignment for different kind of task") t1Assignments[assignment.NodeID]++ } @@ -1025,17 +1009,17 @@ func testMultiplePreferences(t *testing.T, useSpecVersion bool) { err := s.Update(func(tx store.Tx) error { // Prepoulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks from template 1 for i := 0; i != t1Instances; i++ { taskTemplate1.ID = fmt.Sprintf("t1id%d", i) - assert.NoError(t, store.CreateTask(tx, taskTemplate1)) + require.NoError(t, store.CreateTask(tx, taskTemplate1)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1043,16 +1027,14 @@ func testMultiplePreferences(t *testing.T, useSpecVersion bool) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() t1Assignments := make(map[string]int) for i := 0; i != t1Instances; i++ { assignment := watchAssignment(t, watch) - if !strings.HasPrefix(assignment.ID, "t1") { - t.Fatal("got assignment for different kind of task") - } + require.True(t, strings.HasPrefix(assignment.ID, "t1"), "got assignment for different kind of task") t1Assignments[assignment.NodeID]++ } @@ -1205,13 +1187,13 @@ func TestMultiplePreferencesScaleUp(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Prepoulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks from template 1 for i := 0; i != t1Instances; i++ { taskTemplate1.ID = fmt.Sprintf("t1id%d", i) - assert.NoError(t, store.CreateTask(tx, taskTemplate1)) + require.NoError(t, store.CreateTask(tx, taskTemplate1)) } // Populate some running tasks to simulate a service scaling scenario @@ -1224,12 +1206,12 @@ func TestMultiplePreferencesScaleUp(t *testing.T) { taskTemplate1.ID = fmt.Sprintf("t1running-%s-%d", node, i) taskTemplate1.NodeID = node taskTemplate1.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, taskTemplate1)) + require.NoError(t, store.CreateTask(tx, taskTemplate1)) } } return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1237,7 +1219,7 @@ func TestMultiplePreferencesScaleUp(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -1245,9 +1227,7 @@ func TestMultiplePreferencesScaleUp(t *testing.T) { totalAssignments := 0 for i := 0; i != t1Instances; i++ { assignment := watchAssignment(t, watch) - if !strings.HasPrefix(assignment.ID, "t1") { - t.Fatal("got assignment for different kind of task") - } + require.True(t, strings.HasPrefix(assignment.ID, "t1"), "got assignment for different kind of task") t1Assignments[assignment.NodeID]++ totalAssignments++ } @@ -1280,11 +1260,11 @@ func TestSchedulerNoReadyNodes(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial service and task - assert.NoError(t, store.CreateService(tx, &api.Service{ID: "serviceID1"})) - assert.NoError(t, store.CreateTask(tx, initialTask)) + require.NoError(t, store.CreateService(tx, &api.Service{ID: "serviceID1"})) + require.NoError(t, store.CreateTask(tx, initialTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1292,7 +1272,7 @@ func TestSchedulerNoReadyNodes(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -1313,10 +1293,10 @@ func TestSchedulerNoReadyNodes(t *testing.T) { State: api.NodeStatus_READY, }, } - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateNode(tx, node)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment := watchAssignment(t, watch) assert.Equal(t, "newnode", assignment.NodeID) @@ -1378,23 +1358,23 @@ func TestSchedulerFaultyNode(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial nodes, and one task of each type assigned to node id1 - assert.NoError(t, store.CreateNode(tx, node1)) - assert.NoError(t, store.CreateNode(tx, node2)) + require.NoError(t, store.CreateNode(tx, node1)) + require.NoError(t, store.CreateNode(tx, node2)) task1 := replicatedTaskTemplate.Copy() task1.ID = "id1" task1.NodeID = "id1" task1.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task1)) task2 := preassignedTaskTemplate.Copy() task2.ID = "id2" task2.NodeID = "id1" task2.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateTask(tx, task2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1402,7 +1382,7 @@ func TestSchedulerFaultyNode(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -1412,10 +1392,10 @@ func TestSchedulerFaultyNode(t *testing.T) { newReplicatedTask.ID = identity.NewID() err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, newReplicatedTask)) + require.NoError(t, store.CreateTask(tx, newReplicatedTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment := watchAssignment(t, watch) assert.Equal(t, newReplicatedTask.ID, assignment.ID) @@ -1431,7 +1411,7 @@ func TestSchedulerFaultyNode(t *testing.T) { } node2Info, err := scheduler.nodeSet.nodeInfo("id2") - assert.NoError(t, err) + require.NoError(t, err) expectedNode2Failures := i if i > 5 { expectedNode2Failures = 5 @@ -1439,7 +1419,7 @@ func TestSchedulerFaultyNode(t *testing.T) { assert.Len(t, node2Info.recentFailures[versionedService{serviceID: "service1"}], expectedNode2Failures) node1Info, err := scheduler.nodeSet.nodeInfo("id1") - assert.NoError(t, err) + require.NoError(t, err) expectedNode1Failures := i - 5 if i < 5 { @@ -1451,10 +1431,10 @@ func TestSchedulerFaultyNode(t *testing.T) { newPreassignedTask.ID = identity.NewID() err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, newPreassignedTask)) + require.NoError(t, store.CreateTask(tx, newPreassignedTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment = watchAssignment(t, watch) assert.Equal(t, newPreassignedTask.ID, assignment.ID) @@ -1465,23 +1445,23 @@ func TestSchedulerFaultyNode(t *testing.T) { // The service associated with the preassigned task will not be // marked as nodeInfo, err := scheduler.nodeSet.nodeInfo("id1") - assert.NoError(t, err) - assert.Len(t, nodeInfo.recentFailures[versionedService{serviceID: "service2"}], 0) + require.NoError(t, err) + assert.Empty(t, nodeInfo.recentFailures[versionedService{serviceID: "service2"}]) err = s.Update(func(tx store.Tx) error { newReplicatedTask := store.GetTask(tx, newReplicatedTask.ID) require.NotNil(t, newReplicatedTask) newReplicatedTask.Status.State = api.TaskStateFailed - assert.NoError(t, store.UpdateTask(tx, newReplicatedTask)) + require.NoError(t, store.UpdateTask(tx, newReplicatedTask)) newPreassignedTask := store.GetTask(tx, newPreassignedTask.ID) require.NotNil(t, newPreassignedTask) newPreassignedTask.Status.State = api.TaskStateFailed - assert.NoError(t, store.UpdateTask(tx, newPreassignedTask)) + require.NoError(t, store.UpdateTask(tx, newPreassignedTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -1530,17 +1510,17 @@ func TestSchedulerFaultyNodeSpecVersion(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial nodes, and one task assigned to node id1 - assert.NoError(t, store.CreateNode(tx, node1)) - assert.NoError(t, store.CreateNode(tx, node2)) + require.NoError(t, store.CreateNode(tx, node1)) + require.NoError(t, store.CreateNode(tx, node2)) task1 := taskTemplate.Copy() task1.ID = "id1" task1.NodeID = "id1" task1.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1548,7 +1528,7 @@ func TestSchedulerFaultyNodeSpecVersion(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -1564,10 +1544,10 @@ func TestSchedulerFaultyNodeSpecVersion(t *testing.T) { } err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, newTask)) + require.NoError(t, store.CreateTask(tx, newTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment := watchAssignment(t, watch) assert.Equal(t, newTask.ID, assignment.ID) @@ -1585,9 +1565,9 @@ func TestSchedulerFaultyNodeSpecVersion(t *testing.T) { } node1Info, err := scheduler.nodeSet.nodeInfo("id1") - assert.NoError(t, err) + require.NoError(t, err) node2Info, err := scheduler.nodeSet.nodeInfo("id2") - assert.NoError(t, err) + require.NoError(t, err) expectedNode1Spec1Failures := 0 expectedNode1Spec2Failures := 0 expectedNode2Spec1Failures := i @@ -1610,10 +1590,10 @@ func TestSchedulerFaultyNodeSpecVersion(t *testing.T) { newTask := store.GetTask(tx, newTask.ID) require.NotNil(t, newTask) newTask.Status.State = api.TaskStateFailed - assert.NoError(t, store.UpdateTask(tx, newTask)) + require.NoError(t, store.UpdateTask(tx, newTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -1722,14 +1702,14 @@ func TestSchedulerResourceConstraint(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial node, service and task - assert.NoError(t, store.CreateService(tx, initialService)) - assert.NoError(t, store.CreateTask(tx, initialTask)) - assert.NoError(t, store.CreateNode(tx, underprovisionedNode)) - assert.NoError(t, store.CreateNode(tx, nonready1)) - assert.NoError(t, store.CreateNode(tx, nonready2)) + require.NoError(t, store.CreateService(tx, initialService)) + require.NoError(t, store.CreateTask(tx, initialTask)) + require.NoError(t, store.CreateNode(tx, underprovisionedNode)) + require.NoError(t, store.CreateNode(tx, nonready1)) + require.NoError(t, store.CreateNode(tx, nonready2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1737,7 +1717,7 @@ func TestSchedulerResourceConstraint(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -1768,10 +1748,10 @@ func TestSchedulerResourceConstraint(t *testing.T) { State: api.NodeStatus_READY, }, } - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateNode(tx, node)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment := watchAssignment(t, watch) assert.Equal(t, "bignode", assignment.NodeID) @@ -1850,46 +1830,46 @@ func TestSchedulerResourceConstraintHA(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial node and task - assert.NoError(t, store.CreateNode(tx, node1)) - assert.NoError(t, store.CreateNode(tx, node2)) + require.NoError(t, store.CreateNode(tx, node1)) + require.NoError(t, store.CreateNode(tx, node2)) // preassigned tasks task1 := taskTemplate.Copy() task1.ID = "id1" task1.NodeID = "id1" task1.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task1)) task2 := taskTemplate.Copy() task2.ID = "id2" task2.NodeID = "id2" task2.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateTask(tx, task2)) task3 := taskTemplate.Copy() task3.ID = "id3" task3.NodeID = "id2" task3.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task3)) + require.NoError(t, store.CreateTask(tx, task3)) task4 := taskTemplate.Copy() task4.ID = "id4" task4.NodeID = "id2" task4.Status.State = api.TaskStateRunning - assert.NoError(t, store.CreateTask(tx, task4)) + require.NoError(t, store.CreateTask(tx, task4)) // tasks to assign task5 := taskTemplate.Copy() task5.ID = "id5" - assert.NoError(t, store.CreateTask(tx, task5)) + require.NoError(t, store.CreateTask(tx, task5)) task6 := taskTemplate.Copy() task6.ID = "id6" - assert.NoError(t, store.CreateTask(tx, task6)) + require.NoError(t, store.CreateTask(tx, task6)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1897,7 +1877,7 @@ func TestSchedulerResourceConstraintHA(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -1978,12 +1958,12 @@ func TestSchedulerResourceConstraintDeadTask(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial node, service and task - assert.NoError(t, store.CreateService(tx, bigService)) - assert.NoError(t, store.CreateNode(tx, node)) - assert.NoError(t, store.CreateTask(tx, bigTask1)) + require.NoError(t, store.CreateService(tx, bigService)) + require.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateTask(tx, bigTask1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -1991,7 +1971,7 @@ func TestSchedulerResourceConstraintDeadTask(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -2005,7 +1985,7 @@ func TestSchedulerResourceConstraintDeadTask(t *testing.T) { // resource constraints. return store.CreateTask(tx, bigTask2) }) - assert.NoError(t, err) + require.NoError(t, err) failure := watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (insufficient resources on 1 node)", failure.Status.Err) @@ -2016,7 +1996,7 @@ func TestSchedulerResourceConstraintDeadTask(t *testing.T) { updatedTask.Status.State = api.TaskStateShutdown return store.UpdateTask(tx, updatedTask) }) - assert.NoError(t, err) + require.NoError(t, err) // With the first task no longer consuming resources, the second // one can be scheduled. @@ -2081,11 +2061,11 @@ func TestSchedulerPreexistingDeadTask(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial node and task - assert.NoError(t, store.CreateNode(tx, node)) - assert.NoError(t, store.CreateTask(tx, deadTask)) + require.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateTask(tx, deadTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -2093,7 +2073,7 @@ func TestSchedulerPreexistingDeadTask(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -2102,7 +2082,7 @@ func TestSchedulerPreexistingDeadTask(t *testing.T) { // using the resources is past the running state. return store.CreateTask(tx, bigTask2) }) - assert.NoError(t, err) + require.NoError(t, err) assignment := watchAssignment(t, watch) assert.Equal(t, "id2", assignment.ID) @@ -2281,14 +2261,14 @@ func TestSchedulerCompatiblePlatform(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial task, service and nodes to the store - assert.NoError(t, store.CreateService(tx, service1)) - assert.NoError(t, store.CreateTask(tx, task1)) - assert.NoError(t, store.CreateNode(tx, node1)) - assert.NoError(t, store.CreateNode(tx, node2)) - assert.NoError(t, store.CreateNode(tx, node3)) + require.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateNode(tx, node1)) + require.NoError(t, store.CreateNode(tx, node2)) + require.NoError(t, store.CreateNode(tx, node3)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -2296,7 +2276,7 @@ func TestSchedulerCompatiblePlatform(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -2306,37 +2286,37 @@ func TestSchedulerCompatiblePlatform(t *testing.T) { // add task2 err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateTask(tx, task2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) failure := watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (unsupported platform on 3 nodes)", failure.Status.Err) // add task3 err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task3)) + require.NoError(t, store.CreateTask(tx, task3)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment2 := watchAssignment(t, watch) assert.Regexp(t, assignment2.NodeID, "(node2|node3)") // add task4 err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task4)) + require.NoError(t, store.CreateTask(tx, task4)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment3 := watchAssignment(t, watch) assert.Equal(t, "node1", assignment3.NodeID) // add task5 err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task5)) + require.NoError(t, store.CreateTask(tx, task5)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment4 := watchAssignment(t, watch) assert.Regexp(t, assignment4.NodeID, "(node1|node2)") } @@ -2395,12 +2375,12 @@ func TestSchedulerUnassignedMap(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial task, service and nodes to the store - assert.NoError(t, store.CreateService(tx, service1)) - assert.NoError(t, store.CreateTask(tx, task1)) - assert.NoError(t, store.CreateNode(tx, node1)) + require.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateNode(tx, node1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) scheduler.unassignedTasks["id1"] = task1 @@ -2411,10 +2391,10 @@ func TestSchedulerUnassignedMap(t *testing.T) { // delete the service of an unassigned task err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.DeleteService(tx, service1.ID)) + require.NoError(t, store.DeleteService(tx, service1.ID)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler.tick(ctx) // task1 is removed from the unassigned map @@ -2491,16 +2471,16 @@ func TestPreassignedTasks(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Prepopulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks for _, task := range initialTaskSet { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -2508,13 +2488,13 @@ func TestPreassignedTasks(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() //preassigned tasks would be processed first assignment1 := watchAssignment(t, watch) // task2 and task3 are preassigned to node1 - assert.Equal(t, assignment1.NodeID, "node1") + assert.Equal(t, "node1", assignment1.NodeID) assert.Regexp(t, assignment1.ID, "(task2|task3)") assignment2 := watchAssignment(t, watch) @@ -2526,8 +2506,8 @@ func TestPreassignedTasks(t *testing.T) { // task1 would be assigned to node2 because node1 has 2 tasks already assignment3 := watchAssignment(t, watch) - assert.Equal(t, assignment3.ID, "task1") - assert.Equal(t, assignment3.NodeID, "node2") + assert.Equal(t, "task1", assignment3.ID) + assert.Equal(t, "node2", assignment3.NodeID) } func TestIgnoreTasks(t *testing.T) { @@ -2590,16 +2570,16 @@ func TestIgnoreTasks(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Prepopulate nodes for _, n := range initialNodeSet { - assert.NoError(t, store.CreateNode(tx, n)) + require.NoError(t, store.CreateNode(tx, n)) } // Prepopulate tasks for _, task := range initialTaskSet { - assert.NoError(t, store.CreateTask(tx, task)) + require.NoError(t, store.CreateTask(tx, task)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -2607,15 +2587,15 @@ func TestIgnoreTasks(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() // task1 is the only task that gets assigned since other two tasks // are ignored by the scheduler. // Normally task2/task3 should get assigned first since its a preassigned task. assignment3 := watchAssignment(t, watch) - assert.Equal(t, assignment3.ID, "task1") - assert.Equal(t, assignment3.NodeID, "node1") + assert.Equal(t, "task1", assignment3.ID) + assert.Equal(t, "node1", assignment3.NodeID) } // TestNoStuckTask tests that a task which is cannot be scheduled (because of @@ -2702,13 +2682,13 @@ func TestUnscheduleableTask(t *testing.T) { defer s.Close() err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, service1)) - assert.NoError(t, store.CreateTask(tx, task1)) - assert.NoError(t, store.CreateTask(tx, task2)) - assert.NoError(t, store.CreateNode(tx, node)) + require.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateNode(tx, node)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -2716,7 +2696,7 @@ func TestUnscheduleableTask(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -2794,19 +2774,19 @@ watchAttempt: // in the test where the old task might be marked freed, allowing the // failed task to progress. We want to handle the case where this does // not happen - assert.NoError(t, store.UpdateTask(tx, assigned)) + require.NoError(t, store.UpdateTask(tx, assigned)) failed.DesiredState = api.TaskStateShutdown - assert.NoError(t, store.UpdateTask(tx, failed)) + require.NoError(t, store.UpdateTask(tx, failed)) - assert.NoError(t, store.CreateTask(tx, task1Update)) + require.NoError(t, store.CreateTask(tx, task1Update)) - assert.NoError(t, store.UpdateService(tx, service1)) + require.NoError(t, store.UpdateService(tx, service1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // because the failed task is still currently under the purview of the // scheduler, the scheduler should shut it down. @@ -3203,12 +3183,12 @@ func TestSchedulerPluginConstraint(t *testing.T) { // Add initial node, service and task err := s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateService(tx, s1)) - assert.NoError(t, store.CreateTask(tx, t1)) - assert.NoError(t, store.CreateNode(tx, n1)) + require.NoError(t, store.CreateService(tx, s1)) + require.NoError(t, store.CreateTask(tx, t1)) + require.NoError(t, store.CreateNode(tx, n1)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -3216,123 +3196,123 @@ func TestSchedulerPluginConstraint(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() // t1 should get assigned assignment := watchAssignment(t, watch) - assert.Equal(t, assignment.NodeID, "node1_ID") + assert.Equal(t, "node1_ID", assignment.NodeID) // Create t0; it should get assigned because the plugin filter shouldn't // be enabled for tasks that have bind mounts err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, t0)) + require.NoError(t, store.CreateTask(tx, t0)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment0 := watchAssignment(t, watch) - assert.Equal(t, assignment0.ID, "task0_ID") - assert.Equal(t, assignment0.NodeID, "node1_ID") + assert.Equal(t, "task0_ID", assignment0.ID) + assert.Equal(t, "node1_ID", assignment0.NodeID) // Create t2; it should stay in the pending state because there is // no node that with volume plugin `plugin2` err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, t2)) + require.NoError(t, store.CreateTask(tx, t2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) failure := watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (missing plugin on 1 node)", failure.Status.Err) // Now add the second node err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, n2)) + require.NoError(t, store.CreateNode(tx, n2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Check that t2 has been assigned assignment1 := watchAssignment(t, watch) - assert.Equal(t, assignment1.ID, "task2_ID") - assert.Equal(t, assignment1.NodeID, "node2_ID") + assert.Equal(t, "task2_ID", assignment1.ID) + assert.Equal(t, "node2_ID", assignment1.NodeID) // Create t3; it should stay in the pending state because there is // no node that with network plugin `plugin1` err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, t3)) + require.NoError(t, store.CreateTask(tx, t3)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) failure = watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (missing plugin on 2 nodes)", failure.Status.Err) // Now add the node3 err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, n3)) + require.NoError(t, store.CreateNode(tx, n3)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Check that t3 has been assigned assignment2 := watchAssignment(t, watch) - assert.Equal(t, assignment2.ID, "task3_ID") - assert.Equal(t, assignment2.NodeID, "node3_ID") + assert.Equal(t, "task3_ID", assignment2.ID) + assert.Equal(t, "node3_ID", assignment2.NodeID) // Create t4; it should stay in the pending state because there is // no node that with log plugin `plugin1` err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, t4)) + require.NoError(t, store.CreateTask(tx, t4)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // check that t4 has been assigned failure2 := watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (missing plugin on 3 nodes)", failure2.Status.Err) err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, n4)) + require.NoError(t, store.CreateNode(tx, n4)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Check that t4 has been assigned assignment3 := watchAssignment(t, watch) - assert.Equal(t, assignment3.ID, "task4_ID") - assert.Equal(t, assignment3.NodeID, "node4_ID") + assert.Equal(t, "task4_ID", assignment3.ID) + assert.Equal(t, "node4_ID", assignment3.NodeID) err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, t5)) + require.NoError(t, store.CreateTask(tx, t5)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment4 := watchAssignment(t, watch) - assert.Equal(t, assignment4.ID, "task5_ID") - assert.Equal(t, assignment4.NodeID, "node4_ID") + assert.Equal(t, "task5_ID", assignment4.ID) + assert.Equal(t, "node4_ID", assignment4.NodeID) // check that t6 gets assigned to some node err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, t6)) + require.NoError(t, store.CreateTask(tx, t6)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment5 := watchAssignment(t, watch) - assert.Equal(t, assignment5.ID, "task6_ID") - assert.NotEqual(t, assignment5.NodeID, "") + assert.Equal(t, "task6_ID", assignment5.ID) + assert.NotEmpty(t, assignment5.NodeID) // check that t7 gets assigned to some node err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, t7)) + require.NoError(t, store.CreateTask(tx, t7)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assignment6 := watchAssignment(t, watch) - assert.Equal(t, assignment6.ID, "task7_ID") - assert.NotEqual(t, assignment6.NodeID, "") + assert.Equal(t, "task7_ID", assignment6.ID) + assert.NotEmpty(t, assignment6.NodeID) } func BenchmarkScheduler1kNodes1kTasks(b *testing.B) { @@ -3583,12 +3563,12 @@ func TestSchedulerHostPort(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial node, service and task - assert.NoError(t, store.CreateService(tx, service1)) - assert.NoError(t, store.CreateTask(tx, task1)) - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -3596,7 +3576,7 @@ func TestSchedulerHostPort(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -3606,23 +3586,23 @@ func TestSchedulerHostPort(t *testing.T) { err = s.Update(func(tx store.Tx) error { // Add initial node and task - assert.NoError(t, store.CreateNode(tx, node1)) - assert.NoError(t, store.CreateNode(tx, node2)) + require.NoError(t, store.CreateNode(tx, node1)) + require.NoError(t, store.CreateNode(tx, node2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Tasks 1 and 2 should be assigned to different nodes. assignment1 := watchAssignment(t, watch) assignment2 := watchAssignment(t, watch) - assert.True(t, assignment1 != assignment2) + assert.NotSame(t, assignment1, assignment2) // Task 3 should not be schedulable. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task3)) + require.NoError(t, store.CreateTask(tx, task3)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) failure := watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (host-mode port already in use on 2 nodes)", failure.Status.Err) @@ -3719,12 +3699,12 @@ func TestSchedulerMaxReplicas(t *testing.T) { err := s.Update(func(tx store.Tx) error { // Add initial node, service and task - assert.NoError(t, store.CreateService(tx, service1)) - assert.NoError(t, store.CreateTask(tx, task1)) - assert.NoError(t, store.CreateTask(tx, task2)) + require.NoError(t, store.CreateService(tx, service1)) + require.NoError(t, store.CreateTask(tx, task1)) + require.NoError(t, store.CreateTask(tx, task2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) scheduler := New(s) @@ -3732,7 +3712,7 @@ func TestSchedulerMaxReplicas(t *testing.T) { defer cancel() go func() { - assert.NoError(t, scheduler.Run(ctx)) + require.NoError(t, scheduler.Run(ctx)) }() defer scheduler.Stop() @@ -3742,23 +3722,23 @@ func TestSchedulerMaxReplicas(t *testing.T) { err = s.Update(func(tx store.Tx) error { // Add initial node and task - assert.NoError(t, store.CreateNode(tx, node1)) - assert.NoError(t, store.CreateNode(tx, node2)) + require.NoError(t, store.CreateNode(tx, node1)) + require.NoError(t, store.CreateNode(tx, node2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Tasks 1 and 2 should be assigned to different nodes. assignment1 := watchAssignment(t, watch) assignment2 := watchAssignment(t, watch) - assert.True(t, assignment1 != assignment2) + assert.NotSame(t, assignment1, assignment2) // Task 3 should not be schedulable. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task3)) + require.NoError(t, store.CreateTask(tx, task3)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) failure := watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (max replicas per node limit exceed)", failure.Status.Err) @@ -3776,10 +3756,10 @@ func TestSchedulerMaxReplicas(t *testing.T) { }, } err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateNode(tx, node3)) + require.NoError(t, store.CreateNode(tx, node3)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Create four more tasks to node 1 task4 := &api.Task{ @@ -3863,19 +3843,19 @@ func TestSchedulerMaxReplicas(t *testing.T) { }, } err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task4)) - assert.NoError(t, store.CreateTask(tx, task5)) - assert.NoError(t, store.CreateTask(tx, task6)) + require.NoError(t, store.CreateTask(tx, task4)) + require.NoError(t, store.CreateTask(tx, task5)) + require.NoError(t, store.CreateTask(tx, task6)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Task 7 should not be schedulable. err = s.Update(func(tx store.Tx) error { - assert.NoError(t, store.CreateTask(tx, task7)) + require.NoError(t, store.CreateTask(tx, task7)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) failure = watchAssignmentFailure(t, watch) assert.Equal(t, "no suitable node (scheduling constraints not satisfied on 3 nodes)", failure.Status.Err) diff --git a/manager/scheduler/topology_test.go b/manager/scheduler/topology_test.go index 4bbe6e3da3..d7afae5626 100644 --- a/manager/scheduler/topology_test.go +++ b/manager/scheduler/topology_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/moby/swarmkit/v2/api" + "github.com/stretchr/testify/assert" ) func TestIsInTopology(t *testing.T) { @@ -170,8 +171,6 @@ func TestIsInTopology(t *testing.T) { }, } { actual := IsInTopology(tc.top, tc.accessible) - if actual != tc.expected { - t.Errorf("Expected %v to lie within %v", tc.top, tc.accessible) - } + assert.Equalf(t, tc.expected, actual, "Expected %v to lie within %v", tc.top, tc.accessible) } } diff --git a/manager/state/raft/membership/cluster_test.go b/manager/state/raft/membership/cluster_test.go index d78aceb458..df004e8cfa 100644 --- a/manager/state/raft/membership/cluster_test.go +++ b/manager/state/raft/membership/cluster_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/moby/swarmkit/v2/log" + "github.com/stretchr/testify/require" "google.golang.org/grpc/grpclog" "github.com/moby/swarmkit/v2/api" @@ -102,7 +103,7 @@ func TestGetMember(t *testing.T) { m := cls.GetMember(1) assert.NotNil(t, m) - assert.Equal(t, m.RaftID, uint64(1)) + assert.Equal(t, uint64(1), m.RaftID) m = cls.GetMember(2) assert.Nil(t, m) @@ -122,12 +123,12 @@ func TestClusterAddMember(t *testing.T) { // Cannot add a node present in the removed set err := cls.AddMember(&membership.Member{RaftMember: &api.RaftMember{RaftID: 2}}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err, membership.ErrIDRemoved) assert.Nil(t, cls.GetMember(2)) err = cls.AddMember(&membership.Member{RaftMember: &api.RaftMember{RaftID: 3}}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cls.GetMember(3)) } @@ -142,11 +143,11 @@ func TestClusterRemoveMember(t *testing.T) { // Can remove a node whose ID is not yet in the member list err := cls.RemoveMember(3) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, cls.GetMember(3)) err = cls.RemoveMember(1) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, cls.GetMember(1)) } @@ -177,8 +178,8 @@ func TestClear(t *testing.T) { cls := newTestCluster(members, removed) cls.Clear() - assert.Equal(t, len(cls.Members()), 0) - assert.Equal(t, len(cls.Removed()), 0) + assert.Empty(t, cls.Members()) + assert.Empty(t, cls.Removed()) } func TestValidateConfigurationChange(t *testing.T) { @@ -196,58 +197,58 @@ func TestValidateConfigurationChange(t *testing.T) { m := &api.RaftMember{RaftID: 1} existingMember, err := m.Marshal() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, existingMember) m = &api.RaftMember{RaftID: 7} newMember, err := m.Marshal() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, newMember) m = &api.RaftMember{RaftID: 4} removedMember, err := m.Marshal() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, removedMember) n := &api.Node{} node, err := n.Marshal() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, node) // Add node but ID exists cc := raftpb.ConfChange{ID: 1, Type: raftpb.ConfChangeAddNode, NodeID: 1, Context: existingMember} err = cls.ValidateConfigurationChange(cc) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err, membership.ErrIDExists) // Any configuration change but ID in remove set cc = raftpb.ConfChange{ID: 4, Type: raftpb.ConfChangeAddNode, NodeID: 4, Context: removedMember} err = cls.ValidateConfigurationChange(cc) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err, membership.ErrIDRemoved) // Remove Node but ID not found in memberlist cc = raftpb.ConfChange{ID: 7, Type: raftpb.ConfChangeRemoveNode, NodeID: 7, Context: newMember} err = cls.ValidateConfigurationChange(cc) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err, membership.ErrIDNotFound) // Update Node but ID not found in memberlist cc = raftpb.ConfChange{ID: 7, Type: raftpb.ConfChangeUpdateNode, NodeID: 7, Context: newMember} err = cls.ValidateConfigurationChange(cc) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err, membership.ErrIDNotFound) // Any configuration change but can't unmarshal config cc = raftpb.ConfChange{ID: 7, Type: raftpb.ConfChangeAddNode, NodeID: 7, Context: []byte("abcdef")} err = cls.ValidateConfigurationChange(cc) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err, membership.ErrCannotUnmarshalConfig) // Invalid configuration change cc = raftpb.ConfChange{ID: 1, Type: 10, NodeID: 1, Context: newMember} err = cls.ValidateConfigurationChange(cc) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err, membership.ErrConfigChangeInvalid) } @@ -262,7 +263,7 @@ func TestCanRemoveMember(t *testing.T) { nodes[3].ShutdownRaft() // Node 2 and Node 3 should be listed as Unreachable - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { members := nodes[1].GetMemberlist() if len(members) != 3 { return fmt.Errorf("expected 3 nodes, got %d", len(members)) @@ -281,9 +282,9 @@ func TestCanRemoveMember(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() err := nodes[1].RemoveMember(ctx, uint64(i)) - assert.Error(t, err) + require.Error(t, err) members := nodes[1].GetMemberlist() - assert.Equal(t, len(members), 3) + assert.Len(t, members, 3) } // Restart node 2 and node 3 @@ -302,7 +303,7 @@ func TestCanRemoveMember(t *testing.T) { } // Node 2 and Node 3 should be listed as Reachable - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { leader = leaderIndex() if leader == 0 { return errors.New("no leader") @@ -325,7 +326,7 @@ func TestCanRemoveMember(t *testing.T) { nodes[3].ShutdownRaft() // Node 3 should be listed as Unreachable - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { leader = leaderIndex() if leader == 0 { return errors.New("no leader") @@ -344,18 +345,18 @@ func TestCanRemoveMember(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) err := nodes[leader].RemoveMember(ctx, nodes[2].Config.ID) cancel() - assert.EqualError(t, err, raft.ErrCannotRemoveMember.Error()) + require.EqualError(t, err, raft.ErrCannotRemoveMember.Error()) members := nodes[leader].GetMemberlist() - assert.Equal(t, len(members), 3) + assert.Len(t, members, 3) // Removing node 3 works fine because it is already unreachable ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second) err = nodes[leader].RemoveMember(ctx, nodes[3].Config.ID) cancel() - assert.NoError(t, err) + require.NoError(t, err) members = nodes[leader].GetMemberlist() assert.Nil(t, members[nodes[3].Config.ID]) - assert.Equal(t, len(members), 2) + assert.Len(t, members, 2) // Add back node 3 raftutils.ShutdownNode(nodes[3]) @@ -363,7 +364,7 @@ func TestCanRemoveMember(t *testing.T) { raftutils.WaitForCluster(t, clockSource, nodes) // Node 2 and Node 3 should be listed as Reachable - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { leader = leaderIndex() if leader == 0 { return errors.New("no leader") @@ -385,17 +386,17 @@ func TestCanRemoveMember(t *testing.T) { ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second) err = nodes[leader].RemoveMember(ctx, nodes[3].Config.ID) cancel() - assert.NoError(t, err) + require.NoError(t, err) members = nodes[leader].GetMemberlist() assert.Nil(t, members[nodes[3].Config.ID]) - assert.Equal(t, len(members), 2) + assert.Len(t, members, 2) // Removing node 2 should succeed ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second) err = nodes[leader].RemoveMember(ctx, nodes[2].Config.ID) cancel() - assert.NoError(t, err) + require.NoError(t, err) members = nodes[leader].GetMemberlist() assert.Nil(t, members[nodes[2].Config.ID]) - assert.Equal(t, len(members), 1) + assert.Len(t, members, 1) } diff --git a/manager/state/raft/raft_test.go b/manager/state/raft/raft_test.go index eacef14977..9900780ea8 100644 --- a/manager/state/raft/raft_test.go +++ b/manager/state/raft/raft_test.go @@ -106,17 +106,17 @@ func TestRaftJoinTwice(t *testing.T) { // Use gRPC instead of calling handler directly because of // authorization check. cc, err := dial(nodes[3], nodes[1].Address) - assert.NoError(t, err) + require.NoError(t, err) raftClient := api.NewRaftMembershipClient(cc) defer cc.Close() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) _, err = raftClient.Join(ctx, &api.JoinRequest{Addr: l.Addr().String()}) cancel() - assert.NoError(t, err) + require.NoError(t, err) // Propose a value and wait for it to propagate value, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") raftutils.CheckValue(t, clockSource, nodes[2], value) // Restart node 2 @@ -187,7 +187,7 @@ func TestRaftLeaderDown(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, leaderNode, DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // The value should be replicated on all remaining nodes raftutils.CheckValue(t, clockSource, leaderNode, value) @@ -212,7 +212,7 @@ func TestRaftFollowerDown(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // The value should be replicated on all remaining nodes raftutils.CheckValue(t, clockSource, nodes[1], value) @@ -230,7 +230,7 @@ func TestRaftLogReplication(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // All nodes should have the value in the physical store raftutils.CheckValue(t, clockSource, nodes[1], value) @@ -254,7 +254,7 @@ func TestRaftWedgedManager(t *testing.T) { // Propose a value _, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") doneCh := make(chan struct{}) defer close(doneCh) @@ -267,7 +267,7 @@ func TestRaftWedgedManager(t *testing.T) { }) }() - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { if nodes[1].Config.ID == nodes[1].Leader() { return errors.New("leader has not changed") } @@ -285,7 +285,7 @@ func TestRaftLogReplicationWithoutLeader(t *testing.T) { // Propose a value _, err := raftutils.ProposeValue(t, nodes[2], DefaultProposalTime) - assert.Error(t, err) + require.Error(t, err) // No value should be replicated in the store in the absence of the leader raftutils.CheckNoValue(t, clockSource, nodes[2]) @@ -309,7 +309,7 @@ func TestRaftQuorumFailure(t *testing.T) { // Propose a value _, err := raftutils.ProposeValue(t, nodes[1], ShortProposalTime) - assert.Error(t, err) + require.Error(t, err) // The value should not be replicated, we have no majority raftutils.CheckNoValue(t, clockSource, nodes[2]) @@ -344,7 +344,7 @@ func TestRaftQuorumRecovery(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, raftutils.Leader(nodes), DefaultProposalTime) - assert.NoError(t, err) + require.NoError(t, err) for _, node := range nodes { raftutils.CheckValue(t, clockSource, node, value) @@ -364,13 +364,13 @@ func TestRaftFollowerLeave(t *testing.T) { // Use gRPC instead of calling handler directly because of // authorization check. cc, err := dial(nodes[1], nodes[1].Address) - assert.NoError(t, err) + require.NoError(t, err) raftClient := api.NewRaftMembershipClient(cc) defer cc.Close() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) resp, err := raftClient.Leave(ctx, &api.LeaveRequest{Node: &api.RaftMember{RaftID: nodes[5].Config.ID}}) cancel() - assert.NoError(t, err, "error sending message to leave the raft") + require.NoError(t, err, "error sending message to leave the raft") assert.NotNil(t, resp, "leave response message is nil") raftutils.ShutdownNode(nodes[5]) @@ -380,7 +380,7 @@ func TestRaftFollowerLeave(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // Value should be replicated on every node raftutils.CheckValue(t, clockSource, nodes[1], value) @@ -409,13 +409,13 @@ func TestRaftLeaderLeave(t *testing.T) { // Use gRPC instead of calling handler directly because of // authorization check. cc, err := dial(nodes[1], nodes[1].Address) - assert.NoError(t, err) + require.NoError(t, err) raftClient := api.NewRaftMembershipClient(cc) defer cc.Close() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) resp, err := raftClient.Leave(ctx, &api.LeaveRequest{Node: &api.RaftMember{RaftID: nodes[1].Config.ID}}) cancel() - assert.NoError(t, err, "error sending message to leave the raft") + require.NoError(t, err, "error sending message to leave the raft") assert.NotNil(t, resp, "leave response message is nil") newCluster := map[uint64]*raftutils.TestNode{ @@ -452,7 +452,7 @@ func TestRaftLeaderLeave(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, leaderNode, DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // The value should be replicated on all remaining nodes raftutils.CheckValue(t, clockSource, leaderNode, value) @@ -473,7 +473,7 @@ func TestRaftNewNodeGetsData(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // Add a new node raftutils.AddRaftNode(t, clockSource, nodes, tc) @@ -500,7 +500,7 @@ func TestChangesBetween(t *testing.T) { values := make([]*api.Node, 10) for i, nodeID := range nodeIDs { value, err := raftutils.ProposeValue(t, node, DefaultProposalTime, nodeID) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") values[i] = value } @@ -532,31 +532,31 @@ func TestChangesBetween(t *testing.T) { // Satisfiable requests changes, err := node.ChangesBetween(versionAdd(startVersion, -1), *startVersion) - assert.NoError(t, err) - assert.Len(t, changes, 0) + require.NoError(t, err) + assert.Empty(t, changes) changes, err = node.ChangesBetween(*startVersion, versionAdd(startVersion, 1)) - assert.NoError(t, err) + require.NoError(t, err) require.Len(t, changes, 1) assert.Equal(t, expectedChanges(*startVersion, values[:1]), changes) changes, err = node.ChangesBetween(*startVersion, versionAdd(startVersion, 10)) - assert.NoError(t, err) + require.NoError(t, err) require.Len(t, changes, 10) assert.Equal(t, expectedChanges(*startVersion, values), changes) changes, err = node.ChangesBetween(versionAdd(startVersion, 2), versionAdd(startVersion, 6)) - assert.NoError(t, err) + require.NoError(t, err) require.Len(t, changes, 4) assert.Equal(t, expectedChanges(versionAdd(startVersion, 2), values[2:6]), changes) // Unsatisfiable requests _, err = node.ChangesBetween(versionAdd(startVersion, -1), versionAdd(startVersion, 11)) - assert.Error(t, err) + require.Error(t, err) _, err = node.ChangesBetween(versionAdd(startVersion, 11), versionAdd(startVersion, 11)) - assert.Error(t, err) + require.Error(t, err) _, err = node.ChangesBetween(versionAdd(startVersion, 11), versionAdd(startVersion, 15)) - assert.Error(t, err) + require.Error(t, err) } func TestRaftRejoin(t *testing.T) { @@ -571,7 +571,7 @@ func TestRaftRejoin(t *testing.T) { values := make([]*api.Node, 2) var err error values[0], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, ids[0]) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // The value should be replicated on node 3 raftutils.CheckValue(t, clockSource, nodes[3], values[0]) @@ -583,7 +583,7 @@ func TestRaftRejoin(t *testing.T) { // Propose another value values[1], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, ids[1]) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // Nodes 1 and 2 should have the new value raftutils.CheckValuesOnNodes(t, clockSource, map[uint64]*raftutils.TestNode{1: nodes[1], 2: nodes[2]}, ids, values) @@ -604,7 +604,7 @@ func testRaftRestartCluster(t *testing.T, stagger bool) { values := make([]*api.Node, 2) var err error values[0], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, "id1") - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // Stop all nodes for _, node := range nodes { @@ -627,10 +627,10 @@ func testRaftRestartCluster(t *testing.T, stagger bool) { // Propose another value values[1], err = raftutils.ProposeValue(t, raftutils.Leader(nodes), DefaultProposalTime, "id2") - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") for _, node := range nodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error node.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node @@ -704,7 +704,7 @@ func TestRaftForceNewCluster(t *testing.T) { values := make([]*api.Node, 2) var err error values[0], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, "id1") - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // The memberlist should contain 3 members on each node for i := 1; i <= 3; i++ { @@ -740,10 +740,10 @@ func TestRaftForceNewCluster(t *testing.T) { // Propose another value values[1], err = raftutils.ProposeValue(t, raftutils.Leader(nodes), DefaultProposalTime, "id2") - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") for _, node := range nodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error node.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node @@ -802,7 +802,7 @@ func TestRaftUnreachableNode(t *testing.T) { // Propose a value value, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // All nodes should have the value in the physical store raftutils.CheckValue(t, clockSource, nodes[1], value) @@ -822,7 +822,7 @@ func TestRaftJoinWithIncorrectAddress(t *testing.T) { defer raftutils.CleanupNonRunningNode(n) err := n.JoinAndStart(context.Background()) - assert.NotNil(t, err) + require.Error(t, err) assert.Contains(t, testutils.ErrorDesc(err), "could not connect to prospective new cluster member using its advertised address") // Check if first node still has only itself registered in the memberlist @@ -856,7 +856,7 @@ func TestStress(t *testing.T) { if err == nil { pIDs = append(pIDs, id) // if propose successfully, at least there are 3 running nodes - assert.True(t, nup >= 3) + assert.GreaterOrEqual(t, nup, 3) // only leader can propose value assert.True(t, leader == i || leader == -1) // update leader @@ -915,7 +915,7 @@ func TestStress(t *testing.T) { raftutils.WaitForCluster(t, clockSource, nodes) id := strconv.Itoa(1000) val, err := raftutils.ProposeValue(t, raftutils.Leader(nodes), DefaultProposalTime, id) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") pIDs = append(pIDs, id) // increase clock to make cluster stable @@ -959,24 +959,24 @@ func TestStreamRaftMessage(t *testing.T) { defer raftutils.TeardownCluster(nodes) cc, err := dial(nodes[1], nodes[1].Address) - assert.NoError(t, err) + require.NoError(t, err) stream, err := api.NewRaftClient(cc).StreamRaftMessage(ctx) - assert.NoError(t, err) + require.NoError(t, err) err = stream.Send(&api.StreamRaftMessageRequest{Message: raftutils.NewSnapshotMessage(2, 1, transport.GRPCMaxMsgSize/2)}) - assert.NoError(t, err) + require.NoError(t, err) _, err = stream.CloseAndRecv() - assert.NoError(t, err) + require.NoError(t, err) stream, err = api.NewRaftClient(cc).StreamRaftMessage(ctx) - assert.NoError(t, err) + require.NoError(t, err) msg := raftutils.NewSnapshotMessage(2, 1, transport.GRPCMaxMsgSize) raftMsg := &api.StreamRaftMessageRequest{Message: msg} err = stream.Send(raftMsg) - assert.NoError(t, err) + require.NoError(t, err) _, err = stream.CloseAndRecv() errStr := fmt.Sprintf("grpc: received message larger than max (%d vs. %d)", raftMsg.Size(), transport.GRPCMaxMsgSize) @@ -987,16 +987,16 @@ func TestStreamRaftMessage(t *testing.T) { // Sending multiple snap messages with different indexes // should return an error. stream, err = api.NewRaftClient(cc).StreamRaftMessage(ctx) - assert.NoError(t, err) + require.NoError(t, err) msg = raftutils.NewSnapshotMessage(2, 1, 10) raftMsg = &api.StreamRaftMessageRequest{Message: msg} err = stream.Send(raftMsg) - assert.NoError(t, err) + require.NoError(t, err) msg = raftutils.NewSnapshotMessage(2, 1, 10) msg.Index++ raftMsg = &api.StreamRaftMessageRequest{Message: msg} err = stream.Send(raftMsg) - assert.NoError(t, err) + require.NoError(t, err) _, err = stream.CloseAndRecv() s, _ = status.FromError(err) assert.Equal(t, codes.InvalidArgument, s.Code()) @@ -1005,15 +1005,15 @@ func TestStreamRaftMessage(t *testing.T) { // Sending multiple of type != MsgSnap should return an error. stream, err = api.NewRaftClient(cc).StreamRaftMessage(ctx) - assert.NoError(t, err) + require.NoError(t, err) msg = raftutils.NewSnapshotMessage(2, 1, 10) msg.Type = raftpb.MsgApp raftMsg = &api.StreamRaftMessageRequest{Message: msg} err = stream.Send(raftMsg) - assert.NoError(t, err) + require.NoError(t, err) // Send same message again. err = stream.Send(raftMsg) - assert.NoError(t, err) + require.NoError(t, err) _, err = stream.CloseAndRecv() s, _ = status.FromError(err) assert.Equal(t, codes.InvalidArgument, s.Code()) @@ -1040,14 +1040,14 @@ func TestGetNodeIDByRaftID(t *testing.T) { // now go and get the nodeID of every raftID for _, id := range raftIDs { nodeid, err := nodes[1].GetNodeIDByRaftID(id) - assert.NoError(t, err, "raft ID %v should give us a node ID", id) + require.NoError(t, err, "raft ID %v should give us a node ID", id) // now go through the member manually list and make sure this is // correct for _, member := range members { - assert.True(t, + assert.Equal(t, // either both should match, or both should not match. if they // are different, then there is an error - (member.RaftID == id) == (member.NodeID == nodeid), + (member.RaftID == id), (member.NodeID == nodeid), "member with id %v has node id %v, but we expected member with id %v to have node id %v", member.RaftID, member.NodeID, id, nodeid, ) diff --git a/manager/state/raft/storage_test.go b/manager/state/raft/storage_test.go index cb5c731a36..7850be4f04 100644 --- a/manager/state/raft/storage_test.go +++ b/manager/state/raft/storage_test.go @@ -35,14 +35,14 @@ func TestRaftSnapshot(t *testing.T) { var err error for i, nodeID := range nodeIDs[:3] { values[i], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, nodeID) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") } // None of the nodes should have snapshot files yet for _, node := range nodes { dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) - assert.NoError(t, err) - assert.Len(t, dirents, 0) + require.NoError(t, err) + assert.Empty(t, dirents) } // Check all nodes have all the data. @@ -54,11 +54,11 @@ func TestRaftSnapshot(t *testing.T) { // Propose a 4th value values[3], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, nodeIDs[3]) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // All nodes should now have a snapshot file for nodeID, node := range nodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -75,7 +75,7 @@ func TestRaftSnapshot(t *testing.T) { raftutils.AddRaftNode(t, clockSource, nodes, tc) // It should get a copy of the snapshot - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(nodes[4].StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -106,12 +106,12 @@ func TestRaftSnapshot(t *testing.T) { // Propose more values to provoke a second snapshot for i := 4; i != len(nodeIDs); i++ { values[i], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, nodeIDs[i]) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") } // All nodes should have a snapshot under a *different* name for nodeID, node := range nodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -144,7 +144,7 @@ func TestRaftSnapshotRestart(t *testing.T) { var err error for i, nodeID := range nodeIDs[:3] { values[i], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, nodeID) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") } // Take down node 3 @@ -153,13 +153,13 @@ func TestRaftSnapshotRestart(t *testing.T) { // Propose a 4th value before the snapshot values[3], err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, nodeIDs[3]) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // Remaining nodes shouldn't have snapshot files yet for _, node := range []*raftutils.TestNode{nodes[1], nodes[2]} { dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) - assert.NoError(t, err) - assert.Len(t, dirents, 0) + require.NoError(t, err) + assert.Empty(t, dirents) } // Add a node to the cluster before the snapshot. This is the event @@ -169,7 +169,7 @@ func TestRaftSnapshotRestart(t *testing.T) { // Remaining nodes should now have a snapshot file for nodeIdx, node := range []*raftutils.TestNode{nodes[1], nodes[2]} { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -191,7 +191,7 @@ func TestRaftSnapshotRestart(t *testing.T) { raftutils.WaitForCluster(t, clockSource, map[uint64]*raftutils.TestNode{1: nodes[1], 2: nodes[2], 4: nodes[4], 5: nodes[5]}) // New node should get a copy of the snapshot - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(nodes[5].StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -203,7 +203,7 @@ func TestRaftSnapshotRestart(t *testing.T) { })) dirents, err := os.ReadDir(filepath.Join(nodes[5].StateDir, "snap-v3-encrypted")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, dirents, 1) raftutils.CheckValuesOnNodes(t, clockSource, map[uint64]*raftutils.TestNode{1: nodes[1], 2: nodes[2]}, nodeIDs[:5], values[:5]) @@ -264,7 +264,7 @@ func TestRaftSnapshotForceNewCluster(t *testing.T) { // Propose 3 values. for _, nodeID := range nodeIDs[:3] { _, err := raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, nodeID) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") } // Remove one of the original nodes @@ -272,13 +272,13 @@ func TestRaftSnapshotForceNewCluster(t *testing.T) { // Use gRPC instead of calling handler directly because of // authorization check. cc, err := dial(nodes[1], nodes[1].Address) - assert.NoError(t, err) + require.NoError(t, err) raftClient := api.NewRaftMembershipClient(cc) defer cc.Close() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) resp, err := raftClient.Leave(ctx, &api.LeaveRequest{Node: &api.RaftMember{RaftID: nodes[2].Config.ID}}) cancel() - assert.NoError(t, err, "error sending message to leave the raft") + require.NoError(t, err, "error sending message to leave the raft") assert.NotNil(t, resp, "leave response message is nil") raftutils.ShutdownNode(nodes[2]) @@ -287,17 +287,17 @@ func TestRaftSnapshotForceNewCluster(t *testing.T) { // Nodes shouldn't have snapshot files yet for _, node := range nodes { dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) - assert.NoError(t, err) - assert.Len(t, dirents, 0) + require.NoError(t, err) + assert.Empty(t, dirents) } // Trigger a snapshot, with a 4th proposal _, err = raftutils.ProposeValue(t, nodes[1], DefaultProposalTime, nodeIDs[3]) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") // Nodes should now have a snapshot file for nodeIdx, node := range nodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(node.StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -341,14 +341,14 @@ func TestGCWAL(t *testing.T) { for i := 0; i != proposals; i++ { _, err := proposeLargeValue(t, nodes[1], DefaultProposalTime, fmt.Sprintf("id%d", i)) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") } time.Sleep(250 * time.Millisecond) // Snapshot should have been triggered just as the WAL rotated, so // both WAL files should be preserved - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(nodes[1].StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -382,13 +382,13 @@ func TestGCWAL(t *testing.T) { for i := 0; i != proposals; i++ { _, err := proposeLargeValue(t, nodes[1], DefaultProposalTime, fmt.Sprintf("id%d", i)) - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") } time.Sleep(250 * time.Millisecond) // This time only one WAL file should be saved. - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { dirents, err := os.ReadDir(filepath.Join(nodes[1].StateDir, "snap-v3-encrypted")) if err != nil { return err @@ -431,7 +431,7 @@ func TestGCWAL(t *testing.T) { // Is the data intact after restart? for _, node := range nodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error node.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node @@ -450,10 +450,10 @@ func TestGCWAL(t *testing.T) { // It should still be possible to propose values _, err := raftutils.ProposeValue(t, raftutils.Leader(nodes), DefaultProposalTime, "newnode") - assert.NoError(t, err, "failed to propose value") + require.NoError(t, err, "failed to propose value") for _, node := range nodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error node.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node @@ -506,7 +506,7 @@ func proposeLargeValue(t *testing.T, raftNode *raftutils.TestNode, time time.Dur err := raftNode.ProposeValue(ctx, storeActions, func() { err := raftNode.MemoryStore().ApplyStoreActions(storeActions) - assert.NoError(t, err, "error applying actions") + require.NoError(t, err, "error applying actions") }) cancel() if err != nil { diff --git a/manager/state/raft/testutils/testutils.go b/manager/state/raft/testutils/testutils.go index 613f7f3128..4eff08658d 100644 --- a/manager/state/raft/testutils/testutils.go +++ b/manager/state/raft/testutils/testutils.go @@ -21,7 +21,6 @@ import ( "github.com/moby/swarmkit/v2/manager/state/store" "github.com/moby/swarmkit/v2/testutils" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" etcdraft "go.etcd.io/etcd/raft/v3" "go.etcd.io/etcd/raft/v3/raftpb" @@ -99,7 +98,7 @@ func WaitForCluster(t *testing.T, clockSource *fakeclock.FakeClock, nodes map[ui // WaitForPeerNumber waits until peers in cluster converge to specified number func WaitForPeerNumber(t *testing.T, clockSource *fakeclock.FakeClock, nodes map[uint64]*TestNode, count int) { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { for _, n := range nodes { if len(n.GetMemberlist()) != count { return errors.New("unexpected number of members") @@ -336,7 +335,7 @@ func NewInitNode(t *testing.T, tc *cautils.TestCA, raftConfig *api.RaftConfig, o <-leadershipCh if raftConfig != nil { - assert.NoError(t, n.MemoryStore().Update(func(tx store.Tx) error { + require.NoError(t, n.MemoryStore().Update(func(tx store.Tx) error { return store.CreateCluster(tx, &api.Cluster{ ID: identity.NewID(), Spec: api.ClusterSpec{ @@ -531,7 +530,7 @@ func ProposeValue(t *testing.T, raftNode *TestNode, time time.Duration, nodeID . err := raftNode.ProposeValue(ctx, storeActions, func() { err := raftNode.MemoryStore().ApplyStoreActions(storeActions) - assert.NoError(t, err, "error applying actions") + require.NoError(t, err, "error applying actions") }) cancel() if err != nil { @@ -543,7 +542,7 @@ func ProposeValue(t *testing.T, raftNode *TestNode, time time.Duration, nodeID . // CheckValue checks that the value has been propagated between raft members func CheckValue(t *testing.T, clockSource *fakeclock.FakeClock, raftNode *TestNode, createdNode *api.Node) { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error raftNode.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node @@ -566,7 +565,7 @@ func CheckValue(t *testing.T, clockSource *fakeclock.FakeClock, raftNode *TestNo // CheckNoValue checks that there is no value replicated on nodes, generally // used to test the absence of a leader func CheckNoValue(t *testing.T, clockSource *fakeclock.FakeClock, raftNode *TestNode) { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error raftNode.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node @@ -588,7 +587,7 @@ func CheckNoValue(t *testing.T, clockSource *fakeclock.FakeClock, raftNode *Test func CheckValuesOnNodes(t *testing.T, clockSource *fakeclock.FakeClock, checkNodes map[uint64]*TestNode, ids []string, values []*api.Node) { iteration := 0 for checkNodeID, node := range checkNodes { - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error node.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node @@ -622,7 +621,7 @@ func CheckValuesOnNodes(t *testing.T, clockSource *fakeclock.FakeClock, checkNod func GetAllValuesOnNode(t *testing.T, clockSource *fakeclock.FakeClock, raftNode *TestNode) ([]string, []*api.Node) { ids := []string{} values := []*api.Node{} - assert.NoError(t, testutils.PollFunc(clockSource, func() error { + require.NoError(t, testutils.PollFunc(clockSource, func() error { var err error raftNode.MemoryStore().View(func(tx store.ReadTx) { var allNodes []*api.Node diff --git a/manager/state/raft/transport/peer_test.go b/manager/state/raft/transport/peer_test.go index 9222624492..bfc0400177 100644 --- a/manager/state/raft/transport/peer_test.go +++ b/manager/state/raft/transport/peer_test.go @@ -23,7 +23,7 @@ func TestSplitSnapshot(t *testing.T) { check := func(size, expectedNumMsgs int) { raftMsg.Snapshot.Data = make([]byte, size) msgs := splitSnapshotData(ctx, &raftMsg) - assert.Equal(t, expectedNumMsgs, len(msgs), "unexpected number of messages") + assert.Len(t, msgs, expectedNumMsgs, "unexpected number of messages") } check(snaphotSize, int(math.Ceil(float64(snaphotSize)/float64(raftMessagePayloadSize)))) diff --git a/manager/state/raft/transport/transport_test.go b/manager/state/raft/transport/transport_test.go index 35e82772cd..21fc23512d 100644 --- a/manager/state/raft/transport/transport_test.go +++ b/manager/state/raft/transport/transport_test.go @@ -93,7 +93,7 @@ func testSend(ctx context.Context, c *mockCluster, from uint64, to []uint64, msg for _, id := range to { for _, s := range snaps { if s.id == id { - assert.Equal(t, s.status, raft.SnapshotFinish) + assert.Equal(t, raft.SnapshotFinish, s.status) continue loop } } @@ -163,15 +163,15 @@ func TestSendSnapshotFailure(t *testing.T) { select { case snap := <-c.Get(1).processedSnapshots: - assert.Equal(t, snap.id, uint64(2)) - assert.Equal(t, snap.status, raft.SnapshotFailure) + assert.Equal(t, uint64(2), snap.id) + assert.Equal(t, raft.SnapshotFailure, snap.status) case <-msgCtx.Done(): t.Fatal(ctx.Err()) } select { case id := <-c.Get(1).reportedUnreachables: - assert.Equal(t, id, uint64(2)) + assert.Equal(t, uint64(2), id) case <-msgCtx.Done(): t.Fatal(ctx.Err()) } @@ -204,8 +204,8 @@ func TestSendUnknown(t *testing.T) { select { case msg := <-c.Get(2).processedMessages: - assert.Equal(t, msg.To, uint64(2)) - assert.Equal(t, msg.From, uint64(1)) + assert.Equal(t, uint64(2), msg.To) + assert.Equal(t, uint64(1), msg.From) case <-msgCtx.Done(): t.Fatal(msgCtx.Err()) } @@ -263,7 +263,7 @@ func TestUpdatePeerAddrDelayed(t *testing.T) { defer updateCancel() select { case update := <-c.Get(1).updatedNodes: - require.Equal(t, update.id, uint64(3)) + require.Equal(t, uint64(3), update.id) require.Equal(t, update.addr, nr.Addr()) case <-updateCtx.Done(): t.Fatal(updateCtx.Err()) @@ -300,7 +300,7 @@ func TestSendUnreachable(t *testing.T) { require.Contains(t, err.Error(), "peer is unreachable") select { case id := <-c.Get(1).reportedUnreachables: - assert.Equal(t, id, uint64(2)) + assert.Equal(t, uint64(2), id) case <-msgCtx.Done(): t.Fatal(ctx.Err()) } diff --git a/manager/state/store/combinator_test.go b/manager/state/store/combinator_test.go index 98738d0126..47f139e0f9 100644 --- a/manager/state/store/combinator_test.go +++ b/manager/state/store/combinator_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestOrCombinator(t *testing.T) { @@ -14,35 +15,35 @@ func TestOrCombinator(t *testing.T) { s.View(func(readTx ReadTx) { foundNodes, err := FindNodes(readTx, Or()) - assert.NoError(t, err) - assert.Len(t, foundNodes, 0) + require.NoError(t, err) + assert.Empty(t, foundNodes) foundNodes, err = FindNodes(readTx, Or(ByName("name1"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(readTx, Or(ByName("name1"), ByName("name1"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(readTx, Or(ByName("name1"), ByName("name2"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 3) foundNodes, err = FindNodes(readTx, Or(ByName("name1"), ByIDPrefix("id1"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(readTx, Or(ByName("name1"), ByIDPrefix("id5295"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(readTx, Or(ByIDPrefix("id1"), ByIDPrefix("id2"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 2) foundNodes, err = FindNodes(readTx, Or(ByIDPrefix("id1"), ByIDPrefix("id2"), ByIDPrefix("id3"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 3) }) } diff --git a/manager/state/store/memory_test.go b/manager/state/store/memory_test.go index 8635bd8161..bf20fa09b5 100644 --- a/manager/state/store/memory_test.go +++ b/manager/state/store/memory_test.go @@ -424,49 +424,49 @@ func populateTestStore(t *testing.T, s *MemoryStore, err := s.Update(func(tx Tx) error { // Prepoulate clusters for _, c := range clusters { - assert.NoError(t, CreateCluster(tx, c)) + require.NoError(t, CreateCluster(tx, c)) } // Prepoulate nodes for _, n := range nodes { - assert.NoError(t, CreateNode(tx, n)) + require.NoError(t, CreateNode(tx, n)) } // Prepopulate services for _, s := range services { - assert.NoError(t, CreateService(tx, s)) + require.NoError(t, CreateService(tx, s)) } // Prepopulate tasks for _, task := range tasks { - assert.NoError(t, CreateTask(tx, task)) + require.NoError(t, CreateTask(tx, task)) } // Prepopulate networks for _, n := range networks { - assert.NoError(t, CreateNetwork(tx, n)) + require.NoError(t, CreateNetwork(tx, n)) } // Prepopulate configs for _, c := range configs { - assert.NoError(t, CreateConfig(tx, c)) + require.NoError(t, CreateConfig(tx, c)) } // Prepopulate secrets for _, s := range secrets { - assert.NoError(t, CreateSecret(tx, s)) + require.NoError(t, CreateSecret(tx, s)) } // Prepopulate extensions for _, c := range extensions { - assert.NoError(t, CreateExtension(tx, c)) + require.NoError(t, CreateExtension(tx, c)) } // Prepopulate resources for _, s := range resources { - assert.NoError(t, CreateResource(tx, s)) + require.NoError(t, CreateResource(tx, s)) } // Prepopulate volumes for _, v := range volumes { - assert.NoError(t, CreateVolume(tx, v)) + require.NoError(t, CreateVolume(tx, v)) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) } func TestStoreNode(t *testing.T) { @@ -475,7 +475,7 @@ func TestStoreNode(t *testing.T) { s.View(func(readTx ReadTx) { allNodes, err := FindNodes(readTx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, allNodes) }) @@ -483,13 +483,13 @@ func TestStoreNode(t *testing.T) { err := s.Update(func(tx Tx) error { allNodes, err := FindNodes(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allNodes, len(nodeSet)) - assert.Error(t, CreateNode(tx, nodeSet[0]), "duplicate IDs must be rejected") + require.Error(t, CreateNode(tx, nodeSet[0]), "duplicate IDs must be rejected") return nil }) - assert.NoError(t, err) + require.NoError(t, err) s.View(func(readTx ReadTx) { assert.Equal(t, nodeSet[0], GetNode(readTx, "id1")) @@ -497,36 +497,36 @@ func TestStoreNode(t *testing.T) { assert.Equal(t, nodeSet[2], GetNode(readTx, "id3")) foundNodes, err := FindNodes(readTx, ByName("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(readTx, ByName("name2")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 2) foundNodes, err = FindNodes(readTx, Or(ByName("name1"), ByName("name2"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 3) foundNodes, err = FindNodes(readTx, ByName("invalid")) - assert.NoError(t, err) - assert.Len(t, foundNodes, 0) + require.NoError(t, err) + assert.Empty(t, foundNodes) foundNodes, err = FindNodes(readTx, ByIDPrefix("id")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 3) foundNodes, err = FindNodes(readTx, ByRole(api.NodeRoleManager)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(readTx, ByRole(api.NodeRoleWorker)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 2) foundNodes, err = FindNodes(readTx, ByMembership(api.NodeMembershipPending)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(readTx, ByMembership(api.NodeMembershipAccepted)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 2) }) @@ -539,32 +539,32 @@ func TestStoreNode(t *testing.T) { } err = s.Update(func(tx Tx) error { assert.NotEqual(t, update, GetNode(tx, "id3")) - assert.NoError(t, UpdateNode(tx, update)) + require.NoError(t, UpdateNode(tx, update)) assert.Equal(t, update, GetNode(tx, "id3")) foundNodes, err := FindNodes(tx, ByName("name2")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(tx, ByName("name3")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) invalidUpdate := *nodeSet[0] invalidUpdate.ID = "invalid" - assert.Error(t, UpdateNode(tx, &invalidUpdate), "invalid IDs should be rejected") + require.Error(t, UpdateNode(tx, &invalidUpdate), "invalid IDs should be rejected") // Delete assert.NotNil(t, GetNode(tx, "id1")) - assert.NoError(t, DeleteNode(tx, "id1")) + require.NoError(t, DeleteNode(tx, "id1")) assert.Nil(t, GetNode(tx, "id1")) foundNodes, err = FindNodes(tx, ByName("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, foundNodes) assert.Equal(t, DeleteNode(tx, "nonexistent"), ErrNotExist) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } func TestStoreService(t *testing.T) { @@ -573,7 +573,7 @@ func TestStoreService(t *testing.T) { s.View(func(readTx ReadTx) { allServices, err := FindServices(readTx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, allServices) }) @@ -611,7 +611,7 @@ func TestStoreService(t *testing.T) { }), ErrNameConflict, "duplicate check should be case insensitive") return nil }) - assert.NoError(t, err) + require.NoError(t, err) s.View(func(readTx ReadTx) { assert.Equal(t, serviceSet[0], GetService(readTx, "id1")) @@ -619,23 +619,23 @@ func TestStoreService(t *testing.T) { assert.Equal(t, serviceSet[2], GetService(readTx, "id3")) foundServices, err := FindServices(readTx, ByNamePrefix("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundServices, 1) foundServices, err = FindServices(readTx, ByNamePrefix("NAME1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundServices, 1) foundServices, err = FindServices(readTx, ByNamePrefix("invalid")) - assert.NoError(t, err) - assert.Len(t, foundServices, 0) + require.NoError(t, err) + assert.Empty(t, foundServices) foundServices, err = FindServices(readTx, Or(ByNamePrefix("name1"), ByNamePrefix("name2"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundServices, 2) foundServices, err = FindServices(readTx, Or(ByNamePrefix("name1"), ByNamePrefix("name2"), ByNamePrefix("name4"))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundServices, 2) foundServices, err = FindServices(readTx, ByIDPrefix("id")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundServices, 3) }) @@ -648,7 +648,7 @@ func TestStoreService(t *testing.T) { } assert.NotEqual(t, update, GetService(tx, update.ID)) - assert.NoError(t, UpdateService(tx, update)) + require.NoError(t, UpdateService(tx, update)) assert.Equal(t, update, GetService(tx, update.ID)) // Name conflict. @@ -662,43 +662,43 @@ func TestStoreService(t *testing.T) { // Name change. update = GetService(tx, update.ID) foundServices, err := FindServices(tx, ByNamePrefix("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundServices, 1) foundServices, err = FindServices(tx, ByNamePrefix("name4")) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, foundServices) update.Spec.Annotations.Name = "name4" - assert.NoError(t, UpdateService(tx, update)) + require.NoError(t, UpdateService(tx, update)) foundServices, err = FindServices(tx, ByNamePrefix("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, foundServices) foundServices, err = FindServices(tx, ByNamePrefix("name4")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundServices, 1) // Invalid update. invalidUpdate := serviceSet[0].Copy() invalidUpdate.ID = "invalid" - assert.Error(t, UpdateService(tx, invalidUpdate), "invalid IDs should be rejected") + require.Error(t, UpdateService(tx, invalidUpdate), "invalid IDs should be rejected") return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Delete err = s.Update(func(tx Tx) error { assert.NotNil(t, GetService(tx, "id1")) - assert.NoError(t, DeleteService(tx, "id1")) + require.NoError(t, DeleteService(tx, "id1")) assert.Nil(t, GetService(tx, "id1")) foundServices, err := FindServices(tx, ByNamePrefix("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, foundServices) assert.Equal(t, DeleteService(tx, "nonexistent"), ErrNotExist) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } func TestStoreNetwork(t *testing.T) { @@ -707,7 +707,7 @@ func TestStoreNetwork(t *testing.T) { s.View(func(readTx ReadTx) { allNetworks, err := FindNetworks(readTx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, allNetworks) }) @@ -715,13 +715,13 @@ func TestStoreNetwork(t *testing.T) { err := s.Update(func(tx Tx) error { allNetworks, err := FindNetworks(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allNetworks, len(networkSet)) - assert.Error(t, CreateNetwork(tx, networkSet[0]), "duplicate IDs must be rejected") + require.Error(t, CreateNetwork(tx, networkSet[0]), "duplicate IDs must be rejected") return nil }) - assert.NoError(t, err) + require.NoError(t, err) s.View(func(readTx ReadTx) { assert.Equal(t, networkSet[0], GetNetwork(readTx, "id1")) @@ -729,30 +729,30 @@ func TestStoreNetwork(t *testing.T) { assert.Equal(t, networkSet[2], GetNetwork(readTx, "id3")) foundNetworks, err := FindNetworks(readTx, ByName("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNetworks, 1) foundNetworks, err = FindNetworks(readTx, ByName("name2")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNetworks, 1) foundNetworks, err = FindNetworks(readTx, ByName("invalid")) - assert.NoError(t, err) - assert.Len(t, foundNetworks, 0) + require.NoError(t, err) + assert.Empty(t, foundNetworks) }) err = s.Update(func(tx Tx) error { // Delete assert.NotNil(t, GetNetwork(tx, "id1")) - assert.NoError(t, DeleteNetwork(tx, "id1")) + require.NoError(t, DeleteNetwork(tx, "id1")) assert.Nil(t, GetNetwork(tx, "id1")) foundNetworks, err := FindNetworks(tx, ByName("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, foundNetworks) assert.Equal(t, DeleteNetwork(tx, "nonexistent"), ErrNotExist) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } func TestStoreTask(t *testing.T) { @@ -761,7 +761,7 @@ func TestStoreTask(t *testing.T) { s.View(func(tx ReadTx) { allTasks, err := FindTasks(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, allTasks) }) @@ -769,13 +769,13 @@ func TestStoreTask(t *testing.T) { err := s.Update(func(tx Tx) error { allTasks, err := FindTasks(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allTasks, len(taskSet)) - assert.Error(t, CreateTask(tx, taskSet[0]), "duplicate IDs must be rejected") + require.Error(t, CreateTask(tx, taskSet[0]), "duplicate IDs must be rejected") return nil }) - assert.NoError(t, err) + require.NoError(t, err) s.View(func(readTx ReadTx) { assert.Equal(t, taskSet[0], GetTask(readTx, "id1")) @@ -783,43 +783,43 @@ func TestStoreTask(t *testing.T) { assert.Equal(t, taskSet[2], GetTask(readTx, "id3")) foundTasks, err := FindTasks(readTx, ByNamePrefix("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) foundTasks, err = FindTasks(readTx, ByNamePrefix("name2")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 2) foundTasks, err = FindTasks(readTx, ByNamePrefix("invalid")) - assert.NoError(t, err) - assert.Len(t, foundTasks, 0) + require.NoError(t, err) + assert.Empty(t, foundTasks) foundTasks, err = FindTasks(readTx, ByNodeID(nodeSet[0].ID)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) assert.Equal(t, foundTasks[0], taskSet[0]) foundTasks, err = FindTasks(readTx, ByNodeID("invalid")) - assert.NoError(t, err) - assert.Len(t, foundTasks, 0) + require.NoError(t, err) + assert.Empty(t, foundTasks) foundTasks, err = FindTasks(readTx, ByServiceID(serviceSet[0].ID)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) assert.Equal(t, foundTasks[0], taskSet[1]) foundTasks, err = FindTasks(readTx, ByServiceID("invalid")) - assert.NoError(t, err) - assert.Len(t, foundTasks, 0) + require.NoError(t, err) + assert.Empty(t, foundTasks) foundTasks, err = FindTasks(readTx, ByDesiredState(api.TaskStateRunning)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 2) - assert.Equal(t, foundTasks[0].DesiredState, api.TaskStateRunning) - assert.Equal(t, foundTasks[0].DesiredState, api.TaskStateRunning) + assert.Equal(t, api.TaskStateRunning, foundTasks[0].DesiredState) + assert.Equal(t, api.TaskStateRunning, foundTasks[0].DesiredState) foundTasks, err = FindTasks(readTx, ByDesiredState(api.TaskStateShutdown)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) assert.Equal(t, foundTasks[0], taskSet[2]) foundTasks, err = FindTasks(readTx, ByDesiredState(api.TaskStatePending)) - assert.NoError(t, err) - assert.Len(t, foundTasks, 0) + require.NoError(t, err) + assert.Empty(t, foundTasks) }) // Update. @@ -834,32 +834,32 @@ func TestStoreTask(t *testing.T) { } err = s.Update(func(tx Tx) error { assert.NotEqual(t, update, GetTask(tx, "id3")) - assert.NoError(t, UpdateTask(tx, update)) + require.NoError(t, UpdateTask(tx, update)) assert.Equal(t, update, GetTask(tx, "id3")) foundTasks, err := FindTasks(tx, ByNamePrefix("name2")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) foundTasks, err = FindTasks(tx, ByNamePrefix("name3")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundTasks, 1) invalidUpdate := *taskSet[0] invalidUpdate.ID = "invalid" - assert.Error(t, UpdateTask(tx, &invalidUpdate), "invalid IDs should be rejected") + require.Error(t, UpdateTask(tx, &invalidUpdate), "invalid IDs should be rejected") // Delete assert.NotNil(t, GetTask(tx, "id1")) - assert.NoError(t, DeleteTask(tx, "id1")) + require.NoError(t, DeleteTask(tx, "id1")) assert.Nil(t, GetTask(tx, "id1")) foundTasks, err = FindTasks(tx, ByNamePrefix("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, foundTasks) assert.Equal(t, DeleteTask(tx, "nonexistent"), ErrNotExist) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } func TestStoreSnapshot(t *testing.T) { @@ -921,7 +921,7 @@ func TestStoreSnapshot(t *testing.T) { // Fork watcher, cancel, err := ViewAndWatch(s1, copyToS2) defer cancel() - assert.NoError(t, err) + require.NoError(t, err) s2.View(func(tx2 ReadTx) { assert.Equal(t, nodeSet[0], GetNode(tx2, "id1")) @@ -948,12 +948,12 @@ func TestStoreSnapshot(t *testing.T) { } err = s1.Update(func(tx1 Tx) error { - assert.NoError(t, CreateNode(tx1, createNode)) + require.NoError(t, CreateNode(tx1, createNode)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -971,12 +971,12 @@ func TestStoreSnapshot(t *testing.T) { } err = s1.Update(func(tx1 Tx) error { - assert.NoError(t, UpdateNode(tx1, updateNode)) + require.NoError(t, UpdateNode(tx1, updateNode)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -985,12 +985,12 @@ func TestStoreSnapshot(t *testing.T) { err = s1.Update(func(tx1 Tx) error { // Delete node - assert.NoError(t, DeleteNode(tx1, "id1")) + require.NoError(t, DeleteNode(tx1, "id1")) return nil }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -1008,12 +1008,12 @@ func TestStoreSnapshot(t *testing.T) { } err = s1.Update(func(tx1 Tx) error { - assert.NoError(t, CreateService(tx1, createService)) + require.NoError(t, CreateService(tx1, createService)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -1025,12 +1025,12 @@ func TestStoreSnapshot(t *testing.T) { updateService.Spec.Annotations.Name = "new-name" err = s1.Update(func(tx1 Tx) error { assert.NotEqual(t, updateService, GetService(tx1, updateService.ID)) - assert.NoError(t, UpdateService(tx1, updateService)) + require.NoError(t, UpdateService(tx1, updateService)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -1039,12 +1039,12 @@ func TestStoreSnapshot(t *testing.T) { err = s1.Update(func(tx1 Tx) error { // Delete service - assert.NoError(t, DeleteService(tx1, "id1")) + require.NoError(t, DeleteService(tx1, "id1")) return nil }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -1060,12 +1060,12 @@ func TestStoreSnapshot(t *testing.T) { } err = s1.Update(func(tx1 Tx) error { - assert.NoError(t, CreateTask(tx1, createTask)) + require.NoError(t, CreateTask(tx1, createTask)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -1081,11 +1081,11 @@ func TestStoreSnapshot(t *testing.T) { } err = s1.Update(func(tx1 Tx) error { - assert.NoError(t, UpdateTask(tx1, updateTask)) + require.NoError(t, UpdateTask(tx1, updateTask)) return nil }) - assert.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, err) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -1094,11 +1094,11 @@ func TestStoreSnapshot(t *testing.T) { err = s1.Update(func(tx1 Tx) error { // Delete task - assert.NoError(t, DeleteTask(tx1, "id1")) + require.NoError(t, DeleteTask(tx1, "id1")) return nil }) - assert.NoError(t, err) - assert.NoError(t, Apply(s2, <-watcher)) + require.NoError(t, err) + require.NoError(t, Apply(s2, <-watcher)) <-watcher // consume commit event s2.View(func(tx2 ReadTx) { @@ -1115,7 +1115,7 @@ func TestCustomIndex(t *testing.T) { // Add a custom index entry to each node err := s.Update(func(tx Tx) error { allNodes, err := FindNodes(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allNodes, len(nodeSet)) for _, n := range allNodes { @@ -1124,18 +1124,18 @@ func TestCustomIndex(t *testing.T) { n.Spec.Annotations.Indices = []api.IndexEntry{ {Key: "nodesbefore", Val: "id1"}, } - assert.NoError(t, UpdateNode(tx, n)) + require.NoError(t, UpdateNode(tx, n)) case "id3": n.Spec.Annotations.Indices = []api.IndexEntry{ {Key: "nodesbefore", Val: "id1"}, {Key: "nodesbefore", Val: "id2"}, } - assert.NoError(t, UpdateNode(tx, n)) + require.NoError(t, UpdateNode(tx, n)) } } return nil }) - assert.NoError(t, err) + require.NoError(t, err) s.View(func(readTx ReadTx) { foundNodes, err := FindNodes(readTx, ByCustom("", "nodesbefore", "id2")) @@ -1149,7 +1149,7 @@ func TestCustomIndex(t *testing.T) { foundNodes, err = FindNodes(readTx, ByCustom("", "nodesbefore", "id3")) require.NoError(t, err) - require.Len(t, foundNodes, 0) + require.Empty(t, foundNodes) foundNodes, err = FindNodes(readTx, ByCustomPrefix("", "nodesbefore", "id")) require.NoError(t, err) @@ -1157,7 +1157,7 @@ func TestCustomIndex(t *testing.T) { foundNodes, err = FindNodes(readTx, ByCustomPrefix("", "nodesbefore", "id6")) require.NoError(t, err) - require.Len(t, foundNodes, 0) + require.Empty(t, foundNodes) }) } @@ -1174,10 +1174,10 @@ func TestFailedTransaction(t *testing.T) { }, } - assert.NoError(t, CreateNode(tx, n)) + require.NoError(t, CreateNode(tx, n)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Create a second node, but then roll back the transaction err = s.Update(func(tx Tx) error { @@ -1188,21 +1188,21 @@ func TestFailedTransaction(t *testing.T) { }, } - assert.NoError(t, CreateNode(tx, n)) + require.NoError(t, CreateNode(tx, n)) return errors.New("rollback") }) - assert.Error(t, err) + require.Error(t, err) s.View(func(tx ReadTx) { foundNodes, err := FindNodes(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(tx, ByName("name1")) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, foundNodes, 1) foundNodes, err = FindNodes(tx, ByName("name2")) - assert.NoError(t, err) - assert.Len(t, foundNodes, 0) + require.NoError(t, err) + assert.Empty(t, foundNodes) }) } @@ -1225,19 +1225,19 @@ func TestVersion(t *testing.T) { }, } err := s.Update(func(tx Tx) error { - assert.NoError(t, CreateNode(tx, n)) + require.NoError(t, CreateNode(tx, n)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Update the node using an object fetched from the store. n.Spec.Annotations.Name = "name2" err = s.Update(func(tx Tx) error { - assert.NoError(t, UpdateNode(tx, n)) + require.NoError(t, UpdateNode(tx, n)) retrievedNode = GetNode(tx, n.ID) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Make sure the store is updating our local copy with the version. assert.Equal(t, n.Meta.Version, retrievedNode.Meta.Version) @@ -1245,11 +1245,11 @@ func TestVersion(t *testing.T) { // Try again, this time using the retrieved node. retrievedNode.Spec.Annotations.Name = "name2" err = s.Update(func(tx Tx) error { - assert.NoError(t, UpdateNode(tx, retrievedNode)) + require.NoError(t, UpdateNode(tx, retrievedNode)) retrievedNode2 = GetNode(tx, n.ID) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Try to update retrievedNode again. This should fail because it was // already used to perform an update. @@ -1258,16 +1258,16 @@ func TestVersion(t *testing.T) { assert.Equal(t, ErrSequenceConflict, UpdateNode(tx, n)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // But using retrievedNode2 should work, since it has the latest // sequence information. retrievedNode2.Spec.Annotations.Name = "name3" err = s.Update(func(tx Tx) error { - assert.NoError(t, UpdateNode(tx, retrievedNode2)) + require.NoError(t, UpdateNode(tx, retrievedNode2)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } func TestTimestamps(t *testing.T) { @@ -1289,10 +1289,10 @@ func TestTimestamps(t *testing.T) { }, } err := s.Update(func(tx Tx) error { - assert.NoError(t, CreateNode(tx, n)) + require.NoError(t, CreateNode(tx, n)) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Make sure our local copy got updated. assert.NotZero(t, n.Meta.CreatedAt) @@ -1310,11 +1310,11 @@ func TestTimestamps(t *testing.T) { // Make an update. retrievedNode.Spec.Annotations.Name = "name2" err = s.Update(func(tx Tx) error { - assert.NoError(t, UpdateNode(tx, retrievedNode)) + require.NoError(t, UpdateNode(tx, retrievedNode)) updatedNode = GetNode(tx, n.ID) return nil }) - assert.NoError(t, err) + require.NoError(t, err) // Ensure `CreatedAt` is the same after the update and `UpdatedAt` got updated. assert.Equal(t, updatedNode.Meta.CreatedAt, n.Meta.CreatedAt) @@ -1341,45 +1341,39 @@ func TestBatch(t *testing.T) { } batch.Update(func(tx Tx) error { - assert.NoError(t, CreateNode(tx, n)) + require.NoError(t, CreateNode(tx, n)) return nil }) } return nil }) - assert.NoError(t, err) + require.NoError(t, err) for i := 0; i != MaxChangesPerTransaction; i++ { event := <-watch - if _, ok := event.(api.EventCreateNode); !ok { - t.Fatalf("expected EventCreateNode; got %#v", event) - } + _, ok := event.(api.EventCreateNode) + require.Truef(t, ok, "expected EventCreateNode; got %#v", event) } event := <-watch - if _, ok := event.(state.EventCommit); !ok { - t.Fatalf("expected EventCommit; got %#v", event) - } + _, ok := event.(state.EventCommit) + require.Truef(t, ok, "expected EventCommit; got %#v", event) for i := 0; i != MaxChangesPerTransaction; i++ { event := <-watch - if _, ok := event.(api.EventCreateNode); !ok { - t.Fatalf("expected EventCreateNode; got %#v", event) - } + _, ok := event.(api.EventCreateNode) + require.Truef(t, ok, "expected EventCreateNode; got %#v", event) } event = <-watch - if _, ok := event.(state.EventCommit); !ok { - t.Fatalf("expected EventCommit; got %#v", event) - } + _, ok = event.(state.EventCommit) + require.Truef(t, ok, "expected EventCommit; got %#v", event) for i := 0; i != 5; i++ { event := <-watch - if _, ok := event.(api.EventCreateNode); !ok { - t.Fatalf("expected EventCreateNode; got %#v", event) - } + _, ok := event.(api.EventCreateNode) + require.Truef(t, ok, "expected EventCreateNode; got %#v", event) } event = <-watch - if _, ok := event.(state.EventCommit); !ok { - t.Fatalf("expected EventCommit; got %#v", event) - } + _, ok = event.(state.EventCommit) + require.Truef(t, ok, "expected EventCommit; got %#v", event) } func TestBatchFailure(t *testing.T) { @@ -1402,7 +1396,7 @@ func TestBatchFailure(t *testing.T) { } batch.Update(func(tx Tx) error { - assert.NoError(t, CreateNode(tx, n)) + require.NoError(t, CreateNode(tx, n)) return nil }) if i == MaxChangesPerTransaction+8 { @@ -1410,18 +1404,16 @@ func TestBatchFailure(t *testing.T) { } } }) - assert.Error(t, err) + require.Error(t, err) for i := 0; i != MaxChangesPerTransaction; i++ { event := <-watch - if _, ok := event.(api.EventCreateNode); !ok { - t.Fatalf("expected EventCreateNode; got %#v", event) - } + _, ok := event.(api.EventCreateNode) + require.Truef(t, ok, "expected EventCreateNode; got %#v", event) } event := <-watch - if _, ok := event.(state.EventCommit); !ok { - t.Fatalf("expected EventCommit; got %#v", event) - } + _, ok := event.(state.EventCommit) + require.Truef(t, ok, "expected EventCommit; got %#v", event) // Shouldn't be anything after the first transaction select { @@ -1441,7 +1433,7 @@ func TestStoreSaveRestore(t *testing.T) { s1.View(func(tx ReadTx) { var err error snapshot, err = s1.Save(tx) - assert.NoError(t, err) + require.NoError(t, err) }) s2 := NewMemoryStore(nil) @@ -1487,78 +1479,78 @@ func TestStoreSaveRestore(t *testing.T) { watcher, cancel, err := ViewAndWatch(s2, func(ReadTx) error { return nil }) - assert.NoError(t, err) + require.NoError(t, err) defer cancel() err = s2.Restore(snapshot) - assert.NoError(t, err) + require.NoError(t, err) // s2 should end up looking just like s1 s2.View(func(tx ReadTx) { allClusters, err := FindClusters(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allClusters, len(clusterSet)) for i := range allClusters { assert.Equal(t, allClusters[i], clusterSet[i]) } allTasks, err := FindTasks(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allTasks, len(taskSet)) for i := range allTasks { assert.Equal(t, allTasks[i], taskSet[i]) } allNodes, err := FindNodes(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allNodes, len(nodeSet)) for i := range allNodes { assert.Equal(t, allNodes[i], nodeSet[i]) } allNetworks, err := FindNetworks(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allNetworks, len(networkSet)) for i := range allNetworks { assert.Equal(t, allNetworks[i], networkSet[i]) } allServices, err := FindServices(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allServices, len(serviceSet)) for i := range allServices { assert.Equal(t, allServices[i], serviceSet[i]) } allConfigs, err := FindConfigs(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allConfigs, len(configSet)) for i := range allConfigs { assert.Equal(t, allConfigs[i], configSet[i]) } allSecrets, err := FindSecrets(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allSecrets, len(secretSet)) for i := range allSecrets { assert.Equal(t, allSecrets[i], secretSet[i]) } allExtensions, err := FindExtensions(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allExtensions, len(extensionSet)) for i := range allExtensions { assert.Equal(t, allExtensions[i], extensionSet[i]) } allResources, err := FindResources(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allResources, len(resourceSet)) for i := range allResources { assert.Equal(t, allResources[i], resourceSet[i]) } allVolumes, err := FindVolumes(tx, All) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, allVolumes, len(volumeSet)) for i := range allVolumes { assert.Equal(t, allVolumes[i], volumeSet[i]) @@ -1702,7 +1694,7 @@ waitForAllEvents: } assertHasSameIDs := func(changes []api.StoreObject, expected ...api.StoreObject) { - assert.Equal(t, len(expected), len(changes)) + assert.Len(t, changes, len(expected)) expectedIDs := make(map[string]struct{}) for _, s := range expected { expectedIDs[s.GetID()] = struct{}{} @@ -1820,21 +1812,21 @@ func TestWatchFrom(t *testing.T) { } batch.Update(func(tx Tx) error { - assert.NoError(t, CreateNode(tx, node)) + require.NoError(t, CreateNode(tx, node)) return nil }) batch.Update(func(tx Tx) error { - assert.NoError(t, CreateService(tx, service)) + require.NoError(t, CreateService(tx, service)) return nil }) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } // Try to watch from an invalid index _, _, err := WatchFrom(s, &api.Version{Index: 5000}) - assert.Error(t, err) + require.Error(t, err) watch1, cancel1, err := WatchFrom(s, &api.Version{Index: 10}, api.EventCreateNode{}, state.EventCommit{}) require.NoError(t, err) @@ -1844,9 +1836,7 @@ func TestWatchFrom(t *testing.T) { select { case event := <-watch1: nodeEvent, ok := event.(api.EventCreateNode) - if !ok { - t.Fatal("wrong event type - expected node create") - } + require.True(t, ok, "wrong event type - expected node create") if i == 0 { assert.Equal(t, "id3", nodeEvent.Node.ID) @@ -1858,9 +1848,8 @@ func TestWatchFrom(t *testing.T) { } select { case event := <-watch1: - if _, ok := event.(state.EventCommit); !ok { - t.Fatal("wrong event type - expected commit") - } + _, ok := event.(state.EventCommit) + require.True(t, ok, "wrong event type - expected commit") case <-time.After(time.Second): t.Fatal("timed out waiting for event") } @@ -1873,24 +1862,21 @@ func TestWatchFrom(t *testing.T) { select { case event := <-watch2: serviceEvent, ok := event.(api.EventCreateService) - if !ok { - t.Fatal("wrong event type - expected service create") - } + require.True(t, ok, "wrong event type - expected service create") assert.Equal(t, "id4", serviceEvent.Service.ID) case <-time.After(time.Second): t.Fatal("timed out waiting for event") } select { case event := <-watch2: - if _, ok := event.(state.EventCommit); !ok { - t.Fatal("wrong event type - expected commit") - } + _, ok := event.(state.EventCommit) + require.True(t, ok, "wrong event type - expected commit") case <-time.After(time.Second): t.Fatal("timed out waiting for event") } // Create some new objects and make sure they show up in the watches. - assert.NoError(t, s.Update(func(tx Tx) error { + require.NoError(t, s.Update(func(tx Tx) error { node := &api.Node{ ID: "newnode", Spec: api.NodeSpec{ @@ -1909,26 +1895,23 @@ func TestWatchFrom(t *testing.T) { }, } - assert.NoError(t, CreateNode(tx, node)) - assert.NoError(t, CreateService(tx, service)) + require.NoError(t, CreateNode(tx, node)) + require.NoError(t, CreateService(tx, service)) return nil })) select { case event := <-watch1: nodeEvent, ok := event.(api.EventCreateNode) - if !ok { - t.Fatalf("wrong event type - expected node create, got %T", event) - } + require.Truef(t, ok, "wrong event type - expected node create, got %T", event) assert.Equal(t, "newnode", nodeEvent.Node.ID) case <-time.After(time.Second): t.Fatal("timed out waiting for event") } select { case event := <-watch1: - if _, ok := event.(state.EventCommit); !ok { - t.Fatal("wrong event type - expected commit") - } + _, ok := event.(state.EventCommit) + require.True(t, ok, "wrong event type - expected commit") case <-time.After(time.Second): t.Fatal("timed out waiting for event") } @@ -1936,23 +1919,20 @@ func TestWatchFrom(t *testing.T) { select { case event := <-watch2: serviceEvent, ok := event.(api.EventCreateService) - if !ok { - t.Fatalf("wrong event type - expected service create, got %T", event) - } + require.Truef(t, ok, "wrong event type - expected service create, got %T", event) assert.Equal(t, "newservice", serviceEvent.Service.ID) case <-time.After(time.Second): t.Fatal("timed out waiting for event") } select { case event := <-watch2: - if _, ok := event.(state.EventCommit); !ok { - t.Fatal("wrong event type - expected commit") - } + _, ok := event.(state.EventCommit) + require.True(t, ok, "wrong event type - expected commit") case <-time.After(time.Second): t.Fatal("timed out waiting for event") } - assert.NoError(t, s.Update(func(tx Tx) error { + require.NoError(t, s.Update(func(tx Tx) error { node := &api.Node{ ID: "newnode2", Spec: api.NodeSpec{ @@ -1962,34 +1942,30 @@ func TestWatchFrom(t *testing.T) { }, } - assert.NoError(t, CreateNode(tx, node)) + require.NoError(t, CreateNode(tx, node)) return nil })) select { case event := <-watch1: nodeEvent, ok := event.(api.EventCreateNode) - if !ok { - t.Fatalf("wrong event type - expected node create, got %T", event) - } + require.Truef(t, ok, "wrong event type - expected node create, got %T", event) assert.Equal(t, "newnode2", nodeEvent.Node.ID) case <-time.After(time.Second): t.Fatal("timed out waiting for event") } select { case event := <-watch1: - if _, ok := event.(state.EventCommit); !ok { - t.Fatal("wrong event type - expected commit") - } + _, ok := event.(state.EventCommit) + require.True(t, ok, "wrong event type - expected commit") case <-time.After(time.Second): t.Fatal("timed out waiting for event") } select { case event := <-watch2: - if _, ok := event.(state.EventCommit); !ok { - t.Fatal("wrong event type - expected commit") - } + _, ok := event.(state.EventCommit) + require.True(t, ok, "wrong event type - expected commit") case <-time.After(time.Second): t.Fatal("timed out waiting for event") } diff --git a/manager/watchapi/server_test.go b/manager/watchapi/server_test.go index 3cb3a562c8..d98e9f1bdd 100644 --- a/manager/watchapi/server_test.go +++ b/manager/watchapi/server_test.go @@ -53,14 +53,14 @@ func newTestServer(t *testing.T) *testServer { require.NoError(t, ts.Server.Start(context.Background())) temp, err := os.CreateTemp("", "test-socket") - assert.NoError(t, err) - assert.NoError(t, temp.Close()) - assert.NoError(t, os.Remove(temp.Name())) + require.NoError(t, err) + require.NoError(t, temp.Close()) + require.NoError(t, os.Remove(temp.Name())) ts.tempUnixSocket = temp.Name() lis, err := net.Listen("unix", temp.Name()) - assert.NoError(t, err) + require.NoError(t, err) ts.grpcServer = grpc.NewServer() api.RegisterWatchServer(ts.grpcServer, ts.Server) @@ -74,7 +74,7 @@ func newTestServer(t *testing.T) *testServer { grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("unix", addr, timeout) })) - assert.NoError(t, err) + require.NoError(t, err) ts.clientConn = conn ts.Client = api.NewWatchClient(conn) @@ -96,7 +96,7 @@ func createNode(t *testing.T, ts *testServer, id string, role api.NodeRole, memb err := ts.Store.Update(func(tx store.Tx) error { return store.CreateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) return node } diff --git a/manager/watchapi/watch_test.go b/manager/watchapi/watch_test.go index 79aba858a9..962f44d60c 100644 --- a/manager/watchapi/watch_test.go +++ b/manager/watchapi/watch_test.go @@ -25,16 +25,16 @@ func TestWatch(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) // Should receive an initial message that indicates the watch is ready msg, err := watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &api.WatchMessage{}, msg) createNode(t, ts, "id1", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindCreate, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id1", msg.Events[0].Object.GetNode().ID) @@ -77,16 +77,16 @@ func TestWatch(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) // Should receive an initial message that indicates the watch is ready msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &api.WatchMessage{}, msg) createNode(t, ts, "id2", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindCreate, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id2", msg.Events[0].Object.GetNode().ID) @@ -109,7 +109,7 @@ func TestWatch(t *testing.T) { err = ts.Store.Update(func(tx store.Tx) error { return store.CreateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) // Shouldn't be seen either - hostname doesn't match filter node = &api.Node{ @@ -129,7 +129,7 @@ func TestWatch(t *testing.T) { err = ts.Store.Update(func(tx store.Tx) error { return store.CreateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) // This one should be seen node = &api.Node{ @@ -149,10 +149,10 @@ func TestWatch(t *testing.T) { err = ts.Store.Update(func(tx store.Tx) error { return store.CreateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindCreate, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id6", msg.Events[0].Object.GetNode().ID) @@ -175,16 +175,16 @@ func TestWatchMultipleActions(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) // Should receive an initial message that indicates the watch is ready msg, err := watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &api.WatchMessage{}, msg) createNode(t, ts, "id1", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindCreate, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id1", msg.Events[0].Object.GetNode().ID) @@ -196,15 +196,15 @@ func TestWatchMultipleActions(t *testing.T) { node.Role = api.NodeRoleWorker return store.UpdateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) // Delete should be seen err = ts.Store.Update(func(tx store.Tx) error { return store.DeleteNode(tx, "id1") }) - assert.NoError(t, err) + require.NoError(t, err) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindRemove, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id1", msg.Events[0].Object.GetNode().ID) @@ -228,11 +228,11 @@ func TestWatchIncludeOldObject(t *testing.T) { }, IncludeOldObject: true, }) - assert.NoError(t, err) + require.NoError(t, err) // Should receive an initial message that indicates the watch is ready msg, err := watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &api.WatchMessage{}, msg) createNode(t, ts, "id1", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) @@ -243,10 +243,10 @@ func TestWatchIncludeOldObject(t *testing.T) { node.Role = api.NodeRoleWorker return store.UpdateNode(tx, node) }) - assert.NoError(t, err) + require.NoError(t, err) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindUpdate, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id1", msg.Events[0].Object.GetNode().ID) @@ -277,15 +277,15 @@ func TestWatchResumeFrom(t *testing.T) { }, ResumeFrom: &node2.Meta.Version, }) - assert.NoError(t, err) + require.NoError(t, err) // Should receive an initial message that indicates the watch is ready msg, err := watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &api.WatchMessage{}, msg) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindCreate, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id2", msg.Events[0].Object.GetNode().ID) @@ -295,7 +295,7 @@ func TestWatchResumeFrom(t *testing.T) { node3 := createNode(t, ts, "id3", api.NodeRoleManager, api.NodeMembershipAccepted, api.NodeStatus_READY) msg, err = watch.Recv() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, api.WatchActionKindCreate, msg.Events[0].Action) require.NotNil(t, msg.Events[0].Object.GetNode()) assert.Equal(t, "id3", msg.Events[0].Object.GetNode().ID) diff --git a/node/node_test.go b/node/node_test.go index cdf9e8d680..f836b4bdcc 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -566,9 +566,7 @@ func TestCertRenewals(t *testing.T) { nodeCert, err := os.ReadFile(paths.Node.Cert) require.NoError(t, err) - if !bytes.Equal(currentNodeCert, nodeCert) { - t.Fatal("Certificate should not have been renewed") - } + require.True(t, bytes.Equal(currentNodeCert, nodeCert), "Certificate should not have been renewed") // Fake an update from the dispatcher. When DesiredRole doesn't match // the current role, a cert renewal should be triggered. diff --git a/protobuf/plugin/raftproxy/test/raftproxy_test.go b/protobuf/plugin/raftproxy/test/raftproxy_test.go index 1dde5c25e3..07a0037f1b 100644 --- a/protobuf/plugin/raftproxy/test/raftproxy_test.go +++ b/protobuf/plugin/raftproxy/test/raftproxy_test.go @@ -59,6 +59,6 @@ func TestSimpleRedirect(t *testing.T) { client := NewRouteGuideClient(conn) _, err = client.GetFeature(context.Background(), &Point{}) - assert.NotNil(t, err) + require.Error(t, err) assert.Equal(t, codes.ResourceExhausted, testutils.ErrorCode(err)) } diff --git a/remotes/remotes_test.go b/remotes/remotes_test.go index 03dcc0d19d..01cf8f0259 100644 --- a/remotes/remotes_test.go +++ b/remotes/remotes_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/moby/swarmkit/v2/api" + "github.com/stretchr/testify/require" ) func TestRemotesSimple(t *testing.T) { @@ -15,33 +16,25 @@ func TestRemotesSimple(t *testing.T) { seen := make(map[api.Peer]int) for i := 0; i < len(peers)*10; i++ { next, err := remotes.Select() - if err != nil { - t.Fatalf("error selecting remote: %v", err) - } + require.NoErrorf(t, err, "error selecting remote: %v", err) - if _, ok := index[next]; !ok { - t.Fatalf("unexpected remote returned: %q", next) - } + _, ok := index[next] + require.Truef(t, ok, "unexpected remote returned: %q", next) seen[next]++ } for _, peer := range peers { - if _, ok := seen[peer]; !ok { - t.Fatalf("%q not returned after several selection attempts", peer) - } + _, ok := seen[peer] + require.Truef(t, ok, "%q not returned after several selection attempts", peer) } weights := remotes.Weights() var value int for peer := range seen { weight, ok := weights[peer] - if !ok { - t.Fatalf("unexpected remote returned: %v", peer) - } + require.Truef(t, ok, "unexpected remote returned: %v", peer) - if weight <= 0 { - t.Fatalf("weight should not be zero or less: %v (%v)", weight, remotes.Weights()) - } + require.Positivef(t, weight, "weight should not be zero or less: %v (%v)", weight, remotes.Weights()) if value == 0 { // sets benchmark weight, they should all be the same @@ -49,9 +42,7 @@ func TestRemotesSimple(t *testing.T) { continue } - if weight != value { - t.Fatalf("all weights should be same %q: %v != %v, %v", peer, weight, value, weights) - } + require.Equalf(t, weight, value, "all weights should be same %q: %v != %v, %v", peer, weight, value, weights) } } @@ -59,9 +50,7 @@ func TestRemotesEmpty(t *testing.T) { remotes := NewRemotes() _, err := remotes.Select() - if err != errRemotesUnavailable { - t.Fatalf("unexpected return from Select: %v", err) - } + require.Equalf(t, err, errRemotesUnavailable, "unexpected return from Select: %v", err) } @@ -72,32 +61,21 @@ func TestRemotesExclude(t *testing.T) { // exclude all _, err := remotes.Select(excludes...) - if err != errRemotesUnavailable { - t.Fatal("select an excluded peer") - } + require.Equal(t, err, errRemotesUnavailable, "select an excluded peer") // exclude one peer for i := 0; i < len(peers)*10; i++ { next, err := remotes.Select(excludes[0]) - if err != nil { - t.Fatalf("error selecting remote: %v", err) - } + require.NoErrorf(t, err, "error selecting remote: %v", err) - if next == peers[0] { - t.Fatal("select an excluded peer") - } + require.NotEqual(t, next, peers[0], "select an excluded peer") } // exclude 2 peers for i := 0; i < len(peers)*10; i++ { next, err := remotes.Select(excludes[1:]...) - if err != nil { - t.Fatalf("error selecting remote: %v", err) - } - - if next != peers[0] { - t.Fatalf("select an excluded peer: %v", next) - } + require.NoErrorf(t, err, "error selecting remote: %v", err) + require.Equalf(t, next, peers[0], "select an excluded peer: %v", next) } } @@ -109,36 +87,26 @@ func TestRemotesConvergence(t *testing.T) { remotes.Observe(api.Peer{Addr: "one"}, DefaultObservationWeight) // zero weighted against 1 - if float64(remotes.Weights()[api.Peer{Addr: "one"}]) < remoteWeightSmoothingFactor { - t.Fatalf("unexpected weight: %v < %v", remotes.Weights()[api.Peer{Addr: "one"}], remoteWeightSmoothingFactor) - } + require.GreaterOrEqualf(t, float64(remotes.Weights()[api.Peer{Addr: "one"}]), remoteWeightSmoothingFactor, "unexpected weight: %v < %v", remotes.Weights()[api.Peer{Addr: "one"}], remoteWeightSmoothingFactor) // crank it up for i := 0; i < 10; i++ { remotes.Observe(api.Peer{Addr: "one"}, DefaultObservationWeight) } - if float64(remotes.Weights()[api.Peer{Addr: "one"}]) < remoteWeightSmoothingFactor { - t.Fatalf("did not converge towards 1: %v < %v", remotes.Weights()[api.Peer{Addr: "one"}], remoteWeightSmoothingFactor) - } + require.GreaterOrEqualf(t, float64(remotes.Weights()[api.Peer{Addr: "one"}]), remoteWeightSmoothingFactor, "did not converge towards 1: %v < %v", remotes.Weights()[api.Peer{Addr: "one"}], remoteWeightSmoothingFactor) - if remotes.Weights()[api.Peer{Addr: "one"}] > remoteWeightMax { - t.Fatalf("should never go over towards %v: %v > %v", remoteWeightMax, remotes.Weights()[api.Peer{Addr: "one"}], 1.0) - } + require.LessOrEqualf(t, remotes.Weights()[api.Peer{Addr: "one"}], remoteWeightMax, "should never go over towards %v: %v > %v", remoteWeightMax, remotes.Weights()[api.Peer{Addr: "one"}], 1.0) // provided a poor review remotes.Observe(api.Peer{Addr: "one"}, -DefaultObservationWeight) - if remotes.Weights()[api.Peer{Addr: "one"}] > 0 { - t.Fatalf("should be below zero: %v", remotes.Weights()[api.Peer{Addr: "one"}]) - } + require.LessOrEqualf(t, remotes.Weights()[api.Peer{Addr: "one"}], 0, "should be below zero: %v", remotes.Weights()[api.Peer{Addr: "one"}]) // The remote should be heavily downweighted but not completely to -1 expected := (-remoteWeightSmoothingFactor + (1 - remoteWeightSmoothingFactor)) epsilon := -1e-5 - if float64(remotes.Weights()[api.Peer{Addr: "one"}]) < expected+epsilon { - t.Fatalf("weight should not drop so quickly: %v < %v", remotes.Weights()[api.Peer{Addr: "one"}], expected) - } + require.GreaterOrEqualf(t, float64(remotes.Weights()[api.Peer{Addr: "one"}]), expected+epsilon, "weight should not drop so quickly: %v < %v", remotes.Weights()[api.Peer{Addr: "one"}], expected) } func TestRemotesZeroWeights(t *testing.T) { @@ -151,17 +119,14 @@ func TestRemotesZeroWeights(t *testing.T) { seen := map[api.Peer]struct{}{} for i := 0; i < 1000; i++ { peer, err := remotes.Select() - if err != nil { - t.Fatalf("unexpected error from Select: %v", err) - } + require.NoErrorf(t, err, "unexpected error from Select: %v", err) seen[peer] = struct{}{} } for peer := range remotes.Weights() { - if _, ok := seen[peer]; !ok { - t.Fatalf("remote not returned after several tries: %v (seen: %v)", peer, seen) - } + _, ok := seen[peer] + require.Truef(t, ok, "remote not returned after several tries: %v (seen: %v)", peer, seen) } // Pump up number 3! @@ -171,9 +136,7 @@ func TestRemotesZeroWeights(t *testing.T) { for i := 0; i < 100; i++ { // basically, we expect the same one to return peer, err := remotes.Select() - if err != nil { - t.Fatalf("unexpected error from Select: %v", err) - } + require.NoErrorf(t, err, "unexpected error from Select: %v", err) count[peer]++ @@ -205,26 +168,21 @@ func TestRemotesLargeRanges(t *testing.T) { seen := make(map[api.Peer]int) for i := 0; i < len(peers)*remoteWeightMax*4; i++ { next, err := remotes.Select() - if err != nil { - t.Fatalf("error selecting remote: %v", err) - } + require.NoErrorf(t, err, "error selecting remote: %v", err) - if _, ok := index[next]; !ok { - t.Fatalf("unexpected remote returned: %q", next) - } + _, ok := index[next] + require.Truef(t, ok, "unexpected remote returned: %q", next) seen[next]++ } for _, peer := range peers { - if _, ok := seen[peer]; !ok { - t.Fatalf("%q not returned after several selection attempts, %v", peer, remotes) - } + _, ok := seen[peer] + require.Truef(t, ok, "%q not returned after several selection attempts, %v", peer, remotes) } for peer := range seen { - if _, ok := index[peer]; !ok { - t.Fatalf("unexpected remote returned: %v", peer) - } + _, ok := index[peer] + require.Truef(t, ok, "unexpected remote returned: %v", peer) } } @@ -248,18 +206,14 @@ func TestRemotesDownweight(t *testing.T) { for i := 0; i < samples; i++ { p, err := remotes.Select() - if err != nil { - t.Fatalf("error selecting remote: %v", err) - } + require.NoErrorf(t, err, "error selecting remote: %v", err) if p == peers[0] { chosen++ } } ratio := float32(chosen) / float32(samples) t.Logf("ratio: %f", ratio) - if ratio > 0.001 { - t.Fatalf("downweighted peer is chosen too often, ratio: %f", ratio) - } + require.LessOrEqualf(t, ratio, 0.001, "downweighted peer is chosen too often, ratio: %f", ratio) } // TestRemotesPractical ensures that under a single poor observation, such as @@ -274,9 +228,7 @@ func TestRemotesPractical(t *testing.T) { // set a baseline, where selections should be even for i := 0; i < selections; i++ { peer, err := remotes.Select() - if err != nil { - t.Fatalf("error selecting peer: %v", err) - } + require.NoErrorf(t, err, "error selecting peer: %v", err) remotes.Observe(peer, DefaultObservationWeight) seen[peer]++ @@ -296,9 +248,7 @@ func TestRemotesPractical(t *testing.T) { seen = map[api.Peer]int{} // result for i := 0; i < selections; i++ { peer, err := remotes.Select() - if err != nil { - t.Fatalf("error selecting peer: %v", err) - } + require.NoErrorf(t, err, "error selecting peer: %v", err) seen[peer]++ } @@ -312,9 +262,7 @@ func TestRemotesPractical(t *testing.T) { // we have an *extremely* low probability of selecting this node // (like 0.005%) once. Selecting this more than a few times will // fail the test. - if count > 3 { - t.Fatalf("downweighted peer should not be selected, selected %v times", count) - } + require.LessOrEqualf(t, count, 3, "downweighted peer should not be selected, selected %v times", count) } if !(count >= low && count <= high) { diff --git a/swarmd/dockerexec/container_test.go b/swarmd/dockerexec/container_test.go index 0b9add675e..fbfb639ac3 100644 --- a/swarmd/dockerexec/container_test.go +++ b/swarmd/dockerexec/container_test.go @@ -11,6 +11,7 @@ import ( "github.com/docker/go-units" gogotypes "github.com/gogo/protobuf/types" "github.com/moby/swarmkit/v2/api" + "github.com/stretchr/testify/require" ) func TestVolumesAndBinds(t *testing.T) { @@ -48,13 +49,10 @@ func TestVolumesAndBinds(t *testing.T) { }, } - if vols := cfg.config().Volumes; len(vols) != 0 { - t.Fatalf("expected no anonymous volumes: %v", vols) - } + vols := cfg.config().Volumes + require.Emptyf(t, vols, "expected no anonymous volumes: %v", vols) mounts := cfg.hostConfig().Mounts - if len(mounts) != 1 { - t.Fatalf("expected 1 mount: %v", mounts) - } + require.Lenf(t, mounts, 1, "expected 1 mount: %v", mounts) if !reflect.DeepEqual(mounts[0], c.x) { t.Log(c.explain) @@ -97,9 +95,7 @@ func TestTmpfsOptions(t *testing.T) { } mountOpts, ok := cfg.hostConfig().Tmpfs["/kerfluffle"] - if !ok { - t.Fatalf("expected 1 mount, found none") - } + require.Truef(t, ok, "expected 1 mount, found none") if mountOpts != c.x { t.Log(c.explain) @@ -135,9 +131,7 @@ func TestHealthcheck(t *testing.T) { StartPeriod: time.Minute, StartInterval: time.Minute, } - if !reflect.DeepEqual(config.Healthcheck, expected) { - t.Fatalf("expected %#v, got %#v", expected, config.Healthcheck) - } + require.Truef(t, reflect.DeepEqual(config.Healthcheck, expected), "expected %#v, got %#v", expected, config.Healthcheck) } func TestExtraHosts(t *testing.T) { @@ -156,27 +150,19 @@ func TestExtraHosts(t *testing.T) { } hostConfig := c.hostConfig() - if len(hostConfig.ExtraHosts) != 3 { - t.Fatalf("expected 3 extra hosts: %v", hostConfig.ExtraHosts) - } + require.Lenf(t, hostConfig.ExtraHosts, 3, "expected 3 extra hosts: %v", hostConfig.ExtraHosts) expected := "example.com:1.2.3.4" actual := hostConfig.ExtraHosts[0] - if actual != expected { - t.Fatalf("expected %s, got %s", expected, actual) - } + require.Equalf(t, expected, actual, "expected %s, got %s", expected, actual) expected = "example.org:5.6.7.8" actual = hostConfig.ExtraHosts[1] - if actual != expected { - t.Fatalf("expected %s, got %s", expected, actual) - } + require.Equalf(t, expected, actual, "expected %s, got %s", expected, actual) expected = "mylocal:127.0.0.1" actual = hostConfig.ExtraHosts[2] - if actual != expected { - t.Fatalf("expected %s, got %s", expected, actual) - } + require.Equalf(t, expected, actual, "expected %s, got %s", expected, actual) } func TestPidLimit(t *testing.T) { @@ -194,9 +180,7 @@ func TestPidLimit(t *testing.T) { expected := int64(10) actual := hostConfig.PidsLimit - if expected != *actual { - t.Fatalf("expected %d, got %d", expected, actual) - } + require.Equalf(t, expected, *actual, "expected %d, got %d", expected, actual) } func TestStopSignal(t *testing.T) { @@ -212,9 +196,7 @@ func TestStopSignal(t *testing.T) { expected := "SIGWINCH" actual := c.config().StopSignal - if actual != expected { - t.Fatalf("expected %s, got %s", expected, actual) - } + require.Equalf(t, expected, actual, "expected %s, got %s", expected, actual) } func TestInit(t *testing.T) { @@ -229,9 +211,7 @@ func TestInit(t *testing.T) { } var expected *bool actual := c.hostConfig().Init - if actual != expected { - t.Fatalf("expected %v, got %v", expected, actual) - } + require.Samef(t, expected, actual, "expected %v, got %v", expected, actual) c.task.Spec.GetContainer().Init = &gogotypes.BoolValue{ Value: true, } @@ -256,9 +236,7 @@ func TestIsolation(t *testing.T) { expected := "hyperv" actual := string(c.hostConfig().Isolation) - if actual != expected { - t.Fatalf("expected %s, got %s", expected, actual) - } + require.Equalf(t, expected, actual, "expected %s, got %s", expected, actual) } func TestCapabilityAdd(t *testing.T) { @@ -276,9 +254,7 @@ func TestCapabilityAdd(t *testing.T) { expected := strslice.StrSlice{"CAP_NET_RAW", "CAP_SYS_CHROOT"} actual := c.hostConfig().CapAdd - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("expected %s, got %s", expected, actual) - } + require.Truef(t, reflect.DeepEqual(actual, expected), "expected %s, got %s", expected, actual) } func TestCapabilityDrop(t *testing.T) { @@ -296,9 +272,7 @@ func TestCapabilityDrop(t *testing.T) { expected := strslice.StrSlice{"CAP_KILL"} actual := c.hostConfig().CapDrop - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("expected %s, got %s", expected, actual) - } + require.Truef(t, reflect.DeepEqual(actual, expected), "expected %s, got %s", expected, actual) } func TestUlimits(t *testing.T) { @@ -328,7 +302,5 @@ func TestUlimits(t *testing.T) { }, } actual := c.resources().Ulimits - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("expected %v, got %v", expected, actual) - } + require.Truef(t, reflect.DeepEqual(actual, expected), "expected %v, got %v", expected, actual) } diff --git a/swarmd/dockerexec/controller_integration_test.go b/swarmd/dockerexec/controller_integration_test.go index 68e92883a7..07d5f19dab 100644 --- a/swarmd/dockerexec/controller_integration_test.go +++ b/swarmd/dockerexec/controller_integration_test.go @@ -10,6 +10,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/api/genericresource" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -40,7 +41,7 @@ func TestControllerFlowIntegration(t *testing.T) { engineapi.WithHost(dockerTestAddr), engineapi.WithAPIVersionNegotiation(), ) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, client) available := genericresource.NewSet("apple", "blue", "red") @@ -83,21 +84,20 @@ func TestControllerFlowIntegration(t *testing.T) { }) ctlr, err := newController(client, nil, task, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, ctlr) - assert.NoError(t, ctlr.Prepare(ctx)) - assert.NoError(t, ctlr.Start(ctx)) - assert.NoError(t, ctlr.(exec.ControllerLogs).Logs(ctx, publisher, api.LogSubscriptionOptions{ + require.NoError(t, ctlr.Prepare(ctx)) + require.NoError(t, ctlr.Start(ctx)) + require.NoError(t, ctlr.(exec.ControllerLogs).Logs(ctx, publisher, api.LogSubscriptionOptions{ Follow: true, })) - assert.NoError(t, ctlr.Wait(ctx)) + require.NoError(t, ctlr.Wait(ctx)) assert.True(t, receivedLogs) - assert.NoError(t, ctlr.Shutdown(ctx)) - assert.NoError(t, ctlr.Remove(ctx)) - assert.NoError(t, ctlr.Close()) + require.NoError(t, ctlr.Shutdown(ctx)) + require.NoError(t, ctlr.Remove(ctx)) + require.NoError(t, ctlr.Close()) // NOTE(stevvooe): testify has no clue how to correctly do error equality. - if err := ctlr.Close(); err != exec.ErrControllerClosed { - t.Fatalf("expected controller to be closed: %v", err) - } + err = ctlr.Close() + require.Equalf(t, err, exec.ErrControllerClosed, "expected controller to be closed: %v", err) } diff --git a/swarmd/dockerexec/controller_test.go b/swarmd/dockerexec/controller_test.go index 9a7ff1e32f..ada98061da 100644 --- a/swarmd/dockerexec/controller_test.go +++ b/swarmd/dockerexec/controller_test.go @@ -11,6 +11,7 @@ import ( "time" v1 "github.com/opencontainers/image-spec/specs-go/v1" + "github.com/stretchr/testify/require" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" @@ -53,7 +54,7 @@ func TestControllerPrepare(t *testing.T) { panic("unexpected call to ContainerCreate") } - assert.NoError(t, ctlr.Prepare(ctx)) + require.NoError(t, ctlr.Prepare(ctx)) } func TestControllerPrepareAlreadyPrepared(t *testing.T) { @@ -90,9 +91,8 @@ func TestControllerPrepareAlreadyPrepared(t *testing.T) { } // ensure idempotence - if err := ctlr.Prepare(ctx); err != exec.ErrTaskPrepared { - t.Fatalf("expected error %v, got %v", exec.ErrTaskPrepared, err) - } + err := ctlr.Prepare(ctx) + require.Equalf(t, err, exec.ErrTaskPrepared, "expected error %v, got %v", exec.ErrTaskPrepared, err) } func TestControllerStart(t *testing.T) { @@ -124,7 +124,7 @@ func TestControllerStart(t *testing.T) { panic("unexpected call of ContainerStart") } - assert.NoError(t, ctlr.Start(ctx)) + require.NoError(t, ctlr.Start(ctx)) } func TestControllerStartAlreadyStarted(t *testing.T) { @@ -149,9 +149,8 @@ func TestControllerStartAlreadyStarted(t *testing.T) { } // ensure idempotence - if err := ctlr.Start(ctx); err != exec.ErrTaskStarted { - t.Fatalf("expected error %v, got %v", exec.ErrTaskPrepared, err) - } + err := ctlr.Start(ctx) + require.Equalf(t, err, exec.ErrTaskStarted, "expected error %v, got %v", exec.ErrTaskPrepared, err) } func TestControllerWait(t *testing.T) { @@ -194,7 +193,7 @@ func TestControllerWait(t *testing.T) { panic("unexpected call of Events") } - assert.NoError(t, ctlr.Wait(ctx)) + require.NoError(t, ctlr.Wait(ctx)) } func TestControllerWaitUnhealthy(t *testing.T) { @@ -287,9 +286,7 @@ func TestControllerWaitExitError(t *testing.T) { func checkExitError(t *testing.T, expectedCode int, err error) { ec, ok := err.(exec.ExitCoder) - if !ok { - t.Fatalf("expected an exit error, got: %v", err) - } + require.Truef(t, ok, "expected an exit error, got: %v", err) assert.Equal(t, expectedCode, ec.ExitCode()) } @@ -316,7 +313,7 @@ func TestControllerWaitExitedClean(t *testing.T) { } err := ctlr.Wait(ctx) - assert.Nil(t, err) + assert.NoError(t, err) } func TestControllerWaitExitedError(t *testing.T) { @@ -362,7 +359,7 @@ func TestControllerShutdown(t *testing.T) { panic("unexpected call of ContainerStop") } - assert.NoError(t, ctlr.Shutdown(ctx)) + require.NoError(t, ctlr.Shutdown(ctx)) } func TestControllerTerminate(t *testing.T) { @@ -380,7 +377,7 @@ func TestControllerTerminate(t *testing.T) { panic("unexpected call of ContainerKill") } - assert.NoError(t, ctlr.Terminate(ctx)) + require.NoError(t, ctlr.Terminate(ctx)) } func TestControllerRemove(t *testing.T) { @@ -409,7 +406,7 @@ func TestControllerRemove(t *testing.T) { panic("unexpected call of ContainerRemove") } - assert.NoError(t, ctlr.Remove(ctx)) + require.NoError(t, ctlr.Remove(ctx)) } func genTestControllerEnv(t *testing.T, task *api.Task) (context.Context, *StubAPIClient, exec.Controller, *containerConfig, func()) { @@ -423,10 +420,10 @@ func genTestControllerEnv(t *testing.T, task *api.Task) (context.Context, *StubA client := NewStubAPIClient() ctlr, err := newController(client, testNodeDescription, task, nil) - assert.NoError(t, err) + require.NoError(t, err) config, err := newContainerConfig(testNodeDescription, task) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, config) ctx := context.Background() diff --git a/template/context_test.go b/template/context_test.go index 2e81a4b9cc..4538c95bd8 100644 --- a/template/context_test.go +++ b/template/context_test.go @@ -6,6 +6,7 @@ import ( "github.com/moby/swarmkit/v2/api" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTemplateContext(t *testing.T) { @@ -188,9 +189,7 @@ func TestTemplateContext(t *testing.T) { if testcase.Err == nil { t.Fatalf("unexpected error: %v", err) } else { - if err != testcase.Err { - t.Fatalf("unexpected error: %v != %v", err, testcase.Err) - } + require.Equalf(t, err, testcase.Err, "unexpected error: %v != %v", err, testcase.Err) } } diff --git a/template/getter_test.go b/template/getter_test.go index e92d1fa7c6..d1a39bde63 100644 --- a/template/getter_test.go +++ b/template/getter_test.go @@ -281,9 +281,9 @@ func TestTemplatedSecret(t *testing.T) { expandedSecret, err := templatedDependencies.Secrets().Get("templatedsecret") if testCase.expectedErr != "" { - assert.EqualError(t, err, testCase.expectedErr) + require.EqualError(t, err, testCase.expectedErr) } else { - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(t, expandedSecret) assert.Equal(t, testCase.expected, string(expandedSecret.Spec.Data), testCase.desc) } @@ -562,11 +562,11 @@ func TestTemplatedConfig(t *testing.T) { expandedConfig2, sensitive, err2 := templatedDependencies.Configs().(TemplatedConfigGetter).GetAndFlagSecretData("templatedconfig") if testCase.expectedErr != "" { - assert.EqualError(t, err1, testCase.expectedErr) - assert.EqualError(t, err2, testCase.expectedErr) + require.EqualError(t, err1, testCase.expectedErr) + require.EqualError(t, err2, testCase.expectedErr) } else { - assert.NoError(t, err1) - assert.NoError(t, err2) + require.NoError(t, err1) + require.NoError(t, err2) require.NotNil(t, expandedConfig1) require.NotNil(t, expandedConfig2) assert.Equal(t, testCase.expected, string(expandedConfig1.Spec.Data), testCase.desc) diff --git a/watch/watch_test.go b/watch/watch_test.go index 28845a9416..f3383344b3 100644 --- a/watch/watch_test.go +++ b/watch/watch_test.go @@ -106,45 +106,31 @@ func TestWatch(t *testing.T) { q.Publish(testEvent{tags: []string{"t1", "t2"}, str: "foobar"}) q.Publish(testEvent{tags: []string{"t3"}, str: "baz"}) - if (<-c1).(testEvent).str != "foo" { - t.Fatal(`expected "foo" on c1`) - } + require.Equal(t, "foo", (<-c1).(testEvent).str, `expected "foo" on c1`) ev := (<-c1).(testEvent) - if ev.str != "foobar" { - t.Fatal(`expected "foobar" on c1`, ev) - } - if (<-c2).(testEvent).str != "bar" { - t.Fatal(`expected "bar" on c2`) - } - if (<-c2).(testEvent).str != "foobar" { - t.Fatal(`expected "foobar" on c2`) - } + require.Equal(t, "foobar", ev.str, `expected "foobar" on c1`, ev) + require.Equal(t, "bar", (<-c2).(testEvent).str, `expected "bar" on c2`) + require.Equal(t, "foobar", (<-c2).(testEvent).str, `expected "foobar" on c2`) c1cancel() select { case _, ok := <-c1: - if ok { - t.Fatal("unexpected value on c1") - } + require.False(t, ok, "unexpected value on c1") default: // operation does not proceed after cancel } q.Publish(testEvent{tags: []string{"t1", "t2"}, str: "foobar"}) - if (<-c2).(testEvent).str != "foobar" { - t.Fatal(`expected "foobar" on c2`) - } + require.Equal(t, "foobar", (<-c2).(testEvent).str, `expected "foobar" on c2`) c2cancel() select { case _, ok := <-c2: - if ok { - t.Fatal("unexpected value on c2") - } + require.False(t, ok, "unexpected value on c2") default: // operation does not proceed after cancel } From 01794e2293b3bf9ed9869f1d6844d15839dd4c02 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Sat, 14 Jun 2025 13:41:03 +0200 Subject: [PATCH 2/2] vendor update github.com/stretchr/testify to v1.10.0 Signed-off-by: Matthieu MOREL --- go.mod | 2 +- go.sum | 2 + swarmd/go.mod | 2 +- swarmd/go.sum | 2 + swarmd/go.work.sum | 1 + .../gogo/protobuf/protobuf/Makefile | 65 -- .../protobuf/google/protobuf/any.proto | 155 --- .../protobuf/google/protobuf/api.proto | 210 ----- .../google/protobuf/compiler/plugin.proto | 168 ---- .../protobuf/google/protobuf/descriptor.proto | 885 ------------------ .../protobuf/google/protobuf/duration.proto | 116 --- .../protobuf/google/protobuf/empty.proto | 52 - .../protobuf/google/protobuf/field_mask.proto | 245 ----- .../google/protobuf/source_context.proto | 48 - .../protobuf/google/protobuf/struct.proto | 95 -- .../protobuf/google/protobuf/timestamp.proto | 138 --- .../protobuf/google/protobuf/type.proto | 187 ---- .../protobuf/google/protobuf/wrappers.proto | 123 --- .../testify/assert/assertion_compare.go | 63 +- .../assert/assertion_compare_can_convert.go | 16 - .../assert/assertion_compare_legacy.go | 16 - .../testify/assert/assertion_format.go | 64 +- .../testify/assert/assertion_forward.go | 123 ++- .../testify/assert/assertion_order.go | 10 +- .../stretchr/testify/assert/assertions.go | 326 +++++-- .../testify/assert/http_assertions.go | 27 +- .../testify/assert/yaml/yaml_custom.go | 25 + .../testify/assert/yaml/yaml_default.go | 37 + .../stretchr/testify/assert/yaml/yaml_fail.go | 18 + .../stretchr/testify/require/require.go | 473 ++++++---- .../stretchr/testify/require/require.go.tmpl | 2 +- .../testify/require/require_forward.go | 123 ++- .../stretchr/testify/require/requirements.go | 2 +- .../github.com/stretchr/testify/suite/doc.go | 4 + .../stretchr/testify/suite/suite.go | 27 +- vendor/modules.txt | 5 +- 36 files changed, 938 insertions(+), 2919 deletions(-) delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/Makefile delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/api.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/source_context.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/type.proto delete mode 100644 vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go create mode 100644 vendor/github.com/stretchr/testify/assert/yaml/yaml_custom.go create mode 100644 vendor/github.com/stretchr/testify/assert/yaml/yaml_default.go create mode 100644 vendor/github.com/stretchr/testify/assert/yaml/yaml_fail.go diff --git a/go.mod b/go.mod index 7c069b65c2..d039edb590 100644 --- a/go.mod +++ b/go.mod @@ -24,7 +24,7 @@ require ( github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.7.0 - github.com/stretchr/testify v1.8.4 + github.com/stretchr/testify v1.10.0 go.etcd.io/bbolt v1.3.7 go.etcd.io/etcd/client/pkg/v3 v3.5.6 go.etcd.io/etcd/pkg/v3 v3.5.6 diff --git a/go.sum b/go.sum index 3e2525d62c..62fb5a4fee 100644 --- a/go.sum +++ b/go.sum @@ -361,6 +361,8 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tedsuo/ifrit v0.0.0-20230330192023-5cba443a66c4 h1:MGZzzxBuPuK4J0XQo+0uy0NnXQGKzHXhYp5oG1Wy860= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= diff --git a/swarmd/go.mod b/swarmd/go.mod index cbd612527b..6eba080eab 100644 --- a/swarmd/go.mod +++ b/swarmd/go.mod @@ -26,7 +26,7 @@ require ( github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.5 - github.com/stretchr/testify v1.8.4 + github.com/stretchr/testify v1.10.0 go.etcd.io/bbolt v1.3.7 // indirect go.etcd.io/etcd/client/pkg/v3 v3.5.6 go.etcd.io/etcd/pkg/v3 v3.5.6 // indirect diff --git a/swarmd/go.sum b/swarmd/go.sum index f9c1b5e5c4..bdc4027e5a 100644 --- a/swarmd/go.sum +++ b/swarmd/go.sum @@ -370,6 +370,8 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= diff --git a/swarmd/go.work.sum b/swarmd/go.work.sum index 02b6cb16da..d7593e8ea3 100644 --- a/swarmd/go.work.sum +++ b/swarmd/go.work.sum @@ -521,6 +521,7 @@ github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980 h1:lIOOH github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980/go.mod h1:AO3tvPzVZ/ayst6UlUKUv6rcPQInYe3IknH3jYhAKu8= github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/tchap/go-patricia v2.2.6+incompatible h1:JvoDL7JSoIP2HDE8AbDH3zC8QBPxmzYe32HHy5yQ+Ck= github.com/tchap/go-patricia v2.2.6+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= diff --git a/vendor/github.com/gogo/protobuf/protobuf/Makefile b/vendor/github.com/gogo/protobuf/protobuf/Makefile deleted file mode 100644 index e3e107663e..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/Makefile +++ /dev/null @@ -1,65 +0,0 @@ -VERSION=3.9.1 -URL="https://raw.githubusercontent.com/protocolbuffers/protobuf/v${VERSION}/src/google/protobuf" - -regenerate: - go install github.com/gogo/protobuf/protoc-gen-gogotypes - go install github.com/gogo/protobuf/protoc-min-version - - protoc-min-version \ - --version="3.0.0" \ - --gogotypes_out=../types/ \ - -I=. \ - google/protobuf/any.proto \ - google/protobuf/type.proto \ - google/protobuf/empty.proto \ - google/protobuf/api.proto \ - google/protobuf/timestamp.proto \ - google/protobuf/duration.proto \ - google/protobuf/struct.proto \ - google/protobuf/wrappers.proto \ - google/protobuf/field_mask.proto \ - google/protobuf/source_context.proto - - mv ../types/google/protobuf/*.pb.go ../types/ || true - rmdir ../types/google/protobuf || true - rmdir ../types/google || true - -update: - go install github.com/gogo/protobuf/gogoreplace - - (cd ./google/protobuf && rm descriptor.proto; wget ${URL}/descriptor.proto) - # gogoprotobuf requires users to import gogo.proto which imports descriptor.proto - # The descriptor.proto is only compatible with proto3 just because of the reserved keyword. - # We remove it to stay compatible with previous versions of protoc before proto3 - gogoreplace 'reserved 38;' '//reserved 38;' ./google/protobuf/descriptor.proto - gogoreplace 'reserved 8;' '//reserved 8;' ./google/protobuf/descriptor.proto - gogoreplace 'reserved 9;' '//reserved 9;' ./google/protobuf/descriptor.proto - gogoreplace 'reserved 4;' '//reserved 4;' ./google/protobuf/descriptor.proto - gogoreplace 'reserved 5;' '//reserved 5;' ./google/protobuf/descriptor.proto - gogoreplace 'option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor";' 'option go_package = "descriptor";' ./google/protobuf/descriptor.proto - - (cd ./google/protobuf/compiler && rm plugin.proto; wget ${URL}/compiler/plugin.proto) - gogoreplace 'option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go";' 'option go_package = "plugin_go";' ./google/protobuf/compiler/plugin.proto - - (cd ./google/protobuf && rm any.proto; wget ${URL}/any.proto) - gogoreplace 'go_package = "github.com/golang/protobuf/ptypes/any";' 'go_package = "types";' ./google/protobuf/any.proto - (cd ./google/protobuf && rm empty.proto; wget ${URL}/empty.proto) - gogoreplace 'go_package = "github.com/golang/protobuf/ptypes/empty";' 'go_package = "types";' ./google/protobuf/empty.proto - (cd ./google/protobuf && rm timestamp.proto; wget ${URL}/timestamp.proto) - gogoreplace 'go_package = "github.com/golang/protobuf/ptypes/timestamp";' 'go_package = "types";' ./google/protobuf/timestamp.proto - (cd ./google/protobuf && rm duration.proto; wget ${URL}/duration.proto) - gogoreplace 'go_package = "github.com/golang/protobuf/ptypes/duration";' 'go_package = "types";' ./google/protobuf/duration.proto - (cd ./google/protobuf && rm struct.proto; wget ${URL}/struct.proto) - gogoreplace 'go_package = "github.com/golang/protobuf/ptypes/struct;structpb";' 'go_package = "types";' ./google/protobuf/struct.proto - (cd ./google/protobuf && rm wrappers.proto; wget ${URL}/wrappers.proto) - gogoreplace 'go_package = "github.com/golang/protobuf/ptypes/wrappers";' 'go_package = "types";' ./google/protobuf/wrappers.proto - (cd ./google/protobuf && rm field_mask.proto; wget ${URL}/field_mask.proto) - gogoreplace 'option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask";' 'option go_package = "types";' ./google/protobuf/field_mask.proto - (cd ./google/protobuf && rm api.proto; wget ${URL}/api.proto) - gogoreplace 'option go_package = "google.golang.org/genproto/protobuf/api;api";' 'option go_package = "types";' ./google/protobuf/api.proto - (cd ./google/protobuf && rm type.proto; wget ${URL}/type.proto) - gogoreplace 'option go_package = "google.golang.org/genproto/protobuf/ptype;ptype";' 'option go_package = "types";' ./google/protobuf/type.proto - (cd ./google/protobuf && rm source_context.proto; wget ${URL}/source_context.proto) - gogoreplace 'option go_package = "google.golang.org/genproto/protobuf/source_context;source_context";' 'option go_package = "types";' ./google/protobuf/source_context.proto - - diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto deleted file mode 100644 index 4cf3843bd7..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto +++ /dev/null @@ -1,155 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "types"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "AnyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -message Any { - // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. This string must contain at least - // one "/" character. The last segment of the URL's path must represent - // the fully qualified name of the type (as in - // `path/google.protobuf.Duration`). The name should be in a canonical form - // (e.g., leading "." is not accepted). - // - // In practice, teams usually precompile into the binary all types that they - // expect it to use in the context of Any. However, for URLs which use the - // scheme `http`, `https`, or no scheme, one can optionally set up a type - // server that maps type URLs to message definitions as follows: - // - // * If no scheme is provided, `https` is assumed. - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Note: this functionality is not currently available in the official - // protobuf release, and it is not used for type URLs beginning with - // type.googleapis.com. - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - string type_url = 1; - - // Must be a valid serialized protocol buffer of the above specified type. - bytes value = 2; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/api.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/api.proto deleted file mode 100644 index 67c1ddbd9d..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/api.proto +++ /dev/null @@ -1,210 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -import "google/protobuf/source_context.proto"; -import "google/protobuf/type.proto"; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "ApiProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; -option go_package = "types"; - -// Api is a light-weight descriptor for an API Interface. -// -// Interfaces are also described as "protocol buffer services" in some contexts, -// such as by the "service" keyword in a .proto file, but they are different -// from API Services, which represent a concrete implementation of an interface -// as opposed to simply a description of methods and bindings. They are also -// sometimes simply referred to as "APIs" in other contexts, such as the name of -// this message itself. See https://cloud.google.com/apis/design/glossary for -// detailed terminology. -message Api { - - // The fully qualified name of this interface, including package name - // followed by the interface's simple name. - string name = 1; - - // The methods of this interface, in unspecified order. - repeated Method methods = 2; - - // Any metadata attached to the interface. - repeated Option options = 3; - - // A version string for this interface. If specified, must have the form - // `major-version.minor-version`, as in `1.10`. If the minor version is - // omitted, it defaults to zero. If the entire version field is empty, the - // major version is derived from the package name, as outlined below. If the - // field is not empty, the version in the package name will be verified to be - // consistent with what is provided here. - // - // The versioning schema uses [semantic - // versioning](http://semver.org) where the major version number - // indicates a breaking change and the minor version an additive, - // non-breaking change. Both version numbers are signals to users - // what to expect from different versions, and should be carefully - // chosen based on the product plan. - // - // The major version is also reflected in the package name of the - // interface, which must end in `v`, as in - // `google.feature.v1`. For major versions 0 and 1, the suffix can - // be omitted. Zero major versions must only be used for - // experimental, non-GA interfaces. - // - // - string version = 4; - - // Source context for the protocol buffer service represented by this - // message. - SourceContext source_context = 5; - - // Included interfaces. See [Mixin][]. - repeated Mixin mixins = 6; - - // The source syntax of the service. - Syntax syntax = 7; -} - -// Method represents a method of an API interface. -message Method { - - // The simple name of this method. - string name = 1; - - // A URL of the input message type. - string request_type_url = 2; - - // If true, the request is streamed. - bool request_streaming = 3; - - // The URL of the output message type. - string response_type_url = 4; - - // If true, the response is streamed. - bool response_streaming = 5; - - // Any metadata attached to the method. - repeated Option options = 6; - - // The source syntax of this method. - Syntax syntax = 7; -} - -// Declares an API Interface to be included in this interface. The including -// interface must redeclare all the methods from the included interface, but -// documentation and options are inherited as follows: -// -// - If after comment and whitespace stripping, the documentation -// string of the redeclared method is empty, it will be inherited -// from the original method. -// -// - Each annotation belonging to the service config (http, -// visibility) which is not set in the redeclared method will be -// inherited. -// -// - If an http annotation is inherited, the path pattern will be -// modified as follows. Any version prefix will be replaced by the -// version of the including interface plus the [root][] path if -// specified. -// -// Example of a simple mixin: -// -// package google.acl.v1; -// service AccessControl { -// // Get the underlying ACL object. -// rpc GetAcl(GetAclRequest) returns (Acl) { -// option (google.api.http).get = "/v1/{resource=**}:getAcl"; -// } -// } -// -// package google.storage.v2; -// service Storage { -// rpc GetAcl(GetAclRequest) returns (Acl); -// -// // Get a data record. -// rpc GetData(GetDataRequest) returns (Data) { -// option (google.api.http).get = "/v2/{resource=**}"; -// } -// } -// -// Example of a mixin configuration: -// -// apis: -// - name: google.storage.v2.Storage -// mixins: -// - name: google.acl.v1.AccessControl -// -// The mixin construct implies that all methods in `AccessControl` are -// also declared with same name and request/response types in -// `Storage`. A documentation generator or annotation processor will -// see the effective `Storage.GetAcl` method after inherting -// documentation and annotations as follows: -// -// service Storage { -// // Get the underlying ACL object. -// rpc GetAcl(GetAclRequest) returns (Acl) { -// option (google.api.http).get = "/v2/{resource=**}:getAcl"; -// } -// ... -// } -// -// Note how the version in the path pattern changed from `v1` to `v2`. -// -// If the `root` field in the mixin is specified, it should be a -// relative path under which inherited HTTP paths are placed. Example: -// -// apis: -// - name: google.storage.v2.Storage -// mixins: -// - name: google.acl.v1.AccessControl -// root: acls -// -// This implies the following inherited HTTP annotation: -// -// service Storage { -// // Get the underlying ACL object. -// rpc GetAcl(GetAclRequest) returns (Acl) { -// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; -// } -// ... -// } -message Mixin { - // The fully qualified name of the interface which is included. - string name = 1; - - // If non-empty specifies a path under which inherited HTTP paths - // are rooted. - string root = 2; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto deleted file mode 100644 index 4a88adf148..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto +++ /dev/null @@ -1,168 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) -// -// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to -// change. -// -// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is -// just a program that reads a CodeGeneratorRequest from stdin and writes a -// CodeGeneratorResponse to stdout. -// -// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead -// of dealing with the raw protocol defined here. -// -// A plugin executable needs only to be placed somewhere in the path. The -// plugin should be named "protoc-gen-$NAME", and will then be used when the -// flag "--${NAME}_out" is passed to protoc. - -syntax = "proto2"; - -package google.protobuf.compiler; -option java_package = "com.google.protobuf.compiler"; -option java_outer_classname = "PluginProtos"; - -option go_package = "plugin_go"; - -import "google/protobuf/descriptor.proto"; - -// The version number of protocol compiler. -message Version { - optional int32 major = 1; - optional int32 minor = 2; - optional int32 patch = 3; - // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should - // be empty for mainline stable releases. - optional string suffix = 4; -} - -// An encoded CodeGeneratorRequest is written to the plugin's stdin. -message CodeGeneratorRequest { - // The .proto files that were explicitly listed on the command-line. The - // code generator should generate code only for these files. Each file's - // descriptor will be included in proto_file, below. - repeated string file_to_generate = 1; - - // The generator parameter passed on the command-line. - optional string parameter = 2; - - // FileDescriptorProtos for all files in files_to_generate and everything - // they import. The files will appear in topological order, so each file - // appears before any file that imports it. - // - // protoc guarantees that all proto_files will be written after - // the fields above, even though this is not technically guaranteed by the - // protobuf wire format. This theoretically could allow a plugin to stream - // in the FileDescriptorProtos and handle them one by one rather than read - // the entire set into memory at once. However, as of this writing, this - // is not similarly optimized on protoc's end -- it will store all fields in - // memory at once before sending them to the plugin. - // - // Type names of fields and extensions in the FileDescriptorProto are always - // fully qualified. - repeated FileDescriptorProto proto_file = 15; - - // The version number of protocol compiler. - optional Version compiler_version = 3; - -} - -// The plugin writes an encoded CodeGeneratorResponse to stdout. -message CodeGeneratorResponse { - // Error message. If non-empty, code generation failed. The plugin process - // should exit with status code zero even if it reports an error in this way. - // - // This should be used to indicate errors in .proto files which prevent the - // code generator from generating correct code. Errors which indicate a - // problem in protoc itself -- such as the input CodeGeneratorRequest being - // unparseable -- should be reported by writing a message to stderr and - // exiting with a non-zero status code. - optional string error = 1; - - // Represents a single generated file. - message File { - // The file name, relative to the output directory. The name must not - // contain "." or ".." components and must be relative, not be absolute (so, - // the file cannot lie outside the output directory). "/" must be used as - // the path separator, not "\". - // - // If the name is omitted, the content will be appended to the previous - // file. This allows the generator to break large files into small chunks, - // and allows the generated text to be streamed back to protoc so that large - // files need not reside completely in memory at one time. Note that as of - // this writing protoc does not optimize for this -- it will read the entire - // CodeGeneratorResponse before writing files to disk. - optional string name = 1; - - // If non-empty, indicates that the named file should already exist, and the - // content here is to be inserted into that file at a defined insertion - // point. This feature allows a code generator to extend the output - // produced by another code generator. The original generator may provide - // insertion points by placing special annotations in the file that look - // like: - // @@protoc_insertion_point(NAME) - // The annotation can have arbitrary text before and after it on the line, - // which allows it to be placed in a comment. NAME should be replaced with - // an identifier naming the point -- this is what other generators will use - // as the insertion_point. Code inserted at this point will be placed - // immediately above the line containing the insertion point (thus multiple - // insertions to the same point will come out in the order they were added). - // The double-@ is intended to make it unlikely that the generated code - // could contain things that look like insertion points by accident. - // - // For example, the C++ code generator places the following line in the - // .pb.h files that it generates: - // // @@protoc_insertion_point(namespace_scope) - // This line appears within the scope of the file's package namespace, but - // outside of any particular class. Another plugin can then specify the - // insertion_point "namespace_scope" to generate additional classes or - // other declarations that should be placed in this scope. - // - // Note that if the line containing the insertion point begins with - // whitespace, the same whitespace will be added to every line of the - // inserted text. This is useful for languages like Python, where - // indentation matters. In these languages, the insertion point comment - // should be indented the same amount as any inserted code will need to be - // in order to work correctly in that context. - // - // The code generator that generates the initial file and the one which - // inserts into it must both run as part of a single invocation of protoc. - // Code generators are executed in the order in which they appear on the - // command line. - // - // If |insertion_point| is present, |name| must also be present. - optional string insertion_point = 2; - - // The file contents. - optional string content = 15; - } - repeated File file = 15; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto deleted file mode 100644 index 4a08905a56..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto +++ /dev/null @@ -1,885 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// The messages in this file describe the definitions found in .proto files. -// A valid .proto file can be translated directly to a FileDescriptorProto -// without any other information (e.g. without reading its imports). - - -syntax = "proto2"; - -package google.protobuf; - -option go_package = "descriptor"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DescriptorProtos"; -option csharp_namespace = "Google.Protobuf.Reflection"; -option objc_class_prefix = "GPB"; -option cc_enable_arenas = true; - -// descriptor.proto must be optimized for speed because reflection-based -// algorithms don't work during bootstrapping. -option optimize_for = SPEED; - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -message FileDescriptorSet { - repeated FileDescriptorProto file = 1; -} - -// Describes a complete .proto file. -message FileDescriptorProto { - optional string name = 1; // file name, relative to root of source tree - optional string package = 2; // e.g. "foo", "foo.bar", etc. - - // Names of files imported by this file. - repeated string dependency = 3; - // Indexes of the public imported files in the dependency list above. - repeated int32 public_dependency = 10; - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - repeated int32 weak_dependency = 11; - - // All top-level definitions in this file. - repeated DescriptorProto message_type = 4; - repeated EnumDescriptorProto enum_type = 5; - repeated ServiceDescriptorProto service = 6; - repeated FieldDescriptorProto extension = 7; - - optional FileOptions options = 8; - - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - optional SourceCodeInfo source_code_info = 9; - - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - optional string syntax = 12; -} - -// Describes a message type. -message DescriptorProto { - optional string name = 1; - - repeated FieldDescriptorProto field = 2; - repeated FieldDescriptorProto extension = 6; - - repeated DescriptorProto nested_type = 3; - repeated EnumDescriptorProto enum_type = 4; - - message ExtensionRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. - - optional ExtensionRangeOptions options = 3; - } - repeated ExtensionRange extension_range = 5; - - repeated OneofDescriptorProto oneof_decl = 8; - - optional MessageOptions options = 7; - - // Range of reserved tag numbers. Reserved tag numbers may not be used by - // fields or extension ranges in the same message. Reserved ranges may - // not overlap. - message ReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. - } - repeated ReservedRange reserved_range = 9; - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - repeated string reserved_name = 10; -} - -message ExtensionRangeOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -// Describes a field within a message. -message FieldDescriptorProto { - enum Type { - // 0 is reserved for errors. - // Order is weird for historical reasons. - TYPE_DOUBLE = 1; - TYPE_FLOAT = 2; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - TYPE_INT64 = 3; - TYPE_UINT64 = 4; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - TYPE_INT32 = 5; - TYPE_FIXED64 = 6; - TYPE_FIXED32 = 7; - TYPE_BOOL = 8; - TYPE_STRING = 9; - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - TYPE_GROUP = 10; - TYPE_MESSAGE = 11; // Length-delimited aggregate. - - // New in version 2. - TYPE_BYTES = 12; - TYPE_UINT32 = 13; - TYPE_ENUM = 14; - TYPE_SFIXED32 = 15; - TYPE_SFIXED64 = 16; - TYPE_SINT32 = 17; // Uses ZigZag encoding. - TYPE_SINT64 = 18; // Uses ZigZag encoding. - } - - enum Label { - // 0 is reserved for errors - LABEL_OPTIONAL = 1; - LABEL_REQUIRED = 2; - LABEL_REPEATED = 3; - } - - optional string name = 1; - optional int32 number = 3; - optional Label label = 4; - - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - optional Type type = 5; - - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - optional string type_name = 6; - - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - optional string extendee = 2; - - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - optional string default_value = 7; - - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - optional int32 oneof_index = 9; - - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - optional string json_name = 10; - - optional FieldOptions options = 8; -} - -// Describes a oneof. -message OneofDescriptorProto { - optional string name = 1; - optional OneofOptions options = 2; -} - -// Describes an enum type. -message EnumDescriptorProto { - optional string name = 1; - - repeated EnumValueDescriptorProto value = 2; - - optional EnumOptions options = 3; - - // Range of reserved numeric values. Reserved values may not be used by - // entries in the same enum. Reserved ranges may not overlap. - // - // Note that this is distinct from DescriptorProto.ReservedRange in that it - // is inclusive such that it can appropriately represent the entire int32 - // domain. - message EnumReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Inclusive. - } - - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - repeated EnumReservedRange reserved_range = 4; - - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - repeated string reserved_name = 5; -} - -// Describes a value within an enum. -message EnumValueDescriptorProto { - optional string name = 1; - optional int32 number = 2; - - optional EnumValueOptions options = 3; -} - -// Describes a service. -message ServiceDescriptorProto { - optional string name = 1; - repeated MethodDescriptorProto method = 2; - - optional ServiceOptions options = 3; -} - -// Describes a method of a service. -message MethodDescriptorProto { - optional string name = 1; - - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - optional string input_type = 2; - optional string output_type = 3; - - optional MethodOptions options = 4; - - // Identifies if client streams multiple client messages - optional bool client_streaming = 5 [default = false]; - // Identifies if server streams multiple server messages - optional bool server_streaming = 6 [default = false]; -} - - -// =================================================================== -// Options - -// Each of the definitions above may have "options" attached. These are -// just annotations which may cause code to be generated slightly differently -// or may contain hints for code that manipulates protocol messages. -// -// Clients may define custom options as extensions of the *Options messages. -// These extensions may not yet be known at parsing time, so the parser cannot -// store the values in them. Instead it stores them in a field in the *Options -// message called uninterpreted_option. This field must have the same name -// across all *Options messages. We then use this field to populate the -// extensions when we build a descriptor, at which point all protos have been -// parsed and so all extensions are known. -// -// Extension numbers for custom options may be chosen as follows: -// * For options which will only be used within a single application or -// organization, or for experimental options, use field numbers 50000 -// through 99999. It is up to you to ensure that you do not use the -// same number for multiple options. -// * For options which will be published and used publicly by multiple -// independent entities, e-mail protobuf-global-extension-registry@google.com -// to reserve extension numbers. Simply provide your project name (e.g. -// Objective-C plugin) and your project website (if available) -- there's no -// need to explain how you intend to use them. Usually you only need one -// extension number. You can declare multiple options with only one extension -// number by putting them in a sub-message. See the Custom Options section of -// the docs for examples: -// https://developers.google.com/protocol-buffers/docs/proto#options -// If this turns out to be popular, a web service will be set up -// to automatically assign option numbers. - -message FileOptions { - - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - optional string java_package = 1; - - - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - optional string java_outer_classname = 8; - - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - optional bool java_multiple_files = 10 [default = false]; - - // This option does nothing. - optional bool java_generate_equals_and_hash = 20 [deprecated=true]; - - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - optional bool java_string_check_utf8 = 27 [default = false]; - - - // Generated classes can be optimized for speed or code size. - enum OptimizeMode { - SPEED = 1; // Generate complete code for parsing, serialization, - // etc. - CODE_SIZE = 2; // Use ReflectionOps to implement these methods. - LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. - } - optional OptimizeMode optimize_for = 9 [default = SPEED]; - - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - optional string go_package = 11; - - - - - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - optional bool cc_generic_services = 16 [default = false]; - optional bool java_generic_services = 17 [default = false]; - optional bool py_generic_services = 18 [default = false]; - optional bool php_generic_services = 42 [default = false]; - - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - optional bool deprecated = 23 [default = false]; - - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - optional bool cc_enable_arenas = 31 [default = false]; - - - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - optional string objc_class_prefix = 36; - - // Namespace for generated classes; defaults to the package. - optional string csharp_namespace = 37; - - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - optional string swift_prefix = 39; - - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - optional string php_class_prefix = 40; - - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - optional string php_namespace = 41; - - // Use this option to change the namespace of php generated metadata classes. - // Default is empty. When this option is empty, the proto file name will be - // used for determining the namespace. - optional string php_metadata_namespace = 44; - - // Use this option to change the package of ruby generated classes. Default - // is empty. When this option is not set, the package name will be used for - // determining the ruby package. - optional string ruby_package = 45; - - - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. - // See the documentation for the "Options" section above. - extensions 1000 to max; - - //reserved 38; -} - -message MessageOptions { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - optional bool message_set_wire_format = 1 [default = false]; - - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - optional bool no_standard_descriptor_accessor = 2 [default = false]; - - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - optional bool deprecated = 3 [default = false]; - - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementations still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - optional bool map_entry = 7; - - //reserved 8; // javalite_serializable - //reserved 9; // javanano_as_lite - - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message FieldOptions { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - optional CType ctype = 1 [default = STRING]; - enum CType { - // Default mode. - STRING = 0; - - CORD = 1; - - STRING_PIECE = 2; - } - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - optional bool packed = 2; - - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - optional JSType jstype = 6 [default = JS_NORMAL]; - enum JSType { - // Use the default type. - JS_NORMAL = 0; - - // Use JavaScript strings. - JS_STRING = 1; - - // Use JavaScript numbers. - JS_NUMBER = 2; - } - - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - optional bool lazy = 5 [default = false]; - - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - optional bool deprecated = 3 [default = false]; - - // For Google-internal migration only. Do not use. - optional bool weak = 10 [default = false]; - - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; - - //reserved 4; // removed jtype -} - -message OneofOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumOptions { - - // Set this option to true to allow mapping different tag names to the same - // value. - optional bool allow_alias = 2; - - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - optional bool deprecated = 3 [default = false]; - - //reserved 5; // javanano_as_lite - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumValueOptions { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - optional bool deprecated = 1 [default = false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message ServiceOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - optional bool deprecated = 33 [default = false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message MethodOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - optional bool deprecated = 33 [default = false]; - - // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, - // or neither? HTTP based RPC implementation may choose GET verb for safe - // methods, and PUT verb for idempotent methods instead of the default POST. - enum IdempotencyLevel { - IDEMPOTENCY_UNKNOWN = 0; - NO_SIDE_EFFECTS = 1; // implies idempotent - IDEMPOTENT = 2; // idempotent, but may have side effects - } - optional IdempotencyLevel idempotency_level = 34 - [default = IDEMPOTENCY_UNKNOWN]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -message UninterpretedOption { - // The name of the uninterpreted option. Each string represents a segment in - // a dot-separated name. is_extension is true iff a segment represents an - // extension (denoted with parentheses in options specs in .proto files). - // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - // "foo.(bar.baz).qux". - message NamePart { - required string name_part = 1; - required bool is_extension = 2; - } - repeated NamePart name = 2; - - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - optional string identifier_value = 3; - optional uint64 positive_int_value = 4; - optional int64 negative_int_value = 5; - optional double double_value = 6; - optional bytes string_value = 7; - optional string aggregate_value = 8; -} - -// =================================================================== -// Optional source code info - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -message SourceCodeInfo { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendant. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - repeated Location location = 1; - message Location { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - repeated int32 path = 1 [packed = true]; - - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - repeated int32 span = 2 [packed = true]; - - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - optional string leading_comments = 3; - optional string trailing_comments = 4; - repeated string leading_detached_comments = 6; - } -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -message GeneratedCodeInfo { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - repeated Annotation annotation = 1; - message Annotation { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - repeated int32 path = 1 [packed = true]; - - // Identifies the filesystem path to the original source .proto. - optional string source_file = 2; - - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - optional int32 begin = 3; - - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - optional int32 end = 4; - } -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto deleted file mode 100644 index b14bea5d01..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto +++ /dev/null @@ -1,116 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "types"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DurationProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (durations.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -message Duration { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - int64 seconds = 1; - - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto deleted file mode 100644 index 6057c8522d..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto +++ /dev/null @@ -1,52 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "types"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "EmptyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; -option cc_enable_arenas = true; - -// A generic empty message that you can re-use to avoid defining duplicated -// empty messages in your APIs. A typical example is to use it as the request -// or the response type of an API method. For instance: -// -// service Foo { -// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); -// } -// -// The JSON representation for `Empty` is empty JSON object `{}`. -message Empty {} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto deleted file mode 100644 index 7b77007b7e..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto +++ /dev/null @@ -1,245 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "FieldMaskProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; -option go_package = "types"; -option cc_enable_arenas = true; - -// `FieldMask` represents a set of symbolic field paths, for example: -// -// paths: "f.a" -// paths: "f.b.d" -// -// Here `f` represents a field in some root message, `a` and `b` -// fields in the message found in `f`, and `d` a field found in the -// message in `f.b`. -// -// Field masks are used to specify a subset of fields that should be -// returned by a get operation or modified by an update operation. -// Field masks also have a custom JSON encoding (see below). -// -// # Field Masks in Projections -// -// When used in the context of a projection, a response message or -// sub-message is filtered by the API to only contain those fields as -// specified in the mask. For example, if the mask in the previous -// example is applied to a response message as follows: -// -// f { -// a : 22 -// b { -// d : 1 -// x : 2 -// } -// y : 13 -// } -// z: 8 -// -// The result will not contain specific values for fields x,y and z -// (their value will be set to the default, and omitted in proto text -// output): -// -// -// f { -// a : 22 -// b { -// d : 1 -// } -// } -// -// A repeated field is not allowed except at the last position of a -// paths string. -// -// If a FieldMask object is not present in a get operation, the -// operation applies to all fields (as if a FieldMask of all fields -// had been specified). -// -// Note that a field mask does not necessarily apply to the -// top-level response message. In case of a REST get operation, the -// field mask applies directly to the response, but in case of a REST -// list operation, the mask instead applies to each individual message -// in the returned resource list. In case of a REST custom method, -// other definitions may be used. Where the mask applies will be -// clearly documented together with its declaration in the API. In -// any case, the effect on the returned resource/resources is required -// behavior for APIs. -// -// # Field Masks in Update Operations -// -// A field mask in update operations specifies which fields of the -// targeted resource are going to be updated. The API is required -// to only change the values of the fields as specified in the mask -// and leave the others untouched. If a resource is passed in to -// describe the updated values, the API ignores the values of all -// fields not covered by the mask. -// -// If a repeated field is specified for an update operation, new values will -// be appended to the existing repeated field in the target resource. Note that -// a repeated field is only allowed in the last position of a `paths` string. -// -// If a sub-message is specified in the last position of the field mask for an -// update operation, then new value will be merged into the existing sub-message -// in the target resource. -// -// For example, given the target message: -// -// f { -// b { -// d: 1 -// x: 2 -// } -// c: [1] -// } -// -// And an update message: -// -// f { -// b { -// d: 10 -// } -// c: [2] -// } -// -// then if the field mask is: -// -// paths: ["f.b", "f.c"] -// -// then the result will be: -// -// f { -// b { -// d: 10 -// x: 2 -// } -// c: [1, 2] -// } -// -// An implementation may provide options to override this default behavior for -// repeated and message fields. -// -// In order to reset a field's value to the default, the field must -// be in the mask and set to the default value in the provided resource. -// Hence, in order to reset all fields of a resource, provide a default -// instance of the resource and set all fields in the mask, or do -// not provide a mask as described below. -// -// If a field mask is not present on update, the operation applies to -// all fields (as if a field mask of all fields has been specified). -// Note that in the presence of schema evolution, this may mean that -// fields the client does not know and has therefore not filled into -// the request will be reset to their default. If this is unwanted -// behavior, a specific service may require a client to always specify -// a field mask, producing an error if not. -// -// As with get operations, the location of the resource which -// describes the updated values in the request message depends on the -// operation kind. In any case, the effect of the field mask is -// required to be honored by the API. -// -// ## Considerations for HTTP REST -// -// The HTTP kind of an update operation which uses a field mask must -// be set to PATCH instead of PUT in order to satisfy HTTP semantics -// (PUT must only be used for full updates). -// -// # JSON Encoding of Field Masks -// -// In JSON, a field mask is encoded as a single string where paths are -// separated by a comma. Fields name in each path are converted -// to/from lower-camel naming conventions. -// -// As an example, consider the following message declarations: -// -// message Profile { -// User user = 1; -// Photo photo = 2; -// } -// message User { -// string display_name = 1; -// string address = 2; -// } -// -// In proto a field mask for `Profile` may look as such: -// -// mask { -// paths: "user.display_name" -// paths: "photo" -// } -// -// In JSON, the same mask is represented as below: -// -// { -// mask: "user.displayName,photo" -// } -// -// # Field Masks and Oneof Fields -// -// Field masks treat fields in oneofs just as regular fields. Consider the -// following message: -// -// message SampleMessage { -// oneof test_oneof { -// string name = 4; -// SubMessage sub_message = 9; -// } -// } -// -// The field mask can be: -// -// mask { -// paths: "name" -// } -// -// Or: -// -// mask { -// paths: "sub_message" -// } -// -// Note that oneof type names ("test_oneof" in this case) cannot be used in -// paths. -// -// ## Field Mask Verification -// -// The implementation of any API method which has a FieldMask type field in the -// request should verify the included field paths, and return an -// `INVALID_ARGUMENT` error if any path is duplicated or unmappable. -message FieldMask { - // The set of field mask paths. - repeated string paths = 1; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/source_context.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/source_context.proto deleted file mode 100644 index 8654578c77..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/source_context.proto +++ /dev/null @@ -1,48 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "SourceContextProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; -option go_package = "types"; - -// `SourceContext` represents information about the source of a -// protobuf element, like the file in which it is defined. -message SourceContext { - // The path-qualified name of the .proto file that contained the associated - // protobuf element. For example: `"google/protobuf/source_context.proto"`. - string file_name = 1; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto deleted file mode 100644 index 9db0771592..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto +++ /dev/null @@ -1,95 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "types"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "StructProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// `Struct` represents a structured data value, consisting of fields -// which map to dynamically typed values. In some languages, `Struct` -// might be supported by a native representation. For example, in -// scripting languages like JS a struct is represented as an -// object. The details of that representation are described together -// with the proto support for the language. -// -// The JSON representation for `Struct` is JSON object. -message Struct { - // Unordered map of dynamically typed values. - map fields = 1; -} - -// `Value` represents a dynamically typed value which can be either -// null, a number, a string, a boolean, a recursive struct value, or a -// list of values. A producer of value is expected to set one of that -// variants, absence of any variant indicates an error. -// -// The JSON representation for `Value` is JSON value. -message Value { - // The kind of value. - oneof kind { - // Represents a null value. - NullValue null_value = 1; - // Represents a double value. - double number_value = 2; - // Represents a string value. - string string_value = 3; - // Represents a boolean value. - bool bool_value = 4; - // Represents a structured value. - Struct struct_value = 5; - // Represents a repeated `Value`. - ListValue list_value = 6; - } -} - -// `NullValue` is a singleton enumeration to represent the null value for the -// `Value` type union. -// -// The JSON representation for `NullValue` is JSON `null`. -enum NullValue { - // Null value. - NULL_VALUE = 0; -} - -// `ListValue` is a wrapper around a repeated field of values. -// -// The JSON representation for `ListValue` is JSON array. -message ListValue { - // Repeated field of dynamically typed values. - repeated Value values = 1; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto deleted file mode 100644 index 0ebe36ea73..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto +++ /dev/null @@ -1,138 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "types"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "TimestampProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Timestamp represents a point in time independent of any time zone or local -// calendar, encoded as a count of seconds and fractions of seconds at -// nanosecond resolution. The count is relative to an epoch at UTC midnight on -// January 1, 1970, in the proleptic Gregorian calendar which extends the -// Gregorian calendar backwards to year one. -// -// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap -// second table is needed for interpretation, using a [24-hour linear -// smear](https://developers.google.com/time/smear). -// -// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By -// restricting to that range, we ensure that we can convert to and from [RFC -// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required. A proto3 JSON serializer should always use UTC (as indicated by -// "Z") when printing the Timestamp type and a proto3 JSON parser should be -// able to accept both UTC and other timezones (as indicated by an offset). -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard -// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using -// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with -// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use -// the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D -// ) to obtain a formatter capable of generating timestamps in this format. -// -// -message Timestamp { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - int64 seconds = 1; - - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/type.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/type.proto deleted file mode 100644 index cc626250de..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/type.proto +++ /dev/null @@ -1,187 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -import "google/protobuf/any.proto"; -import "google/protobuf/source_context.proto"; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option java_package = "com.google.protobuf"; -option java_outer_classname = "TypeProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; -option go_package = "types"; - -// A protocol buffer message type. -message Type { - // The fully qualified message name. - string name = 1; - // The list of fields. - repeated Field fields = 2; - // The list of types appearing in `oneof` definitions in this type. - repeated string oneofs = 3; - // The protocol buffer options. - repeated Option options = 4; - // The source context. - SourceContext source_context = 5; - // The source syntax. - Syntax syntax = 6; -} - -// A single field of a message type. -message Field { - // Basic field types. - enum Kind { - // Field type unknown. - TYPE_UNKNOWN = 0; - // Field type double. - TYPE_DOUBLE = 1; - // Field type float. - TYPE_FLOAT = 2; - // Field type int64. - TYPE_INT64 = 3; - // Field type uint64. - TYPE_UINT64 = 4; - // Field type int32. - TYPE_INT32 = 5; - // Field type fixed64. - TYPE_FIXED64 = 6; - // Field type fixed32. - TYPE_FIXED32 = 7; - // Field type bool. - TYPE_BOOL = 8; - // Field type string. - TYPE_STRING = 9; - // Field type group. Proto2 syntax only, and deprecated. - TYPE_GROUP = 10; - // Field type message. - TYPE_MESSAGE = 11; - // Field type bytes. - TYPE_BYTES = 12; - // Field type uint32. - TYPE_UINT32 = 13; - // Field type enum. - TYPE_ENUM = 14; - // Field type sfixed32. - TYPE_SFIXED32 = 15; - // Field type sfixed64. - TYPE_SFIXED64 = 16; - // Field type sint32. - TYPE_SINT32 = 17; - // Field type sint64. - TYPE_SINT64 = 18; - } - - // Whether a field is optional, required, or repeated. - enum Cardinality { - // For fields with unknown cardinality. - CARDINALITY_UNKNOWN = 0; - // For optional fields. - CARDINALITY_OPTIONAL = 1; - // For required fields. Proto2 syntax only. - CARDINALITY_REQUIRED = 2; - // For repeated fields. - CARDINALITY_REPEATED = 3; - }; - - // The field type. - Kind kind = 1; - // The field cardinality. - Cardinality cardinality = 2; - // The field number. - int32 number = 3; - // The field name. - string name = 4; - // The field type URL, without the scheme, for message or enumeration - // types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. - string type_url = 6; - // The index of the field type in `Type.oneofs`, for message or enumeration - // types. The first type has index 1; zero means the type is not in the list. - int32 oneof_index = 7; - // Whether to use alternative packed wire representation. - bool packed = 8; - // The protocol buffer options. - repeated Option options = 9; - // The field JSON name. - string json_name = 10; - // The string value of the default value of this field. Proto2 syntax only. - string default_value = 11; -} - -// Enum type definition. -message Enum { - // Enum type name. - string name = 1; - // Enum value definitions. - repeated EnumValue enumvalue = 2; - // Protocol buffer options. - repeated Option options = 3; - // The source context. - SourceContext source_context = 4; - // The source syntax. - Syntax syntax = 5; -} - -// Enum value definition. -message EnumValue { - // Enum value name. - string name = 1; - // Enum value number. - int32 number = 2; - // Protocol buffer options. - repeated Option options = 3; -} - -// A protocol buffer option, which can be attached to a message, field, -// enumeration, etc. -message Option { - // The option's name. For protobuf built-in options (options defined in - // descriptor.proto), this is the short name. For example, `"map_entry"`. - // For custom options, it should be the fully-qualified name. For example, - // `"google.api.http"`. - string name = 1; - // The option's value packed in an Any message. If the value is a primitive, - // the corresponding wrapper type defined in google/protobuf/wrappers.proto - // should be used. If the value is an enum, it should be stored as an int32 - // value using the google.protobuf.Int32Value type. - Any value = 2; -} - -// The syntax in which a protocol buffer element is defined. -enum Syntax { - // Syntax `proto2`. - SYNTAX_PROTO2 = 0; - // Syntax `proto3`. - SYNTAX_PROTO3 = 1; -} diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto deleted file mode 100644 index 59b76acde8..0000000000 --- a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto +++ /dev/null @@ -1,123 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Wrappers for primitive (non-message) types. These types are useful -// for embedding primitives in the `google.protobuf.Any` type and for places -// where we need to distinguish between the absence of a primitive -// typed field and its default value. -// -// These wrappers have no meaningful use within repeated fields as they lack -// the ability to detect presence on individual elements. -// These wrappers have no meaningful use within a map or a oneof since -// individual entries of a map or fields of a oneof can already detect presence. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "types"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "WrappersProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// Wrapper message for `double`. -// -// The JSON representation for `DoubleValue` is JSON number. -message DoubleValue { - // The double value. - double value = 1; -} - -// Wrapper message for `float`. -// -// The JSON representation for `FloatValue` is JSON number. -message FloatValue { - // The float value. - float value = 1; -} - -// Wrapper message for `int64`. -// -// The JSON representation for `Int64Value` is JSON string. -message Int64Value { - // The int64 value. - int64 value = 1; -} - -// Wrapper message for `uint64`. -// -// The JSON representation for `UInt64Value` is JSON string. -message UInt64Value { - // The uint64 value. - uint64 value = 1; -} - -// Wrapper message for `int32`. -// -// The JSON representation for `Int32Value` is JSON number. -message Int32Value { - // The int32 value. - int32 value = 1; -} - -// Wrapper message for `uint32`. -// -// The JSON representation for `UInt32Value` is JSON number. -message UInt32Value { - // The uint32 value. - uint32 value = 1; -} - -// Wrapper message for `bool`. -// -// The JSON representation for `BoolValue` is JSON `true` and `false`. -message BoolValue { - // The bool value. - bool value = 1; -} - -// Wrapper message for `string`. -// -// The JSON representation for `StringValue` is JSON string. -message StringValue { - // The string value. - string value = 1; -} - -// Wrapper message for `bytes`. -// -// The JSON representation for `BytesValue` is JSON string. -message BytesValue { - // The bytes value. - bytes value = 1; -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare.go b/vendor/github.com/stretchr/testify/assert/assertion_compare.go index b774da88d8..7e19eba090 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_compare.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_compare.go @@ -7,10 +7,13 @@ import ( "time" ) -type CompareType int +// Deprecated: CompareType has only ever been for internal use and has accidentally been published since v1.6.0. Do not use it. +type CompareType = compareResult + +type compareResult int const ( - compareLess CompareType = iota - 1 + compareLess compareResult = iota - 1 compareEqual compareGreater ) @@ -28,6 +31,8 @@ var ( uint32Type = reflect.TypeOf(uint32(1)) uint64Type = reflect.TypeOf(uint64(1)) + uintptrType = reflect.TypeOf(uintptr(1)) + float32Type = reflect.TypeOf(float32(1)) float64Type = reflect.TypeOf(float64(1)) @@ -37,7 +42,7 @@ var ( bytesType = reflect.TypeOf([]byte{}) ) -func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { +func compare(obj1, obj2 interface{}, kind reflect.Kind) (compareResult, bool) { obj1Value := reflect.ValueOf(obj1) obj2Value := reflect.ValueOf(obj2) @@ -308,11 +313,11 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { case reflect.Struct: { // All structs enter here. We're not interested in most types. - if !canConvert(obj1Value, timeType) { + if !obj1Value.CanConvert(timeType) { break } - // time.Time can compared! + // time.Time can be compared! timeObj1, ok := obj1.(time.Time) if !ok { timeObj1 = obj1Value.Convert(timeType).Interface().(time.Time) @@ -323,12 +328,18 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { timeObj2 = obj2Value.Convert(timeType).Interface().(time.Time) } - return compare(timeObj1.UnixNano(), timeObj2.UnixNano(), reflect.Int64) + if timeObj1.Before(timeObj2) { + return compareLess, true + } + if timeObj1.Equal(timeObj2) { + return compareEqual, true + } + return compareGreater, true } case reflect.Slice: { // We only care about the []byte type. - if !canConvert(obj1Value, bytesType) { + if !obj1Value.CanConvert(bytesType) { break } @@ -343,7 +354,27 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { bytesObj2 = obj2Value.Convert(bytesType).Interface().([]byte) } - return CompareType(bytes.Compare(bytesObj1, bytesObj2)), true + return compareResult(bytes.Compare(bytesObj1, bytesObj2)), true + } + case reflect.Uintptr: + { + uintptrObj1, ok := obj1.(uintptr) + if !ok { + uintptrObj1 = obj1Value.Convert(uintptrType).Interface().(uintptr) + } + uintptrObj2, ok := obj2.(uintptr) + if !ok { + uintptrObj2 = obj2Value.Convert(uintptrType).Interface().(uintptr) + } + if uintptrObj1 > uintptrObj2 { + return compareGreater, true + } + if uintptrObj1 == uintptrObj2 { + return compareEqual, true + } + if uintptrObj1 < uintptrObj2 { + return compareLess, true + } } } @@ -359,7 +390,7 @@ func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface if h, ok := t.(tHelper); ok { h.Helper() } - return compareTwoValues(t, e1, e2, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) + return compareTwoValues(t, e1, e2, []compareResult{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) } // GreaterOrEqual asserts that the first element is greater than or equal to the second @@ -372,7 +403,7 @@ func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...in if h, ok := t.(tHelper); ok { h.Helper() } - return compareTwoValues(t, e1, e2, []CompareType{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) + return compareTwoValues(t, e1, e2, []compareResult{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) } // Less asserts that the first element is less than the second @@ -384,7 +415,7 @@ func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) if h, ok := t.(tHelper); ok { h.Helper() } - return compareTwoValues(t, e1, e2, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) + return compareTwoValues(t, e1, e2, []compareResult{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) } // LessOrEqual asserts that the first element is less than or equal to the second @@ -397,7 +428,7 @@ func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...inter if h, ok := t.(tHelper); ok { h.Helper() } - return compareTwoValues(t, e1, e2, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) + return compareTwoValues(t, e1, e2, []compareResult{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) } // Positive asserts that the specified element is positive @@ -409,7 +440,7 @@ func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { h.Helper() } zero := reflect.Zero(reflect.TypeOf(e)) - return compareTwoValues(t, e, zero.Interface(), []CompareType{compareGreater}, "\"%v\" is not positive", msgAndArgs...) + return compareTwoValues(t, e, zero.Interface(), []compareResult{compareGreater}, "\"%v\" is not positive", msgAndArgs...) } // Negative asserts that the specified element is negative @@ -421,10 +452,10 @@ func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { h.Helper() } zero := reflect.Zero(reflect.TypeOf(e)) - return compareTwoValues(t, e, zero.Interface(), []CompareType{compareLess}, "\"%v\" is not negative", msgAndArgs...) + return compareTwoValues(t, e, zero.Interface(), []compareResult{compareLess}, "\"%v\" is not negative", msgAndArgs...) } -func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool { +func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []compareResult, failMessage string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } @@ -447,7 +478,7 @@ func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedCompare return true } -func containsValue(values []CompareType, value CompareType) bool { +func containsValue(values []compareResult, value compareResult) bool { for _, v := range values { if v == value { return true diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go b/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go deleted file mode 100644 index da867903e2..0000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build go1.17 -// +build go1.17 - -// TODO: once support for Go 1.16 is dropped, this file can be -// merged/removed with assertion_compare_go1.17_test.go and -// assertion_compare_legacy.go - -package assert - -import "reflect" - -// Wrapper around reflect.Value.CanConvert, for compatibility -// reasons. -func canConvert(value reflect.Value, to reflect.Type) bool { - return value.CanConvert(to) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go b/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go deleted file mode 100644 index 1701af2a3c..0000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !go1.17 -// +build !go1.17 - -// TODO: once support for Go 1.16 is dropped, this file can be -// merged/removed with assertion_compare_go1.17_test.go and -// assertion_compare_can_convert.go - -package assert - -import "reflect" - -// Older versions of Go does not have the reflect.Value.CanConvert -// method. -func canConvert(value reflect.Value, to reflect.Type) bool { - return false -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go index 84dbd6c790..1906341657 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_format.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go @@ -1,7 +1,4 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package assert @@ -107,8 +104,8 @@ func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, return EqualExportedValues(t, expected, actual, append([]interface{}{msg}, args...)...) } -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValuesf asserts that two objects are equal or convertible to the larger +// type and equal. // // assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { @@ -189,7 +186,7 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick // assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -571,6 +568,23 @@ func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, a return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) } +// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// assert.NotElementsMatchf(t, [1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false +// +// assert.NotElementsMatchf(t, [1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true +// +// assert.NotElementsMatchf(t, [1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true +func NotElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) +} + // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -607,7 +621,16 @@ func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg s return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) } -// NotErrorIsf asserts that at none of the errors in err's chain matches target. +// NotErrorAsf asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func NotErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotErrorAs(t, err, target, append([]interface{}{msg}, args...)...) +} + +// NotErrorIsf asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -616,6 +639,16 @@ func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interf return NotErrorIs(t, err, target, append([]interface{}{msg}, args...)...) } +// NotImplementsf asserts that an object does not implement the specified interface. +// +// assert.NotImplementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func NotImplementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotImplements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) +} + // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") @@ -660,10 +693,12 @@ func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, return NotSame(t, expected, actual, append([]interface{}{msg}, args...)...) } -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted") +// assert.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -747,10 +782,11 @@ func Samef(t TestingT, expected interface{}, actual interface{}, msg string, arg return Same(t, expected, actual, append([]interface{}{msg}, args...)...) } -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// assert.Subsetf(t, [1, 2, 3], [1, 2], "error message %s", "formatted") +// assert.Subsetf(t, {"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go index b1d94aec53..21629087ba 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -1,7 +1,4 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package assert @@ -189,8 +186,8 @@ func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface return EqualExportedValuesf(a.t, expected, actual, msg, args...) } -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValues asserts that two objects are equal or convertible to the larger +// type and equal. // // a.EqualValues(uint32(123), int32(123)) func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { @@ -200,8 +197,8 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn return EqualValues(a.t, expected, actual, msgAndArgs...) } -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValuesf asserts that two objects are equal or convertible to the larger +// type and equal. // // a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { @@ -339,7 +336,7 @@ func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, ti // a.EventuallyWithT(func(c *assert.CollectT) { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -364,7 +361,7 @@ func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor // a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func (a *Assertions) EventuallyWithTf(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1131,6 +1128,40 @@ func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg strin return NotContainsf(a.t, s, contains, msg, args...) } +// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// a.NotElementsMatch([1, 1, 2, 3], [1, 1, 2, 3]) -> false +// +// a.NotElementsMatch([1, 1, 2, 3], [1, 2, 3]) -> true +// +// a.NotElementsMatch([1, 2, 3], [1, 2, 4]) -> true +func (a *Assertions) NotElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotElementsMatch(a.t, listA, listB, msgAndArgs...) +} + +// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// a.NotElementsMatchf([1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false +// +// a.NotElementsMatchf([1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true +// +// a.NotElementsMatchf([1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true +func (a *Assertions) NotElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotElementsMatchf(a.t, listA, listB, msg, args...) +} + // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -1203,7 +1234,25 @@ func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg str return NotEqualf(a.t, expected, actual, msg, args...) } -// NotErrorIs asserts that at none of the errors in err's chain matches target. +// NotErrorAs asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func (a *Assertions) NotErrorAs(err error, target interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotErrorAs(a.t, err, target, msgAndArgs...) +} + +// NotErrorAsf asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func (a *Assertions) NotErrorAsf(err error, target interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotErrorAsf(a.t, err, target, msg, args...) +} + +// NotErrorIs asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { @@ -1212,7 +1261,7 @@ func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface return NotErrorIs(a.t, err, target, msgAndArgs...) } -// NotErrorIsf asserts that at none of the errors in err's chain matches target. +// NotErrorIsf asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { @@ -1221,6 +1270,26 @@ func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...in return NotErrorIsf(a.t, err, target, msg, args...) } +// NotImplements asserts that an object does not implement the specified interface. +// +// a.NotImplements((*MyInterface)(nil), new(MyObject)) +func (a *Assertions) NotImplements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotImplements(a.t, interfaceObject, object, msgAndArgs...) +} + +// NotImplementsf asserts that an object does not implement the specified interface. +// +// a.NotImplementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func (a *Assertions) NotImplementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotImplementsf(a.t, interfaceObject, object, msg, args...) +} + // NotNil asserts that the specified object is not nil. // // a.NotNil(err) @@ -1309,10 +1378,12 @@ func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg stri return NotSamef(a.t, expected, actual, msg, args...) } -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// a.NotSubset([1, 3, 4], [1, 2]) +// a.NotSubset({"x": 1, "y": 2}, {"z": 3}) func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1320,10 +1391,12 @@ func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs return NotSubset(a.t, list, subset, msgAndArgs...) } -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// a.NotSubsetf([1, 3, 4], [1, 2], "error message %s", "formatted") +// a.NotSubsetf({"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1483,10 +1556,11 @@ func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, return Samef(a.t, expected, actual, msg, args...) } -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// a.Subset([1, 2, 3], [1, 2]) +// a.Subset({"x": 1, "y": 2}, {"x": 1}) func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1494,10 +1568,11 @@ func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ... return Subset(a.t, list, subset, msgAndArgs...) } -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// a.Subsetf([1, 2, 3], [1, 2], "error message %s", "formatted") +// a.Subsetf({"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/assert/assertion_order.go b/vendor/github.com/stretchr/testify/assert/assertion_order.go index 00df62a059..1d2f71824a 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_order.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_order.go @@ -6,7 +6,7 @@ import ( ) // isOrdered checks that collection contains orderable elements. -func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool { +func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareResult, failMessage string, msgAndArgs ...interface{}) bool { objKind := reflect.TypeOf(object).Kind() if objKind != reflect.Slice && objKind != reflect.Array { return false @@ -50,7 +50,7 @@ func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareT // assert.IsIncreasing(t, []float{1, 2}) // assert.IsIncreasing(t, []string{"a", "b"}) func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) + return isOrdered(t, object, []compareResult{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) } // IsNonIncreasing asserts that the collection is not increasing @@ -59,7 +59,7 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo // assert.IsNonIncreasing(t, []float{2, 1}) // assert.IsNonIncreasing(t, []string{"b", "a"}) func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) + return isOrdered(t, object, []compareResult{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) } // IsDecreasing asserts that the collection is decreasing @@ -68,7 +68,7 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) // assert.IsDecreasing(t, []float{2, 1}) // assert.IsDecreasing(t, []string{"b", "a"}) func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) + return isOrdered(t, object, []compareResult{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) } // IsNonDecreasing asserts that the collection is not decreasing @@ -77,5 +77,5 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo // assert.IsNonDecreasing(t, []float{1, 2}) // assert.IsNonDecreasing(t, []string{"a", "b"}) func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) + return isOrdered(t, object, []compareResult{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) } diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go index a55d1bba92..4e91332bb5 100644 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -19,7 +19,9 @@ import ( "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" - yaml "gopkg.in/yaml.v3" + + // Wrapper around gopkg.in/yaml.v3 + "github.com/stretchr/testify/assert/yaml" ) //go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl" @@ -45,6 +47,10 @@ type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool // for table driven tests. type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool +// PanicAssertionFunc is a common function prototype when validating a panic value. Can be useful +// for table driven tests. +type PanicAssertionFunc = func(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool + // Comparison is a custom function that returns true on success and false on failure type Comparison func() (success bool) @@ -110,7 +116,12 @@ func copyExportedFields(expected interface{}) interface{} { return result.Interface() case reflect.Array, reflect.Slice: - result := reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len()) + var result reflect.Value + if expectedKind == reflect.Array { + result = reflect.New(reflect.ArrayOf(expectedValue.Len(), expectedType.Elem())).Elem() + } else { + result = reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len()) + } for i := 0; i < expectedValue.Len(); i++ { index := expectedValue.Index(i) if isNil(index) { @@ -140,6 +151,8 @@ func copyExportedFields(expected interface{}) interface{} { // structures. // // This function does no assertion of any kind. +// +// Deprecated: Use [EqualExportedValues] instead. func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool { expectedCleaned := copyExportedFields(expected) actualCleaned := copyExportedFields(actual) @@ -153,17 +166,40 @@ func ObjectsAreEqualValues(expected, actual interface{}) bool { return true } - actualType := reflect.TypeOf(actual) - if actualType == nil { + expectedValue := reflect.ValueOf(expected) + actualValue := reflect.ValueOf(actual) + if !expectedValue.IsValid() || !actualValue.IsValid() { return false } - expectedValue := reflect.ValueOf(expected) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + + expectedType := expectedValue.Type() + actualType := actualValue.Type() + if !expectedType.ConvertibleTo(actualType) { + return false + } + + if !isNumericType(expectedType) || !isNumericType(actualType) { // Attempt comparison after type conversion - return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + return reflect.DeepEqual( + expectedValue.Convert(actualType).Interface(), actual, + ) } - return false + // If BOTH values are numeric, there are chances of false positives due + // to overflow or underflow. So, we need to make sure to always convert + // the smaller type to a larger type before comparing. + if expectedType.Size() >= actualType.Size() { + return actualValue.Convert(expectedType).Interface() == expected + } + + return expectedValue.Convert(actualType).Interface() == actual +} + +// isNumericType returns true if the type is one of: +// int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, +// float32, float64, complex64, complex128 +func isNumericType(t reflect.Type) bool { + return t.Kind() >= reflect.Int && t.Kind() <= reflect.Complex128 } /* CallerInfo is necessary because the assert functions use the testing object @@ -266,7 +302,7 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { // Aligns the provided message so that all lines after the first line start at the same location as the first line. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). -// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the +// The longestLabelLen parameter specifies the length of the longest label in the output (required because this is the // basis on which the alignment occurs). func indentMessageLines(message string, longestLabelLen int) string { outBuf := new(bytes.Buffer) @@ -382,6 +418,25 @@ func Implements(t TestingT, interfaceObject interface{}, object interface{}, msg return true } +// NotImplements asserts that an object does not implement the specified interface. +// +// assert.NotImplements(t, (*MyInterface)(nil), new(MyObject)) +func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + interfaceType := reflect.TypeOf(interfaceObject).Elem() + + if object == nil { + return Fail(t, fmt.Sprintf("Cannot check if nil does not implement %v", interfaceType), msgAndArgs...) + } + if reflect.TypeOf(object).Implements(interfaceType) { + return Fail(t, fmt.Sprintf("%T implements %v", object, interfaceType), msgAndArgs...) + } + + return true +} + // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -447,7 +502,13 @@ func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) b h.Helper() } - if !samePointers(expected, actual) { + same, ok := samePointers(expected, actual) + if !ok { + return Fail(t, "Both arguments must be pointers", msgAndArgs...) + } + + if !same { + // both are pointers but not the same type & pointing to the same address return Fail(t, fmt.Sprintf("Not same: \n"+ "expected: %p %#v\n"+ "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...) @@ -467,7 +528,13 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{} h.Helper() } - if samePointers(expected, actual) { + same, ok := samePointers(expected, actual) + if !ok { + //fails when the arguments are not pointers + return !(Fail(t, "Both arguments must be pointers", msgAndArgs...)) + } + + if same { return Fail(t, fmt.Sprintf( "Expected and actual point to the same object: %p %#v", expected, expected), msgAndArgs...) @@ -475,28 +542,30 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{} return true } -// samePointers compares two generic interface objects and returns whether -// they point to the same object -func samePointers(first, second interface{}) bool { +// samePointers checks if two generic interface objects are pointers of the same +// type pointing to the same object. It returns two values: same indicating if +// they are the same type and point to the same object, and ok indicating that +// both inputs are pointers. +func samePointers(first, second interface{}) (same bool, ok bool) { firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second) if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr { - return false + return false, false //not both are pointers } firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second) if firstType != secondType { - return false + return false, true // both are pointers, but of different types } // compare pointer addresses - return first == second + return first == second, true } // formatUnequalValues takes two values of arbitrary types and returns string // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed -// with the type name, and the value will be enclosed in parenthesis similar +// with the type name, and the value will be enclosed in parentheses similar // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { @@ -523,8 +592,8 @@ func truncatingFormat(data interface{}) string { return value } -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValues asserts that two objects are equal or convertible to the larger +// type and equal. // // assert.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { @@ -566,14 +635,6 @@ func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs .. return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) } - if aType.Kind() != reflect.Struct { - return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...) - } - - if bType.Kind() != reflect.Struct { - return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...) - } - expected = copyExportedFields(expected) actual = copyExportedFields(actual) @@ -620,17 +681,6 @@ func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return Fail(t, "Expected value not to be nil.", msgAndArgs...) } -// containsKind checks if a specified kind in the slice of kinds. -func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool { - for i := 0; i < len(kinds); i++ { - if kind == kinds[i] { - return true - } - } - - return false -} - // isNil checks if a specified object is nil or not, without Failing. func isNil(object interface{}) bool { if object == nil { @@ -638,16 +688,13 @@ func isNil(object interface{}) bool { } value := reflect.ValueOf(object) - kind := value.Kind() - isNilableKind := containsKind( - []reflect.Kind{ - reflect.Chan, reflect.Func, - reflect.Interface, reflect.Map, - reflect.Ptr, reflect.Slice, reflect.UnsafePointer}, - kind) - - if isNilableKind && value.IsNil() { - return true + switch value.Kind() { + case + reflect.Chan, reflect.Func, + reflect.Interface, reflect.Map, + reflect.Ptr, reflect.Slice, reflect.UnsafePointer: + + return value.IsNil() } return false @@ -731,16 +778,14 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { } -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { +// getLen tries to get the length of an object. +// It returns (0, false) if impossible. +func getLen(x interface{}) (length int, ok bool) { v := reflect.ValueOf(x) defer func() { - if e := recover(); e != nil { - ok = false - } + ok = recover() == nil }() - return true, v.Len() + return v.Len(), true } // Len asserts that the specified object has specific length. @@ -751,13 +796,13 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) if h, ok := t.(tHelper); ok { h.Helper() } - ok, l := getLen(object) + l, ok := getLen(object) if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) + return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...) } if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) + return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) } return true } @@ -919,10 +964,11 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) } -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// assert.Subset(t, [1, 2, 3], [1, 2]) +// assert.Subset(t, {"x": 1, "y": 2}, {"x": 1}) func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() @@ -975,10 +1021,12 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok return true } -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// assert.NotSubset(t, [1, 3, 4], [1, 2]) +// assert.NotSubset(t, {"x": 1, "y": 2}, {"z": 3}) func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1127,6 +1175,39 @@ func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) stri return msg.String() } +// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// assert.NotElementsMatch(t, [1, 1, 2, 3], [1, 1, 2, 3]) -> false +// +// assert.NotElementsMatch(t, [1, 1, 2, 3], [1, 2, 3]) -> true +// +// assert.NotElementsMatch(t, [1, 2, 3], [1, 2, 4]) -> true +func NotElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if isEmpty(listA) && isEmpty(listB) { + return Fail(t, "listA and listB contain the same elements", msgAndArgs) + } + + if !isList(t, listA, msgAndArgs...) { + return Fail(t, "listA is not a list type", msgAndArgs...) + } + if !isList(t, listB, msgAndArgs...) { + return Fail(t, "listB is not a list type", msgAndArgs...) + } + + extraA, extraB := diffLists(listA, listB) + if len(extraA) == 0 && len(extraB) == 0 { + return Fail(t, "listA and listB contain the same elements", msgAndArgs) + } + + return true +} + // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -1439,12 +1520,15 @@ func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAnd h.Helper() } if math.IsNaN(epsilon) { - return Fail(t, "epsilon must not be NaN") + return Fail(t, "epsilon must not be NaN", msgAndArgs...) } actualEpsilon, err := calcRelativeError(expected, actual) if err != nil { return Fail(t, err.Error(), msgAndArgs...) } + if math.IsNaN(actualEpsilon) { + return Fail(t, "relative error is NaN", msgAndArgs...) + } if actualEpsilon > epsilon { return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) @@ -1458,19 +1542,26 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m if h, ok := t.(tHelper); ok { h.Helper() } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { + + if expected == nil || actual == nil { return Fail(t, "Parameters must be slice", msgAndArgs...) } - actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) + actualSlice := reflect.ValueOf(actual) - for i := 0; i < actualSlice.Len(); i++ { - result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) - if !result { - return result + if expectedSlice.Type().Kind() != reflect.Slice { + return Fail(t, "Expected value must be slice", msgAndArgs...) + } + + expectedLen := expectedSlice.Len() + if !IsType(t, expected, actual) || !Len(t, actual, expectedLen) { + return false + } + + for i := 0; i < expectedLen; i++ { + if !InEpsilon(t, expectedSlice.Index(i).Interface(), actualSlice.Index(i).Interface(), epsilon, "at index %d", i) { + return false } } @@ -1561,7 +1652,6 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in // matchRegexp return true if a specified regexp matches a string. func matchRegexp(rx interface{}, str interface{}) bool { - var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr @@ -1569,7 +1659,14 @@ func matchRegexp(rx interface{}, str interface{}) bool { r = regexp.MustCompile(fmt.Sprint(rx)) } - return (r.FindStringIndex(fmt.Sprint(str)) != nil) + switch v := str.(type) { + case []byte: + return r.Match(v) + case string: + return r.MatchString(v) + default: + return r.MatchString(fmt.Sprint(v)) + } } @@ -1822,7 +1919,7 @@ var spewConfigStringerEnabled = spew.ConfigState{ MaxDepth: 10, } -type tHelper interface { +type tHelper = interface { Helper() } @@ -1861,6 +1958,9 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t // CollectT implements the TestingT interface and collects all errors. type CollectT struct { + // A slice of errors. Non-nil slice denotes a failure. + // If it's non-nil but len(c.errors) == 0, this is also a failure + // obtained by direct c.FailNow() call. errors []error } @@ -1869,26 +1969,32 @@ func (c *CollectT) Errorf(format string, args ...interface{}) { c.errors = append(c.errors, fmt.Errorf(format, args...)) } -// FailNow panics. +// FailNow stops execution by calling runtime.Goexit. func (c *CollectT) FailNow() { - panic("Assertion failed") + c.fail() + runtime.Goexit() } -// Reset clears the collected errors. -func (c *CollectT) Reset() { - c.errors = nil +// Deprecated: That was a method for internal usage that should not have been published. Now just panics. +func (*CollectT) Reset() { + panic("Reset() is deprecated") } -// Copy copies the collected errors to the supplied t. -func (c *CollectT) Copy(t TestingT) { - if tt, ok := t.(tHelper); ok { - tt.Helper() - } - for _, err := range c.errors { - t.Errorf("%v", err) +// Deprecated: That was a method for internal usage that should not have been published. Now just panics. +func (*CollectT) Copy(TestingT) { + panic("Copy() is deprecated") +} + +func (c *CollectT) fail() { + if !c.failed() { + c.errors = []error{} // Make it non-nil to mark a failure. } } +func (c *CollectT) failed() bool { + return c.errors != nil +} + // EventuallyWithT asserts that given condition will be met in waitFor time, // periodically checking target function each tick. In contrast to Eventually, // it supplies a CollectT to the condition function, so that the condition @@ -1906,14 +2012,14 @@ func (c *CollectT) Copy(t TestingT) { // assert.EventuallyWithT(t, func(c *assert.CollectT) { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } - collect := new(CollectT) - ch := make(chan bool, 1) + var lastFinishedTickErrs []error + ch := make(chan *CollectT, 1) timer := time.NewTimer(waitFor) defer timer.Stop() @@ -1924,19 +2030,25 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time for tick := ticker.C; ; { select { case <-timer.C: - collect.Copy(t) + for _, err := range lastFinishedTickErrs { + t.Errorf("%v", err) + } return Fail(t, "Condition never satisfied", msgAndArgs...) case <-tick: tick = nil - collect.Reset() go func() { + collect := new(CollectT) + defer func() { + ch <- collect + }() condition(collect) - ch <- len(collect.errors) == 0 }() - case v := <-ch: - if v { + case collect := <-ch: + if !collect.failed() { return true } + // Keep the errors from the last ended condition, so that they can be copied to t if timeout is reached. + lastFinishedTickErrs = collect.errors tick = ticker.C } } @@ -1998,7 +2110,7 @@ func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool { ), msgAndArgs...) } -// NotErrorIs asserts that at none of the errors in err's chain matches target. +// NotErrorIs asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -2039,6 +2151,24 @@ func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{ ), msgAndArgs...) } +// NotErrorAs asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if !errors.As(err, target) { + return true + } + + chain := buildErrorChainString(err) + + return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+ + "found: %q\n"+ + "in chain: %s", target, chain, + ), msgAndArgs...) +} + func buildErrorChainString(err error) string { if err == nil { return "" diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go index d8038c28a7..861ed4b7ce 100644 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go @@ -12,7 +12,7 @@ import ( // an error if building a new request fails. func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { w := httptest.NewRecorder() - req, err := http.NewRequest(method, url, nil) + req, err := http.NewRequest(method, url, http.NoBody) if err != nil { return -1, err } @@ -32,12 +32,12 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, value } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent if !isSuccessCode { - Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isSuccessCode @@ -54,12 +54,12 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, valu } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect if !isRedirectCode { - Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isRedirectCode @@ -76,12 +76,12 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isErrorCode := code >= http.StatusBadRequest if !isErrorCode { - Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isErrorCode @@ -98,12 +98,12 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, va } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } successful := code == statuscode if !successful { - Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code), msgAndArgs...) } return successful @@ -113,7 +113,10 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, va // empty string if building a new request fails. func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) + if len(values) > 0 { + url += "?" + values.Encode() + } + req, err := http.NewRequest(method, url, http.NoBody) if err != nil { return "" } @@ -135,7 +138,7 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, contains := strings.Contains(body, fmt.Sprint(str)) if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) + Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body), msgAndArgs...) } return contains @@ -155,7 +158,7 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url strin contains := strings.Contains(body, fmt.Sprint(str)) if contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) + Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body), msgAndArgs...) } return !contains diff --git a/vendor/github.com/stretchr/testify/assert/yaml/yaml_custom.go b/vendor/github.com/stretchr/testify/assert/yaml/yaml_custom.go new file mode 100644 index 0000000000..baa0cc7d7f --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/yaml/yaml_custom.go @@ -0,0 +1,25 @@ +//go:build testify_yaml_custom && !testify_yaml_fail && !testify_yaml_default +// +build testify_yaml_custom,!testify_yaml_fail,!testify_yaml_default + +// Package yaml is an implementation of YAML functions that calls a pluggable implementation. +// +// This implementation is selected with the testify_yaml_custom build tag. +// +// go test -tags testify_yaml_custom +// +// This implementation can be used at build time to replace the default implementation +// to avoid linking with [gopkg.in/yaml.v3]. +// +// In your test package: +// +// import assertYaml "github.com/stretchr/testify/assert/yaml" +// +// func init() { +// assertYaml.Unmarshal = func (in []byte, out interface{}) error { +// // ... +// return nil +// } +// } +package yaml + +var Unmarshal func(in []byte, out interface{}) error diff --git a/vendor/github.com/stretchr/testify/assert/yaml/yaml_default.go b/vendor/github.com/stretchr/testify/assert/yaml/yaml_default.go new file mode 100644 index 0000000000..b83c6cf64c --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/yaml/yaml_default.go @@ -0,0 +1,37 @@ +//go:build !testify_yaml_fail && !testify_yaml_custom +// +build !testify_yaml_fail,!testify_yaml_custom + +// Package yaml is just an indirection to handle YAML deserialization. +// +// This package is just an indirection that allows the builder to override the +// indirection with an alternative implementation of this package that uses +// another implementation of YAML deserialization. This allows to not either not +// use YAML deserialization at all, or to use another implementation than +// [gopkg.in/yaml.v3] (for example for license compatibility reasons, see [PR #1120]). +// +// Alternative implementations are selected using build tags: +// +// - testify_yaml_fail: [Unmarshal] always fails with an error +// - testify_yaml_custom: [Unmarshal] is a variable. Caller must initialize it +// before calling any of [github.com/stretchr/testify/assert.YAMLEq] or +// [github.com/stretchr/testify/assert.YAMLEqf]. +// +// Usage: +// +// go test -tags testify_yaml_fail +// +// You can check with "go list" which implementation is linked: +// +// go list -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml +// go list -tags testify_yaml_fail -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml +// go list -tags testify_yaml_custom -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml +// +// [PR #1120]: https://github.com/stretchr/testify/pull/1120 +package yaml + +import goyaml "gopkg.in/yaml.v3" + +// Unmarshal is just a wrapper of [gopkg.in/yaml.v3.Unmarshal]. +func Unmarshal(in []byte, out interface{}) error { + return goyaml.Unmarshal(in, out) +} diff --git a/vendor/github.com/stretchr/testify/assert/yaml/yaml_fail.go b/vendor/github.com/stretchr/testify/assert/yaml/yaml_fail.go new file mode 100644 index 0000000000..e78f7dfe69 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/yaml/yaml_fail.go @@ -0,0 +1,18 @@ +//go:build testify_yaml_fail && !testify_yaml_custom && !testify_yaml_default +// +build testify_yaml_fail,!testify_yaml_custom,!testify_yaml_default + +// Package yaml is an implementation of YAML functions that always fail. +// +// This implementation can be used at build time to replace the default implementation +// to avoid linking with [gopkg.in/yaml.v3]: +// +// go test -tags testify_yaml_fail +package yaml + +import "errors" + +var errNotImplemented = errors.New("YAML functions are not available (see https://pkg.go.dev/github.com/stretchr/testify/assert/yaml)") + +func Unmarshal([]byte, interface{}) error { + return errNotImplemented +} diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go index 63f8521476..d8921950d7 100644 --- a/vendor/github.com/stretchr/testify/require/require.go +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -1,7 +1,4 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package require @@ -37,9 +34,9 @@ func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interfac // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Contains(t, "Hello World", "World") -// assert.Contains(t, ["Hello", "World"], "World") -// assert.Contains(t, {"Hello": "World"}, "Hello") +// require.Contains(t, "Hello World", "World") +// require.Contains(t, ["Hello", "World"], "World") +// require.Contains(t, {"Hello": "World"}, "Hello") func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -53,9 +50,9 @@ func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...int // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") -// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") -// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +// require.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// require.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// require.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -94,7 +91,7 @@ func DirExistsf(t TestingT, path string, msg string, args ...interface{}) { // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // -// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) +// require.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -109,7 +106,7 @@ func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // -// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") +// require.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -123,7 +120,7 @@ func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// assert.Empty(t, obj) +// require.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -137,7 +134,7 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// assert.Emptyf(t, obj, "error message %s", "formatted") +// require.Emptyf(t, obj, "error message %s", "formatted") func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -150,7 +147,7 @@ func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { // Equal asserts that two objects are equal. // -// assert.Equal(t, 123, 123) +// require.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -169,7 +166,7 @@ func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...i // and that it is equal to the provided error. // // actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString) +// require.EqualError(t, err, expectedErrorString) func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -184,7 +181,7 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte // and that it is equal to the provided error. // // actualObj, err := SomeFunction() -// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +// require.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -203,8 +200,8 @@ func EqualErrorf(t TestingT, theError error, errString string, msg string, args // Exported int // notExported int // } -// assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true -// assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false +// require.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true +// require.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false func EqualExportedValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -223,8 +220,8 @@ func EqualExportedValues(t TestingT, expected interface{}, actual interface{}, m // Exported int // notExported int // } -// assert.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true -// assert.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false +// require.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true +// require.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -235,10 +232,10 @@ func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, t.FailNow() } -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValues asserts that two objects are equal or convertible to the larger +// type and equal. // -// assert.EqualValues(t, uint32(123), int32(123)) +// require.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -249,10 +246,10 @@ func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArg t.FailNow() } -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValuesf asserts that two objects are equal or convertible to the larger +// type and equal. // -// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") +// require.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -265,7 +262,7 @@ func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg stri // Equalf asserts that two objects are equal. // -// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// require.Equalf(t, 123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -283,8 +280,8 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() -// if assert.Error(t, err) { -// assert.Equal(t, expectedError, err) +// if require.Error(t, err) { +// require.Equal(t, expectedError, err) // } func Error(t TestingT, err error, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { @@ -324,7 +321,7 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int // and that the error contains the specified substring. // // actualObj, err := SomeFunction() -// assert.ErrorContains(t, err, expectedErrorSubString) +// require.ErrorContains(t, err, expectedErrorSubString) func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -339,7 +336,7 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in // and that the error contains the specified substring. // // actualObj, err := SomeFunction() -// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") +// require.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -377,8 +374,8 @@ func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() -// if assert.Errorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) +// if require.Errorf(t, err, "error message %s", "formatted") { +// require.Equal(t, expectedErrorf, err) // } func Errorf(t TestingT, err error, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { @@ -393,7 +390,7 @@ func Errorf(t TestingT, err error, msg string, args ...interface{}) { // Eventually asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) +// require.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -418,10 +415,10 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t // time.Sleep(8*time.Second) // externalValue = true // }() -// assert.EventuallyWithT(t, func(c *assert.CollectT) { +// require.EventuallyWithT(t, func(c *require.CollectT) { // // add assertions as needed; any assertion failure will fail the current tick -// assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// require.True(c, externalValue, "expected 'externalValue' to be true") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -446,10 +443,10 @@ func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitF // time.Sleep(8*time.Second) // externalValue = true // }() -// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") { +// require.EventuallyWithTf(t, func(c *require.CollectT, "error message %s", "formatted") { // // add assertions as needed; any assertion failure will fail the current tick -// assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// require.True(c, externalValue, "expected 'externalValue' to be true") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -463,7 +460,7 @@ func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), wait // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// require.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -476,7 +473,7 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick // Exactly asserts that two objects are equal in value and type. // -// assert.Exactly(t, int32(123), int64(123)) +// require.Exactly(t, int32(123), int64(123)) func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -489,7 +486,7 @@ func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs .. // Exactlyf asserts that two objects are equal in value and type. // -// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") +// require.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -546,7 +543,7 @@ func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { // False asserts that the specified value is false. // -// assert.False(t, myBool) +// require.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -559,7 +556,7 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) { // Falsef asserts that the specified value is false. // -// assert.Falsef(t, myBool, "error message %s", "formatted") +// require.Falsef(t, myBool, "error message %s", "formatted") func Falsef(t TestingT, value bool, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -596,9 +593,9 @@ func FileExistsf(t TestingT, path string, msg string, args ...interface{}) { // Greater asserts that the first element is greater than the second // -// assert.Greater(t, 2, 1) -// assert.Greater(t, float64(2), float64(1)) -// assert.Greater(t, "b", "a") +// require.Greater(t, 2, 1) +// require.Greater(t, float64(2), float64(1)) +// require.Greater(t, "b", "a") func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -611,10 +608,10 @@ func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface // GreaterOrEqual asserts that the first element is greater than or equal to the second // -// assert.GreaterOrEqual(t, 2, 1) -// assert.GreaterOrEqual(t, 2, 2) -// assert.GreaterOrEqual(t, "b", "a") -// assert.GreaterOrEqual(t, "b", "b") +// require.GreaterOrEqual(t, 2, 1) +// require.GreaterOrEqual(t, 2, 2) +// require.GreaterOrEqual(t, "b", "a") +// require.GreaterOrEqual(t, "b", "b") func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -627,10 +624,10 @@ func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...in // GreaterOrEqualf asserts that the first element is greater than or equal to the second // -// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") +// require.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") +// require.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") +// require.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") +// require.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -643,9 +640,9 @@ func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, arg // Greaterf asserts that the first element is greater than the second // -// assert.Greaterf(t, 2, 1, "error message %s", "formatted") -// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") -// assert.Greaterf(t, "b", "a", "error message %s", "formatted") +// require.Greaterf(t, 2, 1, "error message %s", "formatted") +// require.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") +// require.Greaterf(t, "b", "a", "error message %s", "formatted") func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -659,7 +656,7 @@ func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...in // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // -// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// require.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { @@ -675,7 +672,7 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url s // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // -// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// require.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { @@ -691,7 +688,7 @@ func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // -// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// require.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { @@ -707,7 +704,7 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, ur // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // -// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// require.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { @@ -722,7 +719,7 @@ func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, u // HTTPError asserts that a specified handler returns an error status code. // -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// require.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -737,7 +734,7 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, // HTTPErrorf asserts that a specified handler returns an error status code. // -// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// require.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -752,7 +749,7 @@ func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, // HTTPRedirect asserts that a specified handler returns a redirect status code. // -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// require.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -767,7 +764,7 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url strin // HTTPRedirectf asserts that a specified handler returns a redirect status code. // -// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// require.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -782,7 +779,7 @@ func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url stri // HTTPStatusCode asserts that a specified handler returns a specified status code. // -// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) +// require.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) { @@ -797,7 +794,7 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url str // HTTPStatusCodef asserts that a specified handler returns a specified status code. // -// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// require.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) { @@ -812,7 +809,7 @@ func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url st // HTTPSuccess asserts that a specified handler returns a success status code. // -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// require.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -827,7 +824,7 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string // HTTPSuccessf asserts that a specified handler returns a success status code. // -// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// require.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -842,7 +839,7 @@ func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url strin // Implements asserts that an object is implemented by the specified interface. // -// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) +// require.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -855,7 +852,7 @@ func Implements(t TestingT, interfaceObject interface{}, object interface{}, msg // Implementsf asserts that an object is implemented by the specified interface. // -// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +// require.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -868,7 +865,7 @@ func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, ms // InDelta asserts that the two numerals are within delta of each other. // -// assert.InDelta(t, math.Pi, 22/7.0, 0.01) +// require.InDelta(t, math.Pi, 22/7.0, 0.01) func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -925,7 +922,7 @@ func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta f // InDeltaf asserts that the two numerals are within delta of each other. // -// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") +// require.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -982,9 +979,9 @@ func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon fl // IsDecreasing asserts that the collection is decreasing // -// assert.IsDecreasing(t, []int{2, 1, 0}) -// assert.IsDecreasing(t, []float{2, 1}) -// assert.IsDecreasing(t, []string{"b", "a"}) +// require.IsDecreasing(t, []int{2, 1, 0}) +// require.IsDecreasing(t, []float{2, 1}) +// require.IsDecreasing(t, []string{"b", "a"}) func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -997,9 +994,9 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { // IsDecreasingf asserts that the collection is decreasing // -// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +// require.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") +// require.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") +// require.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1012,9 +1009,9 @@ func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface // IsIncreasing asserts that the collection is increasing // -// assert.IsIncreasing(t, []int{1, 2, 3}) -// assert.IsIncreasing(t, []float{1, 2}) -// assert.IsIncreasing(t, []string{"a", "b"}) +// require.IsIncreasing(t, []int{1, 2, 3}) +// require.IsIncreasing(t, []float{1, 2}) +// require.IsIncreasing(t, []string{"a", "b"}) func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1027,9 +1024,9 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { // IsIncreasingf asserts that the collection is increasing // -// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +// require.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") +// require.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") +// require.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1042,9 +1039,9 @@ func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface // IsNonDecreasing asserts that the collection is not decreasing // -// assert.IsNonDecreasing(t, []int{1, 1, 2}) -// assert.IsNonDecreasing(t, []float{1, 2}) -// assert.IsNonDecreasing(t, []string{"a", "b"}) +// require.IsNonDecreasing(t, []int{1, 1, 2}) +// require.IsNonDecreasing(t, []float{1, 2}) +// require.IsNonDecreasing(t, []string{"a", "b"}) func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1057,9 +1054,9 @@ func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) // IsNonDecreasingf asserts that the collection is not decreasing // -// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +// require.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") +// require.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") +// require.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1072,9 +1069,9 @@ func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interf // IsNonIncreasing asserts that the collection is not increasing // -// assert.IsNonIncreasing(t, []int{2, 1, 1}) -// assert.IsNonIncreasing(t, []float{2, 1}) -// assert.IsNonIncreasing(t, []string{"b", "a"}) +// require.IsNonIncreasing(t, []int{2, 1, 1}) +// require.IsNonIncreasing(t, []float{2, 1}) +// require.IsNonIncreasing(t, []string{"b", "a"}) func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1087,9 +1084,9 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) // IsNonIncreasingf asserts that the collection is not increasing // -// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +// require.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") +// require.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") +// require.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1124,7 +1121,7 @@ func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg strin // JSONEq asserts that two JSON strings are equivalent. // -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// require.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1137,7 +1134,7 @@ func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{ // JSONEqf asserts that two JSON strings are equivalent. // -// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// require.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1151,7 +1148,7 @@ func JSONEqf(t TestingT, expected string, actual string, msg string, args ...int // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// assert.Len(t, mySlice, 3) +// require.Len(t, mySlice, 3) func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1165,7 +1162,7 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // -// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +// require.Lenf(t, mySlice, 3, "error message %s", "formatted") func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1178,9 +1175,9 @@ func Lenf(t TestingT, object interface{}, length int, msg string, args ...interf // Less asserts that the first element is less than the second // -// assert.Less(t, 1, 2) -// assert.Less(t, float64(1), float64(2)) -// assert.Less(t, "a", "b") +// require.Less(t, 1, 2) +// require.Less(t, float64(1), float64(2)) +// require.Less(t, "a", "b") func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1193,10 +1190,10 @@ func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) // LessOrEqual asserts that the first element is less than or equal to the second // -// assert.LessOrEqual(t, 1, 2) -// assert.LessOrEqual(t, 2, 2) -// assert.LessOrEqual(t, "a", "b") -// assert.LessOrEqual(t, "b", "b") +// require.LessOrEqual(t, 1, 2) +// require.LessOrEqual(t, 2, 2) +// require.LessOrEqual(t, "a", "b") +// require.LessOrEqual(t, "b", "b") func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1209,10 +1206,10 @@ func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...inter // LessOrEqualf asserts that the first element is less than or equal to the second // -// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") -// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") +// require.LessOrEqualf(t, 1, 2, "error message %s", "formatted") +// require.LessOrEqualf(t, 2, 2, "error message %s", "formatted") +// require.LessOrEqualf(t, "a", "b", "error message %s", "formatted") +// require.LessOrEqualf(t, "b", "b", "error message %s", "formatted") func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1225,9 +1222,9 @@ func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args . // Lessf asserts that the first element is less than the second // -// assert.Lessf(t, 1, 2, "error message %s", "formatted") -// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") -// assert.Lessf(t, "a", "b", "error message %s", "formatted") +// require.Lessf(t, 1, 2, "error message %s", "formatted") +// require.Lessf(t, float64(1), float64(2), "error message %s", "formatted") +// require.Lessf(t, "a", "b", "error message %s", "formatted") func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1240,8 +1237,8 @@ func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...inter // Negative asserts that the specified element is negative // -// assert.Negative(t, -1) -// assert.Negative(t, -1.23) +// require.Negative(t, -1) +// require.Negative(t, -1.23) func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1254,8 +1251,8 @@ func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) { // Negativef asserts that the specified element is negative // -// assert.Negativef(t, -1, "error message %s", "formatted") -// assert.Negativef(t, -1.23, "error message %s", "formatted") +// require.Negativef(t, -1, "error message %s", "formatted") +// require.Negativef(t, -1.23, "error message %s", "formatted") func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1269,7 +1266,7 @@ func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) { // Never asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) +// require.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1283,7 +1280,7 @@ func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.D // Neverf asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// require.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1296,7 +1293,7 @@ func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time. // Nil asserts that the specified object is nil. // -// assert.Nil(t, err) +// require.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1309,7 +1306,7 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { // Nilf asserts that the specified object is nil. // -// assert.Nilf(t, err, "error message %s", "formatted") +// require.Nilf(t, err, "error message %s", "formatted") func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1347,8 +1344,8 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) { // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, expectedObj, actualObj) +// if require.NoError(t, err) { +// require.Equal(t, expectedObj, actualObj) // } func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { @@ -1363,8 +1360,8 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) { // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() -// if assert.NoErrorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) +// if require.NoErrorf(t, err, "error message %s", "formatted") { +// require.Equal(t, expectedObj, actualObj) // } func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { @@ -1403,9 +1400,9 @@ func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) { // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContains(t, "Hello World", "Earth") -// assert.NotContains(t, ["Hello", "World"], "Earth") -// assert.NotContains(t, {"Hello": "World"}, "Earth") +// require.NotContains(t, "Hello World", "Earth") +// require.NotContains(t, ["Hello", "World"], "Earth") +// require.NotContains(t, {"Hello": "World"}, "Earth") func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1419,9 +1416,9 @@ func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ... // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +// require.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// require.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// require.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1432,11 +1429,51 @@ func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, a t.FailNow() } +// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// require.NotElementsMatch(t, [1, 1, 2, 3], [1, 1, 2, 3]) -> false +// +// require.NotElementsMatch(t, [1, 1, 2, 3], [1, 2, 3]) -> true +// +// require.NotElementsMatch(t, [1, 2, 3], [1, 2, 4]) -> true +func NotElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotElementsMatch(t, listA, listB, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// require.NotElementsMatchf(t, [1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false +// +// require.NotElementsMatchf(t, [1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true +// +// require.NotElementsMatchf(t, [1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true +func NotElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotElementsMatchf(t, listA, listB, msg, args...) { + return + } + t.FailNow() +} + // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) +// if require.NotEmpty(t, obj) { +// require.Equal(t, "two", obj[1]) // } func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { @@ -1451,8 +1488,8 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) +// if require.NotEmptyf(t, obj, "error message %s", "formatted") { +// require.Equal(t, "two", obj[1]) // } func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { @@ -1466,7 +1503,7 @@ func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) // NotEqual asserts that the specified values are NOT equal. // -// assert.NotEqual(t, obj1, obj2) +// require.NotEqual(t, obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1482,7 +1519,7 @@ func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs . // NotEqualValues asserts that two objects are not equal even when converted to the same type // -// assert.NotEqualValues(t, obj1, obj2) +// require.NotEqualValues(t, obj1, obj2) func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1495,7 +1532,7 @@ func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAnd // NotEqualValuesf asserts that two objects are not equal even when converted to the same type // -// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") +// require.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1508,7 +1545,7 @@ func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg s // NotEqualf asserts that the specified values are NOT equal. // -// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// require.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1522,7 +1559,31 @@ func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, t.FailNow() } -// NotErrorIs asserts that at none of the errors in err's chain matches target. +// NotErrorAs asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotErrorAs(t, err, target, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotErrorAsf asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func NotErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotErrorAsf(t, err, target, msg, args...) { + return + } + t.FailNow() +} + +// NotErrorIs asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func NotErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { @@ -1534,7 +1595,7 @@ func NotErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{}) t.FailNow() } -// NotErrorIsf asserts that at none of the errors in err's chain matches target. +// NotErrorIsf asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { @@ -1546,9 +1607,35 @@ func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interf t.FailNow() } +// NotImplements asserts that an object does not implement the specified interface. +// +// require.NotImplements(t, (*MyInterface)(nil), new(MyObject)) +func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotImplements(t, interfaceObject, object, msgAndArgs...) { + return + } + t.FailNow() +} + +// NotImplementsf asserts that an object does not implement the specified interface. +// +// require.NotImplementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func NotImplementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.NotImplementsf(t, interfaceObject, object, msg, args...) { + return + } + t.FailNow() +} + // NotNil asserts that the specified object is not nil. // -// assert.NotNil(t, err) +// require.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1561,7 +1648,7 @@ func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { // NotNilf asserts that the specified object is not nil. // -// assert.NotNilf(t, err, "error message %s", "formatted") +// require.NotNilf(t, err, "error message %s", "formatted") func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1574,7 +1661,7 @@ func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanics(t, func(){ RemainCalm() }) +// require.NotPanics(t, func(){ RemainCalm() }) func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1587,7 +1674,7 @@ func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +// require.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1600,8 +1687,8 @@ func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interfac // NotRegexp asserts that a specified regexp does not match a string. // -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") +// require.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// require.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1614,8 +1701,8 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf // NotRegexpf asserts that a specified regexp does not match a string. // -// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +// require.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") +// require.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1628,7 +1715,7 @@ func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args .. // NotSame asserts that two pointers do not reference the same object. // -// assert.NotSame(t, ptr1, ptr2) +// require.NotSame(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1644,7 +1731,7 @@ func NotSame(t TestingT, expected interface{}, actual interface{}, msgAndArgs .. // NotSamef asserts that two pointers do not reference the same object. // -// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") +// require.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1658,10 +1745,12 @@ func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, t.FailNow() } -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// require.NotSubset(t, [1, 3, 4], [1, 2]) +// require.NotSubset(t, {"x": 1, "y": 2}, {"z": 3}) func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1672,10 +1761,12 @@ func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...i t.FailNow() } -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// require.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted") +// require.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1710,7 +1801,7 @@ func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { // Panics asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panics(t, func(){ GoCrazy() }) +// require.Panics(t, func(){ GoCrazy() }) func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1725,7 +1816,7 @@ func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) +// require.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1740,7 +1831,7 @@ func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAn // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// require.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1754,7 +1845,7 @@ func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +// require.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1768,7 +1859,7 @@ func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, m // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// require.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1781,7 +1872,7 @@ func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, // Panicsf asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +// require.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1794,8 +1885,8 @@ func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{} // Positive asserts that the specified element is positive // -// assert.Positive(t, 1) -// assert.Positive(t, 1.23) +// require.Positive(t, 1) +// require.Positive(t, 1.23) func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1808,8 +1899,8 @@ func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) { // Positivef asserts that the specified element is positive // -// assert.Positivef(t, 1, "error message %s", "formatted") -// assert.Positivef(t, 1.23, "error message %s", "formatted") +// require.Positivef(t, 1, "error message %s", "formatted") +// require.Positivef(t, 1.23, "error message %s", "formatted") func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1822,8 +1913,8 @@ func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) { // Regexp asserts that a specified regexp matches a string. // -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") +// require.Regexp(t, regexp.MustCompile("start"), "it's starting") +// require.Regexp(t, "start...$", "it's not starting") func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1836,8 +1927,8 @@ func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface // Regexpf asserts that a specified regexp matches a string. // -// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +// require.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") +// require.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1850,7 +1941,7 @@ func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...in // Same asserts that two pointers reference the same object. // -// assert.Same(t, ptr1, ptr2) +// require.Same(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1866,7 +1957,7 @@ func Same(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...in // Samef asserts that two pointers reference the same object. // -// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") +// require.Samef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1880,10 +1971,11 @@ func Samef(t TestingT, expected interface{}, actual interface{}, msg string, arg t.FailNow() } -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// require.Subset(t, [1, 2, 3], [1, 2]) +// require.Subset(t, {"x": 1, "y": 2}, {"x": 1}) func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1894,10 +1986,11 @@ func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...inte t.FailNow() } -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// require.Subsetf(t, [1, 2, 3], [1, 2], "error message %s", "formatted") +// require.Subsetf(t, {"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1910,7 +2003,7 @@ func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args // True asserts that the specified value is true. // -// assert.True(t, myBool) +// require.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1923,7 +2016,7 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) { // Truef asserts that the specified value is true. // -// assert.Truef(t, myBool, "error message %s", "formatted") +// require.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1936,7 +2029,7 @@ func Truef(t TestingT, value bool, msg string, args ...interface{}) { // WithinDuration asserts that the two times are within duration delta of each other. // -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) +// require.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1949,7 +2042,7 @@ func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time // WithinDurationf asserts that the two times are within duration delta of each other. // -// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// require.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1962,7 +2055,7 @@ func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta tim // WithinRange asserts that a time is within a time range (inclusive). // -// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) +// require.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1975,7 +2068,7 @@ func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, m // WithinRangef asserts that a time is within a time range (inclusive). // -// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") +// require.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/require/require.go.tmpl b/vendor/github.com/stretchr/testify/require/require.go.tmpl index 55e42ddebd..8b32836850 100644 --- a/vendor/github.com/stretchr/testify/require/require.go.tmpl +++ b/vendor/github.com/stretchr/testify/require/require.go.tmpl @@ -1,4 +1,4 @@ -{{.Comment}} +{{ replace .Comment "assert." "require."}} func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { if h, ok := t.(tHelper); ok { h.Helper() } if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return } diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go index 3b5b09330a..1bd87304f4 100644 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -1,7 +1,4 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package require @@ -190,8 +187,8 @@ func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface EqualExportedValuesf(a.t, expected, actual, msg, args...) } -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValues asserts that two objects are equal or convertible to the larger +// type and equal. // // a.EqualValues(uint32(123), int32(123)) func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { @@ -201,8 +198,8 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn EqualValues(a.t, expected, actual, msgAndArgs...) } -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. +// EqualValuesf asserts that two objects are equal or convertible to the larger +// type and equal. // // a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { @@ -340,7 +337,7 @@ func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, ti // a.EventuallyWithT(func(c *assert.CollectT) { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -365,7 +362,7 @@ func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), w // a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") -// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false") func (a *Assertions) EventuallyWithTf(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1132,6 +1129,40 @@ func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg strin NotContainsf(a.t, s, contains, msg, args...) } +// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// a.NotElementsMatch([1, 1, 2, 3], [1, 1, 2, 3]) -> false +// +// a.NotElementsMatch([1, 1, 2, 3], [1, 2, 3]) -> true +// +// a.NotElementsMatch([1, 2, 3], [1, 2, 4]) -> true +func (a *Assertions) NotElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotElementsMatch(a.t, listA, listB, msgAndArgs...) +} + +// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should not match. +// This is an inverse of ElementsMatch. +// +// a.NotElementsMatchf([1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false +// +// a.NotElementsMatchf([1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true +// +// a.NotElementsMatchf([1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true +func (a *Assertions) NotElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotElementsMatchf(a.t, listA, listB, msg, args...) +} + // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -1204,7 +1235,25 @@ func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg str NotEqualf(a.t, expected, actual, msg, args...) } -// NotErrorIs asserts that at none of the errors in err's chain matches target. +// NotErrorAs asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func (a *Assertions) NotErrorAs(err error, target interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotErrorAs(a.t, err, target, msgAndArgs...) +} + +// NotErrorAsf asserts that none of the errors in err's chain matches target, +// but if so, sets target to that error value. +func (a *Assertions) NotErrorAsf(err error, target interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotErrorAsf(a.t, err, target, msg, args...) +} + +// NotErrorIs asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { @@ -1213,7 +1262,7 @@ func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface NotErrorIs(a.t, err, target, msgAndArgs...) } -// NotErrorIsf asserts that at none of the errors in err's chain matches target. +// NotErrorIsf asserts that none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { @@ -1222,6 +1271,26 @@ func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...in NotErrorIsf(a.t, err, target, msg, args...) } +// NotImplements asserts that an object does not implement the specified interface. +// +// a.NotImplements((*MyInterface)(nil), new(MyObject)) +func (a *Assertions) NotImplements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotImplements(a.t, interfaceObject, object, msgAndArgs...) +} + +// NotImplementsf asserts that an object does not implement the specified interface. +// +// a.NotImplementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func (a *Assertions) NotImplementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + NotImplementsf(a.t, interfaceObject, object, msg, args...) +} + // NotNil asserts that the specified object is not nil. // // a.NotNil(err) @@ -1310,10 +1379,12 @@ func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg stri NotSamef(a.t, expected, actual, msg, args...) } -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// a.NotSubset([1, 3, 4], [1, 2]) +// a.NotSubset({"x": 1, "y": 2}, {"z": 3}) func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1321,10 +1392,12 @@ func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs NotSubset(a.t, list, subset, msgAndArgs...) } -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// a.NotSubsetf([1, 3, 4], [1, 2], "error message %s", "formatted") +// a.NotSubsetf({"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1484,10 +1557,11 @@ func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, Samef(a.t, expected, actual, msg, args...) } -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// a.Subset([1, 2, 3], [1, 2]) +// a.Subset({"x": 1, "y": 2}, {"x": 1}) func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1495,10 +1569,11 @@ func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ... Subset(a.t, list, subset, msgAndArgs...) } -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// a.Subsetf([1, 2, 3], [1, 2], "error message %s", "formatted") +// a.Subsetf({"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go index 91772dfeb9..6b7ce929eb 100644 --- a/vendor/github.com/stretchr/testify/require/requirements.go +++ b/vendor/github.com/stretchr/testify/require/requirements.go @@ -6,7 +6,7 @@ type TestingT interface { FailNow() } -type tHelper interface { +type tHelper = interface { Helper() } diff --git a/vendor/github.com/stretchr/testify/suite/doc.go b/vendor/github.com/stretchr/testify/suite/doc.go index 8d55a3aa89..05a562f721 100644 --- a/vendor/github.com/stretchr/testify/suite/doc.go +++ b/vendor/github.com/stretchr/testify/suite/doc.go @@ -5,6 +5,8 @@ // or individual tests (depending on which interface(s) you // implement). // +// The suite package does not support parallel tests. See [issue 934]. +// // A testing suite is usually built by first extending the built-in // suite functionality from suite.Suite in testify. Alternatively, // you could reproduce that logic on your own if you wanted (you @@ -63,4 +65,6 @@ // func TestExampleTestSuite(t *testing.T) { // suite.Run(t, new(ExampleTestSuite)) // } +// +// [issue 934]: https://github.com/stretchr/testify/issues/934 package suite diff --git a/vendor/github.com/stretchr/testify/suite/suite.go b/vendor/github.com/stretchr/testify/suite/suite.go index 8b4202d890..18443a91c8 100644 --- a/vendor/github.com/stretchr/testify/suite/suite.go +++ b/vendor/github.com/stretchr/testify/suite/suite.go @@ -58,7 +58,7 @@ func (suite *Suite) Require() *require.Assertions { suite.mu.Lock() defer suite.mu.Unlock() if suite.require == nil { - suite.require = require.New(suite.T()) + panic("'Require' must not be called before 'Run' or 'SetT'") } return suite.require } @@ -72,17 +72,19 @@ func (suite *Suite) Assert() *assert.Assertions { suite.mu.Lock() defer suite.mu.Unlock() if suite.Assertions == nil { - suite.Assertions = assert.New(suite.T()) + panic("'Assert' must not be called before 'Run' or 'SetT'") } return suite.Assertions } func recoverAndFailOnPanic(t *testing.T) { + t.Helper() r := recover() failOnPanic(t, r) } func failOnPanic(t *testing.T, r interface{}) { + t.Helper() if r != nil { t.Errorf("test panicked: %v\n%s", r, debug.Stack()) t.FailNow() @@ -96,19 +98,20 @@ func failOnPanic(t *testing.T, r interface{}) { func (suite *Suite) Run(name string, subtest func()) bool { oldT := suite.T() - if setupSubTest, ok := suite.s.(SetupSubTest); ok { - setupSubTest.SetupSubTest() - } + return oldT.Run(name, func(t *testing.T) { + suite.SetT(t) + defer suite.SetT(oldT) + + defer recoverAndFailOnPanic(t) + + if setupSubTest, ok := suite.s.(SetupSubTest); ok { + setupSubTest.SetupSubTest() + } - defer func() { - suite.SetT(oldT) if tearDownSubTest, ok := suite.s.(TearDownSubTest); ok { - tearDownSubTest.TearDownSubTest() + defer tearDownSubTest.TearDownSubTest() } - }() - return oldT.Run(name, func(t *testing.T) { - suite.SetT(t) subtest() }) } @@ -164,6 +167,8 @@ func Run(t *testing.T, suite TestingSuite) { suite.SetT(t) defer recoverAndFailOnPanic(t) defer func() { + t.Helper() + r := recover() if stats != nil { diff --git a/vendor/modules.txt b/vendor/modules.txt index 1bab041831..c0810add86 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -224,9 +224,10 @@ github.com/spf13/cobra # github.com/spf13/pflag v1.0.5 ## explicit; go 1.12 github.com/spf13/pflag -# github.com/stretchr/testify v1.8.4 -## explicit; go 1.20 +# github.com/stretchr/testify v1.10.0 +## explicit; go 1.17 github.com/stretchr/testify/assert +github.com/stretchr/testify/assert/yaml github.com/stretchr/testify/require github.com/stretchr/testify/suite # github.com/weppos/publicsuffix-go v0.15.1-0.20210511084619-b1f36a2d6c0b