From 4073566e285d5bfaafaf0cec2b927fa037bfcb2a Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 20 Jul 2026 20:50:55 +0200 Subject: [PATCH] chore(pkg): refactor: convert tests to testify assert/require part 17 #### Description refactor: convert tests to testify assert/require in pkg/cmd Signed-off-by: Matthieu MOREL --- pkg/action/uninstall_test.go | 4 +- pkg/chart/common/capabilities_test.go | 80 +++++++----------------- pkg/chart/v2/lint/rules/template_test.go | 71 +++++---------------- pkg/cmd/dependency_build_test.go | 67 +++++++------------- pkg/cmd/plugin_package_test.go | 75 +++++++--------------- pkg/cmd/repo_add_test.go | 76 ++++++---------------- 6 files changed, 108 insertions(+), 265 deletions(-) diff --git a/pkg/action/uninstall_test.go b/pkg/action/uninstall_test.go index 913ade1a5..f36fe7874 100644 --- a/pkg/action/uninstall_test.go +++ b/pkg/action/uninstall_test.go @@ -121,7 +121,7 @@ func TestUninstallRelease_Wait(t *testing.T) { unAction.cfg.KubeClient = failer resi, err := unAction.Run(rel.Name) req.Error(err) - is.Contains(err.Error(), "U timed out") + req.ErrorContains(err, "U timed out") res, err := releaserToV1Release(resi.Release) req.NoError(err) is.Equal(common.StatusUninstalled, res.Info.Status) @@ -163,7 +163,7 @@ func TestUninstallRelease_Cascade(t *testing.T) { unAction.cfg.KubeClient = failer _, err := unAction.Run(rel.Name) require.Error(t, err) - is.Contains(err.Error(), "failed to delete release: come-fail-away") + is.ErrorContains(err, "failed to delete release: come-fail-away") } func TestUninstallRun_UnreachableKubeClient(t *testing.T) { diff --git a/pkg/chart/common/capabilities_test.go b/pkg/chart/common/capabilities_test.go index c8d47581c..b099e3193 100644 --- a/pkg/chart/common/capabilities_test.go +++ b/pkg/chart/common/capabilities_test.go @@ -17,68 +17,44 @@ package common import ( "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestVersionSet(t *testing.T) { vs := VersionSet{"v1", "apps/v1"} - if d := len(vs); d != 2 { - t.Errorf("Expected 2 versions, got %d", d) - } + d := len(vs) + assert.Equalf(t, 2, d, "Expected 2 versions, got %d", d) - if !vs.Has("apps/v1") { - t.Error("Expected to find apps/v1") - } + assert.True(t, vs.Has("apps/v1"), "Expected to find apps/v1") - if vs.Has("Spanish/inquisition") { - t.Error("No one expects the Spanish/inquisition") - } + assert.False(t, vs.Has("Spanish/inquisition"), "No one expects the Spanish/inquisition") } func TestDefaultVersionSet(t *testing.T) { - if !DefaultVersionSet.Has("v1") { - t.Error("Expected core v1 version set") - } + assert.True(t, DefaultVersionSet.Has("v1"), "Expected core v1 version set") } func TestDefaultCapabilities(t *testing.T) { caps := DefaultCapabilities kv := caps.KubeVersion - if kv.String() != "v1.20.0" { - t.Errorf("Expected default KubeVersion.String() to be v1.20.0, got %q", kv.String()) - } - if kv.Version != "v1.20.0" { - t.Errorf("Expected default KubeVersion.Version to be v1.20.0, got %q", kv.Version) - } - if kv.GitVersion() != "v1.20.0" { - t.Errorf("Expected default KubeVersion.GitVersion() to be v1.20.0, got %q", kv.Version) - } - if kv.Major != "1" { - t.Errorf("Expected default KubeVersion.Major to be 1, got %q", kv.Major) - } - if kv.Minor != "20" { - t.Errorf("Expected default KubeVersion.Minor to be 20, got %q", kv.Minor) - } + assert.Equalf(t, "v1.20.0", kv.String(), "Expected default KubeVersion.String() to be v1.20.0, got %q", kv.String()) + assert.Equalf(t, "v1.20.0", kv.Version, "Expected default KubeVersion.Version to be v1.20.0, got %q", kv.Version) + assert.Equalf(t, "v1.20.0", kv.GitVersion(), "Expected default KubeVersion.GitVersion() to be v1.20.0, got %q", kv.Version) + assert.Equalf(t, "1", kv.Major, "Expected default KubeVersion.Major to be 1, got %q", kv.Major) + assert.Equalf(t, "20", kv.Minor, "Expected default KubeVersion.Minor to be 20, got %q", kv.Minor) hv := caps.HelmVersion - if hv.Version != "v4.2" { - t.Errorf("Expected default HelmVersion to be v4.2, got %q", hv.Version) - } + assert.Equalf(t, "v4.2", hv.Version, "Expected default HelmVersion to be v4.2, got %q", hv.Version) } func TestParseKubeVersion(t *testing.T) { kv, err := ParseKubeVersion("v1.16.0") - if err != nil { - t.Error("Expected v1.16.0 to parse successfully") - } - if kv.Version != "v1.16.0" { - t.Errorf("Expected parsed KubeVersion.Version to be v1.16.0, got %q", kv.String()) - } - if kv.Major != "1" { - t.Errorf("Expected parsed KubeVersion.Major to be 1, got %q", kv.Major) - } - if kv.Minor != "16" { - t.Errorf("Expected parsed KubeVersion.Minor to be 16, got %q", kv.Minor) - } + require.NoError(t, err, "Expected v1.16.0 to parse successfully") + assert.Equalf(t, "v1.16.0", kv.Version, "Expected parsed KubeVersion.Version to be v1.16.0, got %q", kv.String()) + assert.Equalf(t, "1", kv.Major, "Expected parsed KubeVersion.Major to be 1, got %q", kv.Major) + assert.Equalf(t, "16", kv.Minor, "Expected parsed KubeVersion.Minor to be 16, got %q", kv.Minor) } func TestParseKubeVersionWithVendorSuffixes(t *testing.T) { @@ -101,21 +77,11 @@ func TestParseKubeVersionWithVendorSuffixes(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { kv, err := ParseKubeVersion(tt.input) - if err != nil { - t.Fatalf("ParseKubeVersion() error = %v", err) - } - if kv.Version != tt.wantVer { - t.Errorf("Version = %q, want %q", kv.Version, tt.wantVer) - } - if kv.String() != tt.wantString { - t.Errorf("String() = %q, want %q", kv.String(), tt.wantString) - } - if kv.Major != tt.wantMajor { - t.Errorf("Major = %q, want %q", kv.Major, tt.wantMajor) - } - if kv.Minor != tt.wantMinor { - t.Errorf("Minor = %q, want %q", kv.Minor, tt.wantMinor) - } + require.NoErrorf(t, err, "ParseKubeVersion()") + assert.Equalf(t, tt.wantVer, kv.Version, "Version = %q, want %q", kv.Version, tt.wantVer) + assert.Equalf(t, tt.wantString, kv.String(), "String() = %q, want %q", kv.String(), tt.wantString) + assert.Equalf(t, tt.wantMajor, kv.Major, "Major = %q, want %q", kv.Major, tt.wantMajor) + assert.Equalf(t, tt.wantMinor, kv.Minor, "Minor = %q, want %q", kv.Minor, tt.wantMinor) }) } } diff --git a/pkg/chart/v2/lint/rules/template_test.go b/pkg/chart/v2/lint/rules/template_test.go index 12eec7531..37a33a7eb 100644 --- a/pkg/chart/v2/lint/rules/template_test.go +++ b/pkg/chart/v2/lint/rules/template_test.go @@ -20,7 +20,6 @@ import ( "fmt" "os" "path/filepath" - "strings" "testing" "time" @@ -38,17 +37,11 @@ const templateTestBasedir = "./testdata/albatross" func TestValidateAllowedExtension(t *testing.T) { var failTest = []string{"/foo", "/test.toml"} for _, test := range failTest { - err := validateAllowedExtension(test) - if err == nil || !strings.Contains(err.Error(), "Valid extensions are .yaml, .yml, .tpl, or .txt") { - t.Errorf("validateAllowedExtension('%s') to return \"Valid extensions are .yaml, .yml, .tpl, or .txt\", got no error", test) - } + require.ErrorContainsf(t, validateAllowedExtension(test), "Valid extensions are .yaml, .yml, .tpl, or .txt", "validateAllowedExtension('%s') to return \"Valid extensions are .yaml, .yml, .tpl, or .txt\", got no error", test) } var successTest = []string{"/foo.yaml", "foo.yaml", "foo.tpl", "/foo/bar/baz.yaml", "NOTES.txt"} for _, test := range successTest { - err := validateAllowedExtension(test) - if err != nil { - t.Errorf("validateAllowedExtension('%s') to return no error but got \"%s\"", test, err.Error()) - } + assert.NoError(t, validateAllowedExtension(test), "validateAllowedExtension('%s') to return no error", test) } } @@ -65,13 +58,8 @@ func TestTemplateParsing(t *testing.T) { TemplateLinterSkipSchemaValidation(false)) res := linter.Messages - if len(res) != 1 { - t.Fatalf("Expected one error, got %d, %v", len(res), res) - } - - if !strings.Contains(res[0].Err.Error(), "deliberateSyntaxError") { - t.Errorf("Unexpected error: %s", res[0]) - } + require.Len(t, res, 1, "Expected one error, got %d, %v", len(res), res) + assert.ErrorContains(t, res[0].Err, "deliberateSyntaxError") } var wrongTemplatePath = filepath.Join(templateTestBasedir, "templates", "fail.yaml") @@ -92,9 +80,7 @@ func TestTemplateIntegrationHappyPath(t *testing.T) { TemplateLinterSkipSchemaValidation(false)) res := linter.Messages - if len(res) != 0 { - t.Fatalf("Expected no error, got %d, %v", len(res), res) - } + require.Empty(t, res, "Expected no error, got %d, %v", len(res), res) } func TestMultiTemplateFail(t *testing.T) { @@ -106,13 +92,8 @@ func TestMultiTemplateFail(t *testing.T) { TemplateLinterSkipSchemaValidation(false)) res := linter.Messages - if len(res) != 1 { - t.Fatalf("Expected 1 error, got %d, %v", len(res), res) - } - - if !strings.Contains(res[0].Err.Error(), "object name does not conform to Kubernetes naming requirements") { - t.Errorf("Unexpected error: %s", res[0].Err) - } + require.Len(t, res, 1, "Expected 1 error, got %d, %v", len(res), res) + assert.ErrorContains(t, res[0].Err, "object name does not conform to Kubernetes naming requirements") } func TestValidateMetadataName(t *testing.T) { @@ -221,9 +202,7 @@ func TestDeprecatedAPIFails(t *testing.T) { } tmpdir := t.TempDir() - if err := chartutil.SaveDir(&mychart, tmpdir); err != nil { - t.Fatal(err) - } + require.NoError(t, chartutil.SaveDir(&mychart, tmpdir)) linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())} Templates( @@ -279,9 +258,7 @@ func TestStrictTemplateParsingMapError(t *testing.T) { }, } dir := t.TempDir() - if err := chartutil.SaveDir(&ch, dir); err != nil { - t.Fatal(err) - } + require.NoError(t, chartutil.SaveDir(&ch, dir)) linter := &support.Linter{ ChartDir: filepath.Join(dir, ch.Metadata.Name), } @@ -327,9 +304,7 @@ spec: - name: nginx image: nginx:1.14.2 ` - if err := validateMatchSelector(md, manifest); err != nil { - t.Error(err) - } + require.NoError(t, validateMatchSelector(md, manifest)) manifest = ` apiVersion: apps/v1 kind: Deployment @@ -351,9 +326,7 @@ spec: - name: nginx image: nginx:1.14.2 ` - if err := validateMatchSelector(md, manifest); err != nil { - t.Error(err) - } + require.NoError(t, validateMatchSelector(md, manifest)) manifest = ` apiVersion: apps/v1 kind: Deployment @@ -372,9 +345,7 @@ spec: - name: nginx image: nginx:1.14.2 ` - if err := validateMatchSelector(md, manifest); err == nil { - t.Error("expected Deployment with no selector to fail") - } + assert.Error(t, validateMatchSelector(md, manifest), "expected Deployment with no selector to fail") } func TestValidateTopIndentLevel(t *testing.T) { @@ -413,9 +384,7 @@ func TestEmptyWithCommentsManifests(t *testing.T) { } tmpdir := t.TempDir() - if err := chartutil.SaveDir(&mychart, tmpdir); err != nil { - t.Fatal(err) - } + require.NoError(t, chartutil.SaveDir(&mychart, tmpdir)) linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())} Templates( @@ -448,10 +417,7 @@ items: annotations: helm.sh/resource-policy: keep ` - - if err := validateListAnnotations(md, manifest); err == nil { - t.Fatal("expected list with nested keep annotations to fail") - } + require.Error(t, validateListAnnotations(md, manifest), "expected list with nested keep annotations to fail") manifest = ` apiVersion: v1 @@ -463,10 +429,7 @@ items: - apiVersion: v1 kind: ConfigMap ` - - if err := validateListAnnotations(md, manifest); err != nil { - t.Fatalf("List objects keep annotations should pass. got: %s", err) - } + require.NoErrorf(t, validateListAnnotations(md, manifest), "List objects keep annotations should pass. got") } func TestIsYamlFileExtension(t *testing.T) { @@ -482,8 +445,6 @@ func TestIsYamlFileExtension(t *testing.T) { for _, test := range tests { result := isYamlFileExtension(test.filename) - if result != test.expected { - t.Errorf("isYamlFileExtension(%s) = %v; want %v", test.filename, result, test.expected) - } + assert.Equal(t, test.expected, result, "isYamlFileExtension(%s) = %v; want %v", test.filename, result, test.expected) } } diff --git a/pkg/cmd/dependency_build_test.go b/pkg/cmd/dependency_build_test.go index 7b3bea28a..485ae18b3 100644 --- a/pkg/cmd/dependency_build_test.go +++ b/pkg/cmd/dependency_build_test.go @@ -19,9 +19,11 @@ import ( "fmt" "os" "path/filepath" - "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + chartutil "helm.sh/helm/v4/pkg/chart/v2/util" "helm.sh/helm/v4/pkg/provenance" "helm.sh/helm/v4/pkg/repo/v1" @@ -39,15 +41,12 @@ func TestDependencyBuildCmd(t *testing.T) { srv.LinkIndices() ociSrv, err := repotest.NewOCIServer(t, srv.Root()) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ociChartName := "oci-depending-chart" c := createTestingMetadataForOCI(ociChartName, ociSrv.RegistryURL) - if _, err := chartutil.Save(c, ociSrv.Dir); err != nil { - t.Fatal(err) - } + _, err = chartutil.Save(c, ociSrv.Dir) + require.NoError(t, err) ociSrv.Run(t, repotest.WithDependingChart(c)) dir := func(p ...string) string { @@ -67,25 +66,19 @@ func TestDependencyBuildCmd(t *testing.T) { t.Fatal(err) } - if !strings.Contains(out, `update from the "test" chart repository`) { - t.Errorf("Repo did not get updated\n%s", out) - } + assert.Contains(t, out, `update from the "test" chart repository`, "Repo did not get updated\n%s", out) // Make sure the actual file got downloaded. expect := filepath.Join(rootDir, chartname, "charts", "reqtest-0.1.0.tgz") - if _, err := os.Stat(expect); err != nil { - t.Fatal(err) - } + _, err = os.Stat(expect) + require.NoError(t, err) // In the second pass, we want to remove the chart's request dependency, // then see if it restores from the lock. lockfile := filepath.Join(rootDir, chartname, "Chart.lock") - if _, err := os.Stat(lockfile); err != nil { - t.Fatal(err) - } - if err := os.RemoveAll(expect); err != nil { - t.Fatal(err) - } + _, err = os.Stat(lockfile) + require.NoError(t, err) + require.NoError(t, os.RemoveAll(expect)) _, out, err = executeActionCommand(cmd) if err != nil { @@ -94,28 +87,21 @@ func TestDependencyBuildCmd(t *testing.T) { } // Now repeat the test that the dependency exists. - if _, err := os.Stat(expect); err != nil { - t.Fatal(err) - } + _, err = os.Stat(expect) + require.NoError(t, err) // Make sure that build is also fetching the correct version. hash, err := provenance.DigestFile(expect) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) i, err := repo.LoadIndexFile(filepath.Join(rootDir, "index.yaml")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) reqver := i.Entries["reqtest"][0] - if h := reqver.Digest; h != hash { - t.Errorf("Failed hash match: expected %s, got %s", hash, h) - } - if v := reqver.Version; v != "0.1.0" { - t.Errorf("mismatched versions. Expected %q, got %q", "0.1.0", v) - } + h := reqver.Digest + assert.Equalf(t, h, hash, "Failed hash match: expected %s, got %s", hash, h) + v := reqver.Version + assert.Equalf(t, "0.1.0", v, "mismatched versions. Expected %q, got %q", "0.1.0", v) skipRefreshCmd := fmt.Sprintf("dependency build '%s' --skip-refresh --repository-config %s --repository-cache %s --plain-http", filepath.Join(rootDir, chartname), repoFile, rootDir) _, out, err = executeActionCommand(skipRefreshCmd) @@ -126,14 +112,10 @@ func TestDependencyBuildCmd(t *testing.T) { t.Fatal(err) } - if strings.Contains(out, `update from the "test" chart repository`) { - t.Errorf("Repo did get updated\n%s", out) - } + assert.NotContains(t, out, `update from the "test" chart repository`, "Repo did get updated\n%s", out) // OCI dependencies - if err := chartutil.SaveDir(c, dir()); err != nil { - t.Fatal(err) - } + require.NoError(t, chartutil.SaveDir(c, dir())) cmd = fmt.Sprintf("dependency build '%s' --repository-config %s --repository-cache %s --registry-config %s/config.json --plain-http", dir(ociChartName), dir("repositories.yaml"), @@ -145,9 +127,8 @@ func TestDependencyBuildCmd(t *testing.T) { t.Fatal(err) } expect = dir(ociChartName, "charts/oci-dependent-chart-0.1.0.tgz") - if _, err := os.Stat(expect); err != nil { - t.Fatal(err) - } + _, err = os.Stat(expect) + require.NoError(t, err) } func TestDependencyBuildCmdWithHelmV2Hash(t *testing.T) { diff --git a/pkg/cmd/plugin_package_test.go b/pkg/cmd/plugin_package_test.go index b5ecf2bf1..e04498b98 100644 --- a/pkg/cmd/plugin_package_test.go +++ b/pkg/cmd/plugin_package_test.go @@ -19,8 +19,10 @@ import ( "bytes" "os" "path/filepath" - "strings" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Common plugin.yaml content for v1 format tests @@ -43,14 +45,10 @@ func TestPluginPackageWithoutSigning(t *testing.T) { // Create a test plugin directory tempDir := t.TempDir() pluginDir := filepath.Join(tempDir, "test-plugin") - if err := os.MkdirAll(pluginDir, 0o755); err != nil { - t.Fatal(err) - } + require.NoError(t, os.MkdirAll(pluginDir, 0o755)) // Create a plugin.yaml file - if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644); err != nil { - t.Fatal(err) - } + require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644)) // Create package options with sign=false o := &pluginPackageOptions{ @@ -61,47 +59,34 @@ func TestPluginPackageWithoutSigning(t *testing.T) { // Run the package command out := &bytes.Buffer{} - err := o.run(out) // Should succeed without error - if err != nil { - t.Errorf("unexpected error: %v", err) - } + require.NoError(t, o.run(out)) // Check that tarball was created with plugin name and version tarballPath := filepath.Join(tempDir, "test-plugin-1.0.0.tgz") - if _, err := os.Stat(tarballPath); os.IsNotExist(err) { - t.Error("tarball should exist when sign=false") - } + _, err := os.Stat(tarballPath) + assert.False(t, os.IsNotExist(err), "tarball should exist when sign=false") // Check that no .prov file was created provPath := tarballPath + ".prov" - if _, err := os.Stat(provPath); !os.IsNotExist(err) { - t.Error("provenance file should not exist when sign=false") - } + _, err = os.Stat(provPath) + assert.True(t, os.IsNotExist(err), "provenance file should not exist when sign=false") // Output should contain warning about skipping signing output := out.String() - if !strings.Contains(output, "WARNING: Skipping plugin signing") { - t.Error("should print warning when signing is skipped") - } - if !strings.Contains(output, "Successfully packaged") { - t.Error("should print success message") - } + assert.Contains(t, output, "WARNING: Skipping plugin signing", "should print warning when signing is skipped") + assert.Contains(t, output, "Successfully packaged", "should print success message") } func TestPluginPackageDefaultRequiresSigning(t *testing.T) { // Create a test plugin directory tempDir := t.TempDir() pluginDir := filepath.Join(tempDir, "test-plugin") - if err := os.MkdirAll(pluginDir, 0o755); err != nil { - t.Fatal(err) - } + require.NoError(t, os.MkdirAll(pluginDir, 0o755)) // Create a plugin.yaml file - if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644); err != nil { - t.Fatal(err) - } + require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644)) // Create package options with default sign=true and invalid keyring o := &pluginPackageOptions{ @@ -113,32 +98,24 @@ func TestPluginPackageDefaultRequiresSigning(t *testing.T) { // Run the package command out := &bytes.Buffer{} - err := o.run(out) // Should fail because signing is required by default - if err == nil { - t.Error("expected error when signing fails with default settings") - } + require.Error(t, o.run(out), "expected error when signing fails with default settings") // Check that no tarball was created tarballPath := filepath.Join(tempDir, "test-plugin.tgz") - if _, err := os.Stat(tarballPath); !os.IsNotExist(err) { - t.Error("tarball should not exist when signing fails") - } + _, err := os.Stat(tarballPath) + assert.True(t, os.IsNotExist(err), "tarball should not exist when signing fails") } func TestPluginPackageSigningFailure(t *testing.T) { // Create a test plugin directory tempDir := t.TempDir() pluginDir := filepath.Join(tempDir, "test-plugin") - if err := os.MkdirAll(pluginDir, 0o755); err != nil { - t.Fatal(err) - } + require.NoError(t, os.MkdirAll(pluginDir, 0o755)) // Create a plugin.yaml file - if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644); err != nil { - t.Fatal(err) - } + require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644)) // Create package options with sign flag but invalid keyring o := &pluginPackageOptions{ @@ -150,21 +127,15 @@ func TestPluginPackageSigningFailure(t *testing.T) { // Run the package command out := &bytes.Buffer{} - err := o.run(out) // Should get an error - if err == nil { - t.Error("expected error when signing fails, got nil") - } + require.Error(t, o.run(out), "expected error when signing fails, got nil") // Check that no tarball was created tarballPath := filepath.Join(tempDir, "test-plugin.tgz") - if _, err := os.Stat(tarballPath); !os.IsNotExist(err) { - t.Error("tarball should not exist when signing fails") - } + _, err := os.Stat(tarballPath) + assert.True(t, os.IsNotExist(err), "tarball should not exist when signing fails") // Output should not contain success message - if bytes.Contains(out.Bytes(), []byte("Successfully packaged")) { - t.Error("should not print success message when signing fails") - } + assert.False(t, bytes.Contains(out.Bytes(), []byte("Successfully packaged")), "should not print success message when signing fails") } diff --git a/pkg/cmd/repo_add_test.go b/pkg/cmd/repo_add_test.go index ed677f98a..6ed2a7422 100644 --- a/pkg/cmd/repo_add_test.go +++ b/pkg/cmd/repo_add_test.go @@ -17,16 +17,16 @@ limitations under the License. package cmd import ( - "errors" "fmt" "io" "io/fs" "os" "path/filepath" - "strings" "sync" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "sigs.k8s.io/yaml" "helm.sh/helm/v4/pkg/helmpath" @@ -50,9 +50,7 @@ func TestRepoAddCmd(t *testing.T) { defer srv2.Stop() tmpdir := filepath.Join(t.TempDir(), "path-component.yaml", "data") - if err := os.MkdirAll(tmpdir, 0o777); err != nil { - t.Fatal(err) - } + require.NoError(t, os.MkdirAll(tmpdir, 0o777)) repoFile := filepath.Join(tmpdir, "repositories.yaml") tests := []cmdTestCase{ @@ -101,37 +99,24 @@ func TestRepoAdd(t *testing.T) { } t.Setenv(xdg.CacheHomeEnvVar, rootDir) - if err := o.run(io.Discard); err != nil { - t.Error(err) - } + require.NoError(t, o.run(io.Discard)) f, err := repo.LoadFile(repoFile) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) - if !f.Has(testRepoName) { - t.Errorf("%s was not successfully inserted into %s", testRepoName, repoFile) - } + assert.Truef(t, f.Has(testRepoName), "%s was not successfully inserted into %s", testRepoName, repoFile) idx := filepath.Join(helmpath.CachePath("repository"), helmpath.CacheIndexFile(testRepoName)) - if _, err := os.Stat(idx); errors.Is(err, fs.ErrNotExist) { - t.Errorf("Error cache index file was not created for repository %s", testRepoName) - } + _, err = os.Stat(idx) + require.NotErrorIsf(t, err, fs.ErrNotExist, "Error cache index file was not created for repository %s", testRepoName) idx = filepath.Join(helmpath.CachePath("repository"), helmpath.CacheChartsFile(testRepoName)) - if _, err := os.Stat(idx); errors.Is(err, fs.ErrNotExist) { - t.Errorf("Error cache charts file was not created for repository %s", testRepoName) - } + _, err = os.Stat(idx) + require.NotErrorIsf(t, err, fs.ErrNotExist, "Error cache charts file was not created for repository %s", testRepoName) o.forceUpdate = true - if err := o.run(io.Discard); err != nil { - t.Errorf("Repository was not updated: %s", err) - } - - if err := o.run(io.Discard); err != nil { - t.Error("Duplicate repository name was added") - } + require.NoError(t, o.run(io.Discard), "Repository was not updated") + assert.NoError(t, o.run(io.Discard), "Duplicate repository name was added") } func TestRepoAddCheckLegalName(t *testing.T) { @@ -156,14 +141,7 @@ func TestRepoAddCheckLegalName(t *testing.T) { t.Setenv(xdg.CacheHomeEnvVar, rootDir) wantErrorMsg := fmt.Sprintf("repository name (%s) contains '/', please specify a different name without '/'", testRepoName) - - if err := o.run(io.Discard); err != nil { - if wantErrorMsg != err.Error() { - t.Fatalf("Actual error %s, not equal to expected error %s", err, wantErrorMsg) - } - } else { - t.Fatal("expect reported an error.") - } + require.EqualError(t, o.run(io.Discard), wantErrorMsg) } func TestRepoAddConcurrentGoRoutines(t *testing.T) { @@ -209,29 +187,21 @@ func repoAddConcurrent(t *testing.T, testName, repoFile string) { forceUpdate: false, repoFile: repoFile, } - if err := o.run(io.Discard); err != nil { - t.Error(err) - } + assert.NoError(t, o.run(io.Discard)) }(fmt.Sprintf("%s-%d", testName, i)) } wg.Wait() b, err := os.ReadFile(repoFile) - if err != nil { - t.Error(err) - } + require.NoError(t, err) var f repo.File - if err := yaml.Unmarshal(b, &f); err != nil { - t.Error(err) - } + require.NoError(t, yaml.Unmarshal(b, &f)) var name string for i := range 3 { name = fmt.Sprintf("%s-%d", testName, i) - if !f.Has(name) { - t.Errorf("%s was not successfully inserted into %s: %s", name, repoFile, f.Repositories[0]) - } + assert.Truef(t, f.Has(name), "%s was not successfully inserted into %s: %s", name, repoFile, f.Repositories[0]) } } @@ -252,9 +222,7 @@ func TestRepoAddWithPasswordFromStdin(t *testing.T) { defer resetEnv()() in, err := os.Open("testdata/password") - if err != nil { - t.Errorf("unexpected error, got '%v'", err) - } + require.NoError(t, err) tmpdir := t.TempDir() repoFile := filepath.Join(tmpdir, "repositories.yaml") @@ -266,11 +234,7 @@ func TestRepoAddWithPasswordFromStdin(t *testing.T) { cmd := fmt.Sprintf("repo add %s %s --repository-config %s --repository-cache %s --username %s --password-stdin", testName, srv.URL(), repoFile, tmpdir, username) var result string _, result, err = executeActionCommandStdinC(store, in, cmd) - if err != nil { - t.Errorf("unexpected error, got '%v'", err) - } - if !strings.Contains(result, fmt.Sprintf("%q has been added to your repositories", testName)) { - t.Errorf("Repo was not successfully added. Output: %s", result) - } + require.NoError(t, err) + assert.Contains(t, result, fmt.Sprintf("%q has been added to your repositories", testName), "Repo was not successfully added. Output: %s", result) }