From 0b1aa55cbb14ce3b7c805a6262e2159c4a70bf73 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 20 Jul 2026 20:50:57 +0200 Subject: [PATCH] chore(pkg): refactor: convert tests to testify assert/require part 22 #### Description refactor: convert tests to testify assert/require in pkg/action Signed-off-by: Matthieu MOREL --- pkg/action/history_test.go | 4 +--- pkg/action/hooks_test.go | 17 ++++++----------- pkg/action/release_testing_test.go | 12 ++++-------- pkg/chart/v2/dependency_test.go | 10 ++++++---- pkg/chart/v2/lint/rules/deprecations_test.go | 11 ++++------- pkg/chart/v2/util/compatible_test.go | 10 ++++++---- pkg/cmd/helpers_test.go | 16 ++++++---------- pkg/cmd/show_test.go | 12 +++++------- pkg/registry/client_http_test.go | 10 ++++------ pkg/registry/registry_test.go | 10 ++++------ 10 files changed, 46 insertions(+), 66 deletions(-) diff --git a/pkg/action/history_test.go b/pkg/action/history_test.go index 31fdd4a96..51212b610 100644 --- a/pkg/action/history_test.go +++ b/pkg/action/history_test.go @@ -50,9 +50,7 @@ func TestHistoryRun(t *testing.T) { client.Max = 3 client.cfg.Releases.MaxHistory = 3 for _, rel := range []*release.Release{simpleRelease, updatedRelease} { - if err := client.cfg.Releases.Create(rel); err != nil { - t.Fatal(err, "Could not add releases to Config") - } + require.NoError(t, client.cfg.Releases.Create(rel), "Could not add releases to Config") } releases, err := config.Releases.ListReleases() diff --git a/pkg/action/hooks_test.go b/pkg/action/hooks_test.go index 20442af13..ad3a4b618 100644 --- a/pkg/action/hooks_test.go +++ b/pkg/action/hooks_test.go @@ -401,16 +401,12 @@ data: serverSideApply := true err := configuration.execHook(&tc.inputRelease, hookEvent, kube.StatusWatcherStrategy, nil, 600, serverSideApply) - if !reflect.DeepEqual(kubeClient.deleteRecord, tc.expectedDeleteRecord) { - t.Fatalf("Got unexpected delete record, expected: %#v, but got: %#v", kubeClient.deleteRecord, tc.expectedDeleteRecord) - } - - if err != nil && !tc.expectError { - t.Fatal("Got an unexpected error.") - } + require.Truef(t, reflect.DeepEqual(kubeClient.deleteRecord, tc.expectedDeleteRecord), "Got unexpected delete record, expected: %#v, but got: %#v", kubeClient.deleteRecord, tc.expectedDeleteRecord) - if err == nil && tc.expectError { - t.Fatal("Expected and error but did not get it.") + if !tc.expectError { + require.NoError(t, err) + } else { + require.Error(t, err) } }) } @@ -490,8 +486,7 @@ data: ctx := context.Background() waitOptions := []kube.WaitOption{kube.WithWaitContext(ctx)} - err := configuration.execHook(rel, release.HookPreInstall, kube.StatusWatcherStrategy, waitOptions, 600, false) - req.NoError(err) + req.NoError(configuration.execHook(rel, release.HookPreInstall, kube.StatusWatcherStrategy, waitOptions, 600, false)) // Verify that WaitOptions were passed to GetWaiter is.NotEmpty(failer.RecordedWaitOptions, "WaitOptions should be passed to GetWaiter") diff --git a/pkg/action/release_testing_test.go b/pkg/action/release_testing_test.go index 48a3251a1..91cb548a5 100644 --- a/pkg/action/release_testing_test.go +++ b/pkg/action/release_testing_test.go @@ -190,8 +190,7 @@ func TestGetContainerLogs_MultipleContainers(t *testing.T) { rt := &ReleaseTesting{Namespace: "default"} var buf bytes.Buffer - err := rt.getContainerLogs(&buf, client, "test-pod") - require.NoError(t, err) + require.NoError(t, rt.getContainerLogs(&buf, client, "test-pod")) output := buf.String() assert.Contains(t, output, "POD LOGS: test-pod (main)") assert.Contains(t, output, "POD LOGS: test-pod (sidecar)") @@ -217,8 +216,7 @@ func TestGetContainerLogs_WithInitContainers(t *testing.T) { rt := &ReleaseTesting{Namespace: "default"} var buf bytes.Buffer - err := rt.getContainerLogs(&buf, client, "test-pod") - require.NoError(t, err) + require.NoError(t, rt.getContainerLogs(&buf, client, "test-pod")) output := buf.String() // Init containers should appear before regular containers assert.Contains(t, output, "POD LOGS: test-pod (init-setup)") @@ -230,8 +228,7 @@ func TestGetContainerLogs_PodNotFound(t *testing.T) { rt := &ReleaseTesting{Namespace: "default"} var buf bytes.Buffer - err := rt.getContainerLogs(&buf, client, "nonexistent-pod") - assert.ErrorContains(t, err, "unable to get pod nonexistent-pod") + assert.ErrorContains(t, rt.getContainerLogs(&buf, client, "nonexistent-pod"), "unable to get pod nonexistent-pod") } func TestGetContainerLogs_OutputHeaderFormat(t *testing.T) { @@ -252,8 +249,7 @@ func TestGetContainerLogs_OutputHeaderFormat(t *testing.T) { rt := &ReleaseTesting{Namespace: "default"} var buf bytes.Buffer - err := rt.getContainerLogs(&buf, client, "multi-test") - require.NoError(t, err) + require.NoError(t, rt.getContainerLogs(&buf, client, "multi-test")) output := buf.String() assert.Contains(t, output, "POD LOGS: multi-test (container-a)") assert.Contains(t, output, "POD LOGS: multi-test (container-b)") diff --git a/pkg/chart/v2/dependency_test.go b/pkg/chart/v2/dependency_test.go index 35919bd7a..f44a6b06f 100644 --- a/pkg/chart/v2/dependency_test.go +++ b/pkg/chart/v2/dependency_test.go @@ -17,6 +17,8 @@ package v2 import ( "testing" + + "github.com/stretchr/testify/require" ) func TestValidateDependency(t *testing.T) { @@ -35,10 +37,10 @@ func TestValidateDependency(t *testing.T) { } { dep.Alias = value res := dep.Validate() - if res != nil && !shouldFail { - t.Errorf("Failed on case %q", dep.Alias) - } else if res == nil && shouldFail { - t.Errorf("Expected failure for %q", dep.Alias) + if shouldFail { + require.Errorf(t, res, "Expected failure for %q", dep.Alias) + } else { + require.NoErrorf(t, res, "Failed on case %q", dep.Alias) } } } diff --git a/pkg/chart/v2/lint/rules/deprecations_test.go b/pkg/chart/v2/lint/rules/deprecations_test.go index 0aa983678..3c8553cce 100644 --- a/pkg/chart/v2/lint/rules/deprecations_test.go +++ b/pkg/chart/v2/lint/rules/deprecations_test.go @@ -19,6 +19,7 @@ package rules import ( "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -28,17 +29,13 @@ func TestValidateNoDeprecations(t *testing.T) { Kind: "Deployment", } err := validateNoDeprecations(deprecated, nil) - if err == nil { - t.Fatal("Expected deprecated extension to be flagged") - } + require.Error(t, err, "Expected deprecated extension to be flagged") var depErr deprecatedAPIError require.ErrorAs(t, err, &depErr) require.NotEmptyf(t, depErr.Message, "Expected error message to be non-blank") - if err := validateNoDeprecations(&k8sYamlStruct{ + assert.NoError(t, validateNoDeprecations(&k8sYamlStruct{ APIVersion: "v1", Kind: "Pod", - }, nil); err != nil { - t.Error("Expected a v1 Pod to not be deprecated") - } + }, nil), "Expected a v1 Pod to not be deprecated") } diff --git a/pkg/chart/v2/util/compatible_test.go b/pkg/chart/v2/util/compatible_test.go index e17d33e35..9a57ef64a 100644 --- a/pkg/chart/v2/util/compatible_test.go +++ b/pkg/chart/v2/util/compatible_test.go @@ -17,7 +17,11 @@ limitations under the License. // Package version represents the current version of the project. package util -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestIsCompatibleRange(t *testing.T) { tests := []struct { @@ -36,8 +40,6 @@ func TestIsCompatibleRange(t *testing.T) { } for _, tt := range tests { - if IsCompatibleRange(tt.constraint, tt.ver) != tt.expected { - t.Errorf("expected constraint %s to be %v for %s", tt.constraint, tt.expected, tt.ver) - } + assert.Equal(t, tt.expected, IsCompatibleRange(tt.constraint, tt.ver), "expected constraint %s to be %v for %s", tt.constraint, tt.expected, tt.ver) } } diff --git a/pkg/cmd/helpers_test.go b/pkg/cmd/helpers_test.go index 3db5f38ab..611d1a54c 100644 --- a/pkg/cmd/helpers_test.go +++ b/pkg/cmd/helpers_test.go @@ -56,17 +56,14 @@ func runTestCmd(t *testing.T, tests []cmdTestCase) { storage := storageFixture() for _, rel := range tt.rels { - if err := storage.Create(rel); err != nil { - t.Fatal(err) - } + require.NoError(t, storage.Create(rel)) } t.Logf("running cmd (attempt %d): %s", i+1, tt.cmd) _, out, err := executeActionCommandC(storage, tt.cmd) - if tt.wantError && err == nil { - t.Errorf("expected error, got success with the following output:\n%s", out) - } - if !tt.wantError && err != nil { - t.Errorf("expected no error, got: '%v'", err) + if tt.wantError { + require.Error(t, err, "expected error, got success with the following output:\n%s", out) + } else { + require.NoError(t, err, "expected no error") } if tt.golden != "" { test.AssertGoldenString(t, out, tt.golden) @@ -294,8 +291,7 @@ func TestCmdGetDryRunFlagStrategy(t *testing.T) { if tc.ExpectedLog != nil { logResult := map[string]string{} - err = json.Unmarshal(logBuf.Bytes(), &logResult) - require.NoError(t, err) + require.NoError(t, json.Unmarshal(logBuf.Bytes(), &logResult)) assert.Equal(t, tc.ExpectedLog.Level, logResult["level"]) assert.Equal(t, tc.ExpectedLog.Msg, logResult["msg"]) diff --git a/pkg/cmd/show_test.go b/pkg/cmd/show_test.go index e24b8c442..3ed01d418 100644 --- a/pkg/cmd/show_test.go +++ b/pkg/cmd/show_test.go @@ -19,9 +19,11 @@ package cmd import ( "fmt" "path/filepath" - "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "helm.sh/helm/v4/pkg/repo/v1/repotest" ) @@ -32,9 +34,7 @@ func TestShowPreReleaseChart(t *testing.T) { ) defer srv.Stop() - if err := srv.LinkIndices(); err != nil { - t.Fatal(err) - } + require.NoError(t, srv.LinkIndices()) tests := []struct { name string @@ -79,9 +79,7 @@ func TestShowPreReleaseChart(t *testing.T) { _, _, err := executeActionCommand(cmd) if err != nil { if tt.fail { - if !strings.Contains(err.Error(), tt.expectedErr) { - t.Errorf("%q expected error: %s, got: %s", tt.name, tt.expectedErr, err.Error()) - } + assert.ErrorContains(t, err, tt.expectedErr, "%q expected error: %s, got: %s", tt.name, tt.expectedErr, err.Error()) return } t.Errorf("%q reported error: %s", tt.name, err) diff --git a/pkg/registry/client_http_test.go b/pkg/registry/client_http_test.go index 316a82d3f..0a51b3347 100644 --- a/pkg/registry/client_http_test.go +++ b/pkg/registry/client_http_test.go @@ -39,15 +39,13 @@ func (suite *HTTPRegistryClientTestSuite) TearDownSuite() { } func (suite *HTTPRegistryClientTestSuite) Test_0_Login() { - err := suite.RegistryClient.Login(suite.DockerRegistryHost, + suite.Require().Error(suite.RegistryClient.Login(suite.DockerRegistryHost, LoginOptBasicAuth("badverybad", "ohsobad"), - LoginOptPlainText(true)) - suite.Require().Error(err, "error logging into registry with bad credentials") + LoginOptPlainText(true)), "error logging into registry with bad credentials") - err = suite.RegistryClient.Login(suite.DockerRegistryHost, + suite.Require().NoError(suite.RegistryClient.Login(suite.DockerRegistryHost, LoginOptBasicAuth(testUsername, testPassword), - LoginOptPlainText(true)) - suite.Require().NoError(err, "no error logging into registry with good credentials") + LoginOptPlainText(true)), "no error logging into registry with good credentials") } func (suite *HTTPRegistryClientTestSuite) Test_1_Push() { diff --git a/pkg/registry/registry_test.go b/pkg/registry/registry_test.go index 429b15113..313cb861c 100644 --- a/pkg/registry/registry_test.go +++ b/pkg/registry/registry_test.go @@ -73,10 +73,8 @@ type TestRegistry struct { func setup(suite *TestRegistry, tlsEnabled, insecure bool, auth string) { suite.WorkspaceDir = testWorkspaceDir - err := os.RemoveAll(suite.WorkspaceDir) - suite.Require().NoError(err, "no error removing test workspace dir") - err = os.Mkdir(suite.WorkspaceDir, 0o700) - suite.Require().NoError(err, "no error creating test workspace dir") + suite.Require().NoError(os.RemoveAll(suite.WorkspaceDir), "no error removing test workspace dir") + suite.Require().NoError(os.Mkdir(suite.WorkspaceDir, 0o700), "no error creating test workspace dir") var out bytes.Buffer @@ -92,6 +90,7 @@ func setup(suite *TestRegistry, tlsEnabled, insecure bool, auth string) { ClientOptBasicAuth(testUsername, testPassword), } + var err error if tlsEnabled { var tlsConf *tls.Config if insecure { @@ -122,8 +121,7 @@ func setup(suite *TestRegistry, tlsEnabled, insecure bool, auth string) { pwBytes, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.DefaultCost) suite.Require().NoError(err, "no error generating bcrypt password for test htpasswd file") htpasswdPath := filepath.Join(suite.WorkspaceDir, testHtpasswdFileBasename) - err = os.WriteFile(htpasswdPath, fmt.Appendf(nil, "%s:%s\n", testUsername, string(pwBytes)), 0o644) - suite.Require().NoError(err, "no error creating test htpasswd file") + suite.Require().NoError(os.WriteFile(htpasswdPath, fmt.Appendf(nil, "%s:%s\n", testUsername, string(pwBytes)), 0o644), "no error creating test htpasswd file") // Registry config config := &configuration.Configuration{}