From f0827d5b703edaa6d67a96fbc3d7c720ed66e431 Mon Sep 17 00:00:00 2001 From: Tom Wieczorek Date: Tue, 12 Nov 2024 14:46:25 +0100 Subject: [PATCH] Enable testifylint linter ... and fix lints on the way. Also add the f suffix for methods that are using format strings. This enables the linting of the strings against their varargs list. Signed-off-by: Tom Wieczorek --- .golangci.yml | 7 +++ internal/http/download_test.go | 2 +- internal/oci/download_test.go | 2 +- internal/pkg/dir/dir_test.go | 2 +- internal/pkg/file/atomic_test.go | 30 +++++------ internal/pkg/flags/flags_test.go | 14 ++--- .../pkg/sysinfo/probes/linux/kernel_test.go | 2 +- .../pkg/sysinfo/probes/memory_linux_test.go | 4 +- inttest/addons/addons_test.go | 2 +- inttest/airgap/airgap_test.go | 2 +- inttest/ap-airgap/airgap_test.go | 4 +- .../controllerworker_test.go | 17 +++--- .../ap-platformselect/platformselect_test.go | 15 +++--- inttest/ap-quorum/quorum_test.go | 17 +++--- inttest/ap-selector/selector_test.go | 23 ++++---- inttest/ap-single/single_test.go | 17 +++--- inttest/backup/backup_test.go | 15 ++---- inttest/basic/basic_test.go | 2 +- inttest/cli/cli_test.go | 23 ++++---- inttest/common/bootloosesuite.go | 2 +- inttest/cplb/cplb_test.go | 4 +- inttest/dualstack/dualstack_test.go | 6 +-- inttest/etcdmember/etcdmember_test.go | 4 +- inttest/kine/kine_test.go | 20 ++++--- inttest/kubectl/kubectl_test.go | 4 +- .../kubeletcertrotate_test.go | 23 ++++---- inttest/network-conformance/network_test.go | 2 +- inttest/stackapplier/stackapplier_test.go | 6 ++- .../k0s/v1beta1/clusterconfig_types_test.go | 13 +++-- pkg/apis/k0s/v1beta1/cplb_test.go | 13 ++--- pkg/apis/k0s/v1beta1/storage_test.go | 2 +- .../airgapupdate/schedulable_test.go | 5 +- .../airgapupdate/schedulablewait_test.go | 11 +--- .../cmdprovider/k0supdate/schedulable_test.go | 5 +- .../k0supdate/schedulablewait_test.go | 16 +----- .../plans/core/initprovidershandler_test.go | 6 ++- .../plans/core/planstatecontroller_test.go | 7 +-- .../plans/core/planstatehandler_test.go | 6 ++- pkg/autopilot/controller/plans/init_test.go | 9 ++-- .../controller/plans/predicate_test.go | 16 +++--- .../controller/signal/airgap/init_test.go | 2 +- .../controller/signal/airgap/signal_test.go | 5 +- .../signal/common/predicate/predicate_test.go | 4 +- .../controller/signal/common/signal_test.go | 3 +- .../controller/signal/k0s/apply_test.go | 5 +- .../controller/signal/k0s/download_test.go | 5 +- .../controller/signal/k0s/init_test.go | 2 +- .../controller/signal/k0s/signal_test.go | 7 ++- .../signaling/v2/signaling_v2_test.go | 28 +++++++--- pkg/backup/filesystem_unix_test.go | 4 +- pkg/component/controller/calico_test.go | 14 ++--- pkg/component/controller/csrapprover_test.go | 2 +- .../controller/extensions_controller_test.go | 6 +-- .../controller/k0scloudprovider_test.go | 13 +++-- pkg/component/controller/kuberouter_test.go | 4 +- pkg/component/worker/config/config_test.go | 2 +- pkg/component/worker/nllb/envoy_test.go | 6 +-- pkg/component/worker/nllb/reconciler_test.go | 2 +- pkg/component/worker/ocibundle_test.go | 54 +++++++++---------- pkg/component/worker/static_pods_test.go | 2 +- pkg/constant/constant_test.go | 9 ++-- pkg/k0scontext/context_test.go | 6 +-- pkg/kubernetes/lease_test.go | 4 +- pkg/kubernetes/watch/watcher_test.go | 2 +- pkg/node/nodehostname_test.go | 14 ++--- pkg/supervisor/logwriter_test.go | 10 ++-- pkg/supervisor/supervisor_test.go | 2 +- 67 files changed, 298 insertions(+), 299 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index fc415a734044..47d1413f32ae 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,6 +17,7 @@ linters: - gofmt # Checks whether code was gofmt-ed - goheader # Checks is file headers matche a given pattern - revive # Stricter drop-in replacement for golint + - testifylint # Checks usage of github.com/stretchr/testify linters-settings: depguard: @@ -71,6 +72,12 @@ linters-settings: - name: redefines-builtin-id disabled: true + testifylint: + enable-all: true + disable: + - require-error # flags too many legitimate use cases + - suite-thelper # flags too many legitimate use cases + issues: max-issues-per-linter: 0 max-same-issues: 0 diff --git a/internal/http/download_test.go b/internal/http/download_test.go index 79525949090f..02c791a33afa 100644 --- a/internal/http/download_test.go +++ b/internal/http/download_test.go @@ -209,7 +209,7 @@ func startFakeDownloadServer(t *testing.T, usetls bool, handler http.Handler) st assert.NoError(t, err) cert, err := tls.X509KeyPair(certData, keyData) - require.NoError(t, err) + assert.NoError(t, err) server.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}} serverError <- server.ServeTLS(listener, "", "") diff --git a/internal/oci/download_test.go b/internal/oci/download_test.go index e095f087080a..b860e5e104e2 100644 --- a/internal/oci/download_test.go +++ b/internal/oci/download_test.go @@ -128,7 +128,7 @@ func startOCIMockServer(t *testing.T, tname string, test testFile) string { server := starter( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Log(r.Proto, r.Method, r.RequestURI) - if !assert.Equal(t, r.Method, http.MethodGet) { + if !assert.Equal(t, http.MethodGet, r.Method) { w.WriteHeader(http.StatusMethodNotAllowed) return } diff --git a/internal/pkg/dir/dir_test.go b/internal/pkg/dir/dir_test.go index b850ddd4e33b..e10c6891a92c 100644 --- a/internal/pkg/dir/dir_test.go +++ b/internal/pkg/dir/dir_test.go @@ -36,7 +36,7 @@ func TestGetAll(t *testing.T) { t.Run("filter dirs", func(t *testing.T) { tmpDir := t.TempDir() require.NoError(t, dir.Init(filepath.Join(tmpDir, "dir1"), 0750)) - require.NoError(t, os.WriteFile(filepath.Join(tmpDir, "file1"), []byte{}, 0600), "Unable to create file %s:", "file1") + require.NoError(t, os.WriteFile(filepath.Join(tmpDir, "file1"), []byte{}, 0600)) dirs, err := dir.GetAll(tmpDir) require.NoError(t, err) require.Equal(t, []string{"dir1"}, dirs) diff --git a/internal/pkg/file/atomic_test.go b/internal/pkg/file/atomic_test.go index eb2b313e9d26..db33d9aac5b2 100644 --- a/internal/pkg/file/atomic_test.go +++ b/internal/pkg/file/atomic_test.go @@ -74,7 +74,7 @@ func TestWriteAtomically(t *testing.T) { assertPathError := func(t *testing.T, err error, op, dir string) (pathErr *os.PathError, ok bool) { t.Helper() - if ok = assert.True(t, errors.As(err, &pathErr), "Not a PathError: %v", err); ok { + if assert.ErrorAsf(t, err, &pathErr, "Not a PathError: %v", err) { assert.Equal(t, op, pathErr.Op) assert.Equal( t, dir, filepath.Dir(pathErr.Path), @@ -135,7 +135,7 @@ func TestWriteAtomically(t *testing.T) { errs := flatten(WriteAtomically(file, 0644, func(file io.Writer) error { a, ok := file.(*Atomic) - require.True(t, ok, "Not an Atomic: %T", file) + require.Truef(t, ok, "Not an Atomic: %T", file) require.NoError(t, a.fd.Close()) return nil })) @@ -146,7 +146,7 @@ func TestWriteAtomically(t *testing.T) { // The first error should be about the failed attempt to sync the temporary file. if err, ok := assertPathError(t, errs[0], "sync", dir); ok { tempPath = err.Path - assert.True(t, errors.Is(err, fs.ErrClosed), "Expected fs.ErrClosed: %v", err.Err) + assert.ErrorIsf(t, err, fs.ErrClosed, "Expected fs.ErrClosed: %v", err.Err) } // The second error should be about the failed attempt to close the temporary file. @@ -154,7 +154,7 @@ func TestWriteAtomically(t *testing.T) { if tempPath != "" { assert.Equal(t, tempPath, err.Path, "Temp paths differ between errors") } - assert.True(t, errors.Is(err, fs.ErrClosed), "Expected fs.ErrClosed: %v", err.Err) + assert.ErrorIsf(t, err, fs.ErrClosed, "Expected fs.ErrClosed: %v", err.Err) } assertDirEmpty(t, dir) @@ -170,7 +170,7 @@ func TestWriteAtomically(t *testing.T) { var tempPath string err := WriteAtomically(file, 0644, func(file io.Writer) error { a, ok := file.(*Atomic) - require.True(t, ok, "Not an Atomic: %T", file) + require.Truef(t, ok, "Not an Atomic: %T", file) tempPath = a.fd.Name() require.Equal(t, dir, filepath.Dir(tempPath)) if runtime.GOOS == "windows" { @@ -185,7 +185,7 @@ func TestWriteAtomically(t *testing.T) { // The error should be about the failed chmod. if err, ok := assertPathError(t, err, "chmod", dir); ok { assert.Equal(t, tempPath, err.Path, "Error refers to unexpected path") - assert.True(t, errors.Is(err, fs.ErrNotExist), "Expected fs.ErrNotExist: %v", err.Err) + assert.ErrorIsf(t, err, fs.ErrNotExist, "Expected fs.ErrNotExist: %v", err.Err) } assertDirEmpty(t, dir) @@ -206,7 +206,7 @@ func TestWriteAtomically(t *testing.T) { require.Len(t, errs, 1) var linkErr *os.LinkError - if assert.True(t, errors.As(errs[0], &linkErr), "Not a LinkError: %#+v", errs[0]) { + if assert.ErrorAsf(t, errs[0], &linkErr, "Not a LinkError: %#+v", errs[0]) { assert.Equal(t, "rename", linkErr.Op) assert.Equal( t, dir, filepath.Dir(linkErr.Old), @@ -220,9 +220,9 @@ func TestWriteAtomically(t *testing.T) { var errno syscall.Errno ok := errors.As(linkErr.Err, &errno) ok = ok && errno == ERROR_ACCESS_DENIED - assert.True(t, ok, "Expected ERROR_ACCESS_DENIED: %v", linkErr.Err) + assert.Truef(t, ok, "Expected ERROR_ACCESS_DENIED: %v", linkErr.Err) } else { - assert.True(t, errors.Is(linkErr.Err, fs.ErrExist), "Expected fs.ErrExist: %v", linkErr.Err) + assert.ErrorIsf(t, linkErr.Err, fs.ErrExist, "Expected fs.ErrExist: %v", linkErr.Err) } } @@ -231,7 +231,7 @@ func TestWriteAtomically(t *testing.T) { e := entries[0] name := e.Name() assert.Equal(t, filepath.Base(file), name) - assert.True(t, e.IsDir(), "Not a directory: %s", name) + assert.Truef(t, e.IsDir(), "Not a directory: %s", name) } }) @@ -246,7 +246,7 @@ func TestWriteAtomically(t *testing.T) { var tempPath string errs := flatten(WriteAtomically(file, 0755, func(file io.Writer) error { a, ok := file.(*Atomic) - require.True(t, ok, "Not an Atomic: %T", file) + require.Truef(t, ok, "Not an Atomic: %T", file) tempPath = a.fd.Name() require.Equal(t, dir, filepath.Dir(tempPath)) @@ -274,23 +274,23 @@ func TestWriteAtomically(t *testing.T) { // The first error should be about the failed rename. var linkErr *os.LinkError - if assert.True(t, errors.As(errs[0], &linkErr), "Not a LinkError: %v", linkErr) { + if assert.ErrorAsf(t, errs[0], &linkErr, "Not a LinkError: %v", linkErr) { assert.Equal(t, "rename", linkErr.Op) assert.Equal(t, tempPath, linkErr.Old, "Error refers to unexpected path") assert.Equal(t, file, linkErr.New) - assert.True(t, errors.Is(linkErr.Err, fs.ErrExist), "Expected fs.ErrExist: %v", linkErr.Err) + assert.ErrorIsf(t, linkErr.Err, fs.ErrExist, "Expected fs.ErrExist: %v", linkErr.Err) } // The second error should be about the failed removal. if err, ok := assertPathError(t, errs[1], "remove", dir); ok { assert.Equal(t, tempPath, err.Path, "Error refers to unexpected path") - assert.True(t, errors.Is(err, fs.ErrExist), "Expected fs.ErrExist: %v", err.Err) + assert.ErrorIsf(t, err, fs.ErrExist, "Expected fs.ErrExist: %v", err.Err) } // Expect to see two directories left behind. if entries, err := os.ReadDir(dir); assert.NoError(t, err) && assert.Len(t, entries, 2) { for _, e := range entries { - assert.True(t, e.IsDir(), "Not a directory: %s", e.Name()) + assert.Truef(t, e.IsDir(), "Not a directory: %s", e.Name()) } } }) diff --git a/internal/pkg/flags/flags_test.go b/internal/pkg/flags/flags_test.go index 3a31e57e24b1..f4dbe3a5966c 100644 --- a/internal/pkg/flags/flags_test.go +++ b/internal/pkg/flags/flags_test.go @@ -19,6 +19,8 @@ package flags import ( "testing" + "github.com/k0sproject/k0s/internal/pkg/stringmap" + "github.com/stretchr/testify/assert" ) @@ -27,10 +29,11 @@ func TestFlagSplitting(t *testing.T) { m := Split(args) - assert.Equal(t, 3, len(m)) - assert.Equal(t, "bar", m["--foo"]) - assert.Equal(t, "xyz,asd", m["--foobar"]) - assert.Equal(t, "", m["--bool-flag"]) + assert.Equal(t, stringmap.StringMap{ + "--foo": "bar", + "--foobar": "xyz,asd", + "--bool-flag": "", + }, m) } func TestFlagSplittingBoolFlags(t *testing.T) { @@ -38,6 +41,5 @@ func TestFlagSplittingBoolFlags(t *testing.T) { m := Split(args) - assert.Equal(t, 1, len(m)) - assert.Equal(t, "", m["--bool-flag"]) + assert.Equal(t, stringmap.StringMap{"--bool-flag": ""}, m) } diff --git a/internal/pkg/sysinfo/probes/linux/kernel_test.go b/internal/pkg/sysinfo/probes/linux/kernel_test.go index 0e50329a0ad8..0d9a55223864 100644 --- a/internal/pkg/sysinfo/probes/linux/kernel_test.go +++ b/internal/pkg/sysinfo/probes/linux/kernel_test.go @@ -116,7 +116,7 @@ func TestKConfigProber(t *testing.T) { probeKConfig := newKConfigProber(newUnameProber()) option, err := probeKConfig(ensureKConfig("I_CERTAINLY_DONT_EXIST")) - assert.Equal(t, option, kConfigUnknown) + assert.Equal(t, kConfigUnknown, option) var notFoundErr *noKConfigsFound if errors.As(err, ¬FoundErr) { t.Logf("System doesn't seem to expose its kernel config: %v", err) diff --git a/internal/pkg/sysinfo/probes/memory_linux_test.go b/internal/pkg/sysinfo/probes/memory_linux_test.go index 936fac8571fe..e3a641c3bd64 100644 --- a/internal/pkg/sysinfo/probes/memory_linux_test.go +++ b/internal/pkg/sysinfo/probes/memory_linux_test.go @@ -51,8 +51,8 @@ func TestTotalMemoryProber(t *testing.T) { line := lines.Text() if matches := re.FindStringSubmatch(line); matches != nil { kibiBytes, err := strconv.ParseUint(matches[1], 10, 64) - require.NoError(t, err, "expected an unsigned integer: %s", line) - require.Equal(t, kibiBytes*1024, ram, "/proc/meminfo differs: %s", line) + require.NoErrorf(t, err, "expected an unsigned integer: %s", line) + require.Equalf(t, kibiBytes*1024, ram, "/proc/meminfo differs: %s", line) return } } diff --git a/inttest/addons/addons_test.go b/inttest/addons/addons_test.go index d9e209498f96..a74f96d9c411 100644 --- a/inttest/addons/addons_test.go +++ b/inttest/addons/addons_test.go @@ -114,7 +114,7 @@ func (as *AddonsSuite) renameChart(ctx context.Context) { i := slices.IndexFunc(cfg.Spec.Extensions.Helm.Charts, func(c k0sv1beta1.Chart) bool { return c.Name == "tgz-addon" }) - as.Require().GreaterOrEqual(i, 0, "Didn't find tgz-addon in %v", cfg.Spec.Extensions.Helm.Charts) + as.Require().GreaterOrEqualf(i, 0, "Didn't find tgz-addon in %v", cfg.Spec.Extensions.Helm.Charts) cfg.Spec.Extensions.Helm.Charts[i].Name = "tgz-renamed-addon" cfg, err = configs.Update(ctx, cfg, metav1.UpdateOptions{FieldManager: as.T().Name()}) diff --git a/inttest/airgap/airgap_test.go b/inttest/airgap/airgap_test.go index 2bfb0b852cd4..5455c3f6ada1 100644 --- a/inttest/airgap/airgap_test.go +++ b/inttest/airgap/airgap_test.go @@ -94,7 +94,7 @@ func (s *AirgapSuite) TestK0sGetsUp() { for _, i := range airgap.GetImageURIs(v1beta1.DefaultClusterSpec(), true) { output, err := ssh.ExecWithOutput(ctx, fmt.Sprintf(`k0s ctr i ls "name==%s"`, i)) s.Require().NoError(err) - s.Require().Contains(output, "io.cri-containerd.pinned=pinned", "expected %s image to have io.cri-containerd.pinned=pinned label", i) + s.Require().Containsf(output, "io.cri-containerd.pinned=pinned", "expected %s image to have io.cri-containerd.pinned=pinned label", i) } } diff --git a/inttest/ap-airgap/airgap_test.go b/inttest/ap-airgap/airgap_test.go index 5fc8513aab3a..ffb66db68011 100644 --- a/inttest/ap-airgap/airgap_test.go +++ b/inttest/ap-airgap/airgap_test.go @@ -82,7 +82,7 @@ func (s *airgapSuite) SetupTest() { continue // The pause image is pinned by containerd itself } output, err := ssh.ExecWithOutput(ctx, fmt.Sprintf(`k0s ctr i ls "name==%s"`, i)) - if s.NoError(err, "Failed to check %s", i) { + if s.NoErrorf(err, "Failed to check %s", i) { s.NotContains(output, "io.cri-containerd.pinned=pinned", "%s is already pinned", i) } } @@ -197,7 +197,7 @@ spec: defer ssh.Disconnect() for _, i := range airgap.GetImageURIs(v1beta1.DefaultClusterSpec(), true) { output, err := ssh.ExecWithOutput(ctx, fmt.Sprintf(`k0s ctr i ls "name==%s"`, i)) - if s.NoError(err, "Failed to check %s", i) { + if s.NoErrorf(err, "Failed to check %s", i) { s.Contains(output, "io.cri-containerd.pinned=pinned", "%s is not pinned", i) } } diff --git a/inttest/ap-controllerworker/controllerworker_test.go b/inttest/ap-controllerworker/controllerworker_test.go index 7fa1e07b32ca..bcb12994558b 100644 --- a/inttest/ap-controllerworker/controllerworker_test.go +++ b/inttest/ap-controllerworker/controllerworker_test.go @@ -156,16 +156,17 @@ spec: plan, err := aptest.WaitForPlanState(ctx, client, apconst.AutopilotName, appc.PlanCompleted) s.Require().NoError(err) - s.Equal(1, len(plan.Status.Commands)) - cmd := plan.Status.Commands[0] + if s.Len(plan.Status.Commands, 1) { + cmd := plan.Status.Commands[0] - s.Equal(appc.PlanCompleted, cmd.State) - s.NotNil(cmd.K0sUpdate) - s.NotNil(cmd.K0sUpdate.Controllers) - s.Empty(cmd.K0sUpdate.Workers) + s.Equal(appc.PlanCompleted, cmd.State) + s.NotNil(cmd.K0sUpdate) + s.NotNil(cmd.K0sUpdate.Controllers) + s.Empty(cmd.K0sUpdate.Workers) - for _, node := range cmd.K0sUpdate.Controllers { - s.Equal(appc.SignalCompleted, node.State) + for _, node := range cmd.K0sUpdate.Controllers { + s.Equal(appc.SignalCompleted, node.State) + } } kc, err := s.KubeClient(s.ControllerNode(0)) diff --git a/inttest/ap-platformselect/platformselect_test.go b/inttest/ap-platformselect/platformselect_test.go index 0f9c5eb9693f..a260685923e9 100644 --- a/inttest/ap-platformselect/platformselect_test.go +++ b/inttest/ap-platformselect/platformselect_test.go @@ -96,13 +96,14 @@ spec: plan, err := aptest.WaitForPlanState(ctx, client, apconst.AutopilotName, appc.PlanCompleted) s.Require().NoError(err) - s.Equal(1, len(plan.Status.Commands)) - cmd := plan.Status.Commands[0] - - s.NotNil(cmd.K0sUpdate) - s.NotNil(cmd.K0sUpdate.Controllers) - s.NotEmpty(cmd.K0sUpdate.Controllers) - s.Equal(appc.SignalCompleted, cmd.K0sUpdate.Controllers[0].State) + if s.Len(plan.Status.Commands, 1) { + cmd := plan.Status.Commands[0] + + s.NotNil(cmd.K0sUpdate) + s.NotNil(cmd.K0sUpdate.Controllers) + s.NotEmpty(cmd.K0sUpdate.Controllers) + s.Equal(appc.SignalCompleted, cmd.K0sUpdate.Controllers[0].State) + } } // TestPlatformSelectSuite sets up a suite using a single controller, running various diff --git a/inttest/ap-quorum/quorum_test.go b/inttest/ap-quorum/quorum_test.go index fec18789ab1b..7ef52c08997d 100644 --- a/inttest/ap-quorum/quorum_test.go +++ b/inttest/ap-quorum/quorum_test.go @@ -118,16 +118,17 @@ spec: plan, err := aptest.WaitForPlanState(ctx, client, apconst.AutopilotName, appc.PlanCompleted) s.Require().NoError(err) - s.Equal(1, len(plan.Status.Commands)) - cmd := plan.Status.Commands[0] + if s.Len(plan.Status.Commands, 1) { + cmd := plan.Status.Commands[0] - s.Equal(appc.PlanCompleted, cmd.State) - s.NotNil(cmd.K0sUpdate) - s.NotNil(cmd.K0sUpdate.Controllers) - s.Empty(cmd.K0sUpdate.Workers) + s.Equal(appc.PlanCompleted, cmd.State) + s.NotNil(cmd.K0sUpdate) + s.NotNil(cmd.K0sUpdate.Controllers) + s.Empty(cmd.K0sUpdate.Workers) - for _, node := range cmd.K0sUpdate.Controllers { - s.Equal(appc.SignalCompleted, node.State) + for _, node := range cmd.K0sUpdate.Controllers { + s.Equal(appc.SignalCompleted, node.State) + } } } diff --git a/inttest/ap-selector/selector_test.go b/inttest/ap-selector/selector_test.go index 743c8c91cece..7a4d632b35a8 100644 --- a/inttest/ap-selector/selector_test.go +++ b/inttest/ap-selector/selector_test.go @@ -143,17 +143,18 @@ spec: plan, err := aptest.WaitForPlanState(ctx, client, apconst.AutopilotName, appc.PlanCompleted) s.Require().NoError(err) - s.Equal(1, len(plan.Status.Commands)) - cmd := plan.Status.Commands[0] - - s.Equal(appc.PlanCompleted, cmd.State) - s.NotNil(cmd.K0sUpdate) - s.NotNil(cmd.K0sUpdate.Controllers) - s.NotNil(cmd.K0sUpdate.Workers) - - for _, group := range [][]apv1beta2.PlanCommandTargetStatus{cmd.K0sUpdate.Controllers, cmd.K0sUpdate.Workers} { - for _, node := range group { - s.Equal(appc.SignalCompleted, node.State) + if s.Len(plan.Status.Commands, 1) { + cmd := plan.Status.Commands[0] + + s.Equal(appc.PlanCompleted, cmd.State) + s.NotNil(cmd.K0sUpdate) + s.NotNil(cmd.K0sUpdate.Controllers) + s.NotNil(cmd.K0sUpdate.Workers) + + for _, group := range [][]apv1beta2.PlanCommandTargetStatus{cmd.K0sUpdate.Controllers, cmd.K0sUpdate.Workers} { + for _, node := range group { + s.Equal(appc.SignalCompleted, node.State) + } } } } diff --git a/inttest/ap-single/single_test.go b/inttest/ap-single/single_test.go index 2a63c39b81db..66d63af80126 100644 --- a/inttest/ap-single/single_test.go +++ b/inttest/ap-single/single_test.go @@ -99,14 +99,15 @@ spec: plan, err := aptest.WaitForPlanState(ctx, client, apconst.AutopilotName, appc.PlanCompleted) s.Require().NoError(err, "While waiting for plan to complete") - s.Equal(1, len(plan.Status.Commands)) - cmd := plan.Status.Commands[0] - - s.Equal(appc.PlanCompleted, cmd.State) - s.NotNil(cmd.K0sUpdate) - s.NotNil(cmd.K0sUpdate.Controllers) - s.Empty(cmd.K0sUpdate.Workers) - s.Equal(appc.SignalCompleted, cmd.K0sUpdate.Controllers[0].State) + if s.Len(plan.Status.Commands, 1) { + cmd := plan.Status.Commands[0] + + s.Equal(appc.PlanCompleted, cmd.State) + s.NotNil(cmd.K0sUpdate) + s.NotNil(cmd.K0sUpdate.Controllers) + s.Empty(cmd.K0sUpdate.Workers) + s.Equal(appc.SignalCompleted, cmd.K0sUpdate.Controllers[0].State) + } } // TestPlansSingleControllerSuite sets up a suite using a single controller, running various diff --git a/inttest/backup/backup_test.go b/inttest/backup/backup_test.go index c522dd5c6acb..b83477d73f48 100644 --- a/inttest/backup/backup_test.go +++ b/inttest/backup/backup_test.go @@ -192,8 +192,7 @@ func (s *BackupSuite) takeBackup() error { defer ssh.Disconnect() out, err := ssh.ExecWithOutput(s.Context(), "/usr/local/bin/k0s backup --save-path /root/") - if err != nil { - s.T().Errorf("backup failed with output:\n%s", out) + if !s.NoErrorf(err, "backup failed with output: %s", out) { return err } s.T().Logf("backup taken successfully with output:\n%s", out) @@ -208,14 +207,12 @@ func (s *BackupSuite) takeBackupStdout() error { defer ssh.Disconnect() out, err := ssh.ExecWithOutput(s.Context(), "/usr/local/bin/k0s backup --save-path - > backup.tar.gz") - if err != nil { - s.T().Errorf("backup failed with output:\n%s", out) + if !s.NoErrorf(err, "backup failed with output: %s", out) { return err } out, err = ssh.ExecWithOutput(s.Context(), "tar tf backup.tar.gz") - if err != nil { - s.T().Errorf("backup inspection failed with output:\n%s", out) + if !s.NoErrorf(err, "backup inspection failed with output: %s", out) { return err } @@ -233,8 +230,7 @@ func (s *BackupSuite) restoreBackup() error { s.T().Log("restoring controller from file") out, err := ssh.ExecWithOutput(s.Context(), "/usr/local/bin/k0s restore $(ls /root/k0s_backup_*.tar.gz)") - if err != nil { - s.T().Errorf("restore failed with output:\n%s", out) + if !s.NoErrorf(err, "restore failed with output: %s", out) { return err } s.T().Logf("restored succesfully with output:\n%s", out) @@ -252,8 +248,7 @@ func (s *BackupSuite) restoreBackupStdin() error { s.T().Log("restoring controller from stdin") out, err := ssh.ExecWithOutput(s.Context(), "cat backup.tar.gz | /usr/local/bin/k0s restore -") - if err != nil { - s.T().Errorf("restore failed with output:\n%s", out) + if !s.NoErrorf(err, "restore failed with output: %s", out) { return err } s.T().Logf("restored succesfully with output:\n%s", out) diff --git a/inttest/basic/basic_test.go b/inttest/basic/basic_test.go index 00536543a5a0..927ecea5203a 100644 --- a/inttest/basic/basic_test.go +++ b/inttest/basic/basic_test.go @@ -123,7 +123,7 @@ func (s *BasicSuite) TestK0sGetsUp() { out, err := common.PodExecCmdOutput(kc, restConfig, pod.Name, "kube-system", "gobgp global") s.Require().NoError(err) // Check that the output contains the default AS number, that's a sign that gobgp is working - s.Assert().Regexp(`AS:\s+64512`, out) + s.Regexp(`AS:\s+64512`, out) break } } diff --git a/inttest/cli/cli_test.go b/inttest/cli/cli_test.go index 1950b3fa720d..1d07d5e44e8f 100644 --- a/inttest/cli/cli_test.go +++ b/inttest/cli/cli_test.go @@ -23,7 +23,6 @@ import ( "time" "github.com/k0sproject/k0s/inttest/common" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) @@ -58,22 +57,22 @@ func (s *CliSuite) TestK0sCliKubectlAndResetCommand() { s.Require().NoError(err, "failed to SSH into controller") defer ssh.Disconnect() - s.T().Run("sysinfoSmoketest", func(t *testing.T) { + s.Run("sysinfoSmoketest", func() { out, err := ssh.ExecWithOutput(s.Context(), fmt.Sprintf("%s sysinfo", s.K0sFullPath)) - assert.NoError(t, err, "k0s sysinfo has non-zero exit code") - t.Logf("%s", out) - assert.Regexp(t, "\nOperating system: Linux \\(pass\\)\n", out) - assert.Regexp(t, "\n Linux kernel release: ", out) - assert.Regexp(t, "\n CONFIG_CGROUPS: ", out) - assert.Regexp(t, "\n Control Groups: ", out) - assert.Regexp(t, "\n cgroup controller \"[a-z]+\": ", out) + s.NoError(err, "k0s sysinfo has non-zero exit code") + s.T().Logf("%s", out) + s.Regexp("\nOperating system: Linux \\(pass\\)\n", out) + s.Regexp("\n Linux kernel release: ", out) + s.Regexp("\n CONFIG_CGROUPS: ", out) + s.Regexp("\n Control Groups: ", out) + s.Regexp("\n cgroup controller \"[a-z]+\": ", out) }) - s.T().Run("k0sInstall", func(t *testing.T) { + s.Run("k0sInstall", func() { // Install with some arbitrary kubelet flags so we see those get properly passed to the kubelet out, err := ssh.ExecWithOutput(s.Context(), "/usr/local/bin/k0s install controller --enable-worker --disable-components konnectivity-server,metrics-server --kubelet-extra-args='--housekeeping-interval=10s --log-flush-frequency=5s'") - assert.NoError(t, err) - assert.Equal(t, "", out) + s.NoError(err) + s.Empty(out) }) s.Run("k0sStart", func() { diff --git a/inttest/common/bootloosesuite.go b/inttest/common/bootloosesuite.go index 0e1a5aeb0379..0b3455eef028 100644 --- a/inttest/common/bootloosesuite.go +++ b/inttest/common/bootloosesuite.go @@ -585,7 +585,7 @@ listen stats ` content := bytes.NewBuffer([]byte{}) - s.Assert().NoError(template.Must(template.New("haproxy").Parse(tpl)).Execute(content, struct { + s.NoError(template.Must(template.New("haproxy").Parse(tpl)).Execute(content, struct { KubeAPIExternalPort int K0sAPIExternalPort int KonnectivityAgentPort int diff --git a/inttest/cplb/cplb_test.go b/inttest/cplb/cplb_test.go index 477d6c66112a..6f668bc178d1 100644 --- a/inttest/cplb/cplb_test.go +++ b/inttest/cplb/cplb_test.go @@ -118,7 +118,7 @@ func (s *keepalivedSuite) getLBAddress() string { s.T().Fatalf("Invalid IP address: %q", ip) } lastOctet, err := strconv.Atoi(parts[3]) - s.Require().NoErrorf(err, "Failed to convert last octet '%s' to int", parts[3]) + s.Require().NoErrorf(err, "Failed to convert last octet %q to int", parts[3]) if lastOctet >= 154 { lastOctet -= 100 } else { @@ -144,7 +144,7 @@ func (s *keepalivedSuite) validateRealServers(ctx context.Context, node string, s.Require().NoError(err) for _, server := range servers { - s.Require().Contains(output, fmt.Sprintf("-a -t %s:6443 -r %s", vip, server), "Controller %s is missing a server in ipvsadm", node) + s.Require().Containsf(output, fmt.Sprintf("-a -t %s:6443 -r %s", vip, server), "Controller %s is missing a server in ipvsadm", node) } } diff --git a/inttest/dualstack/dualstack_test.go b/inttest/dualstack/dualstack_test.go index a92802b89b11..cbc778038f8e 100644 --- a/inttest/dualstack/dualstack_test.go +++ b/inttest/dualstack/dualstack_test.go @@ -81,7 +81,7 @@ func (s *DualstackSuite) cmdlineForExecutable(node, binary string) []string { require.Len(pids, 1, "Expected a single pid") output, err = ssh.ExecWithOutput(s.Context(), fmt.Sprintf("cat /proc/%q/cmdline", pids[0])) - require.NoError(err, "Failed to get cmdline for PID %s", pids[0]) + require.NoErrorf(err, "Failed to get cmdline for PID %s", pids[0]) return strings.Split(output, "\x00") } @@ -158,7 +158,7 @@ func (s *DualstackSuite) SetupSuite() { // test ipv6 address err = wait.PollImmediateWithContext(s.Context(), 100*time.Millisecond, time.Minute, func(ctx context.Context) (done bool, err error) { - s.Require().Equal(len(targetPod.Status.PodIPs), 2) + s.Require().Len(targetPod.Status.PodIPs, 2) podIP := targetPod.Status.PodIPs[1].IP targetIP := net.ParseIP(podIP) s.Require().NotNil(targetIP) @@ -175,7 +175,7 @@ func (s *DualstackSuite) SetupSuite() { // test ipv4 address err = wait.PollImmediateWithContext(s.Context(), 100*time.Millisecond, time.Minute, func(ctx context.Context) (done bool, err error) { - s.Require().Equal(len(targetPod.Status.PodIPs), 2) + s.Require().Len(targetPod.Status.PodIPs, 2) podIP := targetPod.Status.PodIPs[0].IP targetIP := net.ParseIP(podIP) s.Require().NotNil(targetIP) diff --git a/inttest/etcdmember/etcdmember_test.go b/inttest/etcdmember/etcdmember_test.go index 43187802bf28..b1763200f4fb 100644 --- a/inttest/etcdmember/etcdmember_test.go +++ b/inttest/etcdmember/etcdmember_test.go @@ -136,7 +136,7 @@ func (s *EtcdMemberSuite) TestDeregistration() { // Make sure the EtcdMember CR status is successfully updated em := s.getMember(ctx, "controller2") - s.Require().Equal(em.Status.ReconcileStatus, "Success") + s.Require().Equal("Success", em.Status.ReconcileStatus) s.Require().Equal(etcdv1beta1.ConditionFalse, em.Status.GetCondition(etcdv1beta1.ConditionTypeJoined).Status) // Stop k0s and reset the node @@ -155,7 +155,7 @@ func (s *EtcdMemberSuite) TestDeregistration() { // Check the CR is present again em = s.getMember(ctx, "controller2") s.Require().Equal(em.Status.PeerAddress, s.GetControllerIPAddress(2)) - s.Require().Equal(false, em.Spec.Leave) + s.Require().False(em.Spec.Leave) s.Require().Equal(etcdv1beta1.ConditionTrue, em.Status.GetCondition(etcdv1beta1.ConditionTypeJoined).Status) // Check that after restarting the controller, the member is still present diff --git a/inttest/kine/kine_test.go b/inttest/kine/kine_test.go index 22d008a08f78..dc61443a9809 100644 --- a/inttest/kine/kine_test.go +++ b/inttest/kine/kine_test.go @@ -23,8 +23,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "k8s.io/apimachinery/pkg/util/wait" @@ -54,25 +52,25 @@ func (s *KineSuite) TestK0sGetsUp() { s.T().Log("waiting to see CNI pods ready") s.NoError(common.WaitForKubeRouterReady(s.Context(), kc), "CNI did not start") - s.T().Run("verify", func(t *testing.T) { + s.Run("verify", func() { ssh, err := s.SSH(s.Context(), s.ControllerNode(0)) - require.NoError(t, err, "failed to SSH into controller") + s.Require().NoError(err, "failed to SSH into controller") defer ssh.Disconnect() - t.Run(("kineIsUsedAsStorage"), func(t *testing.T) { + s.Run(("kineIsUsedAsStorage"), func() { _, err = ssh.ExecWithOutput(s.Context(), "test -e /var/lib/k0s/bin/kine && ps xa | grep kine") - assert.NoError(t, err) + s.NoError(err) }) - t.Run(("noControllerJoinTokens"), func(t *testing.T) { + s.Run(("noControllerJoinTokens"), func() { noToken, err := ssh.ExecWithOutput(s.Context(), fmt.Sprintf("'%s' token create --role=controller", s.K0sFullPath)) - assert.Error(t, err) - assert.Equal(t, "Error: refusing to create token: cannot join controller into current storage", noToken) + s.Error(err) + s.Equal("Error: refusing to create token: cannot join controller into current storage", noToken) }) - t.Run(("workerJoinTokens"), func(t *testing.T) { + s.Run(("workerJoinTokens"), func() { _, err := ssh.ExecWithOutput(s.Context(), fmt.Sprintf("'%s' token create --role=worker", s.K0sFullPath)) - assert.NoError(t, err) + s.NoError(err) }) }) diff --git a/inttest/kubectl/kubectl_test.go b/inttest/kubectl/kubectl_test.go index d18eb1215645..2f3357270322 100644 --- a/inttest/kubectl/kubectl_test.go +++ b/inttest/kubectl/kubectl_test.go @@ -191,9 +191,9 @@ func (s *KubectlSuite) TestEmbeddedKubectl() { func requiredValue[V any](t *testing.T, obj map[string]any, key string) V { value, ok := obj[key] - require.True(t, ok, "Key %q not found", key) + require.Truef(t, ok, "Key %q not found", key) typedValue, ok := value.(V) - require.True(t, ok, "Incompatible type for key %q: %+v", key, value) + require.Truef(t, ok, "Incompatible type for key %q: %+v", key, value) return typedValue } diff --git a/inttest/kubeletcertrotate/kubeletcertrotate_test.go b/inttest/kubeletcertrotate/kubeletcertrotate_test.go index 418283b992f0..a2ac6e2793c9 100644 --- a/inttest/kubeletcertrotate/kubeletcertrotate_test.go +++ b/inttest/kubeletcertrotate/kubeletcertrotate_test.go @@ -137,17 +137,18 @@ spec: s.Require().NoError(err) // Ensure all state/status are completed - s.Equal(1, len(plan.Status.Commands)) - cmd := plan.Status.Commands[0] - - s.Equal(appc.PlanCompleted, cmd.State) - s.NotNil(cmd.K0sUpdate) - //s.Nil(cmd.K0sUpdate.Controllers) - s.NotNil(cmd.K0sUpdate.Workers) - - for _, group := range [][]apv1beta2.PlanCommandTargetStatus{cmd.K0sUpdate.Controllers, cmd.K0sUpdate.Workers} { - for _, node := range group { - s.Equal(appc.SignalCompleted, node.State) + if s.Len(plan.Status.Commands, 1) { + cmd := plan.Status.Commands[0] + + s.Equal(appc.PlanCompleted, cmd.State) + s.NotNil(cmd.K0sUpdate) + //s.Nil(cmd.K0sUpdate.Controllers) + s.NotNil(cmd.K0sUpdate.Workers) + + for _, group := range [][]apv1beta2.PlanCommandTargetStatus{cmd.K0sUpdate.Controllers, cmd.K0sUpdate.Workers} { + for _, node := range group { + s.Equal(appc.SignalCompleted, node.State) + } } } } diff --git a/inttest/network-conformance/network_test.go b/inttest/network-conformance/network_test.go index 8a9fdb2460b7..547f10418780 100644 --- a/inttest/network-conformance/network_test.go +++ b/inttest/network-conformance/network_test.go @@ -79,7 +79,7 @@ func (s *networkSuite) TestK0sGetsUp() { daemonSetName = "kube-router" } s.T().Log("waiting to see CNI pods ready") - s.NoError(common.WaitForDaemonSet(s.Context(), kc, daemonSetName, "kube-system"), fmt.Sprintf("%s did not start", daemonSetName)) + s.NoErrorf(common.WaitForDaemonSet(s.Context(), kc, daemonSetName, "kube-system"), "%s did not start", daemonSetName) restConfig, err := s.GetKubeConfig("controller0") s.Require().NoError(err) diff --git a/inttest/stackapplier/stackapplier_test.go b/inttest/stackapplier/stackapplier_test.go index e6d84af162b8..af12b04d54de 100644 --- a/inttest/stackapplier/stackapplier_test.go +++ b/inttest/stackapplier/stackapplier_test.go @@ -67,6 +67,7 @@ func (s *suite) TestStackApplier() { sgv := schema.GroupVersion{Group: "k0s.example.com", Version: "v1"} + //nolint:testifylint // runs in parallel s.T().Run("hobbit", func(t *testing.T) { t.Cleanup(func() { if t.Failed() { @@ -80,13 +81,14 @@ func (s *suite) TestStackApplier() { WithErrorCallback(retryWatchErrors(t.Logf)). Until(ctx, func(item *unstructured.Unstructured) (bool, error) { speciesName, found, err := unstructured.NestedString(item.Object, "spec", "characteristics") - if assert.NoError(t, err) && assert.True(t, found, "no characteristics found: %v", item.Object) { + if assert.NoError(t, err) && assert.Truef(t, found, "no characteristics found: %v", item.Object) { assert.Equal(t, "hairy feet", speciesName) } return true, nil })) }) + //nolint:testifylint // runs in parallel s.T().Run("frodo", func(t *testing.T) { t.Cleanup(func() { if t.Failed() { @@ -100,7 +102,7 @@ func (s *suite) TestStackApplier() { WithErrorCallback(retryWatchErrors(t.Logf)). Until(ctx, func(item *unstructured.Unstructured) (bool, error) { speciesName, found, err := unstructured.NestedString(item.Object, "spec", "speciesRef", "name") - if assert.NoError(t, err) && assert.True(t, found, "no species found: %v", item.Object) { + if assert.NoError(t, err) && assert.Truef(t, found, "no species found: %v", item.Object) { assert.Equal(t, "hobbit", speciesName) } return true, nil diff --git a/pkg/apis/k0s/v1beta1/clusterconfig_types_test.go b/pkg/apis/k0s/v1beta1/clusterconfig_types_test.go index 140244dbaced..700da2767f78 100644 --- a/pkg/apis/k0s/v1beta1/clusterconfig_types_test.go +++ b/pkg/apis/k0s/v1beta1/clusterconfig_types_test.go @@ -21,9 +21,12 @@ import ( "testing" "github.com/k0sproject/k0s/internal/pkg/iface" - "github.com/stretchr/testify/assert" + corev1 "k8s.io/api/core/v1" "sigs.k8s.io/yaml" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestClusterDefaults(t *testing.T) { @@ -153,7 +156,7 @@ spec: c, err := ConfigFromString(yamlData) assert.NoError(t, err) errors := c.Validate() - assert.Equal(t, 0, len(errors)) + assert.Zero(t, errors) } func TestNetworkValidation_Calico(t *testing.T) { @@ -172,7 +175,7 @@ spec: c, err := ConfigFromString(yamlData) assert.NoError(t, err) errors := c.Validate() - assert.Equal(t, 0, len(errors)) + assert.Zero(t, errors) } func TestNetworkValidation_Invalid(t *testing.T) { @@ -303,7 +306,7 @@ spec: ` c, err := ConfigFromString(yamlData) assert.NoError(t, err) - assert.Equal(t, 2, len(c.Spec.WorkerProfiles)) + require.Len(t, c.Spec.WorkerProfiles, 2) assert.Equal(t, "profile_XXX", c.Spec.WorkerProfiles[0].Name) assert.Equal(t, "profile_YYY", c.Spec.WorkerProfiles[1].Name) @@ -355,7 +358,7 @@ func TestFeatureGates(t *testing.T) { ` c, err := ConfigFromString(yamlData) assert.NoError(t, err) - assert.Equal(t, 3, len(c.Spec.FeatureGates)) + require.Len(t, c.Spec.FeatureGates, 3) assert.Equal(t, "feature_XXX", c.Spec.FeatureGates[0].Name) assert.True(t, c.Spec.FeatureGates[0].Enabled) for _, component := range []string{"x", "y", "z"} { diff --git a/pkg/apis/k0s/v1beta1/cplb_test.go b/pkg/apis/k0s/v1beta1/cplb_test.go index f51e1c57b15c..db1e0e2f6f78 100644 --- a/pkg/apis/k0s/v1beta1/cplb_test.go +++ b/pkg/apis/k0s/v1beta1/cplb_test.go @@ -17,6 +17,7 @@ limitations under the License. package v1beta1 import ( + "errors" "testing" "time" @@ -123,11 +124,11 @@ func (s *CPLBSuite) TestValidateVRRPInstances() { k := &KeepalivedSpec{ VRRPInstances: tt.vrrps, } - err := k.validateVRRPInstances(returnNIC) + errs := k.validateVRRPInstances(returnNIC) if tt.wantErr { - s.Require().NotEmpty(err, "Test case %s expected error. Got none", tt.name) + s.Require().Error(errors.Join(errs...)) } else { - s.Require().Empty(err, "Test case %s expected no errors. Got: %v", tt.name, err) + s.Require().Empty(errs) s.T().Log(k.VRRPInstances) s.Require().Equal(len(tt.expectedVRRPs), len(k.VRRPInstances), "Expected and actual VRRPInstances length mismatch") for i := 0; i < len(tt.expectedVRRPs); i++ { @@ -264,11 +265,11 @@ func (s *CPLBSuite) TestValidateVirtualServers() { for _, tt := range tests { s.Run(tt.name, func() { k := &KeepalivedSpec{VirtualServers: tt.vss} - err := k.validateVirtualServers() + errs := k.validateVirtualServers() if tt.wantErr { - s.Require().NotEmpty(err, "Test case %s expected error. Got none", tt.name) + s.Require().Error(errors.Join(errs...)) } else { - s.Require().Empty(err, "Tedst case %s expected no error. Got: %v", tt.name, err) + s.Require().Empty(errs) for i := range tt.expectedVSS { s.Require().Equal(tt.expectedVSS[i].DelayLoop, k.VirtualServers[i].DelayLoop, "DelayLoop mismatch") s.Require().Equal(tt.expectedVSS[i].LBAlgo, k.VirtualServers[i].LBAlgo, "LBalgo mismatch") diff --git a/pkg/apis/k0s/v1beta1/storage_test.go b/pkg/apis/k0s/v1beta1/storage_test.go index f8f22b3cf7e1..e82e66dc1b62 100644 --- a/pkg/apis/k0s/v1beta1/storage_test.go +++ b/pkg/apis/k0s/v1beta1/storage_test.go @@ -377,7 +377,7 @@ func (s *storageSuite) TestIsTLSEnabled() { for _, tt := range storageSpecs { s.Run(tt.desc, func() { result := tt.spec.Etcd.IsTLSEnabled() - s.Equal(result, tt.expectedResult) + s.Equal(tt.expectedResult, result) }) } } diff --git a/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulable_test.go b/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulable_test.go index aff705b41042..8825430dcc63 100644 --- a/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulable_test.go +++ b/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulable_test.go @@ -46,7 +46,6 @@ func TestSchedulable(t *testing.T) { status apv1beta2.PlanCommandStatus expectedNextState apv1beta2.PlanStateType expectedRetry bool - expectedError bool expectedPlanStatusWorkers []apv1beta2.PlanCommandTargetStatus }{ // Ensures that if a controller is completed, no additional execution will occur. @@ -92,7 +91,6 @@ func TestSchedulable(t *testing.T) { }, appc.PlanCompleted, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalCompleted), }, @@ -142,7 +140,6 @@ func TestSchedulable(t *testing.T) { }, appc.PlanSchedulableWait, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalSent), }, @@ -172,7 +169,7 @@ func TestSchedulable(t *testing.T) { assert.Equal(t, test.expectedNextState, nextState) assert.Equal(t, test.expectedRetry, retry) - assert.Equal(t, test.expectedError, err != nil, "Unexpected error: %v", err) + assert.NoError(t, err) assert.True(t, cmp.Equal(test.expectedPlanStatusWorkers, test.status.AirgapUpdate.Workers, cmpopts.IgnoreFields(apv1beta2.PlanCommandTargetStatus{}, "LastUpdatedTimestamp"))) }) } diff --git a/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulablewait_test.go b/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulablewait_test.go index e6ba548b5e9b..9f7cb3c474da 100644 --- a/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulablewait_test.go +++ b/pkg/autopilot/controller/plans/cmdprovider/airgapupdate/schedulablewait_test.go @@ -54,7 +54,6 @@ func TestSchedulableWait(t *testing.T) { status apv1beta2.PlanCommandStatus expectedNextState apv1beta2.PlanStateType expectedRetry bool - expectedError bool expectedPlanStatusWorkers []apv1beta2.PlanCommandTargetStatus }{ // Worker-only tests @@ -78,7 +77,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanCompleted, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalCompleted), apv1beta2.NewPlanCommandTargetStatus("worker1", appc.SignalCompleted), @@ -104,7 +102,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulableWait, true, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalSent), apv1beta2.NewPlanCommandTargetStatus("worker1", appc.SignalCompleted), @@ -136,7 +133,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalPending), apv1beta2.NewPlanCommandTargetStatus("worker1", appc.SignalCompleted), @@ -169,7 +165,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalCompleted), apv1beta2.NewPlanCommandTargetStatus("worker1", appc.SignalPending), @@ -221,7 +216,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulableWait, true, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalSent), }, @@ -266,7 +260,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalPending), }, @@ -311,7 +304,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanCompleted, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalCompleted), }, @@ -362,7 +354,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanApplyFailed, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalApplyFailed), }, @@ -393,7 +384,7 @@ func TestSchedulableWait(t *testing.T) { assert.Equal(t, test.expectedNextState, nextState) assert.Equal(t, test.expectedRetry, retry) - assert.Equal(t, test.expectedError, err != nil, "Unexpected error: %v", err) + assert.NoError(t, err) assert.True(t, cmp.Equal(test.expectedPlanStatusWorkers, test.status.AirgapUpdate.Workers, cmpopts.IgnoreFields(apv1beta2.PlanCommandTargetStatus{}, "LastUpdatedTimestamp"))) }) } diff --git a/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulable_test.go b/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulable_test.go index 8531de322c3b..d4e5f47cefd6 100644 --- a/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulable_test.go +++ b/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulable_test.go @@ -46,7 +46,6 @@ func TestSchedulable(t *testing.T) { status apv1beta2.PlanCommandStatus expectedNextState apv1beta2.PlanStateType expectedRetry bool - expectedError bool expectedPlanStatusControllers []apv1beta2.PlanCommandTargetStatus expectedPlanStatusWorkers []apv1beta2.PlanCommandTargetStatus }{ @@ -95,7 +94,6 @@ func TestSchedulable(t *testing.T) { }, appc.PlanCompleted, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalCompleted), }, @@ -149,7 +147,6 @@ func TestSchedulable(t *testing.T) { }, appc.PlanSchedulableWait, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalSent), }, @@ -180,7 +177,7 @@ func TestSchedulable(t *testing.T) { assert.Equal(t, test.expectedNextState, nextState) assert.Equal(t, test.expectedRetry, retry) - assert.Equal(t, test.expectedError, err != nil, "Unexpected error: %v", err) + assert.NoError(t, err) assert.True(t, cmp.Equal(test.expectedPlanStatusControllers, test.status.K0sUpdate.Controllers, cmpopts.IgnoreFields(apv1beta2.PlanCommandTargetStatus{}, "LastUpdatedTimestamp"))) assert.True(t, cmp.Equal(test.expectedPlanStatusWorkers, test.status.K0sUpdate.Workers, cmpopts.IgnoreFields(apv1beta2.PlanCommandTargetStatus{}, "LastUpdatedTimestamp"))) diff --git a/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulablewait_test.go b/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulablewait_test.go index 83350cd3d64e..e6426977d273 100644 --- a/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulablewait_test.go +++ b/pkg/autopilot/controller/plans/cmdprovider/k0supdate/schedulablewait_test.go @@ -54,7 +54,6 @@ func TestSchedulableWait(t *testing.T) { status apv1beta2.PlanCommandStatus expectedNextState apv1beta2.PlanStateType expectedRetry bool - expectedError bool expectedPlanStatusControllers []apv1beta2.PlanCommandTargetStatus expectedPlanStatusWorkers []apv1beta2.PlanCommandTargetStatus }{ @@ -79,7 +78,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanCompleted, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalCompleted), apv1beta2.NewPlanCommandTargetStatus("controller1", appc.SignalCompleted), @@ -105,7 +103,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulableWait, true, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalSent), apv1beta2.NewPlanCommandTargetStatus("controller1", appc.SignalCompleted), @@ -132,7 +129,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalPending), apv1beta2.NewPlanCommandTargetStatus("controller1", appc.SignalCompleted), @@ -161,7 +157,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanCompleted, false, - false, nil, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalCompleted), @@ -188,7 +183,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulableWait, true, - false, nil, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalSent), @@ -223,7 +217,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, nil, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalPending), @@ -259,7 +252,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, nil, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalCompleted), @@ -313,7 +305,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanCompleted, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalCompleted), }, @@ -365,7 +356,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanApplyFailed, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalApplyFailed), }, @@ -407,7 +397,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulableWait, true, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalPending), apv1beta2.NewPlanCommandTargetStatus("controller1", appc.SignalSent), @@ -453,7 +442,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("controller0", appc.SignalCompleted), apv1beta2.NewPlanCommandTargetStatus("controller1", appc.SignalCompleted), @@ -507,7 +495,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanSchedulable, false, - false, nil, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalPending), @@ -555,7 +542,6 @@ func TestSchedulableWait(t *testing.T) { }, appc.PlanCompleted, false, - false, nil, []apv1beta2.PlanCommandTargetStatus{ apv1beta2.NewPlanCommandTargetStatus("worker0", appc.SignalCompleted), @@ -587,7 +573,7 @@ func TestSchedulableWait(t *testing.T) { assert.Equal(t, test.expectedNextState, nextState) assert.Equal(t, test.expectedRetry, retry) - assert.Equal(t, test.expectedError, err != nil, "Unexpected error: %v", err) + assert.NoError(t, err) assert.True(t, cmp.Equal(test.expectedPlanStatusControllers, test.status.K0sUpdate.Controllers, cmpopts.IgnoreFields(apv1beta2.PlanCommandTargetStatus{}, "LastUpdatedTimestamp"))) assert.True(t, cmp.Equal(test.expectedPlanStatusWorkers, test.status.K0sUpdate.Workers, cmpopts.IgnoreFields(apv1beta2.PlanCommandTargetStatus{}, "LastUpdatedTimestamp"))) diff --git a/pkg/autopilot/controller/plans/core/initprovidershandler_test.go b/pkg/autopilot/controller/plans/core/initprovidershandler_test.go index 73a9344a872f..2e01c952fdb2 100644 --- a/pkg/autopilot/controller/plans/core/initprovidershandler_test.go +++ b/pkg/autopilot/controller/plans/core/initprovidershandler_test.go @@ -198,7 +198,11 @@ func TestInitProvidersHandle(t *testing.T) { t.Run(test.name, func(t *testing.T) { ctx := context.TODO() res, err := test.handler.Handle(ctx, test.plan) - assert.Equal(t, test.expectedError, err != nil, "Unexpected error: %v", err) + if test.expectedError { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } assert.Equal(t, test.expectedResult, res) if test.expectedPlanStatus != nil { diff --git a/pkg/autopilot/controller/plans/core/planstatecontroller_test.go b/pkg/autopilot/controller/plans/core/planstatecontroller_test.go index c790ba9fee30..659bee23dff3 100644 --- a/pkg/autopilot/controller/plans/core/planstatecontroller_test.go +++ b/pkg/autopilot/controller/plans/core/planstatecontroller_test.go @@ -50,7 +50,6 @@ func TestReconcile(t *testing.T) { name string handler PlanStateHandler plan *apv1beta2.Plan - expectedError bool expectedRequeue bool expectedStatus *apv1beta2.PlanStatus }{ @@ -60,7 +59,6 @@ func TestReconcile(t *testing.T) { nil, &apv1beta2.Plan{}, false, - false, nil, }, @@ -80,7 +78,6 @@ func TestReconcile(t *testing.T) { }, }, false, - false, nil, }, @@ -97,7 +94,6 @@ func TestReconcile(t *testing.T) { Name: "HandleRetry", }, }, - false, true, nil, }, @@ -118,7 +114,6 @@ func TestReconcile(t *testing.T) { }, }, false, - false, &apv1beta2.PlanStatus{ State: PlanCompleted, }, @@ -143,7 +138,7 @@ func TestReconcile(t *testing.T) { ctx := context.TODO() res, err := controller.Reconcile(ctx, req) - assert.Equal(t, test.expectedError, err != nil, "Unexpected error: %v", err) + assert.NoError(t, err) assert.Equal(t, test.expectedRequeue, !res.IsZero()) if test.expectedStatus != nil { diff --git a/pkg/autopilot/controller/plans/core/planstatehandler_test.go b/pkg/autopilot/controller/plans/core/planstatehandler_test.go index c6f92af122d8..390f9df20612 100644 --- a/pkg/autopilot/controller/plans/core/planstatehandler_test.go +++ b/pkg/autopilot/controller/plans/core/planstatehandler_test.go @@ -453,7 +453,11 @@ func TestHandle(t *testing.T) { t.Run(test.name, func(t *testing.T) { ctx := context.TODO() res, err := test.handler.Handle(ctx, test.plan) - assert.Equal(t, test.expectedError, err != nil, "Unexpected error: %v", err) + if test.expectedError { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } assert.Equal(t, test.expectedResult, res) if test.expectedPlanStatus != nil { diff --git a/pkg/autopilot/controller/plans/init_test.go b/pkg/autopilot/controller/plans/init_test.go index 9154dd31be01..552140632173 100644 --- a/pkg/autopilot/controller/plans/init_test.go +++ b/pkg/autopilot/controller/plans/init_test.go @@ -15,7 +15,6 @@ package plans import ( - "fmt" "testing" apv1beta2 "github.com/k0sproject/k0s/pkg/apis/autopilot/v1beta2" @@ -133,10 +132,10 @@ func TestSchedulableWaitEventFilter(t *testing.T) { pred := schedulableWaitEventFilter() - for idx, test := range tests { + for _, test := range tests { t.Run(test.name, func(t *testing.T) { event := crev.UpdateEvent{ObjectNew: test.plan} - assert.Equal(t, test.expected, pred.Update(event), fmt.Sprintf("Failed at #%d '%s'", idx, test.name)) + assert.Equal(t, test.expected, pred.Update(event)) }) } } @@ -201,10 +200,10 @@ func TestSchedulableEventFilter(t *testing.T) { pred := schedulableEventFilter() - for idx, test := range tests { + for _, test := range tests { t.Run(test.name, func(t *testing.T) { event := crev.UpdateEvent{ObjectNew: test.plan} - assert.Equal(t, test.expected, pred.Update(event), fmt.Sprintf("Failed at #%d '%s'", idx, test.name)) + assert.Equal(t, test.expected, pred.Update(event)) }) } } diff --git a/pkg/autopilot/controller/plans/predicate_test.go b/pkg/autopilot/controller/plans/predicate_test.go index bbd53b954578..5696b50a9e52 100644 --- a/pkg/autopilot/controller/plans/predicate_test.go +++ b/pkg/autopilot/controller/plans/predicate_test.go @@ -36,10 +36,10 @@ func TestPlanNamePredicate(t *testing.T) { } pred := PlanNamePredicate("foo") - assert.Equal(t, true, pred.Create(crev.CreateEvent{Object: createPlan("foo")})) - assert.Equal(t, true, pred.Update(crev.UpdateEvent{ObjectNew: createPlan("foo")})) - assert.Equal(t, false, pred.Create(crev.CreateEvent{Object: createPlan("bar")})) - assert.Equal(t, false, pred.Update(crev.UpdateEvent{ObjectNew: createPlan("bar")})) + assert.True(t, pred.Create(crev.CreateEvent{Object: createPlan("foo")})) + assert.True(t, pred.Update(crev.UpdateEvent{ObjectNew: createPlan("foo")})) + assert.False(t, pred.Create(crev.CreateEvent{Object: createPlan("bar")})) + assert.False(t, pred.Update(crev.UpdateEvent{ObjectNew: createPlan("bar")})) } // TestPlanStatusPredicate ensures that plans can be identified by their status @@ -57,8 +57,8 @@ func TestPlanStatusPredicate(t *testing.T) { } pred := PlanStatusPredicate(appc.PlanSchedulable) - assert.Equal(t, true, pred.Update(crev.UpdateEvent{ObjectNew: createPlan(appc.PlanSchedulable)})) - assert.Equal(t, true, pred.Create(crev.CreateEvent{Object: createPlan(appc.PlanSchedulable)})) - assert.Equal(t, false, pred.Update(crev.UpdateEvent{ObjectNew: createPlan("unknown")})) - assert.Equal(t, false, pred.Create(crev.CreateEvent{Object: createPlan("unknown")})) + assert.True(t, pred.Update(crev.UpdateEvent{ObjectNew: createPlan(appc.PlanSchedulable)})) + assert.True(t, pred.Create(crev.CreateEvent{Object: createPlan(appc.PlanSchedulable)})) + assert.False(t, pred.Update(crev.UpdateEvent{ObjectNew: createPlan("unknown")})) + assert.False(t, pred.Create(crev.CreateEvent{Object: createPlan("unknown")})) } diff --git a/pkg/autopilot/controller/signal/airgap/init_test.go b/pkg/autopilot/controller/signal/airgap/init_test.go index 7481f3a781da..b548aec3fc13 100644 --- a/pkg/autopilot/controller/signal/airgap/init_test.go +++ b/pkg/autopilot/controller/signal/airgap/init_test.go @@ -63,7 +63,7 @@ func TestSignalDataUpdateCommandAirgapPredicate(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, pred(test.data), "Failed in '%s'", test.name) + assert.Equal(t, test.success, pred(test.data)) }) } } diff --git a/pkg/autopilot/controller/signal/airgap/signal_test.go b/pkg/autopilot/controller/signal/airgap/signal_test.go index e8e07c78cc4b..a1fe20fff74e 100644 --- a/pkg/autopilot/controller/signal/airgap/signal_test.go +++ b/pkg/autopilot/controller/signal/airgap/signal_test.go @@ -16,7 +16,6 @@ package airgap import ( "context" - "fmt" "testing" apv1beta2 "github.com/k0sproject/k0s/pkg/apis/autopilot/v1beta2" @@ -224,9 +223,9 @@ func TestSignalControllerEventFilter(t *testing.T) { return false }) - for idx, test := range tests { + for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, pred.Update(test.event), fmt.Sprintf("Failed in #%d '%s'", idx, test.name)) + assert.Equal(t, test.success, pred.Update(test.event)) }) } } diff --git a/pkg/autopilot/controller/signal/common/predicate/predicate_test.go b/pkg/autopilot/controller/signal/common/predicate/predicate_test.go index 0802a0002309..ba8606887f4b 100644 --- a/pkg/autopilot/controller/signal/common/predicate/predicate_test.go +++ b/pkg/autopilot/controller/signal/common/predicate/predicate_test.go @@ -52,7 +52,7 @@ func TestDataStatusPredicate(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, test.pred(test.data), "Failed on '%s'", test.name) + assert.Equal(t, test.success, test.pred(test.data)) }) } } @@ -72,7 +72,7 @@ func TestDataNoStatusPredicate(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, pred(test.data), "Failed on '%s'", test.name) + assert.Equal(t, test.success, pred(test.data)) }) } } diff --git a/pkg/autopilot/controller/signal/common/signal_test.go b/pkg/autopilot/controller/signal/common/signal_test.go index 8039cd02a7a0..7bca19998e3a 100644 --- a/pkg/autopilot/controller/signal/common/signal_test.go +++ b/pkg/autopilot/controller/signal/common/signal_test.go @@ -15,7 +15,6 @@ package common import ( - "fmt" "testing" "github.com/sirupsen/logrus" @@ -94,7 +93,7 @@ func TestExtractSignalData(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { signalData := extractSignalData(logger, test.data) - assert.Equal(t, test.found, (signalData != nil), fmt.Sprintf("Failure in '%s'", test.name)) + assert.Equalf(t, test.found, (signalData != nil), "Failure in '%s'", test.name) }) } } diff --git a/pkg/autopilot/controller/signal/k0s/apply_test.go b/pkg/autopilot/controller/signal/k0s/apply_test.go index f70fe14893ea..e1b468f9eebb 100644 --- a/pkg/autopilot/controller/signal/k0s/apply_test.go +++ b/pkg/autopilot/controller/signal/k0s/apply_test.go @@ -15,7 +15,6 @@ package k0s import ( - "fmt" "testing" apv1beta2 "github.com/k0sproject/k0s/pkg/apis/autopilot/v1beta2" @@ -224,9 +223,9 @@ func TestApplyingUpdateEventFilter(t *testing.T) { return false }) - for idx, test := range tests { + for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, pred.Update(test.event), fmt.Sprintf("Failed in #%d '%s'", idx, test.name)) + assert.Equal(t, test.success, pred.Update(test.event)) }) } } diff --git a/pkg/autopilot/controller/signal/k0s/download_test.go b/pkg/autopilot/controller/signal/k0s/download_test.go index 381e0389b3be..7e33ddb61be9 100644 --- a/pkg/autopilot/controller/signal/k0s/download_test.go +++ b/pkg/autopilot/controller/signal/k0s/download_test.go @@ -15,7 +15,6 @@ package k0s import ( - "fmt" "testing" apv1beta2 "github.com/k0sproject/k0s/pkg/apis/autopilot/v1beta2" @@ -164,9 +163,9 @@ func TestDownloadingEventFilter(t *testing.T) { return false }) - for idx, test := range tests { + for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, pred.Update(test.event), fmt.Sprintf("Failed in #%d '%s'", idx, test.name)) + assert.Equal(t, test.success, pred.Update(test.event)) }) } } diff --git a/pkg/autopilot/controller/signal/k0s/init_test.go b/pkg/autopilot/controller/signal/k0s/init_test.go index 3dc422fbca76..b130e004509b 100644 --- a/pkg/autopilot/controller/signal/k0s/init_test.go +++ b/pkg/autopilot/controller/signal/k0s/init_test.go @@ -63,7 +63,7 @@ func TestSignalDataUpdateCommandK0sPredicate(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, pred(test.data), "Failed in '%s'", test.name) + assert.Equal(t, test.success, pred(test.data)) }) } } diff --git a/pkg/autopilot/controller/signal/k0s/signal_test.go b/pkg/autopilot/controller/signal/k0s/signal_test.go index 08908f0f8d26..88aaaeb59a8f 100644 --- a/pkg/autopilot/controller/signal/k0s/signal_test.go +++ b/pkg/autopilot/controller/signal/k0s/signal_test.go @@ -16,7 +16,6 @@ package k0s import ( "context" - "fmt" "testing" "time" @@ -228,9 +227,9 @@ func TestSignalControllerEventFilter(t *testing.T) { return false }) - for idx, test := range tests { + for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.success, pred.Update(test.event), fmt.Sprintf("Failed in #%d '%s'", idx, test.name)) + assert.Equal(t, test.success, pred.Update(test.event)) }) } } @@ -635,7 +634,7 @@ func TestCheckExpiredInvalid(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { expired := checkExpiredInvalid(logger, test.data, test.timeout) - assert.Equal(t, test.expired, expired, fmt.Sprintf("Failure in '%s'", test.name)) + assert.Equal(t, test.expired, expired) }) } } diff --git a/pkg/autopilot/signaling/v2/signaling_v2_test.go b/pkg/autopilot/signaling/v2/signaling_v2_test.go index 8456b568f233..d59c4667c83f 100644 --- a/pkg/autopilot/signaling/v2/signaling_v2_test.go +++ b/pkg/autopilot/signaling/v2/signaling_v2_test.go @@ -15,6 +15,8 @@ package v2 import ( + "maps" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -35,7 +37,11 @@ func TestSignalValid(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { err := test.signal.Validate() - assert.Equal(t, test.valid, err == nil, "Test '%s': validate failed - %v", test.name, err) + if test.valid { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } }) } } @@ -68,7 +74,11 @@ func TestSignalDataValid(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { err := test.data.Validate() - assert.Equal(t, test.successful, err == nil, "Test '%s': validate failed - %v", test.name, err) + if test.successful { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } }) } } @@ -137,7 +147,11 @@ func TestSignalDataUpdateK0sValid(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { err := test.data.Validate() - assert.Equal(t, test.successful, err == nil, "Test '%s': validate failed - %v", test.name, err) + if test.successful { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } }) } } @@ -166,9 +180,11 @@ func TestMarshaling(t *testing.T) { // Forward .. assert.NoError(t, signalData1.Marshal(m)) assert.NotEmpty(t, m) - assert.Equal(t, 2, len(m)) - assert.Contains(t, m, "k0sproject.io/autopilot-signal-version") - assert.Contains(t, m, "k0sproject.io/autopilot-signal-data") + mapKeys := slices.Collect(maps.Keys(m)) + assert.ElementsMatch(t, []string{ + "k0sproject.io/autopilot-signal-version", + "k0sproject.io/autopilot-signal-data", + }, mapKeys) // .. and backward signalData2 := SignalData{} diff --git a/pkg/backup/filesystem_unix_test.go b/pkg/backup/filesystem_unix_test.go index e3d30ed9290d..64fcd3770144 100644 --- a/pkg/backup/filesystem_unix_test.go +++ b/pkg/backup/filesystem_unix_test.go @@ -120,12 +120,12 @@ func TestFileSystemStepRestore(t *testing.T) { for _, dir := range expectedDirs { p := filepath.Join(src, dir) - require.NoErrorf(t, os.Mkdir(p, 0700), "Unable to create directory %s", p) + require.NoError(t, os.Mkdir(p, 0700)) } for _, file := range expectedFiles { p := filepath.Join(src, file) - require.NoError(t, os.WriteFile(p, []byte{}, 0600), "Unable to create file %s:", p) + require.NoError(t, os.WriteFile(p, []byte{}, 0600)) } step1 := NewFileSystemStep(filepath.Join(src, "dir1")) diff --git a/pkg/component/controller/calico_test.go b/pkg/component/controller/calico_test.go index 774c12e86a80..303f1d4b8619 100644 --- a/pkg/component/controller/calico_test.go +++ b/pkg/component/controller/calico_test.go @@ -51,7 +51,7 @@ func TestCalicoManifests(t *testing.T) { for k := range saver { require.NotContains(t, k, "calico-crd") } - require.Len(t, crdSaver, 0) + require.Empty(t, crdSaver) }) t.Run("must_have_wireguard_enabled_if_config_has", func(t *testing.T) { @@ -89,14 +89,16 @@ func TestCalicoManifests(t *testing.T) { t.Run("ip_autodetection", func(t *testing.T) { t.Run("use_IPAutodetectionMethod_for_both_families_by_default", func(t *testing.T) { - clusterConfig.Spec.Network.Calico.IPAutodetectionMethod = "somemethod" + calicoNetSpec := clusterConfig.Spec.Network.Calico + calicoNetSpec.IPAutodetectionMethod = "somemethod" saver := inMemorySaver{} crdSaver := inMemorySaver{} calico := NewCalico(k0sVars, crdSaver, saver) templateContext, err := calico.getConfig(clusterConfig) require.NoError(t, err) - require.Equal(t, clusterConfig.Spec.Network.Calico.IPAutodetectionMethod, templateContext.IPAutodetectionMethod) - require.Equal(t, templateContext.IPV6AutodetectionMethod, templateContext.IPV6AutodetectionMethod) + require.Equal(t, calicoNetSpec.IPAutodetectionMethod, templateContext.IPAutodetectionMethod) + require.Equal(t, calicoNetSpec.IPAutodetectionMethod, templateContext.IPV6AutodetectionMethod, + "IPv6 autodetection was not specified, hence it should be the same as the IPv4 autodetection method.") cfg, err := calico.getConfig(clusterConfig) require.NoError(t, err) _ = calico.processConfigChanges(cfg) @@ -169,7 +171,7 @@ func (ds daemonSetContainersEnv) RequireContainerHasEnvVariable(t *testing.T, co require.Equal(t, envSpec.Value, varValue) } } - require.True(t, found, "Variable %s not found", varName) + require.Truef(t, found, "Variable %s not found", varName) } } @@ -184,6 +186,6 @@ func (ds daemonSetContainersEnv) RequireContainerHasNoEnvVariable(t *testing.T, found = true } } - require.False(t, found, "Variable %s must not be found", varName) + require.Falsef(t, found, "Variable %s must not be found", varName) } } diff --git a/pkg/component/controller/csrapprover_test.go b/pkg/component/controller/csrapprover_test.go index 20d154260ae4..85c46c4dccd9 100644 --- a/pkg/component/controller/csrapprover_test.go +++ b/pkg/component/controller/csrapprover_test.go @@ -79,7 +79,7 @@ func TestBasicCRSApprover(t *testing.T) { csr, err := client.CertificatesV1().CertificateSigningRequests().Get(ctx, newCsr.Name, metav1.GetOptions{}) assert.NoError(t, err) assert.NotNil(t, csr) - assert.True(t, csr.Name == newCsr.Name) + assert.Equal(t, newCsr.Name, csr.Name) for _, c := range csr.Status.Conditions { assert.True(t, c.Type == certv1.CertificateApproved && c.Reason == "Autoapproved by K0S CSRApprover" && c.Status == core.ConditionTrue) } diff --git a/pkg/component/controller/extensions_controller_test.go b/pkg/component/controller/extensions_controller_test.go index c98af93a84c7..a9b322eb9060 100644 --- a/pkg/component/controller/extensions_controller_test.go +++ b/pkg/component/controller/extensions_controller_test.go @@ -163,9 +163,9 @@ func TestChartManifestFileName(t *testing.T) { Order: 2, } - assert.Equal(t, chartManifestFileName(&chart), "0_helm_extension_release.yaml") - assert.Equal(t, chartManifestFileName(&chart1), "1_helm_extension_release.yaml") - assert.Equal(t, chartManifestFileName(&chart2), "2_helm_extension_release.yaml") + assert.Equal(t, "0_helm_extension_release.yaml", chartManifestFileName(&chart)) + assert.Equal(t, "1_helm_extension_release.yaml", chartManifestFileName(&chart1)) + assert.Equal(t, "2_helm_extension_release.yaml", chartManifestFileName(&chart2)) assert.True(t, isChartManifestFileName("0_helm_extension_release.yaml")) } diff --git a/pkg/component/controller/k0scloudprovider_test.go b/pkg/component/controller/k0scloudprovider_test.go index cfa12c6e9177..4e37537db50f 100644 --- a/pkg/component/controller/k0scloudprovider_test.go +++ b/pkg/component/controller/k0scloudprovider_test.go @@ -24,7 +24,6 @@ import ( "github.com/k0sproject/k0s/pkg/component/manager" "github.com/k0sproject/k0s/pkg/k0scloudprovider" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" v1 "k8s.io/api/core/v1" ) @@ -77,12 +76,12 @@ func (suite *K0sCloudProviderSuite) SetupTest() { } suite.ccp = newK0sCloudProvider(config, DummyCommandBuilder(&suite.wg, &suite.cancelled)) - assert.NotNil(suite.T(), suite.ccp) + suite.NotNil(suite.ccp) } // TestInit covers the `Init()` function. func (suite *K0sCloudProviderSuite) TestInit() { - assert.Nil(suite.T(), suite.ccp.Init(context.TODO())) + suite.NoError(suite.ccp.Init(context.TODO())) } // TestRunStop covers the scenario of issuing a `Start()`, and ensuring @@ -91,14 +90,14 @@ func (suite *K0sCloudProviderSuite) TestInit() { // `Stop()`, without worrying about what was actually running. func (suite *K0sCloudProviderSuite) TestRunStop() { ctx := context.TODO() - assert.Nil(suite.T(), suite.ccp.Init(ctx)) - assert.Nil(suite.T(), suite.ccp.Start(ctx)) + suite.NoError(suite.ccp.Init(ctx)) + suite.NoError(suite.ccp.Start(ctx)) // Ensures that the stopping mechanism actually closes the stop channel. - assert.Nil(suite.T(), suite.ccp.Stop()) + suite.NoError(suite.ccp.Stop()) suite.wg.Wait() - assert.Equal(suite.T(), true, suite.cancelled) + suite.True(suite.cancelled) } // TestK0sCloudProviderTestSuite sets up the suite for testing. diff --git a/pkg/component/controller/kuberouter_test.go b/pkg/component/controller/kuberouter_test.go index aac4d31b220d..85c943b63f62 100644 --- a/pkg/component/controller/kuberouter_test.go +++ b/pkg/component/controller/kuberouter_test.go @@ -72,7 +72,7 @@ func TestKubeRouterConfig(t *testing.T) { p, err := getKubeRouterPlugin(cm, "bridge") require.NoError(t, err) - require.Equal(t, float64(1450), p.Dig("mtu")) + require.InEpsilon(t, 1450, p.Dig("mtu"), 0) require.Equal(t, true, p.Dig("hairpinMode")) require.Equal(t, true, p.Dig("ipMasq")) } @@ -190,7 +190,7 @@ func TestKubeRouterManualMTUManifests(t *testing.T) { p, err := getKubeRouterPlugin(cm, "bridge") require.NoError(t, err) - require.Equal(t, float64(1234), p.Dig("mtu")) + require.InEpsilon(t, 1234, p.Dig("mtu"), 0) } func TestExtraArgs(t *testing.T) { diff --git a/pkg/component/worker/config/config_test.go b/pkg/component/worker/config/config_test.go index d438aabe1f02..945ec34a8057 100644 --- a/pkg/component/worker/config/config_test.go +++ b/pkg/component/worker/config/config_test.go @@ -66,7 +66,7 @@ func TestFromConfigMapData(t *testing.T) { errs := composite.Unwrap() assert.Len(t, errs, 4) for i, err := range errs { - assert.ErrorContains(t, err, "json: cannot unmarshal number into Go value of type", "For error #%d", i+1) + assert.ErrorContainsf(t, err, "json: cannot unmarshal number into Go value of type", "For error #%d", i+1) } } assert.Nil(t, config) diff --git a/pkg/component/worker/nllb/envoy_test.go b/pkg/component/worker/nllb/envoy_test.go index 14ce1826bab3..6e8d38de2eac 100644 --- a/pkg/component/worker/nllb/envoy_test.go +++ b/pkg/component/worker/nllb/envoy_test.go @@ -61,7 +61,7 @@ func TestWriteEnvoyConfigFiles(t *testing.T) { parse := func(t *testing.T, file string) (parsed map[string]any) { content, err := os.ReadFile(filepath.Join(dir, file)) require.NoError(t, err) - require.NoError(t, yaml.Unmarshal(content, &parsed), "invalid YAML in %s", file) + require.NoErrorf(t, yaml.Unmarshal(content, &parsed), "invalid YAML in %s", file) return } @@ -83,9 +83,9 @@ func TestWriteEnvoyConfigFiles(t *testing.T) { for i, ep := range eps { host, herr := evalJSONPath[string](ep, ".endpoint.address.socket_address.address") port, perr := evalJSONPath[float64](ep, ".endpoint.address.socket_address.port_value") - if assert.NoError(t, errors.Join(herr, perr), "For endpoint %d", i) { + if assert.NoErrorf(t, errors.Join(herr, perr), "For endpoint %d", i) { iport := int64(port) - if assert.Equal(t, float64(iport), port, "Port is not an integer for endpoint %d", i) { + if assert.InEpsilonf(t, iport, port, 0, "Port is not an integer for endpoint %d", i) { addrs = append(addrs, fmt.Sprintf("%s:%d", host, iport)) } } diff --git a/pkg/component/worker/nllb/reconciler_test.go b/pkg/component/worker/nllb/reconciler_test.go index 0c8402700dae..764f22f196ae 100644 --- a/pkg/component/worker/nllb/reconciler_test.go +++ b/pkg/component/worker/nllb/reconciler_test.go @@ -426,7 +426,7 @@ func TestReconciler_ConfigMgmt(t *testing.T) { configBytes, err := os.ReadFile(envoyConfig) if assert.NoError(t, err) { var yamlConfig any - assert.NoError(t, yaml.Unmarshal(configBytes, &yamlConfig), "invalid YAML in config file: %s", string(configBytes)) + assert.NoErrorf(t, yaml.Unmarshal(configBytes, &yamlConfig), "invalid YAML in config file: %s", string(configBytes)) } }) } diff --git a/pkg/component/worker/ocibundle_test.go b/pkg/component/worker/ocibundle_test.go index 2dfb13f89246..d670aaf33b08 100644 --- a/pkg/component/worker/ocibundle_test.go +++ b/pkg/component/worker/ocibundle_test.go @@ -29,14 +29,14 @@ import ( func TestGetImageSources(t *testing.T) { // test image without label got, err := GetImageSources(images.Image{}) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, ImageSources{}, got) // test image with label when := time.Now().Truncate(time.Hour) value := map[string]time.Time{"path": when} data, err := json.Marshal(value) - require.Nil(t, err) + require.NoError(t, err) image := images.Image{ Labels: map[string]string{ @@ -45,7 +45,7 @@ func TestGetImageSources(t *testing.T) { } expected := ImageSources{"path": when} got, err = GetImageSources(image) - require.Nil(t, err) + require.NoError(t, err) require.True(t, expected["path"].Equal(got["path"]), "dates mismatch") // test image with invalid label @@ -55,7 +55,7 @@ func TestGetImageSources(t *testing.T) { }, } _, err = GetImageSources(image) - require.NotNil(t, err) + require.Error(t, err) require.Contains(t, err.Error(), "failed to unmarshal label") } @@ -63,110 +63,110 @@ func TestSetImageSources(t *testing.T) { // test adding empty sources image := images.Image{} err := SetImageSources(&image, ImageSources{}) - require.Nil(t, err) + require.NoError(t, err) require.Empty(t, image.Labels) // test setting one source fp, err := os.CreateTemp("", "test") - require.Nil(t, err) + require.NoError(t, err) defer func() { _ = fp.Close() _ = os.Remove(fp.Name()) }() info, err := fp.Stat() - require.Nil(t, err) + require.NoError(t, err) image = images.Image{} expected := ImageSources{fp.Name(): info.ModTime()} err = SetImageSources(&image, expected) - require.Nil(t, err) + require.NoError(t, err) got, err := GetImageSources(image) - require.Nil(t, err) + require.NoError(t, err) require.True(t, expected[fp.Name()].Equal(got[fp.Name()]), "dates mismatch") // test sources replacement img0, err := os.CreateTemp("", "test") - require.Nil(t, err) + require.NoError(t, err) defer func() { _ = img0.Close() _ = os.Remove(img0.Name()) }() info0, err := img0.Stat() - require.Nil(t, err) + require.NoError(t, err) data, err := json.Marshal(map[string]time.Time{img0.Name(): info0.ModTime()}) - require.Nil(t, err) + require.NoError(t, err) image = images.Image{ Labels: map[string]string{ImageSourcePathsLabel: string(data)}, } img1, err := os.CreateTemp("", "test") - require.Nil(t, err) + require.NoError(t, err) defer func() { _ = img1.Close() _ = os.Remove(img1.Name()) }() info1, err := img1.Stat() - require.Nil(t, err) + require.NoError(t, err) newsrc := ImageSources{img1.Name(): info1.ModTime()} err = SetImageSources(&image, newsrc) - require.Nil(t, err) + require.NoError(t, err) expected = ImageSources{img1.Name(): info1.ModTime()} got, err = GetImageSources(image) - require.Nil(t, err) + require.NoError(t, err) require.True(t, expected[img1.Name()].Equal(got[img1.Name()]), "dates mismatch") } func TestAddToImageSources(t *testing.T) { // test replacing sources img0, err := os.CreateTemp("", "test") - require.Nil(t, err) + require.NoError(t, err) defer func() { _ = img0.Close() _ = os.Remove(img0.Name()) }() info0, err := img0.Stat() - require.Nil(t, err) + require.NoError(t, err) data, err := json.Marshal(map[string]time.Time{img0.Name(): info0.ModTime()}) - require.Nil(t, err) + require.NoError(t, err) image := images.Image{ Labels: map[string]string{ImageSourcePathsLabel: string(data)}, } img1, err := os.CreateTemp("", "test") - require.Nil(t, err) + require.NoError(t, err) defer func() { _ = img1.Close() _ = os.Remove(img1.Name()) }() info1, err := img1.Stat() - require.Nil(t, err) + require.NoError(t, err) err = AddToImageSources(&image, img1.Name(), info1.ModTime()) - require.Nil(t, err) + require.NoError(t, err) expected := ImageSources{ img0.Name(): info0.ModTime(), img1.Name(): info1.ModTime(), } got, err := GetImageSources(image) - require.Nil(t, err) + require.NoError(t, err) require.True(t, expected[img0.Name()].Equal(got[img0.Name()]), "dates mismatch") require.True(t, expected[img1.Name()].Equal(got[img1.Name()]), "dates mismatch") // test if it trims the sources err = img0.Close() - require.Nil(t, err) + require.NoError(t, err) err = os.Remove(img0.Name()) - require.Nil(t, err) + require.NoError(t, err) err = AddToImageSources(&image, img1.Name(), info1.ModTime()) - require.Nil(t, err) + require.NoError(t, err) expected = ImageSources{img1.Name(): info1.ModTime()} got, err = GetImageSources(image) - require.Nil(t, err) + require.NoError(t, err) require.True(t, expected[img1.Name()].Equal(got[img1.Name()]), "dates mismatch") } diff --git a/pkg/component/worker/static_pods_test.go b/pkg/component/worker/static_pods_test.go index 958f365e2c16..1f41a916c5af 100644 --- a/pkg/component/worker/static_pods_test.go +++ b/pkg/component/worker/static_pods_test.go @@ -291,7 +291,7 @@ func TestStaticPods_Lifecycle(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, resp.Body.Close()) }) - assert.Equal(t, resp.StatusCode, http.StatusOK) + assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) diff --git a/pkg/constant/constant_test.go b/pkg/constant/constant_test.go index 11f2335465ef..413a9c4db057 100644 --- a/pkg/constant/constant_test.go +++ b/pkg/constant/constant_test.go @@ -46,8 +46,9 @@ func TestConstants(t *testing.T) { t.Run("KubernetesMajorMinorVersion", func(t *testing.T) { ver := strings.Split(getVersion(t, "kubernetes"), ".") - require.GreaterOrEqual(t, len(ver), 2, "failed to spilt Kubernetes version %q", ver) + require.GreaterOrEqualf(t, len(ver), 2, "failed to spilt Kubernetes version %q", ver) kubeMajorMinor := ver[0] + "." + ver[1] + //nolint:testifylint // kubeMajorMinor _is_ the expected value assert.Equal(t, kubeMajorMinor, KubernetesMajorMinorVersion) }) } @@ -60,7 +61,7 @@ func TestTLSCipherSuites(t *testing.T) { return x.ID == cipherSuite }) if idx < 0 { - assert.Fail(t, "Not in tls.CipherSuites(), potentially insecure", "(0x%04x) %s", cipherSuite, tls.CipherSuiteName(cipherSuite)) + assert.Failf(t, "Not in tls.CipherSuites(), potentially insecure", "(0x%04x) %s", cipherSuite, tls.CipherSuiteName(cipherSuite)) } } } @@ -98,7 +99,7 @@ func TestKubernetesModuleVersions(t *testing.T) { func TestEtcdModuleVersions(t *testing.T) { etcdVersion := getVersion(t, "etcd") etcdVersionParts := strings.Split(etcdVersion, ".") - require.GreaterOrEqual(t, len(etcdVersionParts), 1, "failed to spilt etcd version %q", etcdVersion) + require.GreaterOrEqualf(t, len(etcdVersionParts), 1, "failed to spilt etcd version %q", etcdVersion) assertPackageModules(t, func(modulePath string) bool { @@ -158,7 +159,7 @@ func getVersion(t *testing.T, component string) string { out, err := cmd.Output() require.NoError(t, err) - require.NotEmpty(t, out, "failed to get %s version", component) + require.NotEmptyf(t, out, "failed to get %s version", component) trailingNewlines := regexp.MustCompilePOSIX("(\r?\n)+$") return string(trailingNewlines.ReplaceAll(out, []byte{})) diff --git a/pkg/k0scontext/context_test.go b/pkg/k0scontext/context_test.go index 5726c4d645ca..92db1dcc0c90 100644 --- a/pkg/k0scontext/context_test.go +++ b/pkg/k0scontext/context_test.go @@ -85,10 +85,10 @@ func TestValue_StructPtrs(t *testing.T) { assert.Zero(t, k0scontext.Value[*Bar](ctx)) ctxWithFoo := k0scontext.WithValue(ctx, &Foo{}) - assert.Equal(t, k0scontext.Value[*Foo](ctxWithFoo), &Foo{}) + assert.Equal(t, &Foo{}, k0scontext.Value[*Foo](ctxWithFoo)) assert.Zero(t, k0scontext.Value[*Bar](ctx)) ctxWithFooAndBar := k0scontext.WithValue(ctxWithFoo, &Bar{}) - assert.Equal(t, k0scontext.Value[*Foo](ctxWithFooAndBar), &Foo{}) - assert.Equal(t, k0scontext.Value[*Bar](ctxWithFooAndBar), &Bar{}) + assert.Equal(t, &Foo{}, k0scontext.Value[*Foo](ctxWithFooAndBar)) + assert.Equal(t, &Bar{}, k0scontext.Value[*Bar](ctxWithFooAndBar)) } diff --git a/pkg/kubernetes/lease_test.go b/pkg/kubernetes/lease_test.go index 0599cb65cddf..dec2a50ada2c 100644 --- a/pkg/kubernetes/lease_test.go +++ b/pkg/kubernetes/lease_test.go @@ -36,7 +36,7 @@ func TestValidLease(t *testing.T) { }, } - assert.Equal(t, true, IsValidLease(lease)) + assert.True(t, IsValidLease(lease)) } func TestExpiredLease(t *testing.T) { @@ -50,5 +50,5 @@ func TestExpiredLease(t *testing.T) { }, } - assert.Equal(t, false, IsValidLease(lease)) + assert.False(t, IsValidLease(lease)) } diff --git a/pkg/kubernetes/watch/watcher_test.go b/pkg/kubernetes/watch/watcher_test.go index 7947af997902..25326c462dfc 100644 --- a/pkg/kubernetes/watch/watcher_test.go +++ b/pkg/kubernetes/watch/watcher_test.go @@ -651,7 +651,7 @@ func forbiddenWatch(t *testing.T) func(metav1.ListOptions) error { func forbiddenErrorCallback(t *testing.T) watch.ErrorCallback { return func(err error) (time.Duration, error) { - require.Fail(t, "ErrorCallback shouldn't be called.", "Error was: %v", err) + require.Failf(t, "ErrorCallback shouldn't be called.", "Error was: %v", err) return 0, nil } } diff --git a/pkg/node/nodehostname_test.go b/pkg/node/nodehostname_test.go index d34867411208..73d416ec634f 100644 --- a/pkg/node/nodehostname_test.go +++ b/pkg/node/nodehostname_test.go @@ -34,30 +34,30 @@ func TestGetNodename(t *testing.T) { t.Run("should_always_return_override_if_given", func(t *testing.T) { name, err := GetNodename("override") require.Equal(t, "override", name) - require.Nil(t, err) + require.NoError(t, err) }) t.Run("should_call_kubernetes_hostname_helper_on_linux", func(t *testing.T) { name, err := GetNodename("") name2, err2 := nodeutil.GetHostname("") require.Equal(t, name, name2) - require.Nil(t, err) - require.Nil(t, err2) + require.NoError(t, err) + require.NoError(t, err2) }) t.Run("windows_no_metadata_service_available", func(t *testing.T) { name, err := getNodeNameWindows("", baseURL) nodename, err2 := nodeutil.GetHostname("") - require.Nil(t, err) - require.Nil(t, err2) + require.NoError(t, err) + require.NoError(t, err2) require.Equal(t, nodename, name) }) t.Run("windows_metadata_service_is_available", func(t *testing.T) { name, err := getNodeNameWindows("", baseURL+"/latest/meta-data/local-hostname") nodename, err2 := nodeutil.GetHostname("") - require.Nil(t, err) - require.Nil(t, err2) + require.NoError(t, err) + require.NoError(t, err2) require.NotEqual(t, nodename, name) }) } diff --git a/pkg/supervisor/logwriter_test.go b/pkg/supervisor/logwriter_test.go index 49b58182c6ac..c05baa72bbf6 100644 --- a/pkg/supervisor/logwriter_test.go +++ b/pkg/supervisor/logwriter_test.go @@ -86,22 +86,22 @@ func TestLogWriter(t *testing.T) { remaining := logs.AllEntries() for i, line := range test.out { - if !assert.NotEmpty(t, remaining, "Expected additional log entry: %s", line) { + if !assert.NotEmptyf(t, remaining, "Expected additional log entry: %s", line) { continue } chunk, isChunk := remaining[0].Data["chunk"] - assert.Equal(t, line.chunk != 0, isChunk, "Log entry %d chunk mismatch", i) + assert.Equalf(t, line.chunk != 0, isChunk, "Log entry %d chunk mismatch", i) if isChunk { - assert.Equal(t, line.chunk, chunk, "Log entry %d differs in chunk", i) + assert.Equalf(t, line.chunk, chunk, "Log entry %d differs in chunk", i) } - assert.Equal(t, line.msg, remaining[0].Message, "Log entry %d differs in message", i) + assert.Equalf(t, line.msg, remaining[0].Message, "Log entry %d differs in message", i) remaining = remaining[1:] } for _, entry := range remaining { - assert.Fail(t, "Unexpected log entry", "%s", entry.Message) + assert.Failf(t, "Unexpected log entry", "%s", entry.Message) } }) } diff --git a/pkg/supervisor/supervisor_test.go b/pkg/supervisor/supervisor_test.go index 925486546b24..80de74d10792 100644 --- a/pkg/supervisor/supervisor_test.go +++ b/pkg/supervisor/supervisor_test.go @@ -412,6 +412,6 @@ func selectCmd(t *testing.T, cmds ...cmd) (_ cmd) { tested = append(tested, candidate.binPath) } - require.Fail(t, "none of those executables in PATH, dunno how to create test process: %s", strings.Join(tested, ", ")) + require.Failf(t, "none of those executables in PATH, dunno how to create test process: %s", strings.Join(tested, ", ")) return // diverges above }