From da901472a7f9773c051608c2b66ed2866b447aa4 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Thu, 18 Jul 2024 19:37:38 +0200 Subject: [PATCH] testifylint: enable go-require, float-compare and require-error rules Signed-off-by: Matthieu MOREL --- .github/workflows/pr-linter-check.yml | 2 +- .golangci.yaml | 5 -- hack/build-image/Dockerfile | 2 +- internal/hook/hook_tracker_test.go | 13 ++-- internal/hook/item_hook_handler_test.go | 23 +++--- internal/hook/wait_exec_hook_handler_test.go | 6 +- .../json_merge_patch_test.go | 6 +- .../resource_modifiers_test.go | 27 +++---- .../strategic_merge_patch_test.go | 6 +- .../resource_policies_test.go | 9 +-- .../restartabletest/restartable_delegate.go | 2 +- pkg/archive/parser_test.go | 4 +- pkg/backup/actions/backup_pv_action_test.go | 6 +- pkg/backup/actions/csi/pvc_action_test.go | 11 +-- .../actions/service_account_action_test.go | 4 +- pkg/backup/backup_test.go | 18 ++--- pkg/client/client_test.go | 5 +- pkg/client/config_test.go | 11 +-- pkg/client/factory_test.go | 9 +-- pkg/cmd/cli/backup/create_test.go | 24 +++---- pkg/cmd/cli/backup/describe_test.go | 3 +- pkg/cmd/cli/backup/download_test.go | 6 +- pkg/cmd/cli/backup/get_test.go | 4 +- pkg/cmd/cli/backup/logs_test.go | 2 +- pkg/cmd/cli/backuplocation/create_test.go | 27 +++---- pkg/cmd/cli/backuplocation/delete_test.go | 13 ++-- pkg/cmd/cli/backuplocation/set_test.go | 3 +- pkg/cmd/cli/nodeagent/server_test.go | 5 +- pkg/cmd/cli/restore/describe_test.go | 3 +- pkg/cmd/cli/restore/logs_test.go | 3 +- pkg/cmd/cli/select_option_test.go | 4 +- pkg/cmd/server/server_test.go | 40 +++++------ pkg/cmd/util/flag/enum_test.go | 2 +- pkg/cmd/util/flag/optional_bool_test.go | 7 +- pkg/cmd/util/output/output_test.go | 9 +-- pkg/controller/backup_controller_test.go | 6 +- .../backup_deletion_controller_test.go | 12 ++-- .../backup_repository_controller_test.go | 35 ++++----- ...backup_storage_location_controller_test.go | 5 +- .../data_download_controller_test.go | 24 +++---- pkg/controller/data_upload_controller_test.go | 16 ++--- pkg/controller/restore_controller_test.go | 6 +- .../restore_finalizer_controller_test.go | 6 +- pkg/datamover/backup_micro_service_test.go | 13 ++-- pkg/datamover/restore_micro_service_test.go | 15 ++-- pkg/datapath/manager_test.go | 11 +-- pkg/datapath/micro_service_watcher_test.go | 3 +- pkg/discovery/helper_test.go | 18 ++--- pkg/exposer/csi_snapshot_test.go | 23 +++--- pkg/exposer/generic_restore_test.go | 10 +-- pkg/exposer/host_path_test.go | 4 +- pkg/exposer/image_test.go | 3 +- pkg/install/install_test.go | 2 +- .../actions/service_account_action_test.go | 4 +- pkg/kopia/kopia_log_test.go | 2 +- pkg/nodeagent/node_agent_test.go | 17 ++--- pkg/persistence/object_store_test.go | 62 ++++++++-------- .../v1/restartable_backup_item_action_test.go | 6 +- .../v2/restartable_backup_item_action_test.go | 6 +- .../v1/restartable_item_block_action_test.go | 4 +- pkg/plugin/clientmgmt/manager_test.go | 16 ++--- pkg/plugin/clientmgmt/process/process_test.go | 2 +- .../restartable_delete_item_action_test.go | 6 +- .../restartable_object_store_test.go | 20 +++--- .../restartable_restore_item_action_test.go | 6 +- .../restartable_restore_item_action_test.go | 6 +- .../v1/restartable_volume_snapshotter_test.go | 20 +++--- pkg/plugin/framework/validation_test.go | 20 +++--- pkg/podexec/pod_command_executor_test.go | 12 ++-- pkg/podvolume/backupper_test.go | 12 ++-- pkg/podvolume/restorer_test.go | 2 +- pkg/repository/backup_repo_op_test.go | 6 +- pkg/repository/config/config_test.go | 5 +- pkg/repository/ensurer_test.go | 9 +-- pkg/repository/maintenance_test.go | 17 ++--- pkg/repository/provider/unified_repo_test.go | 42 +++++------ .../kopialib/backend/file_system_test.go | 5 +- .../udmrepo/kopialib/backend/gcs_test.go | 5 +- .../udmrepo/kopialib/backend/s3_test.go | 6 +- .../udmrepo/kopialib/lib_repo_test.go | 72 +++++++++---------- .../udmrepo/kopialib/repo_init_test.go | 10 +-- pkg/restic/exec_commands_test.go | 7 +- .../admissionwebhook_config_action_test.go | 13 ++-- .../actions/change_image_name_action_test.go | 4 +- .../actions/change_pvc_node_selector_test.go | 4 +- .../change_storageclass_action_test.go | 4 +- pkg/restore/actions/csi/pvc_action_test.go | 8 +-- .../actions/csi/volumesnapshot_action_test.go | 4 +- .../init_restorehook_pod_action_test.go | 4 +- pkg/restore/actions/pod_action_test.go | 4 +- .../actions/pod_volume_restore_action_test.go | 2 +- pkg/restore/pv_restorer_test.go | 6 +- pkg/restore/restore_test.go | 23 +++--- pkg/test/comparisons.go | 10 +-- pkg/uploader/kopia/shim_test.go | 12 ++-- pkg/uploader/kopia/snapshot_test.go | 12 ++-- pkg/uploader/provider/kopia_test.go | 14 ++-- pkg/uploader/provider/provider_test.go | 3 +- pkg/uploader/provider/restic_test.go | 12 ++-- pkg/uploader/types_test.go | 5 +- pkg/util/csi/volume_snapshot_test.go | 38 +++++----- pkg/util/kube/pod_test.go | 15 ++-- pkg/util/kube/pvc_pv_test.go | 37 +++++----- pkg/util/kube/resource_requirements_test.go | 5 +- pkg/util/kube/security_context_test.go | 5 +- pkg/util/kube/utils_test.go | 4 +- pkg/util/logging/error_location_hook_test.go | 2 +- pkg/util/logging/log_counter_hook_test.go | 5 +- pkg/util/logging/log_merge_hook_test.go | 6 +- pkg/util/podvolume/pod_volume_test.go | 5 +- 110 files changed, 616 insertions(+), 593 deletions(-) diff --git a/.github/workflows/pr-linter-check.yml b/.github/workflows/pr-linter-check.yml index 429b7b169e..711f265700 100644 --- a/.github/workflows/pr-linter-check.yml +++ b/.github/workflows/pr-linter-check.yml @@ -15,5 +15,5 @@ jobs: - name: Linter check uses: golangci/golangci-lint-action@v6 with: - version: v1.57.2 + version: v1.59.1 args: --verbose diff --git a/.golangci.yaml b/.golangci.yaml index 4c414b8439..b6cac9e38d 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -236,11 +236,6 @@ linters-settings: packages: - github.com/jmoiron/sqlx testifylint: - # TODO: enable them all - disable: - - go-require - - float-compare - - require-error enable-all: true testpackage: # regexp pattern to skip files diff --git a/hack/build-image/Dockerfile b/hack/build-image/Dockerfile index fb72a5290c..934f09d3cf 100644 --- a/hack/build-image/Dockerfile +++ b/hack/build-image/Dockerfile @@ -94,7 +94,7 @@ RUN ARCH=$(go env GOARCH) && \ chmod +x /usr/bin/goreleaser # get golangci-lint -RUN curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.57.2 +RUN curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.59.1 # install kubectl RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/$(go env GOARCH)/kubectl diff --git a/internal/hook/hook_tracker_test.go b/internal/hook/hook_tracker_test.go index c90a3c80fd..4229ff0ab7 100644 --- a/internal/hook/hook_tracker_test.go +++ b/internal/hook/hook_tracker_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewHookTracker(t *testing.T) { @@ -65,13 +66,13 @@ func TestHookTracker_Record(t *testing.T) { info := tracker.tracker[key] assert.True(t, info.hookFailed) assert.True(t, info.hookExecuted) - assert.NoError(t, err) + require.NoError(t, err) err = tracker.Record("ns2", "pod2", "container1", HookSourceAnnotation, "h1", "", true, fmt.Errorf("err")) - assert.Error(t, err) + require.Error(t, err) err = tracker.Record("ns1", "pod1", "container1", HookSourceAnnotation, "h1", "", false, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, info.hookFailed) } @@ -141,13 +142,13 @@ func TestMultiHookTracker_Record(t *testing.T) { info := mht.trackers["restore1"].tracker[key] assert.True(t, info.hookFailed) assert.True(t, info.hookExecuted) - assert.NoError(t, err) + require.NoError(t, err) err = mht.Record("restore1", "ns2", "pod2", "container1", HookSourceAnnotation, "h1", "", true, fmt.Errorf("err")) - assert.Error(t, err) + require.Error(t, err) err = mht.Record("restore2", "ns2", "pod2", "container1", HookSourceAnnotation, "h1", "", true, fmt.Errorf("err")) - assert.Error(t, err) + require.Error(t, err) } func TestMultiHookTracker_Stat(t *testing.T) { diff --git a/internal/hook/item_hook_handler_test.go b/internal/hook/item_hook_handler_test.go index 086ca5ff52..427a033874 100644 --- a/internal/hook/item_hook_handler_test.go +++ b/internal/hook/item_hook_handler_test.go @@ -120,7 +120,7 @@ func TestHandleHooksSkips(t *testing.T) { groupResource := schema.ParseGroupResource(test.groupResource) err := h.HandleHooks(velerotest.NewLogger(), groupResource, test.item, test.hooks, PhasePre, hookTracker) - assert.NoError(t, err) + require.NoError(t, err) }) } } @@ -490,11 +490,10 @@ func TestHandleHooks(t *testing.T) { err := h.HandleHooks(velerotest.NewLogger(), groupResource, test.item, test.hooks, test.phase, hookTracker) if test.expectedError != nil { - assert.EqualError(t, err, test.expectedError.Error()) - return + require.EqualError(t, err, test.expectedError.Error()) + } else { + require.NoError(t, err) } - - require.NoError(t, err) }) } } @@ -1199,7 +1198,7 @@ func TestGroupRestoreExecHooks(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { actual, err := GroupRestoreExecHooks("restore1", tc.resourceRestoreHooks, tc.pod, velerotest.NewLogger(), hookTracker) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expected, actual) }) } @@ -1381,7 +1380,11 @@ func TestGetRestoreHooksFromSpec(t *testing.T) { actual, err := GetRestoreHooksFromSpec(tc.hookSpec) assert.Equal(t, tc.expected, actual) - assert.Equal(t, tc.expectedError, err) + if tc.expectedError != nil { + require.EqualError(t, err, tc.expectedError.Error()) + } else { + require.NoError(t, err) + } }) } } @@ -1955,13 +1958,13 @@ func TestHandleRestoreHooks(t *testing.T) { t.Run(tc.name, func(t *testing.T) { handler := InitContainerRestoreHookHandler{} podMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&tc.podInput) - assert.NoError(t, err) + require.NoError(t, err) actual, err := handler.HandleRestoreHooks(velerotest.NewLogger(), kuberesource.Pods, &unstructured.Unstructured{Object: podMap}, tc.restoreHooks, tc.namespaceMapping) assert.Equal(t, tc.expectedError, err) if actual != nil { actualPod := new(corev1api.Pod) err = runtime.DefaultUnstructuredConverter.FromUnstructured(actual.UnstructuredContent(), actualPod) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedPod, actualPod) } }) @@ -1976,7 +1979,7 @@ func TestValidateContainer(t *testing.T) { expectedError := fmt.Errorf("invalid InitContainer in restore hook, it doesn't have Command, Name or Image field") // valid string should return nil as result. - assert.NoError(t, ValidateContainer([]byte(valid))) + require.NoError(t, ValidateContainer([]byte(valid))) // noName string should return expected error as result. assert.Equal(t, expectedError, ValidateContainer([]byte(noName))) diff --git a/internal/hook/wait_exec_hook_handler_test.go b/internal/hook/wait_exec_hook_handler_test.go index 44f253705d..f725b60dba 100644 --- a/internal/hook/wait_exec_hook_handler_test.go +++ b/internal/hook/wait_exec_hook_handler_test.go @@ -732,7 +732,7 @@ func TestWaitExecHandleHooks(t *testing.T) { for _, e := range test.expectedExecutions { obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(e.pod) - assert.NoError(t, err) + require.NoError(t, err) podCommandExecutor.On("ExecutePodCommand", mock.Anything, obj, e.pod.Namespace, e.pod.Name, e.name, e.hook).Return(e.error) } @@ -749,7 +749,7 @@ func TestWaitExecHandleHooks(t *testing.T) { // for i, ee := range test.expectedErrors { require.Len(t, errs, len(test.expectedErrors)) for i, ee := range test.expectedErrors { - assert.EqualError(t, errs[i], ee.Error()) + require.EqualError(t, errs[i], ee.Error()) } }) } @@ -1269,7 +1269,7 @@ func TestRestoreHookTrackerUpdate(t *testing.T) { for _, e := range test.expectedExecutions { obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(e.pod) - assert.NoError(t, err) + require.NoError(t, err) podCommandExecutor.On("ExecutePodCommand", mock.Anything, obj, e.pod.Namespace, e.pod.Name, e.name, e.hook).Return(e.error) } diff --git a/internal/resourcemodifiers/json_merge_patch_test.go b/internal/resourcemodifiers/json_merge_patch_test.go index b7323fc617..89f0dc841d 100644 --- a/internal/resourcemodifiers/json_merge_patch_test.go +++ b/internal/resourcemodifiers/json_merge_patch_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" @@ -28,14 +28,14 @@ func TestJsonMergePatchFailure(t *testing.T) { t.Run(tt.name, func(t *testing.T) { scheme := runtime.NewScheme() err := clientgoscheme.AddToScheme(scheme) - assert.NoError(t, err) + require.NoError(t, err) pt := &JSONMergePatcher{ patches: []JSONMergePatch{{PatchData: tt.data}}, } u := &unstructured.Unstructured{} _, err = pt.Patch(u, logrus.New()) - assert.Error(t, err) + require.Error(t, err) }) } } diff --git a/internal/resourcemodifiers/resource_modifiers_test.go b/internal/resourcemodifiers/resource_modifiers_test.go index d6aad99fc8..fd8f1ca1a9 100644 --- a/internal/resourcemodifiers/resource_modifiers_test.go +++ b/internal/resourcemodifiers/resource_modifiers_test.go @@ -21,6 +21,7 @@ import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -1303,27 +1304,27 @@ func TestResourceModifiers_ApplyResourceModifierRules_StrategicMergePatch(t *tes utilruntime.Must(clientgoscheme.AddToScheme(scheme)) unstructuredSerializer := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme) o1, _, err := unstructuredSerializer.Decode([]byte(podYAMLWithNFSVolume), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) podWithNFSVolume := o1.(*unstructured.Unstructured) o2, _, err := unstructuredSerializer.Decode([]byte(podYAMLWithPVCVolume), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) podWithPVCVolume := o2.(*unstructured.Unstructured) o3, _, err := unstructuredSerializer.Decode([]byte(svcYAMLWithPort8000), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) svcWithPort8000 := o3.(*unstructured.Unstructured) o4, _, err := unstructuredSerializer.Decode([]byte(svcYAMLWithPort9000), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) svcWithPort9000 := o4.(*unstructured.Unstructured) o5, _, err := unstructuredSerializer.Decode([]byte(podYAMLWithNginxImage), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) podWithNginxImage := o5.(*unstructured.Unstructured) o6, _, err := unstructuredSerializer.Decode([]byte(podYAMLWithNginx1Image), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) podWithNginx1Image := o6.(*unstructured.Unstructured) tests := []struct { @@ -1467,15 +1468,15 @@ func TestResourceModifiers_ApplyResourceModifierRules_StrategicMergePatch(t *tes func TestResourceModifiers_ApplyResourceModifierRules_JSONMergePatch(t *testing.T) { unstructuredSerializer := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme) o1, _, err := unstructuredSerializer.Decode([]byte(cmYAMLWithLabelAToB), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) cmWithLabelAToB := o1.(*unstructured.Unstructured) o2, _, err := unstructuredSerializer.Decode([]byte(cmYAMLWithLabelAToC), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) cmWithLabelAToC := o2.(*unstructured.Unstructured) o3, _, err := unstructuredSerializer.Decode([]byte(cmYAMLWithoutLabelA), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) cmWithoutLabelA := o3.(*unstructured.Unstructured) tests := []struct { @@ -1618,11 +1619,11 @@ func TestResourceModifiers_ApplyResourceModifierRules_JSONMergePatch(t *testing. func TestResourceModifiers_wildcard_in_GroupResource(t *testing.T) { unstructuredSerializer := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme) o1, _, err := unstructuredSerializer.Decode([]byte(cmYAMLWithLabelAToB), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) cmWithLabelAToB := o1.(*unstructured.Unstructured) o2, _, err := unstructuredSerializer.Decode([]byte(cmYAMLWithLabelAToC), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) cmWithLabelAToC := o2.(*unstructured.Unstructured) tests := []struct { @@ -1694,11 +1695,11 @@ func TestResourceModifiers_wildcard_in_GroupResource(t *testing.T) { func TestResourceModifiers_conditional_patches(t *testing.T) { unstructuredSerializer := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme) o1, _, err := unstructuredSerializer.Decode([]byte(cmYAMLWithLabelAToB), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) cmWithLabelAToB := o1.(*unstructured.Unstructured) o2, _, err := unstructuredSerializer.Decode([]byte(cmYAMLWithLabelAToC), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) cmWithLabelAToC := o2.(*unstructured.Unstructured) tests := []struct { diff --git a/internal/resourcemodifiers/strategic_merge_patch_test.go b/internal/resourcemodifiers/strategic_merge_patch_test.go index 6c3c700f54..6c18ad6cb0 100644 --- a/internal/resourcemodifiers/strategic_merge_patch_test.go +++ b/internal/resourcemodifiers/strategic_merge_patch_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -37,7 +37,7 @@ func TestStrategicMergePatchFailure(t *testing.T) { t.Run(tt.name, func(t *testing.T) { scheme := runtime.NewScheme() err := clientgoscheme.AddToScheme(scheme) - assert.NoError(t, err) + require.NoError(t, err) pt := &StrategicMergePatcher{ patches: []StrategicMergePatch{{PatchData: tt.data}}, scheme: scheme, @@ -46,7 +46,7 @@ func TestStrategicMergePatchFailure(t *testing.T) { u := &unstructured.Unstructured{} u.SetGroupVersionKind(schema.GroupVersionKind{Version: "v1", Kind: tt.kind}) _, err = pt.Patch(u, logrus.New()) - assert.Error(t, err) + require.Error(t, err) }) } } diff --git a/internal/resourcepolicies/resource_policies_test.go b/internal/resourcepolicies/resource_policies_test.go index 4fd705731e..dff9973239 100644 --- a/internal/resourcepolicies/resource_policies_test.go +++ b/internal/resourcepolicies/resource_policies_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -232,7 +233,7 @@ func TestGetResourcePoliciesFromConfig(t *testing.T) { // Call the function and check for errors resPolicies, err := getResourcePoliciesFromConfig(cm) - assert.NoError(t, err) + require.NoError(t, err) // Check that the returned resourcePolicies object contains the expected data assert.Equal(t, "v1", resPolicies.version) @@ -422,12 +423,12 @@ volumePolicies: if err != nil { t.Fatalf("got error when get match action %v", err) } - assert.NoError(t, err) + require.NoError(t, err) policies := &Policies{} err = policies.BuildPolicy(resPolicies) - assert.NoError(t, err) + require.NoError(t, err) action, err := policies.GetMatchAction(tc.vol) - assert.NoError(t, err) + require.NoError(t, err) if tc.skip { if action.Type != Skip { diff --git a/internal/restartabletest/restartable_delegate.go b/internal/restartabletest/restartable_delegate.go index 37f73e4c39..bf2234c940 100644 --- a/internal/restartabletest/restartable_delegate.go +++ b/internal/restartabletest/restartable_delegate.go @@ -114,7 +114,7 @@ func RunRestartableDelegateTests( expectedErr, expectedErrOk := expected[i].(error) // If both are errors, use EqualError if actualErrOk && expectedErrOk { - assert.EqualError(t, actualErr, expectedErr.Error()) + require.EqualError(t, actualErr, expectedErr.Error()) continue } diff --git a/pkg/archive/parser_test.go b/pkg/archive/parser_test.go index c9ad517480..1af8077e89 100644 --- a/pkg/archive/parser_test.go +++ b/pkg/archive/parser_test.go @@ -112,7 +112,7 @@ func TestParse(t *testing.T) { if tc.wantErrMsg != nil { assert.ErrorIs(t, err, tc.wantErrMsg, "Error should be: %v, got: %v", tc.wantErrMsg, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.want, res) } }) @@ -226,7 +226,7 @@ func TestParseGroupVersions(t *testing.T) { if tc.wantErrMsg != nil { assert.ErrorIs(t, err, tc.wantErrMsg, "Error should be: %v, got: %v", tc.wantErrMsg, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.want, res) } }) diff --git a/pkg/backup/actions/backup_pv_action_test.go b/pkg/backup/actions/backup_pv_action_test.go index b66021132d..16fd092c4f 100644 --- a/pkg/backup/actions/backup_pv_action_test.go +++ b/pkg/backup/actions/backup_pv_action_test.go @@ -49,14 +49,14 @@ func TestBackupPVAction(t *testing.T) { // no spec.volumeName should result in no error // and no additional items _, additional, err := a.Execute(pvc, backup) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, additional) // empty spec.volumeName should result in no error // and no additional items pvc.Object["spec"].(map[string]interface{})["volumeName"] = "" _, additional, err = a.Execute(pvc, backup) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, additional) // Action should clean the spec.Selector when the StorageClassName is not set. @@ -147,6 +147,6 @@ func TestBackupPVAction(t *testing.T) { // result in no error and no additional items pvc.Object["spec"].(map[string]interface{})["volumeName"] = "" _, additional, err = a.Execute(pvc, backup) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, additional) } diff --git a/pkg/backup/actions/csi/pvc_action_test.go b/pkg/backup/actions/csi/pvc_action_test.go index 59da6145f4..ca9f17c533 100644 --- a/pkg/backup/actions/csi/pvc_action_test.go +++ b/pkg/backup/actions/csi/pvc_action_test.go @@ -27,6 +27,7 @@ import ( snapshotv1api "github.com/kubernetes-csi/external-snapshotter/client/v7/apis/volumesnapshot/v1" v1 "github.com/kubernetes-csi/external-snapshotter/client/v7/apis/volumesnapshot/v1" "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" storagev1 "k8s.io/api/storage/v1" @@ -175,8 +176,8 @@ func TestExecute(t *testing.T) { var vsList v1.VolumeSnapshotList err := wait.PollUntilContextTimeout(context.Background(), 1*time.Second, 10*time.Second, true, func(ctx context.Context) (bool, error) { err = pvcBIA.crClient.List(ctx, &vsList, &crclient.ListOptions{Namespace: tc.pvc.Namespace}) - - require.NoError(t, err) + //nolint:testifylint // false-positive + assert.NoError(t, err) if err != nil || len(vsList.Items) == 0 { //lint:ignore nilerr reason return false, nil // ignore @@ -184,7 +185,7 @@ func TestExecute(t *testing.T) { return true, nil }) - require.NoError(t, err) + assert.NoError(t, err) vscName := "testVSC" readyToUse := true vsList.Items[0].Status = &v1.VolumeSnapshotStatus{ @@ -192,12 +193,12 @@ func TestExecute(t *testing.T) { ReadyToUse: &readyToUse, } err = pvcBIA.crClient.Update(context.Background(), &vsList.Items[0]) - require.NoError(t, err) + assert.NoError(t, err) handleName := "testHandle" vsc := builder.ForVolumeSnapshotContent("testVSC").Status(&snapshotv1api.VolumeSnapshotContentStatus{SnapshotHandle: &handleName}).Result() err = pvcBIA.crClient.Create(context.Background(), vsc) - require.NoError(t, err) + assert.NoError(t, err) }() } diff --git a/pkg/backup/actions/service_account_action_test.go b/pkg/backup/actions/service_account_action_test.go index 1ea578ce01..f0821ecedd 100644 --- a/pkg/backup/actions/service_account_action_test.go +++ b/pkg/backup/actions/service_account_action_test.go @@ -385,7 +385,7 @@ func TestServiceAccountActionExecute(t *testing.T) { res, additional, err := action.Execute(test.serviceAccount, nil) assert.Equal(t, test.serviceAccount, res) - assert.NoError(t, err) + require.NoError(t, err) // ensure slices are ordered for valid comparison sort.Slice(test.expectedAdditionalItems, func(i, j int) bool { @@ -592,7 +592,7 @@ func TestServiceAccountActionExecuteOnBeta1(t *testing.T) { res, additional, err := action.Execute(test.serviceAccount, nil) assert.Equal(t, test.serviceAccount, res) - assert.NoError(t, err) + require.NoError(t, err) // ensure slices are ordered for valid comparison sort.Slice(test.expectedAdditionalItems, func(i, j int) bool { diff --git a/pkg/backup/backup_test.go b/pkg/backup/backup_test.go index 325ebab2c5..d29db3ac86 100644 --- a/pkg/backup/backup_test.go +++ b/pkg/backup/backup_test.go @@ -1440,7 +1440,7 @@ func TestBackupItemActionsForSkippedPV(t *testing.T) { } err := h.backupper.Backup(h.log, tc.backupReq, backupFile, actions, nil) - assert.NoError(t, err) + require.NoError(t, err) if tc.expectSkippedPVs != nil { for pvName, reasons := range tc.expectSkippedPVs { @@ -1654,7 +1654,7 @@ func TestBackupActionsRunForCorrectItems(t *testing.T) { } err := h.backupper.Backup(h.log, req, backupFile, actions, nil) - assert.NoError(t, err) + require.NoError(t, err) for action, want := range tc.actions { assert.Equal(t, want, action.ids) @@ -1729,7 +1729,7 @@ func TestBackupWithInvalidActions(t *testing.T) { h.addItems(t, resource) } - assert.Error(t, h.backupper.Backup(h.log, req, backupFile, tc.actions, nil)) + require.Error(t, h.backupper.Backup(h.log, req, backupFile, tc.actions, nil)) }) } } @@ -1876,7 +1876,7 @@ func TestBackupActionModifications(t *testing.T) { } err := h.backupper.Backup(h.log, req, backupFile, tc.actions, nil) - assert.NoError(t, err) + require.NoError(t, err) assertTarballFileContents(t, backupFile, tc.want) }) @@ -2131,7 +2131,7 @@ func TestBackupActionAdditionalItems(t *testing.T) { } err := h.backupper.Backup(h.log, req, backupFile, tc.actions, nil) - assert.NoError(t, err) + require.NoError(t, err) assertTarballContents(t, backupFile, append(tc.want, "metadata/version")...) }) @@ -2586,7 +2586,7 @@ func TestBackupWithSnapshots(t *testing.T) { } err := h.backupper.Backup(h.log, tc.req, backupFile, nil, tc.snapshotterGetter) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.want, tc.req.VolumeSnapshots) }) @@ -2745,7 +2745,7 @@ func TestBackupWithAsyncOperations(t *testing.T) { } err := h.backupper.Backup(h.log, tc.req, backupFile, tc.actions, nil) - assert.NoError(t, err) + require.NoError(t, err) resultOper := *tc.req.GetItemOperationsList() // set want Created times so it won't fail the assert.Equal test @@ -2810,7 +2810,7 @@ func TestBackupWithInvalidHooks(t *testing.T) { h.addItems(t, resource) } - assert.EqualError(t, h.backupper.Backup(h.log, req, backupFile, nil, nil), tc.want.Error()) + require.EqualError(t, h.backupper.Backup(h.log, req, backupFile, nil, nil), tc.want.Error()) }) } } @@ -3455,7 +3455,7 @@ func assertTarballFileContents(t *testing.T, backupFile io.Reader, want map[stri // json-unmarshal the data from the tarball var got unstructuredObject err := json.Unmarshal(gotData, &got) - assert.NoError(t, err) + require.NoError(t, err) if err != nil { continue } diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index b336bdd433..0e337441ff 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBuildUserAgent(t *testing.T) { @@ -79,9 +80,9 @@ func TestConfig(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { client, err := Config(test.kubeconfig, test.kubecontext, "velero", test.QPS, test.burst) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.expectedHost, client.Host) - assert.Equal(t, test.QPS, client.QPS) + assert.InDelta(t, test.QPS, client.QPS, 0.01) assert.Equal(t, test.burst, client.Burst) }) } diff --git a/pkg/client/config_test.go b/pkg/client/config_test.go index 3180d674d3..6437c6d702 100644 --- a/pkg/client/config_test.go +++ b/pkg/client/config_test.go @@ -23,6 +23,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestVeleroConfig(t *testing.T) { @@ -62,13 +63,13 @@ func TestConfigOperations(t *testing.T) { // Remove config file if it exists err := removeConfigfileName() - assert.NoError(t, err) + require.NoError(t, err) // Test LoadConfig: expect an empty velero config expectedConfig := VeleroConfig{} config, err := LoadConfig() - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, reflect.DeepEqual(expectedConfig, config)) // Test savedConfig @@ -84,9 +85,9 @@ func TestConfigOperations(t *testing.T) { err = SaveConfig(config) - assert.NoError(t, err) + require.NoError(t, err) savedConfig, err := LoadConfig() - assert.NoError(t, err) + require.NoError(t, err) // Test Features feature := savedConfig.Features() @@ -107,7 +108,7 @@ func TestConfigOperations(t *testing.T) { t.Cleanup(func() { err = removeConfigfileName() - assert.NoError(t, err) + require.NoError(t, err) os.Unsetenv("HOME") os.Setenv("HOME", preHomeEnv) }) diff --git a/pkg/client/factory_test.go b/pkg/client/factory_test.go index 10b0e86f02..827137a647 100644 --- a/pkg/client/factory_test.go +++ b/pkg/client/factory_test.go @@ -24,6 +24,7 @@ import ( flag "github.com/spf13/pflag" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" ) @@ -95,7 +96,7 @@ func TestFactory(t *testing.T) { baseName := "velero-bn" config, err := LoadConfig() - assert.NoError(t, err) + require.NoError(t, err) for _, test := range tests { t.Run(test.name, func(t *testing.T) { f = NewFactory(baseName, config) @@ -108,7 +109,7 @@ func TestFactory(t *testing.T) { flags.Parse([]string{"--kubeconfig", test.kubeconfig, "--kubecontext", test.kubecontext}) clientConfig, _ := f.ClientConfig() assert.Equal(t, test.expectedHost, clientConfig.Host) - assert.Equal(t, test.QPS, clientConfig.QPS) + assert.InDelta(t, test.QPS, clientConfig.QPS, 0.01) assert.Equal(t, test.burst, clientConfig.Burst) strings.Contains(clientConfig.UserAgent, test.baseName) @@ -134,11 +135,11 @@ func TestFactory(t *testing.T) { assert.NotNil(t, dynamicClient) kubebuilderClient, e := f.KubebuilderClient() - assert.NoError(t, e) + require.NoError(t, e) assert.NotNil(t, kubebuilderClient) kbClientWithWatch, e := f.KubebuilderWatchClient() - assert.NoError(t, e) + require.NoError(t, e) assert.NotNil(t, kbClientWithWatch) }) } diff --git a/pkg/cmd/cli/backup/create_test.go b/pkg/cmd/cli/backup/create_test.go index a099c3adbf..2e9423ac7a 100644 --- a/pkg/cmd/cli/backup/create_test.go +++ b/pkg/cmd/cli/backup/create_test.go @@ -56,10 +56,10 @@ func TestCreateOptions_BuildBackup(t *testing.T) { }, } o.OrSelector.OrLabelSelectors = orLabelSelectors - assert.NoError(t, err) + require.NoError(t, err) backup, err := o.BuildBackup(cmdtest.VeleroNameSpace) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, velerov1api.BackupSpec{ TTL: metav1.Duration{Duration: o.TTL}, @@ -116,7 +116,7 @@ func TestCreateOptions_BuildBackupFromSchedule(t *testing.T) { t.Run("command line labels take precedence over schedule labels", func(t *testing.T) { o.Labels.Set("velero.io/test=yes,custom-label=true") backup, err := o.BuildBackup(cmdtest.VeleroNameSpace) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expectedBackupSpec, backup.Spec) assert.Equal(t, map[string]string{ @@ -129,10 +129,10 @@ func TestCreateOptions_BuildBackupFromSchedule(t *testing.T) { func TestCreateOptions_OrderedResources(t *testing.T) { _, err := ParseOrderedResources("pods= ns1/p1; ns1/p2; persistentvolumeclaims=ns2/pvc1, ns2/pvc2") - assert.Error(t, err) + require.Error(t, err) orderedResources, err := ParseOrderedResources("pods= ns1/p1,ns1/p2 ; persistentvolumeclaims=ns2/pvc1,ns2/pvc2") - assert.NoError(t, err) + require.NoError(t, err) expectedResources := map[string]string{ "pods": "ns1/p1,ns1/p2", @@ -141,7 +141,7 @@ func TestCreateOptions_OrderedResources(t *testing.T) { assert.Equal(t, expectedResources, orderedResources) orderedResources, err = ParseOrderedResources("pods= ns1/p1,ns1/p2 ; persistentvolumes=pv1,pv2") - assert.NoError(t, err) + require.NoError(t, err) expectedMixedResources := map[string]string{ "pods": "ns1/p1,ns1/p2", @@ -288,7 +288,7 @@ func TestCreateCommand(t *testing.T) { // Complete e := o.Complete(args, f) - assert.NoError(t, e) + require.NoError(t, e) // Validate e = o.Validate(cmd, args, f) @@ -319,11 +319,11 @@ func TestCreateCommand(t *testing.T) { // Complete e := o.Complete(args, f) - assert.NoError(t, e) + require.NoError(t, e) // Validate e = o.Validate(cmd, args, f) - assert.NoError(t, e) + require.NoError(t, e) }) t.Run("create the other create command with fromSchedule option for Run() other branches", func(t *testing.T) { @@ -347,13 +347,13 @@ func TestCreateCommand(t *testing.T) { f.On("KubebuilderWatchClient").Return(kbclient, nil) e := o.Complete(args, f) - assert.NoError(t, e) + require.NoError(t, e) e = o.Run(c, f) - assert.NoError(t, e) + require.NoError(t, e) c.SetArgs([]string{"bk-1"}) e = c.Execute() - assert.NoError(t, e) + require.NoError(t, e) }) } diff --git a/pkg/cmd/cli/backup/describe_test.go b/pkg/cmd/cli/backup/describe_test.go index 660f5e6352..8db741fdbc 100644 --- a/pkg/cmd/cli/backup/describe_test.go +++ b/pkg/cmd/cli/backup/describe_test.go @@ -24,6 +24,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/client-go/rest" controllerclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -58,7 +59,7 @@ func TestNewDescribeCommand(t *testing.T) { c.SetArgs([]string{backupName}) e := c.Execute() - assert.NoError(t, e) + require.NoError(t, e) if os.Getenv(cmdtest.CaptureFlag) == "1" { return diff --git a/pkg/cmd/cli/backup/download_test.go b/pkg/cmd/cli/backup/download_test.go index a709a814b8..68dc670be3 100644 --- a/pkg/cmd/cli/backup/download_test.go +++ b/pkg/cmd/cli/backup/download_test.go @@ -74,10 +74,10 @@ func TestNewDownloadCommand(t *testing.T) { args := []string{backupName, "arg2"} e := o.Complete(args) - assert.NoError(t, e) + require.NoError(t, e) e = o.Validate(c, args, f) - assert.NoError(t, e) + require.NoError(t, e) // verify all options are set as expected assert.Equal(t, output, o.Output) @@ -89,7 +89,7 @@ func TestNewDownloadCommand(t *testing.T) { if os.Getenv(cmdtest.CaptureFlag) == "1" { e = c.Execute() defer os.Remove("bk-to-be-download-data.tar.gz") - assert.NoError(t, e) + require.NoError(t, e) return } cmd := exec.Command(os.Args[0], []string{"-test.run=TestNewDownloadCommand"}...) diff --git a/pkg/cmd/cli/backup/get_test.go b/pkg/cmd/cli/backup/get_test.go index 628b92e627..126f9d1d0a 100644 --- a/pkg/cmd/cli/backup/get_test.go +++ b/pkg/cmd/cli/backup/get_test.go @@ -58,7 +58,7 @@ func TestNewGetCommand(t *testing.T) { c.SetArgs(args) e := c.Execute() - assert.NoError(t, e) + require.NoError(t, e) if os.Getenv(cmdtest.CaptureFlag) == "1" { return @@ -83,7 +83,7 @@ func TestNewGetCommand(t *testing.T) { d := NewGetCommand(f, "velero backup get") c.SetArgs([]string{"-l", "abc=abc"}) e = d.Execute() - assert.NoError(t, e) + require.NoError(t, e) cmd = exec.Command(os.Args[0], []string{"-test.run=TestNewGetCommand"}...) cmd.Env = append(os.Environ(), fmt.Sprintf("%s=1", cmdtest.CaptureFlag)) diff --git a/pkg/cmd/cli/backup/logs_test.go b/pkg/cmd/cli/backup/logs_test.go index 2d6ee828ed..6daf5ae308 100644 --- a/pkg/cmd/cli/backup/logs_test.go +++ b/pkg/cmd/cli/backup/logs_test.go @@ -136,7 +136,7 @@ func TestNewLogsCommand(t *testing.T) { done := make(chan bool) go func() { err = l.Run(c, f) - require.Error(t, err) + assert.Error(t, err) }() select { diff --git a/pkg/cmd/cli/backuplocation/create_test.go b/pkg/cmd/cli/backuplocation/create_test.go index 495758b6d4..16b0b37769 100644 --- a/pkg/cmd/cli/backuplocation/create_test.go +++ b/pkg/cmd/cli/backuplocation/create_test.go @@ -26,6 +26,7 @@ import ( flag "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -38,7 +39,7 @@ func TestBuildBackupStorageLocationSetsNamespace(t *testing.T) { o := NewCreateOptions() bsl, err := o.BuildBackupStorageLocation("velero-test-ns", false, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "velero-test-ns", bsl.Namespace) } @@ -47,11 +48,11 @@ func TestBuildBackupStorageLocationSetsSyncPeriod(t *testing.T) { o.BackupSyncPeriod = 2 * time.Minute bsl, err := o.BuildBackupStorageLocation("velero-test-ns", false, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, bsl.Spec.BackupSyncPeriod) bsl, err = o.BuildBackupStorageLocation("velero-test-ns", true, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &metav1.Duration{Duration: 2 * time.Minute}, bsl.Spec.BackupSyncPeriod) } @@ -60,11 +61,11 @@ func TestBuildBackupStorageLocationSetsValidationFrequency(t *testing.T) { o.ValidationFrequency = 2 * time.Minute bsl, err := o.BuildBackupStorageLocation("velero-test-ns", false, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, bsl.Spec.ValidationFrequency) bsl, err = o.BuildBackupStorageLocation("velero-test-ns", false, true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &metav1.Duration{Duration: 2 * time.Minute}, bsl.Spec.ValidationFrequency) } @@ -72,14 +73,14 @@ func TestBuildBackupStorageLocationSetsCredential(t *testing.T) { o := NewCreateOptions() bsl, err := o.BuildBackupStorageLocation("velero-test-ns", false, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, bsl.Spec.Credential) setErr := o.Credential.Set("my-secret=key-from-secret") - assert.NoError(t, setErr) + require.NoError(t, setErr) bsl, err = o.BuildBackupStorageLocation("velero-test-ns", false, true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &v1.SecretKeySelector{ LocalObjectReference: v1.LocalObjectReference{Name: "my-secret"}, Key: "key-from-secret", @@ -90,10 +91,10 @@ func TestBuildBackupStorageLocationSetsLabels(t *testing.T) { o := NewCreateOptions() err := o.Labels.Set("key=value") - assert.NoError(t, err) + require.NoError(t, err) bsl, err := o.BuildBackupStorageLocation("velero-test-ns", false, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]string{"key": "value"}, bsl.Labels) } @@ -148,7 +149,7 @@ func TestCreateCommand_Run(t *testing.T) { o.Complete(args, f) e := o.Validate(c, args, f) - assert.NoError(t, e) + require.NoError(t, e) e = o.Run(c, f) assert.Contains(t, e.Error(), fmt.Sprintf("%s: no such file or directory", caCertFile)) @@ -178,8 +179,8 @@ func TestCreateCommand_Run(t *testing.T) { o.Complete(args, f) e = o.Run(c, f) - assert.NoError(t, e) + require.NoError(t, e) c.SetArgs([]string{"bsl-1", "--provider=aws", "--bucket=bk1", "--default"}) e = c.Execute() - assert.NoError(t, e) + require.NoError(t, e) } diff --git a/pkg/cmd/cli/backuplocation/delete_test.go b/pkg/cmd/cli/backuplocation/delete_test.go index 2ebddca80a..5eebda7ce8 100644 --- a/pkg/cmd/cli/backuplocation/delete_test.go +++ b/pkg/cmd/cli/backuplocation/delete_test.go @@ -25,6 +25,7 @@ import ( flag "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks" @@ -52,15 +53,15 @@ func TestNewDeleteCommand(t *testing.T) { args := []string{"bk-loc-1", "bk-loc-2"} e := o.Complete(f, args) - assert.NoError(t, e) + require.NoError(t, e) e = o.Validate(c, f, args) - assert.NoError(t, e) + require.NoError(t, e) c.SetArgs([]string{"bk-1", "--confirm"}) e = c.Execute() - assert.NoError(t, e) + require.NoError(t, e) e = Run(f, o) - assert.NoError(t, e) + require.NoError(t, e) if os.Getenv(cmdtest.CaptureFlag) == "1" { return } @@ -88,13 +89,13 @@ func TestDeleteFunctions(t *testing.T) { t.Run("findAssociatedBackups", func(t *testing.T) { bkList, e := findAssociatedBackups(kbclient, "bk-loc-1", "ns1") assert.Empty(t, bkList.Items) - assert.NoError(t, e) + require.NoError(t, e) }) t.Run("findAssociatedBackupRepos", func(t *testing.T) { bkrepoList, e := findAssociatedBackupRepos(kbclient, "bk-loc-1", "ns1") assert.Empty(t, bkrepoList.Items) - assert.NoError(t, e) + require.NoError(t, e) }) t.Run("deleteBackups", func(t *testing.T) { diff --git a/pkg/cmd/cli/backuplocation/set_test.go b/pkg/cmd/cli/backuplocation/set_test.go index 79f49cd721..04cfcba2c2 100644 --- a/pkg/cmd/cli/backuplocation/set_test.go +++ b/pkg/cmd/cli/backuplocation/set_test.go @@ -26,6 +26,7 @@ import ( flag "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks" cmdtest "github.com/vmware-tanzu/velero/pkg/cmd/test" @@ -66,7 +67,7 @@ func TestNewSetCommand(t *testing.T) { args := []string{backupName} o.Complete(args, f) e := o.Validate(c, args, f) - assert.NoError(t, e) + require.NoError(t, e) e = o.Run(c, f) assert.Contains(t, e.Error(), fmt.Sprintf("%s: no such file or directory", cacert)) diff --git a/pkg/cmd/cli/nodeagent/server_test.go b/pkg/cmd/cli/nodeagent/server_test.go index bf3e203ca2..2ddf8efb64 100644 --- a/pkg/cmd/cli/nodeagent/server_test.go +++ b/pkg/cmd/cli/nodeagent/server_test.go @@ -24,6 +24,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -105,9 +106,9 @@ func Test_validatePodVolumesHostPath(t *testing.T) { err := s.validatePodVolumesHostPath(kubeClient) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } diff --git a/pkg/cmd/cli/restore/describe_test.go b/pkg/cmd/cli/restore/describe_test.go index f0e83cce57..9023dd44f2 100644 --- a/pkg/cmd/cli/restore/describe_test.go +++ b/pkg/cmd/cli/restore/describe_test.go @@ -24,6 +24,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/client-go/rest" controllerclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -58,7 +59,7 @@ func TestNewDescribeCommand(t *testing.T) { c.SetArgs([]string{restoreName}) e := c.Execute() - assert.NoError(t, e) + require.NoError(t, e) if os.Getenv(cmdtest.CaptureFlag) == "1" { return diff --git a/pkg/cmd/cli/restore/logs_test.go b/pkg/cmd/cli/restore/logs_test.go index 007da70440..f664d808fd 100644 --- a/pkg/cmd/cli/restore/logs_test.go +++ b/pkg/cmd/cli/restore/logs_test.go @@ -21,7 +21,6 @@ import ( "testing" flag "github.com/spf13/pflag" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks" @@ -48,7 +47,7 @@ func TestNewLogsCommand(t *testing.T) { if os.Getenv(cmdtest.CaptureFlag) == "1" { c.SetArgs([]string{"test"}) e := c.Execute() - assert.NoError(t, e) + require.NoError(t, e) return } }) diff --git a/pkg/cmd/cli/select_option_test.go b/pkg/cmd/cli/select_option_test.go index 633d500517..0d7619e87c 100644 --- a/pkg/cmd/cli/select_option_test.go +++ b/pkg/cmd/cli/select_option_test.go @@ -38,8 +38,8 @@ func TestValidateOfSelectOption(t *testing.T) { Selector: flag.LabelSelector{}, All: false, } - assert.Error(t, option.Validate()) + require.Error(t, option.Validate()) option.All = true - assert.NoError(t, option.Validate()) + require.NoError(t, option.Validate()) } diff --git a/pkg/cmd/server/server_test.go b/pkg/cmd/server/server_test.go index 6e59955861..4fc513a0ff 100644 --- a/pkg/cmd/server/server_test.go +++ b/pkg/cmd/server/server_test.go @@ -62,7 +62,7 @@ func TestVeleroResourcesExist(t *testing.T) { }, }, } - assert.Error(t, server.veleroResourcesExist()) + require.Error(t, server.veleroResourcesExist()) // Velero v1 API group doesn't contain any custom resources: should error veleroAPIResourceListVelerov1 := &metav1.APIResourceList{ @@ -70,7 +70,7 @@ func TestVeleroResourcesExist(t *testing.T) { } fakeDiscoveryHelper.ResourceList = append(fakeDiscoveryHelper.ResourceList, veleroAPIResourceListVelerov1) - assert.Error(t, server.veleroResourcesExist()) + require.Error(t, server.veleroResourcesExist()) // Velero v2alpha1 API group doesn't contain any custom resources: should error veleroAPIResourceListVeleroV2alpha1 := &metav1.APIResourceList{ @@ -78,7 +78,7 @@ func TestVeleroResourcesExist(t *testing.T) { } fakeDiscoveryHelper.ResourceList = append(fakeDiscoveryHelper.ResourceList, veleroAPIResourceListVeleroV2alpha1) - assert.Error(t, server.veleroResourcesExist()) + require.Error(t, server.veleroResourcesExist()) // Velero v1 API group contains all custom resources, but v2alpha1 doesn't contain any custom resources: should error for kind := range velerov1api.CustomResources() { @@ -86,7 +86,7 @@ func TestVeleroResourcesExist(t *testing.T) { Kind: kind, }) } - assert.Error(t, server.veleroResourcesExist()) + require.Error(t, server.veleroResourcesExist()) // Velero v1 and v2alpha1 API group contain all custom resources: should not error for kind := range velerov2alpha1api.CustomResources() { @@ -94,11 +94,11 @@ func TestVeleroResourcesExist(t *testing.T) { Kind: kind, }) } - assert.NoError(t, server.veleroResourcesExist()) + require.NoError(t, server.veleroResourcesExist()) // Velero API group contains some but not all custom resources: should error veleroAPIResourceListVelerov1.APIResources = veleroAPIResourceListVelerov1.APIResources[:3] - assert.Error(t, server.veleroResourcesExist()) + require.Error(t, server.veleroResourcesExist()) } func TestRemoveControllers(t *testing.T) { @@ -166,9 +166,9 @@ func TestRemoveControllers(t *testing.T) { totalNumOriginalControllers := len(enabledRuntimeControllers) if tt.errorExpected { - assert.Error(t, removeControllers(tt.disabledControllers, enabledRuntimeControllers, logger)) + require.Error(t, removeControllers(tt.disabledControllers, enabledRuntimeControllers, logger)) } else { - assert.NoError(t, removeControllers(tt.disabledControllers, enabledRuntimeControllers, logger)) + require.NoError(t, removeControllers(tt.disabledControllers, enabledRuntimeControllers, logger)) totalNumEnabledControllers := len(enabledRuntimeControllers) assert.Equal(t, totalNumEnabledControllers, totalNumOriginalControllers-len(tt.disabledControllers)) @@ -194,21 +194,21 @@ func Test_newServer(t *testing.T) { _, err := newServer(factory, serverConfig{ uploaderType: "invalid", }, logger) - assert.Error(t, err) + require.Error(t, err) // invalid clientQPS _, err = newServer(factory, serverConfig{ uploaderType: uploader.KopiaType, clientQPS: -1, }, logger) - assert.Error(t, err) + require.Error(t, err) // invalid clientQPS Restic uploader _, err = newServer(factory, serverConfig{ uploaderType: uploader.ResticType, clientQPS: -1, }, logger) - assert.Error(t, err) + require.Error(t, err) // invalid clientBurst factory.On("SetClientQPS", mock.Anything).Return() @@ -217,7 +217,7 @@ func Test_newServer(t *testing.T) { clientQPS: 1, clientBurst: -1, }, logger) - assert.Error(t, err) + require.Error(t, err) // invalid clientBclientPageSizeurst factory.On("SetClientQPS", mock.Anything).Return(). @@ -228,7 +228,7 @@ func Test_newServer(t *testing.T) { clientBurst: 1, clientPageSize: -1, }, logger) - assert.Error(t, err) + require.Error(t, err) // got error when creating client factory.On("SetClientQPS", mock.Anything).Return(). @@ -242,7 +242,7 @@ func Test_newServer(t *testing.T) { clientBurst: 1, clientPageSize: 100, }, logger) - assert.Error(t, err) + require.Error(t, err) } func Test_namespaceExists(t *testing.T) { @@ -257,10 +257,10 @@ func Test_namespaceExists(t *testing.T) { } // namespace doesn't exist - assert.Error(t, server.namespaceExists("not-exist")) + require.Error(t, server.namespaceExists("not-exist")) // namespace exists - assert.NoError(t, server.namespaceExists("velero")) + require.NoError(t, server.namespaceExists("velero")) } func Test_veleroResourcesExist(t *testing.T) { @@ -272,7 +272,7 @@ func Test_veleroResourcesExist(t *testing.T) { // velero resources don't exist helper.On("Resources").Return(nil) - assert.Error(t, server.veleroResourcesExist()) + require.Error(t, server.veleroResourcesExist()) // velero resources exist helper.On("Resources").Unset() @@ -301,7 +301,7 @@ func Test_veleroResourcesExist(t *testing.T) { }, }, }) - assert.NoError(t, server.veleroResourcesExist()) + require.NoError(t, server.veleroResourcesExist()) } func Test_markInProgressBackupsFailed(t *testing.T) { @@ -420,9 +420,9 @@ func Test_setDefaultBackupLocation(t *testing.T) { // no default location specified c = fake.NewClientBuilder().WithScheme(scheme).Build() err := setDefaultBackupLocation(context.Background(), c, "velero", "", logrus.New()) - assert.NoError(t, err) + require.NoError(t, err) // no default location created err = setDefaultBackupLocation(context.Background(), c, "velero", "default", logrus.New()) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/pkg/cmd/util/flag/enum_test.go b/pkg/cmd/util/flag/enum_test.go index 66230aa621..58dc5399ad 100644 --- a/pkg/cmd/util/flag/enum_test.go +++ b/pkg/cmd/util/flag/enum_test.go @@ -14,7 +14,7 @@ func TestStringOfEnum(t *testing.T) { func TestSetOfEnum(t *testing.T) { enum := NewEnum("a", "a", "b", "c") - assert.Error(t, enum.Set("d")) + require.Error(t, enum.Set("d")) require.NoError(t, enum.Set("b")) assert.Equal(t, "b", enum.String()) diff --git a/pkg/cmd/util/flag/optional_bool_test.go b/pkg/cmd/util/flag/optional_bool_test.go index 584563b777..1427865bbf 100644 --- a/pkg/cmd/util/flag/optional_bool_test.go +++ b/pkg/cmd/util/flag/optional_bool_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStringOfOptionalBool(t *testing.T) { @@ -25,16 +26,16 @@ func TestStringOfOptionalBool(t *testing.T) { func TestSetOfOptionalBool(t *testing.T) { // error ob := NewOptionalBool(nil) - assert.Error(t, ob.Set("invalid")) + require.Error(t, ob.Set("invalid")) // nil ob = NewOptionalBool(nil) - assert.NoError(t, ob.Set("")) + require.NoError(t, ob.Set("")) assert.Nil(t, ob.Value) // true ob = NewOptionalBool(nil) - assert.NoError(t, ob.Set("true")) + require.NoError(t, ob.Set("true")) assert.True(t, *ob.Value) } diff --git a/pkg/cmd/util/output/output_test.go b/pkg/cmd/util/output/output_test.go index ba9c278435..a28430fb61 100644 --- a/pkg/cmd/util/output/output_test.go +++ b/pkg/cmd/util/output/output_test.go @@ -3,6 +3,7 @@ package output import ( "github.com/spf13/cobra" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/runtime" velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" @@ -88,9 +89,9 @@ func TestValidateFlags(t *testing.T) { t.Run(tc.name, func(t *testing.T) { err := ValidateFlags(tc.input) if tc.hasErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -372,9 +373,9 @@ func TestPrintWithFormat(t *testing.T) { t.Run(tc.name, func(t *testing.T) { p, err := PrintWithFormat(tc.input.cmd, tc.input.obj) if tc.hasErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, tc.printed, p) }) diff --git a/pkg/controller/backup_controller_test.go b/pkg/controller/backup_controller_test.go index c175c70415..ee5c6bc17c 100644 --- a/pkg/controller/backup_controller_test.go +++ b/pkg/controller/backup_controller_test.go @@ -140,7 +140,7 @@ func TestProcessBackupNonProcessedItems(t *testing.T) { } actualResult, err := c.Reconcile(ctx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: test.backup.Namespace, Name: test.backup.Name}}) assert.Equal(t, ctrl.Result{}, actualResult) - assert.NoError(t, err) + require.NoError(t, err) // Any backup that would actually proceed to validation will cause a segfault because this // test hasn't set up the necessary controller dependencies for validation/etc. So the lack @@ -230,7 +230,7 @@ func TestProcessBackupValidationFailures(t *testing.T) { actualResult, err := c.Reconcile(ctx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: test.backup.Namespace, Name: test.backup.Name}}) assert.Equal(t, ctrl.Result{}, actualResult) - assert.NoError(t, err) + require.NoError(t, err) res := &velerov1api.Backup{} err = c.kbClient.Get(context.Background(), kbclient.ObjectKey{Namespace: test.backup.Namespace, Name: test.backup.Name}, res) require.NoError(t, err) @@ -1378,7 +1378,7 @@ func TestProcessBackupCompletions(t *testing.T) { actualResult, err := c.Reconcile(ctx, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: test.backup.Namespace, Name: test.backup.Name}}) assert.Equal(t, ctrl.Result{}, actualResult) - assert.NoError(t, err) + require.NoError(t, err) // Disable CSI feature to not impact other test cases. if test.enableCSI { diff --git a/pkg/controller/backup_deletion_controller_test.go b/pkg/controller/backup_deletion_controller_test.go index c1c5b70187..2228a6592e 100644 --- a/pkg/controller/backup_deletion_controller_test.go +++ b/pkg/controller/backup_deletion_controller_test.go @@ -187,7 +187,7 @@ func TestBackupDeletionControllerReconcile(t *testing.T) { err = td.fakeClient.Create(context.TODO(), existing2) require.NoError(t, err) _, err = td.controller.Reconcile(context.TODO(), td.req) - assert.NoError(t, err) + require.NoError(t, err) // verify "existing" is deleted err = td.fakeClient.Get(context.TODO(), types.NamespacedName{ Namespace: existing.Namespace, @@ -197,7 +197,7 @@ func TestBackupDeletionControllerReconcile(t *testing.T) { assert.True(t, apierrors.IsNotFound(err), "Expected not found error, but actual value of error: %v", err) // verify "existing2" remains - assert.NoError(t, td.fakeClient.Get(context.TODO(), types.NamespacedName{ + require.NoError(t, td.fakeClient.Get(context.TODO(), types.NamespacedName{ Namespace: existing2.Namespace, Name: existing2.Name, }, &velerov1api.DeleteBackupRequest{})) @@ -363,7 +363,7 @@ func TestBackupDeletionControllerReconcile(t *testing.T) { Namespace: velerov1api.DefaultNamespace, Name: "restore-3", }, &velerov1api.Restore{}) - assert.NoError(t, err) + require.NoError(t, err) td.backupStore.AssertCalled(t, "DeleteBackup", input.Spec.BackupName) @@ -484,7 +484,7 @@ func TestBackupDeletionControllerReconcile(t *testing.T) { Namespace: velerov1api.DefaultNamespace, Name: "restore-3", }, &velerov1api.Restore{}) - assert.NoError(t, err) + require.NoError(t, err) // Make sure snapshot was deleted assert.Equal(t, 0, td.volumeSnapshotter.SnapshotsTaken.Len()) @@ -849,7 +849,7 @@ func TestGetSnapshotsInBackup(t *testing.T) { }) res, err := getSnapshotsInBackup(context.TODO(), veleroBackup, clientBuilder.Build()) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, reflect.DeepEqual(res, test.expected)) }) @@ -1021,7 +1021,7 @@ func TestDeleteMovedSnapshots(t *testing.T) { } else { assert.Equal(t, len(test.expected), len(errs)) for i := range test.expected { - assert.EqualError(t, errs[i], test.expected[i]) + require.EqualError(t, errs[i], test.expected[i]) } } }) diff --git a/pkg/controller/backup_repository_controller_test.go b/pkg/controller/backup_repository_controller_test.go index 873d2ce18f..cfe6e225e4 100644 --- a/pkg/controller/backup_repository_controller_test.go +++ b/pkg/controller/backup_repository_controller_test.go @@ -21,6 +21,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -68,12 +69,12 @@ func TestPatchBackupRepository(t *testing.T) { rr := mockBackupRepositoryCR() reconciler := mockBackupRepoReconciler(t, "", nil, nil) err := reconciler.Client.Create(context.TODO(), rr) - assert.NoError(t, err) + require.NoError(t, err) err = reconciler.patchBackupRepository(context.Background(), rr, repoReady()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, velerov1api.BackupRepositoryPhaseReady, rr.Status.Phase) err = reconciler.patchBackupRepository(context.Background(), rr, repoNotReady("not ready")) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, velerov1api.BackupRepositoryPhaseReady, rr.Status.Phase) } @@ -84,7 +85,7 @@ func TestCheckNotReadyRepo(t *testing.T) { rr.Spec.VolumeNamespace = "volume-ns-1" reconciler := mockBackupRepoReconciler(t, "PrepareRepo", rr, nil) err := reconciler.Client.Create(context.TODO(), rr) - assert.NoError(t, err) + require.NoError(t, err) locations := &velerov1api.BackupStorageLocation{ Spec: velerov1api.BackupStorageLocationSpec{ Config: map[string]string{"resticRepoPrefix": "s3:test.amazonaws.com/bucket/restic"}, @@ -96,9 +97,9 @@ func TestCheckNotReadyRepo(t *testing.T) { } err = reconciler.Client.Create(context.TODO(), locations) - assert.NoError(t, err) + require.NoError(t, err) _, err = reconciler.checkNotReadyRepo(context.TODO(), rr, reconciler.logger) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, velerov1api.BackupRepositoryPhaseReady, rr.Status.Phase) assert.Equal(t, "s3:test.amazonaws.com/bucket/restic/volume-ns-1", rr.Spec.ResticIdentifier) } @@ -107,16 +108,16 @@ func TestRunMaintenanceIfDue(t *testing.T) { rr := mockBackupRepositoryCR() reconciler := mockBackupRepoReconciler(t, "PruneRepo", rr, nil) err := reconciler.Client.Create(context.TODO(), rr) - assert.NoError(t, err) + require.NoError(t, err) lastTm := rr.Status.LastMaintenanceTime err = reconciler.runMaintenanceIfDue(context.TODO(), rr, reconciler.logger) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, rr.Status.LastMaintenanceTime, lastTm) rr.Status.LastMaintenanceTime = &metav1.Time{Time: time.Now()} lastTm = rr.Status.LastMaintenanceTime err = reconciler.runMaintenanceIfDue(context.TODO(), rr, reconciler.logger) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, rr.Status.LastMaintenanceTime, lastTm) } @@ -125,7 +126,7 @@ func TestInitializeRepo(t *testing.T) { rr.Spec.BackupStorageLocation = "default" reconciler := mockBackupRepoReconciler(t, "PrepareRepo", rr, nil) err := reconciler.Client.Create(context.TODO(), rr) - assert.NoError(t, err) + require.NoError(t, err) locations := &velerov1api.BackupStorageLocation{ Spec: velerov1api.BackupStorageLocationSpec{ Config: map[string]string{"resticRepoPrefix": "s3:test.amazonaws.com/bucket/restic"}, @@ -137,9 +138,9 @@ func TestInitializeRepo(t *testing.T) { } err = reconciler.Client.Create(context.TODO(), locations) - assert.NoError(t, err) + require.NoError(t, err) err = reconciler.initializeRepo(context.TODO(), rr, reconciler.logger) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, velerov1api.BackupRepositoryPhaseReady, rr.Status.Phase) } @@ -196,12 +197,12 @@ func TestBackupRepoReconcile(t *testing.T) { t.Run(test.name, func(t *testing.T) { reconciler := mockBackupRepoReconciler(t, "", test.repo, nil) err := reconciler.Client.Create(context.TODO(), test.repo) - assert.NoError(t, err) + require.NoError(t, err) _, err = reconciler.Reconcile(context.TODO(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: test.repo.Namespace, Name: test.repo.Name}}) if test.expectNil { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.Error(t, err) + require.Error(t, err) } }) } @@ -477,9 +478,9 @@ func TestGetBackupRepositoryConfig(t *testing.T) { result, err := getBackupRepositoryConfig(context.Background(), fakeClient, test.congiName, velerov1api.DefaultNamespace, test.repoName, test.repoType, velerotest.NewLogger()) if test.expectedErr != "" { - assert.EqualError(t, err, test.expectedErr) + require.EqualError(t, err, test.expectedErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.expectedResult, result) } }) diff --git a/pkg/controller/backup_storage_location_controller_test.go b/pkg/controller/backup_storage_location_controller_test.go index 69d473dfe4..0a49389c4a 100644 --- a/pkg/controller/backup_storage_location_controller_test.go +++ b/pkg/controller/backup_storage_location_controller_test.go @@ -26,6 +26,7 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -238,7 +239,7 @@ func TestEnsureSingleDefaultBSL(t *testing.T) { for _, test := range tests { // Setup reconciler - assert.NoError(t, velerov1api.AddToScheme(scheme.Scheme)) + require.NoError(t, velerov1api.AddToScheme(scheme.Scheme)) t.Run(test.name, func(t *testing.T) { r := &backupStorageLocationReconciler{ ctx: context.Background(), @@ -282,7 +283,7 @@ func TestBSLReconcile(t *testing.T) { pluginManager.On("CleanupClients").Return(nil) for _, test := range tests { // Setup reconciler - assert.NoError(t, velerov1api.AddToScheme(scheme.Scheme)) + require.NoError(t, velerov1api.AddToScheme(scheme.Scheme)) t.Run(test.name, func(t *testing.T) { r := &backupStorageLocationReconciler{ ctx: context.Background(), diff --git a/pkg/controller/data_download_controller_test.go b/pkg/controller/data_download_controller_test.go index a675b73cd5..4d4e9cb692 100644 --- a/pkg/controller/data_download_controller_test.go +++ b/pkg/controller/data_download_controller_test.go @@ -532,15 +532,15 @@ func TestOnDataDownloadFailed(t *testing.T) { namespace := dd.Namespace ddName := dd.Name // Add the DataDownload object to the fake client - assert.NoError(t, r.client.Create(ctx, dd)) + require.NoError(t, r.client.Create(ctx, dd)) r.OnDataDownloadFailed(ctx, namespace, ddName, fmt.Errorf("Failed to handle %v", ddName)) updatedDD := &velerov2alpha1api.DataDownload{} if getErr { - assert.Error(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) + require.Error(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) assert.NotEqual(t, velerov2alpha1api.DataDownloadPhaseFailed, updatedDD.Status.Phase) assert.True(t, updatedDD.Status.StartTimestamp.IsZero()) } else { - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) assert.Equal(t, velerov2alpha1api.DataDownloadPhaseFailed, updatedDD.Status.Phase) assert.True(t, updatedDD.Status.StartTimestamp.IsZero()) } @@ -558,15 +558,15 @@ func TestOnDataDownloadCancelled(t *testing.T) { namespace := dd.Namespace ddName := dd.Name // Add the DataDownload object to the fake client - assert.NoError(t, r.client.Create(ctx, dd)) + require.NoError(t, r.client.Create(ctx, dd)) r.OnDataDownloadCancelled(ctx, namespace, ddName) updatedDD := &velerov2alpha1api.DataDownload{} if getErr { - assert.Error(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) + require.Error(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) assert.NotEqual(t, velerov2alpha1api.DataDownloadPhaseFailed, updatedDD.Status.Phase) assert.True(t, updatedDD.Status.StartTimestamp.IsZero()) } else { - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) assert.Equal(t, velerov2alpha1api.DataDownloadPhaseCanceled, updatedDD.Status.Phase) assert.False(t, updatedDD.Status.StartTimestamp.IsZero()) assert.False(t, updatedDD.Status.CompletionTimestamp.IsZero()) @@ -610,15 +610,15 @@ func TestOnDataDownloadCompleted(t *testing.T) { namespace := dd.Namespace ddName := dd.Name // Add the DataDownload object to the fake client - assert.NoError(t, r.client.Create(ctx, dd)) + require.NoError(t, r.client.Create(ctx, dd)) r.OnDataDownloadCompleted(ctx, namespace, ddName, datapath.Result{}) updatedDD := &velerov2alpha1api.DataDownload{} if test.isGetErr { - assert.Error(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) + require.Error(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) assert.Equal(t, velerov2alpha1api.DataDownloadPhase(""), updatedDD.Status.Phase) assert.True(t, updatedDD.Status.CompletionTimestamp.IsZero()) } else { - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: ddName, Namespace: namespace}, updatedDD)) assert.Equal(t, velerov2alpha1api.DataDownloadPhaseCompleted, updatedDD.Status.Phase) assert.False(t, updatedDD.Status.CompletionTimestamp.IsZero()) } @@ -668,7 +668,7 @@ func TestOnDataDownloadProgress(t *testing.T) { namespace := dd.Namespace duName := dd.Name // Add the DataDownload object to the fake client - assert.NoError(t, r.client.Create(context.Background(), dd)) + require.NoError(t, r.client.Create(context.Background(), dd)) // Create a Progress object progress := &uploader.Progress{ @@ -681,7 +681,7 @@ func TestOnDataDownloadProgress(t *testing.T) { if len(test.needErrs) != 0 && !test.needErrs[0] { // Get the updated DataDownload object from the fake client updatedDu := &velerov2alpha1api.DataDownload{} - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) // Assert that the DataDownload object has been updated with the progress assert.Equal(t, test.progress.TotalBytes, updatedDu.Status.Progress.TotalBytes) assert.Equal(t, test.progress.BytesDone, updatedDu.Status.Progress.BytesDone) @@ -1070,7 +1070,7 @@ func TestAttemptDataDownloadResume(t *testing.T) { r.client.Delete(ctx, test.dd, &kbclient.DeleteOptions{}) }() - assert.NoError(t, r.client.Create(ctx, test.dd)) + require.NoError(t, r.client.Create(ctx, test.dd)) dt := &duResumeTestHelper{ resumeErr: test.resumeErr, diff --git a/pkg/controller/data_upload_controller_test.go b/pkg/controller/data_upload_controller_test.go index 5de53c1003..1c01382771 100644 --- a/pkg/controller/data_upload_controller_test.go +++ b/pkg/controller/data_upload_controller_test.go @@ -625,11 +625,11 @@ func TestOnDataUploadCancelled(t *testing.T) { namespace := du.Namespace duName := du.Name // Add the DataUpload object to the fake client - assert.NoError(t, r.client.Create(ctx, du)) + require.NoError(t, r.client.Create(ctx, du)) r.OnDataUploadCancelled(ctx, namespace, duName) updatedDu := &velerov2alpha1api.DataUpload{} - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) assert.Equal(t, velerov2alpha1api.DataUploadPhaseCanceled, updatedDu.Status.Phase) assert.False(t, updatedDu.Status.CompletionTimestamp.IsZero()) assert.False(t, updatedDu.Status.StartTimestamp.IsZero()) @@ -677,7 +677,7 @@ func TestOnDataUploadProgress(t *testing.T) { namespace := du.Namespace duName := du.Name // Add the DataUpload object to the fake client - assert.NoError(t, r.client.Create(context.Background(), du)) + require.NoError(t, r.client.Create(context.Background(), du)) // Create a Progress object progress := &uploader.Progress{ @@ -690,7 +690,7 @@ func TestOnDataUploadProgress(t *testing.T) { if len(test.needErrs) != 0 && !test.needErrs[0] { // Get the updated DataUpload object from the fake client updatedDu := &velerov2alpha1api.DataUpload{} - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) // Assert that the DataUpload object has been updated with the progress assert.Equal(t, test.progress.TotalBytes, updatedDu.Status.Progress.TotalBytes) assert.Equal(t, test.progress.BytesDone, updatedDu.Status.Progress.BytesDone) @@ -709,11 +709,11 @@ func TestOnDataUploadFailed(t *testing.T) { namespace := du.Namespace duName := du.Name // Add the DataUpload object to the fake client - assert.NoError(t, r.client.Create(ctx, du)) + require.NoError(t, r.client.Create(ctx, du)) r.snapshotExposerList = map[velerov2alpha1api.SnapshotType]exposer.SnapshotExposer{velerov2alpha1api.SnapshotTypeCSI: exposer.NewCSISnapshotExposer(r.kubeClient, r.csiSnapshotClient, velerotest.NewLogger())} r.OnDataUploadFailed(ctx, namespace, duName, fmt.Errorf("Failed to handle %v", duName)) updatedDu := &velerov2alpha1api.DataUpload{} - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) assert.Equal(t, velerov2alpha1api.DataUploadPhaseFailed, updatedDu.Status.Phase) assert.False(t, updatedDu.Status.CompletionTimestamp.IsZero()) assert.False(t, updatedDu.Status.StartTimestamp.IsZero()) @@ -728,11 +728,11 @@ func TestOnDataUploadCompleted(t *testing.T) { namespace := du.Namespace duName := du.Name // Add the DataUpload object to the fake client - assert.NoError(t, r.client.Create(ctx, du)) + require.NoError(t, r.client.Create(ctx, du)) r.snapshotExposerList = map[velerov2alpha1api.SnapshotType]exposer.SnapshotExposer{velerov2alpha1api.SnapshotTypeCSI: exposer.NewCSISnapshotExposer(r.kubeClient, r.csiSnapshotClient, velerotest.NewLogger())} r.OnDataUploadCompleted(ctx, namespace, duName, datapath.Result{}) updatedDu := &velerov2alpha1api.DataUpload{} - assert.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) + require.NoError(t, r.client.Get(ctx, types.NamespacedName{Name: duName, Namespace: namespace}, updatedDu)) assert.Equal(t, velerov2alpha1api.DataUploadPhaseCompleted, updatedDu.Status.Phase) assert.False(t, updatedDu.Status.CompletionTimestamp.IsZero()) } diff --git a/pkg/controller/restore_controller_test.go b/pkg/controller/restore_controller_test.go index 09fd12d10e..a506e615e4 100644 --- a/pkg/controller/restore_controller_test.go +++ b/pkg/controller/restore_controller_test.go @@ -124,7 +124,7 @@ func TestFetchBackupInfo(t *testing.T) { } for _, itm := range test.informerBackups { - assert.NoError(t, r.kbClient.Create(context.Background(), itm)) + require.NoError(t, r.kbClient.Create(context.Background(), itm)) } } @@ -179,7 +179,7 @@ func TestProcessQueueItemSkips(t *testing.T) { ) if test.restore != nil { - assert.NoError(t, fakeClient.Create(context.Background(), test.restore)) + require.NoError(t, fakeClient.Create(context.Background(), test.restore)) } r := NewRestoreReconciler( @@ -505,7 +505,7 @@ func TestRestoreReconcile(t *testing.T) { require.NoError(t, r.kbClient.Create(context.Background(), test.location)) } if test.backup != nil { - assert.NoError(t, r.kbClient.Create(context.Background(), test.backup)) + require.NoError(t, r.kbClient.Create(context.Background(), test.backup)) } if test.restore != nil { diff --git a/pkg/controller/restore_finalizer_controller_test.go b/pkg/controller/restore_finalizer_controller_test.go index 32b28765cd..b034b2385f 100644 --- a/pkg/controller/restore_finalizer_controller_test.go +++ b/pkg/controller/restore_finalizer_controller_test.go @@ -147,7 +147,7 @@ func TestRestoreFinalizerReconcile(t *testing.T) { backupStore.On("GetRestoredResourceList", test.restore.Name).Return(map[string][]string{}, nil) } if test.backup != nil { - assert.NoError(t, r.Client.Create(context.Background(), test.backup)) + require.NoError(t, r.Client.Create(context.Background(), test.backup)) backupStore.On("GetBackupVolumeInfos", test.backup.Name).Return(nil, nil) pluginManager.On("GetRestoreItemActionsV2").Return(nil, nil) pluginManager.On("CleanupClients") @@ -453,7 +453,7 @@ func TestPatchDynamicPVWithVolumeInfo(t *testing.T) { for pvName, expectedPVInfo := range tc.expectedPatch { pv := &corev1api.PersistentVolume{} err := ctx.crClient.Get(context.Background(), crclient.ObjectKey{Name: pvName}, pv) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expectedPVInfo.ReclaimPolicy, string(pv.Spec.PersistentVolumeReclaimPolicy)) assert.Equal(t, expectedPVInfo.Labels, pv.Labels) @@ -551,7 +551,7 @@ func TestWaitRestoreExecHook(t *testing.T) { updated := &velerov1api.Restore{} err := ctx.crClient.Get(context.Background(), crclient.ObjectKey{Namespace: velerov1api.DefaultNamespace, Name: tc.restore.Name}, updated) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedHooksAttempted, updated.Status.HookStatus.HooksAttempted) assert.Equal(t, tc.expectedHooksFailed, updated.Status.HookStatus.HooksFailed) } diff --git a/pkg/datamover/backup_micro_service_test.go b/pkg/datamover/backup_micro_service_test.go index cca428ee88..fce6dfa7ee 100644 --- a/pkg/datamover/backup_micro_service_test.go +++ b/pkg/datamover/backup_micro_service_test.go @@ -27,6 +27,7 @@ import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/runtime" "github.com/vmware-tanzu/velero/pkg/builder" @@ -105,7 +106,7 @@ func TestOnDataUploadFailed(t *testing.T) { go bs.OnDataUploadFailed(context.TODO(), velerov1api.DefaultNamespace, dataUploadName, errors.New("fake-error")) result := <-bs.resultSignal - assert.EqualError(t, result.err, expectedErr) + require.EqualError(t, result.err, expectedErr) assert.Equal(t, expectedEventReason, bt.EventReason()) assert.Equal(t, expectedEventMsg, bt.EventMessage()) } @@ -129,7 +130,7 @@ func TestOnDataUploadCancelled(t *testing.T) { go bs.OnDataUploadCancelled(context.TODO(), velerov1api.DefaultNamespace, dataUploadName) result := <-bs.resultSignal - assert.EqualError(t, result.err, expectedErr) + require.EqualError(t, result.err, expectedErr) assert.Equal(t, expectedEventReason, bt.EventReason()) assert.Equal(t, expectedEventMsg, bt.EventMessage()) } @@ -180,7 +181,7 @@ func TestOnDataUploadCompleted(t *testing.T) { if test.marshalErr != nil { assert.EqualError(t, result.err, test.expectedErr) } else { - assert.NoError(t, result.err) + require.NoError(t, result.err) assert.Equal(t, test.expectedEventReason, bt.EventReason()) assert.Equal(t, test.expectedEventMsg, bt.EventMessage()) } @@ -273,7 +274,7 @@ func TestCancelDataUpload(t *testing.T) { result := <-bs.resultSignal - assert.EqualError(t, result.err, test.expectedErr) + require.EqualError(t, result.err, test.expectedErr) assert.True(t, bt.withEvent) assert.Equal(t, test.expectedEventReason, bt.EventReason()) assert.Equal(t, test.expectedEventMsg, bt.EventMessage()) @@ -422,9 +423,9 @@ func TestRunCancelableDataPath(t *testing.T) { result, err := bs.RunCancelableDataPath(test.ctx) if test.expectedErr != "" { - assert.EqualError(t, err, test.expectedErr) + require.EqualError(t, err, test.expectedErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.result.result, result) } diff --git a/pkg/datamover/restore_micro_service_test.go b/pkg/datamover/restore_micro_service_test.go index 8a3ed61e1f..ff63441088 100644 --- a/pkg/datamover/restore_micro_service_test.go +++ b/pkg/datamover/restore_micro_service_test.go @@ -26,6 +26,7 @@ import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/runtime" kbclient "sigs.k8s.io/controller-runtime/pkg/client" clientFake "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -60,7 +61,7 @@ func TestOnDataDownloadFailed(t *testing.T) { go bs.OnDataDownloadFailed(context.TODO(), velerov1api.DefaultNamespace, dataDownloadName, errors.New("fake-error")) result := <-bs.resultSignal - assert.EqualError(t, result.err, expectedErr) + require.EqualError(t, result.err, expectedErr) assert.Equal(t, expectedEventReason, bt.EventReason()) assert.Equal(t, expectedEventMsg, bt.EventMessage()) } @@ -84,7 +85,7 @@ func TestOnDataDownloadCancelled(t *testing.T) { go bs.OnDataDownloadCancelled(context.TODO(), velerov1api.DefaultNamespace, dataDownloadName) result := <-bs.resultSignal - assert.EqualError(t, result.err, expectedErr) + require.EqualError(t, result.err, expectedErr) assert.Equal(t, expectedEventReason, bt.EventReason()) assert.Equal(t, expectedEventMsg, bt.EventMessage()) } @@ -133,9 +134,9 @@ func TestOnDataDownloadCompleted(t *testing.T) { result := <-bs.resultSignal if test.marshalErr != nil { - assert.EqualError(t, result.err, test.expectedErr) + require.EqualError(t, result.err, test.expectedErr) } else { - assert.NoError(t, result.err) + require.NoError(t, result.err) assert.Equal(t, test.expectedEventReason, bt.EventReason()) assert.Equal(t, test.expectedEventMsg, bt.EventMessage()) } @@ -226,7 +227,7 @@ func TestCancelDataDownload(t *testing.T) { result := <-bs.resultSignal - assert.EqualError(t, result.err, test.expectedErr) + require.EqualError(t, result.err, test.expectedErr) assert.True(t, bt.withEvent) assert.Equal(t, test.expectedEventReason, bt.EventReason()) assert.Equal(t, test.expectedEventMsg, bt.EventMessage()) @@ -375,9 +376,9 @@ func TestRunCancelableRestore(t *testing.T) { result, err := rs.RunCancelableDataPath(test.ctx) if test.expectedErr != "" { - assert.EqualError(t, err, test.expectedErr) + require.EqualError(t, err, test.expectedErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.result.result, result) } diff --git a/pkg/datapath/manager_test.go b/pkg/datapath/manager_test.go index 0db6051341..57b5220d10 100644 --- a/pkg/datapath/manager_test.go +++ b/pkg/datapath/manager_test.go @@ -21,16 +21,17 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateFileSystemBR(t *testing.T) { m := NewManager(2) async_job_1, err := m.CreateFileSystemBR("job-1", "test", context.TODO(), nil, "velero", Callbacks{}, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = m.CreateFileSystemBR("job-2", "test", context.TODO(), nil, "velero", Callbacks{}, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = m.CreateFileSystemBR("job-3", "test", context.TODO(), nil, "velero", Callbacks{}, nil) assert.Equal(t, ConcurrentLimitExceed, err) @@ -55,16 +56,16 @@ func TestCreateMicroServiceBRWatcher(t *testing.T) { m := NewManager(2) async_job_1, err := m.CreateMicroServiceBRWatcher(context.TODO(), nil, nil, nil, "test", "job-1", "velero", "pod-1", "container", "du-1", Callbacks{}, false, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = m.CreateMicroServiceBRWatcher(context.TODO(), nil, nil, nil, "test", "job-2", "velero", "pod-2", "container", "du-2", Callbacks{}, false, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = m.CreateMicroServiceBRWatcher(context.TODO(), nil, nil, nil, "test", "job-3", "velero", "pod-3", "container", "du-3", Callbacks{}, false, nil) assert.Equal(t, ConcurrentLimitExceed, err) async_job_4, err := m.CreateMicroServiceBRWatcher(context.TODO(), nil, nil, nil, "test", "job-4", "velero", "pod-4", "container", "du-4", Callbacks{}, true, nil) - assert.NoError(t, err) + require.NoError(t, err) ret := m.GetAsyncBR("job-0") assert.Nil(t, ret) diff --git a/pkg/datapath/micro_service_watcher_test.go b/pkg/datapath/micro_service_watcher_test.go index f926363e07..8b910de2ee 100644 --- a/pkg/datapath/micro_service_watcher_test.go +++ b/pkg/datapath/micro_service_watcher_test.go @@ -594,8 +594,7 @@ func TestRedirectDataMoverLogs(t *testing.T) { if test.expectErr != "" { assert.EqualError(t, err, test.expectErr) } else { - assert.NoError(t, err) - + require.NoError(t, err) assert.True(t, strings.Contains(buffer, test.logMessage)) } }) diff --git a/pkg/discovery/helper_test.go b/pkg/discovery/helper_test.go index 37a16b5361..102223115e 100644 --- a/pkg/discovery/helper_test.go +++ b/pkg/discovery/helper_test.go @@ -195,9 +195,9 @@ func TestRefreshServerPreferredResources(t *testing.T) { t.Run(test.name, func(t *testing.T) { resources, err := refreshServerPreferredResources(fakeServer, logging.DefaultLogger(logrus.DebugLevel, formatFlag)) if test.returnError != nil { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.returnError, err) } @@ -310,7 +310,7 @@ func TestHelper_ResourceFor(t *testing.T) { } gvr, apiResource, err := h.ResourceFor(*tc.input) if tc.err == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { require.ErrorContains(t, err, tc.err) } @@ -415,7 +415,7 @@ func TestHelper_KindFor(t *testing.T) { t.Run(tc.name, func(t *testing.T) { gvr, apiResource, err := h.KindFor(*tc.input) if tc.err == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { require.ErrorContains(t, err, tc.err) } @@ -568,9 +568,9 @@ func TestHelper_refreshServerPreferredResources(t *testing.T) { resources, err := refreshServerPreferredResources(fakeClient, logrus.New()) if tc.expectedErr != nil { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, resources) } }) @@ -623,9 +623,9 @@ func TestHelper_refreshServerGroupsAndResources(t *testing.T) { serverGroups, serverResources, err := refreshServerGroupsAndResources(fakeClient, logrus.New()) if tc.expectedErr != nil { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, serverGroups) assert.NotNil(t, serverResources) } @@ -638,7 +638,7 @@ func TestHelper(t *testing.T) { Fake: &clientgotesting.Fake{}, } h, err := NewHelper(fakeDiscoveryClient, logrus.New()) - assert.NoError(t, err) + require.NoError(t, err) // All below calls put together for the implementation are empty or just very simple, and just want to cover testing // If wanting to write unit tests for some functions could remove it and with writing new function alone h.Resources() diff --git a/pkg/exposer/csi_snapshot_test.go b/pkg/exposer/csi_snapshot_test.go index 82044dbb8b..12110b4791 100644 --- a/pkg/exposer/csi_snapshot_test.go +++ b/pkg/exposer/csi_snapshot_test.go @@ -29,6 +29,7 @@ import ( snapshotFake "github.com/kubernetes-csi/external-snapshotter/client/v7/clientset/versioned/fake" "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -424,19 +425,19 @@ func TestExpose(t *testing.T) { err := exposer.Expose(context.Background(), ownerObject, &test.exposeParam) if err == nil { - assert.NoError(t, err) + require.NoError(t, err) _, err = exposer.kubeClient.CoreV1().Pods(ownerObject.Namespace).Get(context.Background(), ownerObject.Name, metav1.GetOptions{}) - assert.NoError(t, err) + require.NoError(t, err) backupPVC, err := exposer.kubeClient.CoreV1().PersistentVolumeClaims(ownerObject.Namespace).Get(context.Background(), ownerObject.Name, metav1.GetOptions{}) - assert.NoError(t, err) + require.NoError(t, err) expectedVS, err := exposer.csiSnapshotClient.VolumeSnapshots(ownerObject.Namespace).Get(context.Background(), ownerObject.Name, metav1.GetOptions{}) - assert.NoError(t, err) + require.NoError(t, err) expectedVSC, err := exposer.csiSnapshotClient.VolumeSnapshotContents().Get(context.Background(), ownerObject.Name, metav1.GetOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expectedVS.Annotations, vsObject.Annotations) assert.Equal(t, *expectedVS.Spec.VolumeSnapshotClassName, *vsObject.Spec.VolumeSnapshotClassName) @@ -453,7 +454,7 @@ func TestExpose(t *testing.T) { assert.Equal(t, *resource.NewQuantity(restoreSize, ""), backupPVC.Spec.Resources.Requests[corev1.ResourceStorage]) } } else { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } }) } @@ -620,17 +621,17 @@ func TestGetExpose(t *testing.T) { result, err := exposer.GetExposed(context.Background(), ownerObject, test.Timeout, &test.exposeWaitParam) if test.err == "" { - assert.NoError(t, err) + require.NoError(t, err) if test.expectedResult == nil { assert.Nil(t, result) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.expectedResult.ByPod.VolumeName, result.ByPod.VolumeName) assert.Equal(t, test.expectedResult.ByPod.HostingPod.Name, result.ByPod.HostingPod.Name) } } else { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } }) } @@ -718,9 +719,9 @@ func TestPeekExpose(t *testing.T) { err := exposer.PeekExposed(context.Background(), ownerObject) if test.err == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } }) } diff --git a/pkg/exposer/generic_restore_test.go b/pkg/exposer/generic_restore_test.go index 4c3221b5ca..5da296f32f 100644 --- a/pkg/exposer/generic_restore_test.go +++ b/pkg/exposer/generic_restore_test.go @@ -22,7 +22,7 @@ import ( "time" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/fake" @@ -181,7 +181,7 @@ func TestRestoreExpose(t *testing.T) { } err := exposer.Expose(context.Background(), ownerObject, test.targetPVCName, test.sourceNamespace, map[string]string{}, corev1.ResourceRequirements{}, time.Millisecond) - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) }) } } @@ -416,7 +416,7 @@ func TestRebindVolume(t *testing.T) { hookCount = 0 err := exposer.RebindVolume(context.Background(), ownerObject, test.targetPVCName, test.sourceNamespace, time.Millisecond) - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) }) } } @@ -500,9 +500,9 @@ func TestRestorePeekExpose(t *testing.T) { err := exposer.PeekExposed(context.Background(), ownerObject) if test.err == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } }) } diff --git a/pkg/exposer/host_path_test.go b/pkg/exposer/host_path_test.go index 1022dffd30..94fa1b1147 100644 --- a/pkg/exposer/host_path_test.go +++ b/pkg/exposer/host_path_test.go @@ -22,7 +22,7 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -97,7 +97,7 @@ func TestGetPodVolumeHostPath(t *testing.T) { _, err := GetPodVolumeHostPath(context.Background(), test.pod, test.pvc, nil, nil, velerotest.NewLogger()) if test.err != "" || err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } }) } diff --git a/pkg/exposer/image_test.go b/pkg/exposer/image_test.go index b9aaf51ebc..1e88e5f324 100644 --- a/pkg/exposer/image_test.go +++ b/pkg/exposer/image_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes" @@ -261,7 +262,7 @@ func TestGetInheritedPodInfo(t *testing.T) { info, err := getInheritedPodInfo(context.Background(), fakeKubeClient, test.namespace) if test.expectErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, reflect.DeepEqual(info, test.result)) } else { assert.EqualError(t, err, test.expectErr) diff --git a/pkg/install/install_test.go b/pkg/install/install_test.go index 52bfbaf418..c261900ce0 100644 --- a/pkg/install/install_test.go +++ b/pkg/install/install_test.go @@ -53,7 +53,7 @@ func TestInstall(t *testing.T) { require.NoError(t, appendUnstructured(resources, v1crds.CRDs[0])) require.NoError(t, appendUnstructured(resources, Namespace("velero"))) - assert.NoError(t, Install(factory, c, resources, os.Stdout)) + require.NoError(t, Install(factory, c, resources, os.Stdout)) } func Test_crdsAreReady(t *testing.T) { diff --git a/pkg/itemblock/actions/service_account_action_test.go b/pkg/itemblock/actions/service_account_action_test.go index 52c39b0bc4..dbf367a45f 100644 --- a/pkg/itemblock/actions/service_account_action_test.go +++ b/pkg/itemblock/actions/service_account_action_test.go @@ -384,7 +384,7 @@ func TestServiceAccountActionExecute(t *testing.T) { additional, err := action.GetRelatedItems(test.serviceAccount, nil) - assert.NoError(t, err) + require.NoError(t, err) // ensure slices are ordered for valid comparison sort.Slice(test.expectedAdditionalItems, func(i, j int) bool { @@ -590,7 +590,7 @@ func TestServiceAccountActionExecuteOnBeta1(t *testing.T) { additional, err := action.GetRelatedItems(test.serviceAccount, nil) - assert.NoError(t, err) + require.NoError(t, err) // ensure slices are ordered for valid comparison sort.Slice(test.expectedAdditionalItems, func(i, j int) bool { diff --git a/pkg/kopia/kopia_log_test.go b/pkg/kopia/kopia_log_test.go index d50a4bba36..bb03a89cc5 100644 --- a/pkg/kopia/kopia_log_test.go +++ b/pkg/kopia/kopia_log_test.go @@ -335,7 +335,7 @@ func TestWrite(t *testing.T) { err := log.Write(tc.ent, nil) - assert.NoError(t, err) + require.NoError(t, err) if len(tc.logMessage) > 0 { assert.Contains(t, logMessage, tc.logMessage) diff --git a/pkg/nodeagent/node_agent_test.go b/pkg/nodeagent/node_agent_test.go index 9bbf0f46d1..330f98ce6a 100644 --- a/pkg/nodeagent/node_agent_test.go +++ b/pkg/nodeagent/node_agent_test.go @@ -22,6 +22,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -95,9 +96,9 @@ func TestIsRunning(t *testing.T) { err := IsRunning(context.TODO(), fakeKubeClient, test.namespace) if test.expectErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, test.expectErr) + require.EqualError(t, err, test.expectErr) } }) } @@ -175,9 +176,9 @@ func TestIsRunningInNode(t *testing.T) { err := IsRunningInNode(context.TODO(), "", test.nodeName, fakeClient) if test.expectErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, test.expectErr) + require.EqualError(t, err, test.expectErr) } }) } @@ -231,10 +232,10 @@ func TestGetPodSpec(t *testing.T) { spec, err := GetPodSpec(context.TODO(), fakeKubeClient, test.namespace) if test.expectErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, *spec, test.expectSpec) } else { - assert.EqualError(t, err, test.expectErr) + require.EqualError(t, err, test.expectErr) } }) } @@ -316,7 +317,7 @@ func TestGetConfigs(t *testing.T) { result, err := GetConfigs(context.TODO(), test.namespace, fakeKubeClient, "node-agent-config") if test.expectErr == "" { - assert.NoError(t, err) + require.NoError(t, err) if test.expectResult == nil { assert.Nil(t, result) @@ -326,7 +327,7 @@ func TestGetConfigs(t *testing.T) { assert.Equal(t, *test.expectResult.LoadConcurrency, *result.LoadConcurrency) } } else { - assert.EqualError(t, err, test.expectErr) + require.EqualError(t, err, test.expectErr) } }) } diff --git a/pkg/persistence/object_store_test.go b/pkg/persistence/object_store_test.go index e8eb3b9a0e..f21e2f74c2 100644 --- a/pkg/persistence/object_store_test.go +++ b/pkg/persistence/object_store_test.go @@ -162,9 +162,9 @@ func TestIsValid(t *testing.T) { err := harness.IsValid() if tc.expectErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -207,7 +207,7 @@ func TestListBackups(t *testing.T) { res, err := harness.ListBackups() - velerotest.AssertErrorMatches(t, tc.expectedErr, err) + velerotest.RequireErrorMatches(t, tc.expectedErr, err) sort.Strings(tc.expectedRes) sort.Strings(res) @@ -361,7 +361,7 @@ func TestPutBackup(t *testing.T) { } err := harness.PutBackup(backupInfo) - velerotest.AssertErrorMatches(t, tc.expectedErr, err) + velerotest.RequireErrorMatches(t, tc.expectedErr, err) assert.Len(t, harness.objectStore.Data[harness.bucket], len(tc.expectedKeys)) for _, key := range tc.expectedKeys { assert.Contains(t, harness.objectStore.Data[harness.bucket], key) @@ -421,13 +421,13 @@ func TestGetBackupVolumeSnapshots(t *testing.T) { // volumesnapshots file not found should not error harness.objectStore.PutObject(harness.bucket, "backups/test-backup/velero-backup.json", newStringReadSeeker("foo")) res, err := harness.GetBackupVolumeSnapshots("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, res) // volumesnapshots file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-volumesnapshots.json.gz", newStringReadSeeker("foo")) _, err = harness.GetBackupVolumeSnapshots("test-backup") - assert.Error(t, err) + require.Error(t, err) // volumesnapshots file containing gzipped json data should return correctly snapshots := []*volume.Snapshot{ @@ -453,7 +453,7 @@ func TestGetBackupVolumeSnapshots(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-volumesnapshots.json.gz", obj)) res, err = harness.GetBackupVolumeSnapshots("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, snapshots, res) } @@ -463,13 +463,13 @@ func TestGetBackupItemOperations(t *testing.T) { // itemoperations file not found should not error harness.objectStore.PutObject(harness.bucket, "backups/test-backup/velero-backup.json", newStringReadSeeker("foo")) res, err := harness.GetBackupItemOperations("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, res) // itemoperations file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-itemoperations.json.gz", newStringReadSeeker("foo")) _, err = harness.GetBackupItemOperations("test-backup") - assert.Error(t, err) + require.Error(t, err) // itemoperations file containing gzipped json data should return correctly operations := []*itemoperation.BackupOperation{ @@ -503,7 +503,7 @@ func TestGetBackupItemOperations(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-itemoperations.json.gz", obj)) res, err = harness.GetBackupItemOperations("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, operations, res) } @@ -512,13 +512,13 @@ func TestGetRestoreItemOperations(t *testing.T) { // itemoperations file not found should not error res, err := harness.GetRestoreItemOperations("test-restore") - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, res) // itemoperations file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "restores/test-restore/restore-test-restore-itemoperations.json.gz", newStringReadSeeker("foo")) _, err = harness.GetRestoreItemOperations("test-restore") - assert.Error(t, err) + require.Error(t, err) // itemoperations file containing gzipped json data should return correctly operations := []*itemoperation.RestoreOperation{ @@ -552,7 +552,7 @@ func TestGetRestoreItemOperations(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "restores/test-restore/restore-test-restore-itemoperations.json.gz", obj)) res, err = harness.GetRestoreItemOperations("test-restore") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, operations, res) } @@ -617,7 +617,7 @@ func TestDeleteBackup(t *testing.T) { err := backupStore.DeleteBackup("bak") - velerotest.AssertErrorMatches(t, test.expectedErr, err) + velerotest.RequireErrorMatches(t, test.expectedErr, err) }) } } @@ -669,7 +669,7 @@ func TestDeleteRestore(t *testing.T) { err := backupStore.DeleteRestore("bak") - velerotest.AssertErrorMatches(t, test.expectedErr, err) + velerotest.RequireErrorMatches(t, test.expectedErr, err) }) } } @@ -800,13 +800,13 @@ func TestGetCSIVolumeSnapshotClasses(t *testing.T) { // file not found should not error res, err := harness.GetCSIVolumeSnapshotClasses("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, res) // file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-csi-volumesnapshotclasses.json.gz", newStringReadSeeker("foo")) _, err = harness.GetCSIVolumeSnapshotClasses("test-backup") - assert.Error(t, err) + require.Error(t, err) // file containing gzipped json data should return correctly classes := []*snapshotv1api.VolumeSnapshotClass{ @@ -823,7 +823,7 @@ func TestGetCSIVolumeSnapshotClasses(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-csi-volumesnapshotclasses.json.gz", obj)) res, err = harness.GetCSIVolumeSnapshotClasses("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, classes, res) } @@ -832,13 +832,13 @@ func TestGetCSIVolumeSnapshots(t *testing.T) { // file not found should not error res, err := harness.GetCSIVolumeSnapshots("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, res) // file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-csi-volumesnapshots.json.gz", newStringReadSeeker("foo")) _, err = harness.GetCSIVolumeSnapshots("test-backup") - assert.Error(t, err) + require.Error(t, err) // file containing gzipped json data should return correctly snapshots := []*snapshotv1api.VolumeSnapshot{ @@ -859,7 +859,7 @@ func TestGetCSIVolumeSnapshots(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-csi-volumesnapshots.json.gz", obj)) res, err = harness.GetCSIVolumeSnapshots("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, snapshots, res) } @@ -868,13 +868,13 @@ func TestGetCSIVolumeSnapshotContents(t *testing.T) { // file not found should not error res, err := harness.GetCSIVolumeSnapshotContents("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, res) // file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-csi-volumesnapshotcontents.json.gz", newStringReadSeeker("foo")) _, err = harness.GetCSIVolumeSnapshotContents("test-backup") - assert.Error(t, err) + require.Error(t, err) // file containing gzipped json data should return correctly contents := []*snapshotv1api.VolumeSnapshotContent{ @@ -893,7 +893,7 @@ func TestGetCSIVolumeSnapshotContents(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-csi-volumesnapshotcontents.json.gz", obj)) res, err = harness.GetCSIVolumeSnapshotContents("test-backup") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, contents, res) } @@ -1150,12 +1150,12 @@ func TestGetRestoreResults(t *testing.T) { // file not found should not error _, err := harness.GetRestoreResults("test-restore") - assert.NoError(t, err) + require.NoError(t, err) // file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "restores/test-restore/restore-test-restore-results.gz", newStringReadSeeker("foo")) _, err = harness.GetRestoreResults("test-restore") - assert.Error(t, err) + require.Error(t, err) // file containing gzipped json data should return correctly contents := map[string]results.Result{ @@ -1170,7 +1170,7 @@ func TestGetRestoreResults(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "restores/test-restore/restore-test-restore-results.gz", obj)) res, err := harness.GetRestoreResults("test-restore") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, contents["warnings"], res["warnings"]) assert.EqualValues(t, contents["errors"], res["errors"]) } @@ -1180,12 +1180,12 @@ func TestGetRestoredResourceList(t *testing.T) { // file not found should not error _, err := harness.GetRestoredResourceList("test-restore") - assert.NoError(t, err) + require.NoError(t, err) // file containing invalid data should error harness.objectStore.PutObject(harness.bucket, "restores/test-restore/restore-test-restore-resource-list.json.gz", newStringReadSeeker("foo")) _, err = harness.GetRestoredResourceList("test-restore") - assert.Error(t, err) + require.Error(t, err) // file containing gzipped json data should return correctly list := map[string][]string{ @@ -1199,7 +1199,7 @@ func TestGetRestoredResourceList(t *testing.T) { require.NoError(t, harness.objectStore.PutObject(harness.bucket, "restores/test-restore/restore-test-restore-resource-list.json.gz", obj)) res, err := harness.GetRestoredResourceList("test-restore") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, list["pod"], res["pod"]) } @@ -1238,7 +1238,7 @@ func TestPutBackupVolumeInfos(t *testing.T) { err := harness.PutBackupVolumeInfos("backup-1", buf) - velerotest.AssertErrorMatches(t, tc.expectedErr, err) + velerotest.RequireErrorMatches(t, tc.expectedErr, err) assert.Len(t, harness.objectStore.Data[harness.bucket], len(tc.expectedKeys)) for _, key := range tc.expectedKeys { assert.Contains(t, harness.objectStore.Data[harness.bucket], key) diff --git a/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go b/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go index ce8d072614..e92bdb9fc2 100644 --- a/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go +++ b/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go @@ -68,7 +68,7 @@ func TestRestartableGetBackupItemAction(t *testing.T) { r := NewRestartableBackupItemAction(name, p) a, err := r.getBackupItemAction() if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) @@ -88,7 +88,7 @@ func TestRestartableBackupItemActionGetDelegate(t *testing.T) { r := NewRestartableBackupItemAction(name, p) a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path p.On("ResetIfNeeded").Return(nil) @@ -97,7 +97,7 @@ func TestRestartableBackupItemActionGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(expected, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, a) } diff --git a/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go b/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go index efcb94927c..3c78c36996 100644 --- a/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go +++ b/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go @@ -68,7 +68,7 @@ func TestRestartableGetBackupItemAction(t *testing.T) { r := NewRestartableBackupItemAction(name, p) a, err := r.getBackupItemAction() if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) @@ -88,7 +88,7 @@ func TestRestartableBackupItemActionGetDelegate(t *testing.T) { r := NewRestartableBackupItemAction(name, p) a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path p.On("ResetIfNeeded").Return(nil) @@ -97,7 +97,7 @@ func TestRestartableBackupItemActionGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(expected, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, a) } diff --git a/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go b/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go index eeec9c74c5..bb3516fcbd 100644 --- a/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go +++ b/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go @@ -88,7 +88,7 @@ func TestRestartableItemBlockActionGetDelegate(t *testing.T) { r := NewRestartableItemBlockAction(name, p) a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path p.On("ResetIfNeeded").Return(nil) @@ -97,7 +97,7 @@ func TestRestartableItemBlockActionGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(expected, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, a) } diff --git a/pkg/plugin/clientmgmt/manager_test.go b/pkg/plugin/clientmgmt/manager_test.go index 6919fc9c36..0144ca31e1 100644 --- a/pkg/plugin/clientmgmt/manager_test.go +++ b/pkg/plugin/clientmgmt/manager_test.go @@ -108,7 +108,7 @@ func TestGetRestartableProcess(t *testing.T) { registry.On("Get", pluginKind, pluginName).Return(nil, errors.Errorf("registry")).Once() rp, err := m.getRestartableProcess(pluginKind, pluginName) assert.Nil(t, rp) - assert.EqualError(t, err, "registry") + require.EqualError(t, err, "registry") // Test 2: registry ok, factory error podID := framework.PluginIdentifier{ @@ -120,7 +120,7 @@ func TestGetRestartableProcess(t *testing.T) { factory.On("NewRestartableProcess", podID.Command, logger, logLevel).Return(nil, errors.Errorf("factory")).Once() rp, err = m.getRestartableProcess(pluginKind, pluginName) assert.Nil(t, rp) - assert.EqualError(t, err, "factory") + require.EqualError(t, err, "factory") // Test 3: registry ok, factory ok restartableProcess := &restartabletest.MockRestartableProcess{} @@ -309,7 +309,7 @@ func getPluginTest( factory.On("NewRestartableProcess", pluginID.Command, logger, logLevel).Return(nil, errors.Errorf("NewRestartableProcess")).Once() actual, err := getPluginFunc(m, pluginName) assert.Nil(t, actual) - assert.EqualError(t, err, "NewRestartableProcess") + require.EqualError(t, err, "NewRestartableProcess") // Test 2: happy path factory.On("NewRestartableProcess", pluginID.Command, logger, logLevel).Return(restartableProcess, nil).Once() @@ -404,7 +404,7 @@ func TestGetBackupItemActions(t *testing.T) { backupItemActions, err := m.GetBackupItemActions() if tc.newRestartableProcessError != nil { assert.Nil(t, backupItemActions) - assert.EqualError(t, err, "NewRestartableProcess") + require.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) var actual []interface{} @@ -496,7 +496,7 @@ func TestGetBackupItemActionsV2(t *testing.T) { backupItemActions, err := m.GetBackupItemActionsV2() if tc.newRestartableProcessError != nil { assert.Nil(t, backupItemActions) - assert.EqualError(t, err, "NewRestartableProcess") + require.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) var actual []interface{} @@ -588,7 +588,7 @@ func TestGetRestoreItemActions(t *testing.T) { restoreItemActions, err := m.GetRestoreItemActions() if tc.newRestartableProcessError != nil { assert.Nil(t, restoreItemActions) - assert.EqualError(t, err, "NewRestartableProcess") + require.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) var actual []interface{} @@ -680,7 +680,7 @@ func TestGetRestoreItemActionsV2(t *testing.T) { restoreItemActions, err := m.GetRestoreItemActionsV2() if tc.newRestartableProcessError != nil { assert.Nil(t, restoreItemActions) - assert.EqualError(t, err, "NewRestartableProcess") + require.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) var actual []interface{} @@ -789,7 +789,7 @@ func TestGetDeleteItemActions(t *testing.T) { deleteItemActions, err := m.GetDeleteItemActions() if tc.newRestartableProcessError != nil { assert.Nil(t, deleteItemActions) - assert.EqualError(t, err, "NewRestartableProcess") + require.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) var actual []interface{} diff --git a/pkg/plugin/clientmgmt/process/process_test.go b/pkg/plugin/clientmgmt/process/process_test.go index e65c890511..0069ae0ecf 100644 --- a/pkg/plugin/clientmgmt/process/process_test.go +++ b/pkg/plugin/clientmgmt/process/process_test.go @@ -114,7 +114,7 @@ func TestDispense(t *testing.T) { dispensed, err := p.dispense(key) if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) diff --git a/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go b/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go index b6cf8d8366..a0881c9385 100644 --- a/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go +++ b/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go @@ -67,7 +67,7 @@ func TestRestartableGetDeleteItemAction(t *testing.T) { r := NewRestartableDeleteItemAction(name, p) a, err := r.getDeleteItemAction() if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) @@ -87,7 +87,7 @@ func TestRestartableDeleteItemActionGetDelegate(t *testing.T) { r := NewRestartableDeleteItemAction(name, p) a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path // Currently broken since this mocks out the restore item action interface @@ -97,7 +97,7 @@ func TestRestartableDeleteItemActionGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(expected, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, a) } diff --git a/pkg/plugin/clientmgmt/restartable_object_store_test.go b/pkg/plugin/clientmgmt/restartable_object_store_test.go index 04cdedda0e..3d83f11593 100644 --- a/pkg/plugin/clientmgmt/restartable_object_store_test.go +++ b/pkg/plugin/clientmgmt/restartable_object_store_test.go @@ -71,7 +71,7 @@ func TestRestartableGetObjectStore(t *testing.T) { } a, err := r.getObjectStore() if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) @@ -97,7 +97,7 @@ func TestRestartableObjectStoreReinitialize(t *testing.T) { } err := r.Reinitialize(3) - assert.EqualError(t, err, "plugin int is not a ObjectStore") + require.EqualError(t, err, "plugin int is not a ObjectStore") objectStore := new(providermocks.ObjectStore) objectStore.Test(t) @@ -105,11 +105,11 @@ func TestRestartableObjectStoreReinitialize(t *testing.T) { objectStore.On("Init", r.config).Return(errors.Errorf("init error")).Once() err = r.Reinitialize(objectStore) - assert.EqualError(t, err, "init error") + require.EqualError(t, err, "init error") objectStore.On("Init", r.config).Return(nil) err = r.Reinitialize(objectStore) - assert.NoError(t, err) + require.NoError(t, err) } func TestRestartableObjectStoreGetDelegate(t *testing.T) { @@ -127,7 +127,7 @@ func TestRestartableObjectStoreGetDelegate(t *testing.T) { } a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path p.On("ResetIfNeeded").Return(nil) @@ -137,7 +137,7 @@ func TestRestartableObjectStoreGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(objectStore, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, objectStore, a) } @@ -159,7 +159,7 @@ func TestRestartableObjectStoreInit(t *testing.T) { "color": "blue", } err := r.Init(config) - assert.EqualError(t, err, "GetByKindAndName error") + require.EqualError(t, err, "GetByKindAndName error") // Delegate returns error objectStore := new(providermocks.ObjectStore) @@ -169,7 +169,7 @@ func TestRestartableObjectStoreInit(t *testing.T) { objectStore.On("Init", config).Return(errors.Errorf("Init error")).Once() err = r.Init(config) - assert.EqualError(t, err, "Init error") + require.EqualError(t, err, "Init error") // wipe this out because the previous failed Init call set it r.config = nil @@ -177,12 +177,12 @@ func TestRestartableObjectStoreInit(t *testing.T) { // Happy path objectStore.On("Init", config).Return(nil) err = r.Init(config) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, config, r.config) // Calling Init twice is forbidden err = r.Init(config) - assert.EqualError(t, err, "already initialized") + require.EqualError(t, err, "already initialized") } func TestRestartableObjectStoreDelegatedFunctions(t *testing.T) { diff --git a/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go b/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go index e00a6fddae..2dee7ae0ec 100644 --- a/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go +++ b/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go @@ -67,7 +67,7 @@ func TestRestartableGetRestoreItemAction(t *testing.T) { r := NewRestartableRestoreItemAction(name, p) a, err := r.getRestoreItemAction() if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) @@ -87,7 +87,7 @@ func TestRestartableRestoreItemActionGetDelegate(t *testing.T) { r := NewRestartableRestoreItemAction(name, p) a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path p.On("ResetIfNeeded").Return(nil) @@ -96,7 +96,7 @@ func TestRestartableRestoreItemActionGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(expected, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, a) } diff --git a/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go b/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go index 73d4f81455..9c9bc7285c 100644 --- a/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go +++ b/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go @@ -67,7 +67,7 @@ func TestRestartableGetRestoreItemAction(t *testing.T) { r := NewRestartableRestoreItemAction(name, p) a, err := r.getRestoreItemAction() if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) @@ -87,7 +87,7 @@ func TestRestartableRestoreItemActionGetDelegate(t *testing.T) { r := NewRestartableRestoreItemAction(name, p) a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path p.On("ResetIfNeeded").Return(nil) @@ -96,7 +96,7 @@ func TestRestartableRestoreItemActionGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(expected, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, a) } diff --git a/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go b/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go index eaa3862896..ea5cdafaeb 100644 --- a/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go +++ b/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go @@ -70,7 +70,7 @@ func TestRestartableGetVolumeSnapshotter(t *testing.T) { } a, err := r.getVolumeSnapshotter() if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) @@ -96,7 +96,7 @@ func TestRestartableVolumeSnapshotterReinitialize(t *testing.T) { } err := r.Reinitialize(3) - assert.EqualError(t, err, "plugin int is not a VolumeSnapshotter") + require.EqualError(t, err, "plugin int is not a VolumeSnapshotter") volumeSnapshotter := new(providermocks.VolumeSnapshotter) volumeSnapshotter.Test(t) @@ -104,11 +104,11 @@ func TestRestartableVolumeSnapshotterReinitialize(t *testing.T) { volumeSnapshotter.On("Init", r.config).Return(errors.Errorf("init error")).Once() err = r.Reinitialize(volumeSnapshotter) - assert.EqualError(t, err, "init error") + require.EqualError(t, err, "init error") volumeSnapshotter.On("Init", r.config).Return(nil) err = r.Reinitialize(volumeSnapshotter) - assert.NoError(t, err) + require.NoError(t, err) } func TestRestartableVolumeSnapshotterGetDelegate(t *testing.T) { @@ -126,7 +126,7 @@ func TestRestartableVolumeSnapshotterGetDelegate(t *testing.T) { } a, err := r.getDelegate() assert.Nil(t, a) - assert.EqualError(t, err, "reset error") + require.EqualError(t, err, "reset error") // Happy path p.On("ResetIfNeeded").Return(nil) @@ -136,7 +136,7 @@ func TestRestartableVolumeSnapshotterGetDelegate(t *testing.T) { p.On("GetByKindAndName", key).Return(volumeSnapshotter, nil) a, err = r.getDelegate() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, volumeSnapshotter, a) } @@ -158,7 +158,7 @@ func TestRestartableVolumeSnapshotterInit(t *testing.T) { "color": "blue", } err := r.Init(config) - assert.EqualError(t, err, "GetByKindAndName error") + require.EqualError(t, err, "GetByKindAndName error") // Delegate returns error volumeSnapshotter := new(providermocks.VolumeSnapshotter) @@ -168,7 +168,7 @@ func TestRestartableVolumeSnapshotterInit(t *testing.T) { volumeSnapshotter.On("Init", config).Return(errors.Errorf("Init error")).Once() err = r.Init(config) - assert.EqualError(t, err, "Init error") + require.EqualError(t, err, "Init error") // wipe this out because the previous failed Init call set it r.config = nil @@ -176,12 +176,12 @@ func TestRestartableVolumeSnapshotterInit(t *testing.T) { // Happy path volumeSnapshotter.On("Init", config).Return(nil) err = r.Init(config) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, config, r.config) // Calling Init twice is forbidden err = r.Init(config) - assert.EqualError(t, err, "already initialized") + require.EqualError(t, err, "already initialized") } func TestRestartableVolumeSnapshotterDelegatedFunctions(t *testing.T) { diff --git a/pkg/plugin/framework/validation_test.go b/pkg/plugin/framework/validation_test.go index 5160485dc9..b660484c82 100644 --- a/pkg/plugin/framework/validation_test.go +++ b/pkg/plugin/framework/validation_test.go @@ -19,19 +19,19 @@ package framework import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidateConfigKeys(t *testing.T) { - assert.NoError(t, validateConfigKeys(nil)) - assert.NoError(t, validateConfigKeys(map[string]string{})) - assert.NoError(t, validateConfigKeys(map[string]string{"foo": "bar"}, "foo")) - assert.NoError(t, validateConfigKeys(map[string]string{"foo": "bar", "bar": "baz"}, "foo", "bar")) + require.NoError(t, validateConfigKeys(nil)) + require.NoError(t, validateConfigKeys(map[string]string{})) + require.NoError(t, validateConfigKeys(map[string]string{"foo": "bar"}, "foo")) + require.NoError(t, validateConfigKeys(map[string]string{"foo": "bar", "bar": "baz"}, "foo", "bar")) - assert.Error(t, validateConfigKeys(map[string]string{"foo": "bar"})) - assert.Error(t, validateConfigKeys(map[string]string{"foo": "bar"}, "Foo")) - assert.Error(t, validateConfigKeys(map[string]string{"foo": "bar", "boo": ""}, "foo")) + require.Error(t, validateConfigKeys(map[string]string{"foo": "bar"})) + require.Error(t, validateConfigKeys(map[string]string{"foo": "bar"}, "Foo")) + require.Error(t, validateConfigKeys(map[string]string{"foo": "bar", "boo": ""}, "foo")) - assert.NoError(t, ValidateObjectStoreConfigKeys(map[string]string{"bucket": "foo"})) - assert.Error(t, ValidateVolumeSnapshotterConfigKeys(map[string]string{"bucket": "foo"})) + require.NoError(t, ValidateObjectStoreConfigKeys(map[string]string{"bucket": "foo"})) + require.Error(t, ValidateVolumeSnapshotterConfigKeys(map[string]string{"bucket": "foo"})) } diff --git a/pkg/podexec/pod_command_executor_test.go b/pkg/podexec/pod_command_executor_test.go index 150c1babdf..80dd8c723c 100644 --- a/pkg/podexec/pod_command_executor_test.go +++ b/pkg/podexec/pod_command_executor_test.go @@ -120,7 +120,7 @@ func TestExecutePodCommandMissingInputs(t *testing.T) { pod := new(corev1api.Pod) hookPodContainerNotSame := false if err := runtime.DefaultUnstructuredConverter.FromUnstructured(test.item, pod); err != nil { - assert.Error(t, err) + require.Error(t, err) } if (len(pod.Spec.Containers) > 0) && (pod.Spec.Containers[0].Name != test.hook.Container) { hookPodContainerNotSame = true @@ -130,9 +130,9 @@ func TestExecutePodCommandMissingInputs(t *testing.T) { err := e.ExecutePodCommand(velerotest.NewLogger(), test.item, test.podNamespace, test.podName, test.hookName, test.hook) if hookPodContainerNotSame && test.hook.Container == pod.Spec.Containers[0].Name { - assert.Error(t, fmt.Errorf("hook exec container is overwritten")) + require.Error(t, fmt.Errorf("hook exec container is overwritten")) } - assert.Error(t, err) + require.Error(t, err) }) } } @@ -236,7 +236,7 @@ func TestExecutePodCommand(t *testing.T) { err = podCommandExecutor.ExecutePodCommand(velerotest.NewLogger(), pod, "namespace", "name", "hookName", &hook) if test.expectedError != "" { - assert.EqualError(t, err, test.expectedError) + require.EqualError(t, err, test.expectedError) return } @@ -257,10 +257,10 @@ func TestEnsureContainerExists(t *testing.T) { } err := ensureContainerExists(pod, "bar") - assert.EqualError(t, err, `no such container: "bar"`) + require.EqualError(t, err, `no such container: "bar"`) err = ensureContainerExists(pod, "foo") - assert.NoError(t, err) + require.NoError(t, err) } func TestPodCompeted(t *testing.T) { diff --git a/pkg/podvolume/backupper_test.go b/pkg/podvolume/backupper_test.go index 16d4ce2862..a8e75e351a 100644 --- a/pkg/podvolume/backupper_test.go +++ b/pkg/podvolume/backupper_test.go @@ -51,7 +51,7 @@ func TestIsHostPathVolume(t *testing.T) { }, } isHostPath, err := isHostPathVolume(vol, nil, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isHostPath) // non-hostPath pod volume @@ -61,7 +61,7 @@ func TestIsHostPathVolume(t *testing.T) { }, } isHostPath, err = isHostPathVolume(vol, nil, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isHostPath) // PVC that doesn't have a PV @@ -79,7 +79,7 @@ func TestIsHostPathVolume(t *testing.T) { }, } isHostPath, err = isHostPathVolume(vol, pvc, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isHostPath) // PVC that claims a non-hostPath PV @@ -107,7 +107,7 @@ func TestIsHostPathVolume(t *testing.T) { } crClient1 := velerotest.NewFakeControllerRuntimeClient(t, pv) isHostPath, err = isHostPathVolume(vol, pvc, crClient1) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isHostPath) // PVC that claims a hostPath PV @@ -140,7 +140,7 @@ func TestIsHostPathVolume(t *testing.T) { crClient2 := velerotest.NewFakeControllerRuntimeClient(t, pv) isHostPath, err = isHostPathVolume(vol, pvc, crClient2) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isHostPath) } @@ -572,7 +572,7 @@ func TestBackupPodVolumes(t *testing.T) { assert.Nil(t, test.errs) } else { for i := 0; i < len(errs); i++ { - assert.EqualError(t, errs[i], test.errs[i]) + require.EqualError(t, errs[i], test.errs[i]) } } diff --git a/pkg/podvolume/restorer_test.go b/pkg/podvolume/restorer_test.go index 5d52cf21d2..11d2b3bf50 100644 --- a/pkg/podvolume/restorer_test.go +++ b/pkg/podvolume/restorer_test.go @@ -115,7 +115,7 @@ func TestGetVolumesRepositoryType(t *testing.T) { assert.Equal(t, tc.expectedErr, errMsg) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } } }) diff --git a/pkg/repository/backup_repo_op_test.go b/pkg/repository/backup_repo_op_test.go index a317e22c2b..48b216520a 100644 --- a/pkg/repository/backup_repo_op_test.go +++ b/pkg/repository/backup_repo_op_test.go @@ -20,8 +20,6 @@ import ( "context" "fmt" - "github.com/stretchr/testify/assert" - "testing" "github.com/stretchr/testify/require" @@ -160,9 +158,9 @@ func TestGetBackupRepository(t *testing.T) { } if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } diff --git a/pkg/repository/config/config_test.go b/pkg/repository/config/config_test.go index 4f18d6faea..f5e1746441 100644 --- a/pkg/repository/config/config_test.go +++ b/pkg/repository/config/config_test.go @@ -21,6 +21,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" ) @@ -250,9 +251,9 @@ func TestGetRepoIdentifier(t *testing.T) { id, err := GetRepoIdentifier(tc.bsl, tc.repoName) assert.Equal(t, tc.expected, id) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) assert.Empty(t, id) } }) diff --git a/pkg/repository/ensurer_test.go b/pkg/repository/ensurer_test.go index d480ba1a47..12f828687a 100644 --- a/pkg/repository/ensurer_test.go +++ b/pkg/repository/ensurer_test.go @@ -22,6 +22,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -127,9 +128,9 @@ func TestEnsureRepo(t *testing.T) { repo, err := ensurer.EnsureRepo(context.Background(), velerov1.DefaultNamespace, test.namespace, test.bsl, test.repositoryType) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.expectedRepo, repo) @@ -204,9 +205,9 @@ func TestCreateBackupRepositoryAndWait(t *testing.T) { RepositoryType: test.repositoryType, }) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.expectedRepo, repo) diff --git a/pkg/repository/maintenance_test.go b/pkg/repository/maintenance_test.go index ca88c1577d..bd860667bf 100644 --- a/pkg/repository/maintenance_test.go +++ b/pkg/repository/maintenance_test.go @@ -25,6 +25,7 @@ import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" batchv1 "k8s.io/api/batch/v1" v1 "k8s.io/api/core/v1" @@ -110,12 +111,12 @@ func TestDeleteOldMaintenanceJobs(t *testing.T) { // Call the function err := deleteOldMaintenanceJobs(cli, repo, keep) - assert.NoError(t, err) + require.NoError(t, err) // Get the remaining jobs jobList := &batchv1.JobList{} err = cli.List(context.TODO(), jobList, client.MatchingLabels(map[string]string{RepositoryNameLabel: repo})) - assert.NoError(t, err) + require.NoError(t, err) // We expect the number of jobs to be equal to 'keep' assert.Len(t, jobList.Items, keep) @@ -172,9 +173,9 @@ func TestWaitForJobComplete(t *testing.T) { // Check if the error matches the expectation if tc.expectError { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -216,7 +217,7 @@ func TestGetMaintenanceResultFromJob(t *testing.T) { result, err := getMaintenanceResultFromJob(cli, job) // Check if the result and error match the expectation - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "test message", result) } @@ -258,7 +259,7 @@ func TestGetLatestMaintenanceJob(t *testing.T) { // Call the function job, err := getLatestMaintenanceJob(cli, "default") - assert.NoError(t, err) + require.NoError(t, err) // We expect the returned job to be the newer job assert.Equal(t, newerJob.Name, job.Name) @@ -354,10 +355,10 @@ func TestBuildMaintenanceJob(t *testing.T) { // Check the error if tc.expectedError { - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, job) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, job) assert.Contains(t, job.Name, tc.expectedJobName) assert.Equal(t, param.BackupRepo.Namespace, job.Namespace) diff --git a/pkg/repository/provider/unified_repo_test.go b/pkg/repository/provider/unified_repo_test.go index a5063bbbfa..1df3f28687 100644 --- a/pkg/repository/provider/unified_repo_test.go +++ b/pkg/repository/provider/unified_repo_test.go @@ -206,9 +206,9 @@ func TestGetStorageCredentials(t *testing.T) { require.Equal(t, tc.expected, actual) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -470,9 +470,9 @@ func TestGetStorageVariables(t *testing.T) { require.Equal(t, tc.expected, actual) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -525,9 +525,9 @@ func TestGetRepoPassword(t *testing.T) { require.Equal(t, tc.expected, password) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -591,9 +591,9 @@ func TestGetStoreOptions(t *testing.T) { require.Equal(t, tc.expected, options) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -724,9 +724,9 @@ func TestPrepareRepo(t *testing.T) { }) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -873,9 +873,9 @@ func TestForget(t *testing.T) { }) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1029,7 +1029,7 @@ func TestBatchForget(t *testing.T) { assert.Equal(t, len(tc.expectedErr), len(errs)) for i := range tc.expectedErr { - assert.EqualError(t, errs[i], tc.expectedErr[i]) + require.EqualError(t, errs[i], tc.expectedErr[i]) } } }) @@ -1116,9 +1116,9 @@ func TestInitRepo(t *testing.T) { }) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1204,9 +1204,9 @@ func TestConnectToRepo(t *testing.T) { }) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1348,9 +1348,9 @@ func TestBoostRepoConnect(t *testing.T) { }) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1436,9 +1436,9 @@ func TestPruneRepo(t *testing.T) { }) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } diff --git a/pkg/repository/udmrepo/kopialib/backend/file_system_test.go b/pkg/repository/udmrepo/kopialib/backend/file_system_test.go index fe9b8e624a..1134876a83 100644 --- a/pkg/repository/udmrepo/kopialib/backend/file_system_test.go +++ b/pkg/repository/udmrepo/kopialib/backend/file_system_test.go @@ -22,6 +22,7 @@ import ( "github.com/kopia/kopia/repo/blob/filesystem" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/vmware-tanzu/velero/pkg/repository/udmrepo" ) @@ -70,10 +71,10 @@ func TestFSSetup(t *testing.T) { err := fsFlags.Setup(context.Background(), tc.flags) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedOptions, fsFlags.options) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } diff --git a/pkg/repository/udmrepo/kopialib/backend/gcs_test.go b/pkg/repository/udmrepo/kopialib/backend/gcs_test.go index 759e9baae4..3460df23fb 100644 --- a/pkg/repository/udmrepo/kopialib/backend/gcs_test.go +++ b/pkg/repository/udmrepo/kopialib/backend/gcs_test.go @@ -22,6 +22,7 @@ import ( "github.com/kopia/kopia/repo/blob/gcs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/vmware-tanzu/velero/pkg/repository/udmrepo" ) @@ -92,10 +93,10 @@ func TestGcsSetup(t *testing.T) { err := gcsFlags.Setup(context.Background(), tc.flags) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedOptions, gcsFlags.options) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } diff --git a/pkg/repository/udmrepo/kopialib/backend/s3_test.go b/pkg/repository/udmrepo/kopialib/backend/s3_test.go index df96de36e9..b17e906c34 100644 --- a/pkg/repository/udmrepo/kopialib/backend/s3_test.go +++ b/pkg/repository/udmrepo/kopialib/backend/s3_test.go @@ -21,7 +21,7 @@ import ( "testing" "github.com/kopia/kopia/repo/blob/s3" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/vmware-tanzu/velero/pkg/repository/udmrepo" ) @@ -122,9 +122,9 @@ func TestS3Setup(t *testing.T) { err := s3Flags.Setup(context.Background(), tc.flags) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } diff --git a/pkg/repository/udmrepo/kopialib/lib_repo_test.go b/pkg/repository/udmrepo/kopialib/lib_repo_test.go index 952d3fcdaa..4c56a38129 100644 --- a/pkg/repository/udmrepo/kopialib/lib_repo_test.go +++ b/pkg/repository/udmrepo/kopialib/lib_repo_test.go @@ -140,9 +140,9 @@ func TestOpen(t *testing.T) { } if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -254,9 +254,9 @@ func TestMaintain(t *testing.T) { err := service.Maintain(ctx, tc.repoOptions) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -352,9 +352,9 @@ func TestWriteInitParameters(t *testing.T) { err := writeInitParameters(ctx, tc.repoOptions, logger) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -449,9 +449,9 @@ func TestOpenObject(t *testing.T) { _, err := kr.OpenObject(context.Background(), udmrepo.ID(tc.objectID)) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -491,9 +491,9 @@ func TestGetManifest(t *testing.T) { err := kr.GetManifest(context.Background(), udmrepo.ID(""), &udmrepo.RepoManifest{}) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -530,9 +530,9 @@ func TestFindManifests(t *testing.T) { _, err := kr.FindManifests(context.Background(), udmrepo.ManifestFilter{}) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -589,9 +589,9 @@ func TestClose(t *testing.T) { err := kr.Close(context.Background()) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -630,9 +630,9 @@ func TestPutManifest(t *testing.T) { }) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -669,9 +669,9 @@ func TestDeleteManifest(t *testing.T) { err := kr.DeleteManifest(context.Background(), udmrepo.ID("")) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -708,9 +708,9 @@ func TestFlush(t *testing.T) { err := kr.Flush(context.Background()) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -780,9 +780,9 @@ func TestConcatenateObjects(t *testing.T) { _, err := kr.ConcatenateObjects(context.Background(), tc.objectIDs) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -904,9 +904,9 @@ func TestReaderRead(t *testing.T) { _, err := kr.Read(nil) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -951,10 +951,10 @@ func TestReaderSeek(t *testing.T) { ret, err := kr.Seek(0, 0) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedRet, ret) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -994,9 +994,9 @@ func TestReaderClose(t *testing.T) { err := kr.Close() if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1082,10 +1082,10 @@ func TestWriterWrite(t *testing.T) { ret, err := kr.Write(nil) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedRet, ret) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1130,10 +1130,10 @@ func TestWriterCheckpoint(t *testing.T) { ret, err := kr.Checkpoint() if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedRet, ret) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1178,10 +1178,10 @@ func TestWriterResult(t *testing.T) { ret, err := kr.Result() if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedRet, ret) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -1221,9 +1221,9 @@ func TestWriterClose(t *testing.T) { err := kr.Close() if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } diff --git a/pkg/repository/udmrepo/kopialib/repo_init_test.go b/pkg/repository/udmrepo/kopialib/repo_init_test.go index f91296d1f3..f869f018f9 100644 --- a/pkg/repository/udmrepo/kopialib/repo_init_test.go +++ b/pkg/repository/udmrepo/kopialib/repo_init_test.go @@ -20,8 +20,8 @@ import ( "context" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" "github.com/vmware-tanzu/velero/pkg/repository/udmrepo" storagemocks "github.com/vmware-tanzu/velero/pkg/repository/udmrepo/kopialib/backend/mocks" @@ -144,9 +144,9 @@ func TestCreateBackupRepo(t *testing.T) { err := CreateBackupRepo(context.Background(), tc.repoOptions) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } @@ -228,9 +228,9 @@ func TestConnectBackupRepo(t *testing.T) { err := ConnectBackupRepo(context.Background(), tc.repoOptions) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr) + require.EqualError(t, err, tc.expectedErr) } }) } diff --git a/pkg/restic/exec_commands_test.go b/pkg/restic/exec_commands_test.go index 2fdd39e88b..bf60035cc9 100644 --- a/pkg/restic/exec_commands_test.go +++ b/pkg/restic/exec_commands_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/vmware-tanzu/velero/pkg/test" "github.com/vmware-tanzu/velero/pkg/util/filesystem" @@ -54,9 +55,9 @@ func Test_getSummaryLine(t *testing.T) { t.Run(tt.name, func(t *testing.T) { summary, err := getSummaryLine([]byte(tt.output)) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, summaryLine, string(summary)) } }) @@ -105,6 +106,6 @@ func Test_getVolumeSize(t *testing.T) { actualSize, err := getVolumeSize("/") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expectedSize, actualSize) } diff --git a/pkg/restore/actions/admissionwebhook_config_action_test.go b/pkg/restore/actions/admissionwebhook_config_action_test.go index fb0205cb4e..e7be973c66 100644 --- a/pkg/restore/actions/admissionwebhook_config_action_test.go +++ b/pkg/restore/actions/admissionwebhook_config_action_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -186,26 +187,26 @@ func TestNewAdmissionWebhookConfigurationActionExecute(t *testing.T) { } output, err := action.Execute(input) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } if tt.NoneSideEffectsIndex != nil { wb, _, err := unstructured.NestedSlice(output.UpdatedItem.UnstructuredContent(), "webhooks") - assert.NoError(t, err) + require.NoError(t, err) for _, i := range tt.NoneSideEffectsIndex { it, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&wb[i]) - assert.NoError(t, err) + require.NoError(t, err) s := it["sideEffects"].(string) assert.Equal(t, "None", s) } } if tt.NotNoneSideEffectsIndex != nil { wb, _, err := unstructured.NestedSlice(output.UpdatedItem.UnstructuredContent(), "webhooks") - assert.NoError(t, err) + require.NoError(t, err) for _, i := range tt.NotNoneSideEffectsIndex { it, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&wb[i]) - assert.NoError(t, err) + require.NoError(t, err) s := it["sideEffects"].(string) assert.NotEqual(t, "None", s) } diff --git a/pkg/restore/actions/change_image_name_action_test.go b/pkg/restore/actions/change_image_name_action_test.go index 134fc154ce..e560b460d3 100644 --- a/pkg/restore/actions/change_image_name_action_test.go +++ b/pkg/restore/actions/change_image_name_action_test.go @@ -167,9 +167,9 @@ func TestChangeImageRepositoryActionExecute(t *testing.T) { // validate for both error and non-error cases switch { case tc.wantErr != nil: - assert.EqualError(t, err, tc.wantErr.Error()) + require.EqualError(t, err, tc.wantErr.Error()) default: - assert.NoError(t, err) + require.NoError(t, err) pod := new(corev1.Pod) err = runtime.DefaultUnstructuredConverter.FromUnstructured(res.UpdatedItem.UnstructuredContent(), pod) require.NoError(t, err) diff --git a/pkg/restore/actions/change_pvc_node_selector_test.go b/pkg/restore/actions/change_pvc_node_selector_test.go index eee2bca092..c2c760dd61 100644 --- a/pkg/restore/actions/change_pvc_node_selector_test.go +++ b/pkg/restore/actions/change_pvc_node_selector_test.go @@ -172,10 +172,10 @@ func TestChangePVCNodeSelectorActionExecute(t *testing.T) { // validate for both error and non-error cases switch { case tc.wantErr != nil: - assert.EqualError(t, err, tc.wantErr.Error()) + require.EqualError(t, err, tc.wantErr.Error()) default: fmt.Printf("got +%v\n", res.UpdatedItem) - assert.NoError(t, err) + require.NoError(t, err) wantUnstructured, err := runtime.DefaultUnstructuredConverter.ToUnstructured(tc.want) fmt.Printf("expected +%v\n", wantUnstructured) diff --git a/pkg/restore/actions/change_storageclass_action_test.go b/pkg/restore/actions/change_storageclass_action_test.go index 4d32a6bade..d704417d27 100644 --- a/pkg/restore/actions/change_storageclass_action_test.go +++ b/pkg/restore/actions/change_storageclass_action_test.go @@ -257,9 +257,9 @@ func TestChangeStorageClassActionExecute(t *testing.T) { // validate for both error and non-error cases switch { case tc.wantErr != nil: - assert.EqualError(t, err, tc.wantErr.Error()) + require.EqualError(t, err, tc.wantErr.Error()) default: - assert.NoError(t, err) + require.NoError(t, err) wantUnstructured, err := runtime.DefaultUnstructuredConverter.ToUnstructured(tc.want) require.NoError(t, err) diff --git a/pkg/restore/actions/csi/pvc_action_test.go b/pkg/restore/actions/csi/pvc_action_test.go index 53e1908f2f..36b78581d8 100644 --- a/pkg/restore/actions/csi/pvc_action_test.go +++ b/pkg/restore/actions/csi/pvc_action_test.go @@ -260,11 +260,11 @@ func TestResetPVCResourceRequest(t *testing.T) { var storageReq50Mi, storageReq1Gi, cpuQty resource.Quantity storageReq50Mi, err := resource.ParseQuantity("50Mi") - assert.NoError(t, err) + require.NoError(t, err) storageReq1Gi, err = resource.ParseQuantity("1Gi") - assert.NoError(t, err) + require.NoError(t, err) cpuQty, err = resource.ParseQuantity("100m") - assert.NoError(t, err) + require.NoError(t, err) testCases := []struct { name string @@ -345,7 +345,7 @@ func TestResetPVCResourceRequest(t *testing.T) { log := logrus.New().WithField("unit-test", tc.name) setPVCStorageResourceRequest(&tc.pvc, tc.restoreSize, log) expected, err := resource.ParseQuantity(tc.expectedStorageRequestQty) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, tc.pvc.Spec.Resources.Requests[corev1api.ResourceStorage]) }) } diff --git a/pkg/restore/actions/csi/volumesnapshot_action_test.go b/pkg/restore/actions/csi/volumesnapshot_action_test.go index 1cc3f0ba94..af4596b2ca 100644 --- a/pkg/restore/actions/csi/volumesnapshot_action_test.go +++ b/pkg/restore/actions/csi/volumesnapshot_action_test.go @@ -89,8 +89,8 @@ func TestResetVolumeSnapshotSpecForRestore(t *testing.T) { before := tc.vs.DeepCopy() resetVolumeSnapshotSpecForRestore(&tc.vs, &tc.vscName) - assert.Equalf(t, tc.vs.Name, before.Name, "unexpected change to Object.Name, Want: %s; Got %s", tc.name, before.Name, tc.vs.Name) - assert.Equal(t, tc.vs.Namespace, before.Namespace, "unexpected change to Object.Namespace, Want: %s; Got %s", tc.name, before.Namespace, tc.vs.Namespace) + assert.Equalf(t, tc.vs.Name, before.Name, "unexpected change to Object.Name, Want: %s; Got %s", before.Name, tc.vs.Name) + assert.Equalf(t, tc.vs.Namespace, before.Namespace, "unexpected change to Object.Namespace, Want: %s; Got %s", before.Namespace, tc.vs.Namespace) assert.NotNil(t, tc.vs.Spec.Source) assert.Nil(t, tc.vs.Spec.Source.PersistentVolumeClaimName) assert.NotNil(t, tc.vs.Spec.Source.VolumeSnapshotContentName) diff --git a/pkg/restore/actions/init_restorehook_pod_action_test.go b/pkg/restore/actions/init_restorehook_pod_action_test.go index 259898cba7..2453b40879 100644 --- a/pkg/restore/actions/init_restorehook_pod_action_test.go +++ b/pkg/restore/actions/init_restorehook_pod_action_test.go @@ -131,10 +131,10 @@ func TestInitContainerRestoreHookPodActionExecute(t *testing.T) { Restore: tc.restore, }) if tc.expectedErr { - assert.Error(t, err, "expected an error") + require.Error(t, err, "expected an error") return } - assert.NoError(t, err, "expected no error, got %v", err) + require.NoError(t, err, "expected no error, got %v", err) var pod corev1api.Pod require.NoError(t, runtime.DefaultUnstructuredConverter.FromUnstructured(res.UpdatedItem.UnstructuredContent(), &pod)) diff --git a/pkg/restore/actions/pod_action_test.go b/pkg/restore/actions/pod_action_test.go index 2c886d39cd..41009c281b 100644 --- a/pkg/restore/actions/pod_action_test.go +++ b/pkg/restore/actions/pod_action_test.go @@ -236,10 +236,10 @@ func TestPodActionExecute(t *testing.T) { }) if test.expectedErr { - assert.Error(t, err, "expected an error") + require.Error(t, err, "expected an error") return } - assert.NoError(t, err, "expected no error, got %v", err) + require.NoError(t, err, "expected no error, got %v", err) var pod corev1api.Pod require.NoError(t, runtime.DefaultUnstructuredConverter.FromUnstructured(res.UpdatedItem.UnstructuredContent(), &pod)) diff --git a/pkg/restore/actions/pod_volume_restore_action_test.go b/pkg/restore/actions/pod_volume_restore_action_test.go index 7be617bd40..75e7df9998 100644 --- a/pkg/restore/actions/pod_volume_restore_action_test.go +++ b/pkg/restore/actions/pod_volume_restore_action_test.go @@ -291,7 +291,7 @@ func TestPodVolumeRestoreActionExecute(t *testing.T) { // method under test res, err := a.Execute(input) - assert.NoError(t, err) + require.NoError(t, err) updatedPod := new(corev1api.Pod) require.NoError(t, runtime.DefaultUnstructuredConverter.FromUnstructured(res.UpdatedItem.UnstructuredContent(), updatedPod)) diff --git a/pkg/restore/pv_restorer_test.go b/pkg/restore/pv_restorer_test.go index 86ee05e408..83668dd235 100644 --- a/pkg/restore/pv_restorer_test.go +++ b/pkg/restore/pv_restorer_test.go @@ -135,10 +135,10 @@ func TestExecutePVAction_NoSnapshotRestores(t *testing.T) { switch tc.expectedErr { case true: assert.Nil(t, res) - assert.Error(t, err) + require.Error(t, err) case false: assert.Equal(t, tc.expectedRes, res) - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -209,7 +209,7 @@ func TestExecutePVAction_SnapshotRestores(t *testing.T) { volumeSnapshotter.On("SetVolumeID", tc.obj, "volume-1").Return(tc.obj, nil) _, err := r.executePVAction(tc.obj) - assert.NoError(t, err) + require.NoError(t, err) volumeSnapshotter.AssertExpectations(t) }) diff --git a/pkg/restore/restore_test.go b/pkg/restore/restore_test.go index 4aa0d6d6a8..8215d486da 100644 --- a/pkg/restore/restore_test.go +++ b/pkg/restore/restore_test.go @@ -2316,11 +2316,10 @@ func TestShouldRestore(t *testing.T) { res, err := ctx.shouldRestore(tc.pvName, pvClient) assert.Equal(t, tc.want, res) if tc.wantErr != nil { - if assert.Error(t, err, "expected a non-nil error") { - assert.EqualError(t, err, tc.wantErr.Error()) - } + require.Error(t, err, "expected a non-nil error") + require.EqualError(t, err, tc.wantErr.Error()) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -2340,21 +2339,15 @@ func assertRestoredItems(t *testing.T, h *harness, want []*test.APIResource) { } res, err := client.Get(context.TODO(), item.GetName(), metav1.GetOptions{}) - if !assert.NoError(t, err) { - continue - } + require.NoError(t, err) itemJSON, err := json.Marshal(item) - if !assert.NoError(t, err) { - continue - } + require.NoError(t, err) t.Logf("%v", string(itemJSON)) u := make(map[string]interface{}) - if !assert.NoError(t, json.Unmarshal(itemJSON, &u)) { - continue - } + require.NoError(t, json.Unmarshal(itemJSON, &u)) want := &unstructured.Unstructured{Object: u} // These fields get non-nil zero values in the unstructured objects if they're @@ -3623,7 +3616,7 @@ func (cr *createRecorder) reactor() func(kubetesting.Action) (bool, runtime.Obje } accessor, err := meta.Accessor(createAction.GetObject()) - assert.NoError(cr.t, err) + require.NoError(cr.t, err) cr.resources = append(cr.resources, resourceID{ groupResource: action.GetResource().GroupResource().String(), @@ -3646,7 +3639,7 @@ func assertAPIContents(t *testing.T, h *harness, want map[*test.APIResource][]st for r, want := range want { res, err := h.DynamicClient.Resource(r.GVR()).List(context.TODO(), metav1.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) if err != nil { continue } diff --git a/pkg/test/comparisons.go b/pkg/test/comparisons.go index 677c39449e..ab5d5c62b2 100644 --- a/pkg/test/comparisons.go +++ b/pkg/test/comparisons.go @@ -111,14 +111,14 @@ func AssertDeepEqual(t *testing.T, expected, actual interface{}) bool { return true } -// AssertErrorMatches asserts that if expected is the empty string, actual +// RequireErrorMatches asserts that if expected is the empty string, actual // is nil, otherwise, that actual's error string matches expected. -func AssertErrorMatches(t *testing.T, expected string, actual error) bool { +func RequireErrorMatches(t *testing.T, expected string, actual error) { if expected != "" { - return assert.EqualError(t, actual, expected) + require.EqualError(t, actual, expected) + return } - - return assert.NoError(t, actual) + require.NoError(t, actual) } func CompareSlice(x, y []string) bool { diff --git a/pkg/uploader/kopia/shim_test.go b/pkg/uploader/kopia/shim_test.go index c3fe1ad42b..524b3b0e36 100644 --- a/pkg/uploader/kopia/shim_test.go +++ b/pkg/uploader/kopia/shim_test.go @@ -115,7 +115,7 @@ func TestOpenObject(t *testing.T) { assert.Nil(t, reader) } else { assert.NotNil(t, reader) - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -154,7 +154,7 @@ func TestFindManifests(t *testing.T) { if tc.isGetManifestError { require.ErrorContains(t, err, "failed") } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -278,9 +278,9 @@ func TestReplaceManifests(t *testing.T) { id, err := NewShimRepo(tc.backupRepo).ReplaceManifests(ctx, map[string]string{}, nil) if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, tc.expectedID, id) @@ -341,9 +341,9 @@ func TestConcatenateObjects(t *testing.T) { _, err := NewShimRepo(tc.backupRepo).ConcatenateObjects(ctx, tc.objectIDs) if tc.expectedError != "" { - assert.EqualError(t, err, tc.expectedError) + require.EqualError(t, err, tc.expectedError) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } diff --git a/pkg/uploader/kopia/snapshot_test.go b/pkg/uploader/kopia/snapshot_test.go index de621ce85b..6ce9b7abc6 100644 --- a/pkg/uploader/kopia/snapshot_test.go +++ b/pkg/uploader/kopia/snapshot_test.go @@ -87,7 +87,7 @@ func TestSnapshotSource(t *testing.T) { Path: "/var", } rootDir, err := getLocalFSEntry(sourceInfo.Path) - assert.NoError(t, err) + require.NoError(t, err) log := logrus.New() manifest := &snapshot.Manifest{ ID: "test", @@ -202,9 +202,9 @@ func TestSnapshotSource(t *testing.T) { MockFuncs(s, tc.args) _, _, err = SnapshotSource(ctx, s.repoWriterMock, s.uploderMock, sourceInfo, rootDir, false, "/", nil, tc.uploaderCfg, log, "TestSnapshotSource") if tc.notError { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.Error(t, err) + require.Error(t, err) } }) } @@ -563,7 +563,7 @@ func TestFindPreviousSnapshotManifest(t *testing.T) { if tc.expectedError != nil { require.ErrorContains(t, err, tc.expectedError.Error()) } else { - assert.NoError(t, err) + require.NoError(t, err) } // Check the number of returned snapshots @@ -656,7 +656,7 @@ func TestBackup(t *testing.T) { if tc.expectedError != nil { require.ErrorContains(t, err, tc.expectedError.Error()) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, tc.expectedEmpty, isSnapshotEmpty) @@ -795,7 +795,7 @@ func TestRestore(t *testing.T) { if tc.expectedError != nil { require.ErrorContains(t, err, tc.expectedError.Error()) } else { - assert.NoError(t, err) + require.NoError(t, err) } // Check the number of bytes restored diff --git a/pkg/uploader/provider/kopia_test.go b/pkg/uploader/provider/kopia_test.go index 7a7d5d2714..40f16a6b2d 100644 --- a/pkg/uploader/provider/kopia_test.go +++ b/pkg/uploader/provider/kopia_test.go @@ -108,9 +108,9 @@ func TestRunBackup(t *testing.T) { BackupFunc = tc.hookBackupFunc _, _, err := kp.RunBackup(context.Background(), "var", "", nil, false, "", tc.volMode, map[string]string{}, &updater) if tc.notError { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.Error(t, err) + require.Error(t, err) } }) } @@ -159,9 +159,9 @@ func TestRunRestore(t *testing.T) { RestoreFunc = tc.hookRestoreFunc err := kp.RunRestore(context.Background(), "", "/var", tc.volMode, map[string]string{}, &updater) if tc.notError { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.Error(t, err) + require.Error(t, err) } }) } @@ -284,9 +284,9 @@ func TestGetPassword(t *testing.T) { password, err := kp.GetPassword(nil) if tc.expectError { - assert.Error(t, err, "Expected an error") + require.Error(t, err, "Expected an error") } else { - assert.NoError(t, err, "Expected no error") + require.NoError(t, err, "Expected no error") } assert.Equal(t, tc.expectedPass, password, "Expected password to match") @@ -383,7 +383,7 @@ func TestNewKopiaUploaderProvider(t *testing.T) { if tc.expectedError != "" { require.ErrorContains(t, err, tc.expectedError) } else { - assert.NoError(t, err) + require.NoError(t, err) } // Verify that the expected methods were called on the mocks. diff --git a/pkg/uploader/provider/provider_test.go b/pkg/uploader/provider/provider_test.go index 492a58a68e..0ffaf34a95 100644 --- a/pkg/uploader/provider/provider_test.go +++ b/pkg/uploader/provider/provider_test.go @@ -21,7 +21,6 @@ import ( "testing" "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -89,7 +88,7 @@ func TestNewUploaderProvider(t *testing.T) { } _, err := NewUploaderProvider(ctx, client, testCase.UploaderType, testCase.RequestorType, repoIdentifier, bsl, backupRepo, credGetter, repoKeySelector, log) if testCase.ExpectedError == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { require.ErrorContains(t, err, testCase.ExpectedError) } diff --git a/pkg/uploader/provider/restic_test.go b/pkg/uploader/provider/restic_test.go index 2ef72b134b..1f04d69799 100644 --- a/pkg/uploader/provider/restic_test.go +++ b/pkg/uploader/provider/restic_test.go @@ -312,7 +312,7 @@ func TestNewResticUploaderProvider(t *testing.T) { credGetter.On("Path", repoKeySelector).Return("temp-credentials", nil) }, checkFunc: func(provider Provider, err error) { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, provider) }, }, { @@ -321,7 +321,7 @@ func TestNewResticUploaderProvider(t *testing.T) { credGetter.On("Path", repoKeySelector).Return("", errors.New("error creating temp credentials file")) }, checkFunc: func(provider Provider, err error) { - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, provider) }, }, { @@ -333,7 +333,7 @@ func TestNewResticUploaderProvider(t *testing.T) { return "", errors.New("error writing CACert file") }, checkFunc: func(provider Provider, err error) { - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, provider) }, }, { @@ -348,7 +348,7 @@ func TestNewResticUploaderProvider(t *testing.T) { return nil, errors.New("error generating repository cmnd env") }, checkFunc: func(provider Provider, err error) { - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, provider) }, }, { @@ -363,7 +363,7 @@ func TestNewResticUploaderProvider(t *testing.T) { return nil, nil }, checkFunc: func(provider Provider, err error) { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, provider) }, }, @@ -380,7 +380,7 @@ func TestNewResticUploaderProvider(t *testing.T) { return nil, nil }, checkFunc: func(provider Provider, err error) { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, provider) }, }, diff --git a/pkg/uploader/types_test.go b/pkg/uploader/types_test.go index e92f20c798..42702931b3 100644 --- a/pkg/uploader/types_test.go +++ b/pkg/uploader/types_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidateUploaderType(t *testing.T) { @@ -36,9 +37,9 @@ func TestValidateUploaderType(t *testing.T) { t.Run(tt.name, func(t *testing.T) { msg, err := ValidateUploaderType(tt.input) if tt.wantErr != "" { - assert.EqualError(t, err, tt.wantErr) + require.EqualError(t, err, tt.wantErr) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, tt.wantMsg, msg) diff --git a/pkg/util/csi/volume_snapshot_test.go b/pkg/util/csi/volume_snapshot_test.go index 3876d96edb..cfd116c7bd 100644 --- a/pkg/util/csi/volume_snapshot_test.go +++ b/pkg/util/csi/volume_snapshot_test.go @@ -200,9 +200,9 @@ func TestWaitVolumeSnapshotReady(t *testing.T) { vs, err := WaitVolumeSnapshotReady(context.Background(), fakeClient.SnapshotV1(), test.vsName, test.namespace, time.Millisecond, velerotest.NewLogger()) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.expect, vs) @@ -286,9 +286,9 @@ func TestGetVolumeSnapshotContentForVolumeSnapshot(t *testing.T) { vs, err := GetVolumeSnapshotContentForVolumeSnapshot(test.snapshotObj, fakeClient.SnapshotV1()) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.expect, vs) @@ -352,9 +352,9 @@ func TestEnsureDeleteVS(t *testing.T) { err := EnsureDeleteVS(context.Background(), fakeSnapshotClient.SnapshotV1(), test.vsName, test.namespace, time.Millisecond) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -425,9 +425,9 @@ func TestEnsureDeleteVSC(t *testing.T) { err := EnsureDeleteVSC(context.Background(), fakeSnapshotClient.SnapshotV1(), test.vscName, time.Millisecond) if test.err != "" { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -646,9 +646,9 @@ func TestRetainVSC(t *testing.T) { returned, err := RetainVSC(context.Background(), fakeSnapshotClient.SnapshotV1(), test.vsc) if len(test.err) == 0 { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } if test.updated != nil { @@ -740,14 +740,14 @@ func TestRemoveVSCProtect(t *testing.T) { err := RemoveVSCProtect(context.Background(), fakeSnapshotClient.SnapshotV1(), test.vsc, test.timeout) if len(test.err) == 0 { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } if test.updated != nil { updated, err := fakeSnapshotClient.SnapshotV1().VolumeSnapshotContents().Get(context.Background(), test.vsc, metav1.GetOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.updated.Finalizers, updated.Finalizers) } @@ -955,7 +955,7 @@ func TestGetVolumeSnapshotClass(t *testing.T) { actualSnapshotClass, actualError := GetVolumeSnapshotClass( tc.driverName, tc.backup, tc.pvc, logrus.New(), fakeClient) if tc.expectError { - assert.Error(t, actualError) + require.Error(t, actualError) assert.Nil(t, actualSnapshotClass) return } @@ -1070,7 +1070,7 @@ func TestGetVolumeSnapshotClassForStorageClass(t *testing.T) { actualVSC, actualError := GetVolumeSnapshotClassForStorageClass(tc.driverName, snapshotClasses) if tc.expectError { - assert.Error(t, actualError) + require.Error(t, actualError) assert.Nil(t, actualVSC) return } @@ -1361,16 +1361,16 @@ func TestSetVolumeSnapshotContentDeletionPolicy(t *testing.T) { fakeClient := velerotest.NewFakeControllerRuntimeClient(t, tc.objs...) err := SetVolumeSnapshotContentDeletionPolicy(tc.inputVSCName, fakeClient) if tc.expectError { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) actual := new(snapshotv1api.VolumeSnapshotContent) err := fakeClient.Get( context.TODO(), crclient.ObjectKey{Name: tc.inputVSCName}, actual, ) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal( t, snapshotv1api.VolumeSnapshotContentDelete, @@ -1647,7 +1647,7 @@ func TestWaitUntilVSCHandleIsReady(t *testing.T) { t.Run(tc.name, func(t *testing.T) { actualVSC, actualError := WaitUntilVSCHandleIsReady(tc.volSnap, fakeClient, logrus.New().WithField("fake", "test"), tc.wait, 0) if tc.expectError && actualError == nil { - assert.Error(t, actualError) + require.Error(t, actualError) assert.Nil(t, actualVSC) return } diff --git a/pkg/util/kube/pod_test.go b/pkg/util/kube/pod_test.go index 7ccb225781..32ad3fb93d 100644 --- a/pkg/util/kube/pod_test.go +++ b/pkg/util/kube/pod_test.go @@ -25,6 +25,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1api "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -90,9 +91,9 @@ func TestEnsureDeletePod(t *testing.T) { err := EnsureDeletePod(context.Background(), kubeClient.CoreV1(), test.podName, test.namespace, time.Millisecond) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -175,9 +176,9 @@ func TestIsPodRunning(t *testing.T) { t.Run(test.name, func(t *testing.T) { err := IsPodRunning(test.pod) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -275,9 +276,9 @@ func TestIsPodScheduled(t *testing.T) { t.Run(test.name, func(t *testing.T) { err := IsPodScheduled(test.pod) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -691,7 +692,7 @@ func TestCollectPodLogs(t *testing.T) { if test.expectErr != "" { assert.EqualError(t, err, test.expectErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, fp.outputMessage, test.message) } }) diff --git a/pkg/util/kube/pvc_pv_test.go b/pkg/util/kube/pvc_pv_test.go index 5f6c3be74d..564b22befd 100644 --- a/pkg/util/kube/pvc_pv_test.go +++ b/pkg/util/kube/pvc_pv_test.go @@ -23,6 +23,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes" @@ -125,9 +126,9 @@ func TestWaitPVCBound(t *testing.T) { pv, err := WaitPVCBound(context.Background(), kubeClient.CoreV1(), kubeClient.CoreV1(), test.pvcName, test.pvcNamespace, time.Millisecond) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.expected, pv) @@ -278,9 +279,9 @@ func TestWaitPVCConsumed(t *testing.T) { selectedNode, pvc, err := WaitPVCConsumed(context.Background(), kubeClient.CoreV1(), test.pvcName, test.pvcNamespace, kubeClient.StorageV1(), time.Millisecond) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.expectedPVC, pvc) @@ -663,9 +664,9 @@ func TestEnsureDeletePVC(t *testing.T) { err := EnsureDeletePVC(context.Background(), kubeClient.CoreV1(), test.pvcName, test.namespace, test.timeout) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -737,9 +738,9 @@ func TestRebindPVC(t *testing.T) { result, err := RebindPVC(context.Background(), kubeClient.CoreV1(), test.pvc, test.pv) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.result, result) @@ -844,9 +845,9 @@ func TestResetPVBinding(t *testing.T) { result, err := ResetPVBinding(context.Background(), kubeClient.CoreV1(), test.pv, test.labels, test.pvc) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.result, result) @@ -922,9 +923,9 @@ func TestSetPVReclaimPolicy(t *testing.T) { result, err := SetPVReclaimPolicy(context.Background(), kubeClient.CoreV1(), test.pv, test.policy) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.result, result) @@ -1073,9 +1074,9 @@ func TestWaitPVBound(t *testing.T) { pv, err := WaitPVBound(context.Background(), kubeClient.CoreV1(), test.pvName, test.pvcName, test.pvcNamespace, time.Millisecond) if err != nil { - assert.EqualError(t, err, test.err) + require.EqualError(t, err, test.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, test.expectedPV, pv) @@ -1248,12 +1249,12 @@ func TestGetPVForPVC(t *testing.T) { actualPV, actualError := GetPVForPVC(tc.inPVC, fakeClient) if tc.expectError { - assert.Error(t, actualError, "Want error; Got nil error") + require.Error(t, actualError, "Want error; Got nil error") assert.Nilf(t, actualPV, "Want PV: nil; Got PV: %q", actualPV) return } - assert.NoErrorf(t, actualError, "Want: nil error; Got: %v", actualError) + require.NoErrorf(t, actualError, "Want: nil error; Got: %v", actualError) assert.Equalf(t, actualPV.Name, tc.expectedPV.Name, "Want PV with name %q; Got PV with name %q", tc.expectedPV.Name, actualPV.Name) }) } @@ -1371,11 +1372,11 @@ func TestGetPVCForPodVolume(t *testing.T) { t.Run(tc.name, func(t *testing.T) { actualPVC, actualError := GetPVCForPodVolume(tc.vol, samplePod, fakeClient) if tc.expectedError { - assert.Error(t, actualError, "Want error; Got nil error") + require.Error(t, actualError, "Want error; Got nil error") assert.Nilf(t, actualPVC, "Want PV: nil; Got PV: %q", actualPVC) return } - assert.NoErrorf(t, actualError, "Want: nil error; Got: %v", actualError) + require.NoErrorf(t, actualError, "Want: nil error; Got: %v", actualError) assert.Equalf(t, actualPVC.Name, tc.expectedPVC.Name, "Want PVC with name %q; Got PVC with name %q", tc.expectedPVC.Name, actualPVC) }) } diff --git a/pkg/util/kube/resource_requirements_test.go b/pkg/util/kube/resource_requirements_test.go index 68bdfc4970..e4bbc3d6e0 100644 --- a/pkg/util/kube/resource_requirements_test.go +++ b/pkg/util/kube/resource_requirements_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" ) @@ -75,10 +76,10 @@ func TestParseResourceRequirements(t *testing.T) { t.Run(tt.name, func(t *testing.T) { got, err := ParseResourceRequirements(tt.args.cpuRequest, tt.args.memRequest, tt.args.cpuLimit, tt.args.memLimit) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) var expected corev1.ResourceRequirements if tt.expected == nil { diff --git a/pkg/util/kube/security_context_test.go b/pkg/util/kube/security_context_test.go index 64a9a22cb8..e77a750c7d 100644 --- a/pkg/util/kube/security_context_test.go +++ b/pkg/util/kube/security_context_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" "github.com/vmware-tanzu/velero/pkg/util/boolptr" @@ -257,10 +258,10 @@ allowPrivilegeEscalation: false`}, t.Run(tt.name, func(t *testing.T) { got, err := ParseSecurityContext(tt.args.runAsUser, tt.args.runAsGroup, tt.args.allowPrivilegeEscalation, tt.args.secCtx) if err != nil && tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) if tt.expected == nil { tt.expected = &corev1.SecurityContext{} diff --git a/pkg/util/kube/utils_test.go b/pkg/util/kube/utils_test.go index 6feb9bd946..bb3f1dc422 100644 --- a/pkg/util/kube/utils_test.go +++ b/pkg/util/kube/utils_test.go @@ -469,7 +469,7 @@ func TestIsCRDReady(t *testing.T) { err := json.Unmarshal(resBytes, obj) require.NoError(t, err) _, err = IsCRDReady(obj) - assert.Error(t, err) + require.Error(t, err) } func TestSinglePathMatch(t *testing.T) { @@ -478,7 +478,7 @@ func TestSinglePathMatch(t *testing.T) { fakeFS.MkdirAll("testDir2/subpath", 0755) _, err := SinglePathMatch("./*/subpath", fakeFS, logrus.StandardLogger()) - assert.Error(t, err) + require.Error(t, err) require.ErrorContains(t, err, "expected one matching path") } diff --git a/pkg/util/logging/error_location_hook_test.go b/pkg/util/logging/error_location_hook_test.go index 1dd73d6936..734122b49d 100644 --- a/pkg/util/logging/error_location_hook_test.go +++ b/pkg/util/logging/error_location_hook_test.go @@ -166,7 +166,7 @@ func TestGetInnermostTrace(t *testing.T) { res := getInnermostTrace(test.err) if test.expectedRes == nil { - assert.NoError(t, res) + require.NoError(t, res) return } diff --git a/pkg/util/logging/log_counter_hook_test.go b/pkg/util/logging/log_counter_hook_test.go index 2043543149..1afd2bc292 100644 --- a/pkg/util/logging/log_counter_hook_test.go +++ b/pkg/util/logging/log_counter_hook_test.go @@ -7,6 +7,7 @@ import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/vmware-tanzu/velero/pkg/util/results" ) @@ -26,7 +27,7 @@ func TestLogHook_Fire(t *testing.T) { } err := hook.Fire(entry) - assert.NoError(t, err) + require.NoError(t, err) // Verify the counts assert.Equal(t, 1, hook.counts[logrus.ErrorLevel]) @@ -47,7 +48,7 @@ func TestLogHook_Fire(t *testing.T) { } err = hook.Fire(entry1) - assert.NoError(t, err) + require.NoError(t, err) // Verify the counts assert.Equal(t, 2, hook.counts[logrus.ErrorLevel]) diff --git a/pkg/util/logging/log_merge_hook_test.go b/pkg/util/logging/log_merge_hook_test.go index d103152b82..f894a8bcca 100644 --- a/pkg/util/logging/log_merge_hook_test.go +++ b/pkg/util/logging/log_merge_hook_test.go @@ -68,7 +68,7 @@ func TestMergeHook_Fire(t *testing.T) { // method under test err := hook.Fire(&test.entry) - assert.NoError(t, err) + require.NoError(t, err) if test.expectHook { assert.NotNil(t, test.entry.Logger.Out.(*hookWriter)) @@ -161,7 +161,7 @@ func TestMergeHook_Write(t *testing.T) { n, err := writer.Write(test.content) if test.expectError == "" { - assert.NoError(t, err) + require.NoError(t, err) expectStr := string(test.content) if expectStr == ListeningMessage { @@ -174,7 +174,7 @@ func TestMergeHook_Write(t *testing.T) { writtenStr := string(fakeWriter.p) assert.Equal(t, writtenStr, expectStr) } else { - assert.EqualError(t, err, test.expectError) + require.EqualError(t, err, test.expectError) } if test.needRollBackHook { diff --git a/pkg/util/podvolume/pod_volume_test.go b/pkg/util/podvolume/pod_volume_test.go index 9f6738a652..26787a0bdb 100644 --- a/pkg/util/podvolume/pod_volume_test.go +++ b/pkg/util/podvolume/pod_volume_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1api "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -669,7 +670,7 @@ func TestGetPodVolumeNameForPVC(t *testing.T) { t.Run(tc.name, func(t *testing.T) { actualVolumeName, err := getPodVolumeNameForPVC(tc.pod, tc.pvcName) if tc.expectError && err == nil { - assert.Error(t, err, "Want error; Got nil error") + require.Error(t, err, "Want error; Got nil error") return } assert.Equalf(t, tc.expectedVolumeName, actualVolumeName, "unexpected podVolumename returned. Want %s; Got %s", tc.expectedVolumeName, actualVolumeName) @@ -787,7 +788,7 @@ func TestGetPodsUsingPVC(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { actualPods, err := GetPodsUsingPVC(tc.pvcNamespace, tc.pvcName, fakeClient) - assert.NoErrorf(t, err, "Want error=nil; Got error=%v", err) + require.NoErrorf(t, err, "Want error=nil; Got error=%v", err) assert.Lenf(t, actualPods, tc.expectedPodCount, "unexpected number of pods in result; Want: %d; Got: %d", tc.expectedPodCount, len(actualPods)) }) }