Merge pull request #32433 from mmorel-35/testifylint-manual-assert-pkg-17

chore(pkg): refactor: convert tests to testify assert/require part 17
pull/32453/head
Terry Howe 2 months ago committed by GitHub
commit 54b915e38a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -121,7 +121,7 @@ func TestUninstallRelease_Wait(t *testing.T) {
unAction.cfg.KubeClient = failer unAction.cfg.KubeClient = failer
resi, err := unAction.Run(rel.Name) resi, err := unAction.Run(rel.Name)
req.Error(err) req.Error(err)
is.Contains(err.Error(), "U timed out") req.ErrorContains(err, "U timed out")
res, err := releaserToV1Release(resi.Release) res, err := releaserToV1Release(resi.Release)
req.NoError(err) req.NoError(err)
is.Equal(common.StatusUninstalled, res.Info.Status) is.Equal(common.StatusUninstalled, res.Info.Status)
@ -163,7 +163,7 @@ func TestUninstallRelease_Cascade(t *testing.T) {
unAction.cfg.KubeClient = failer unAction.cfg.KubeClient = failer
_, err := unAction.Run(rel.Name) _, err := unAction.Run(rel.Name)
require.Error(t, err) 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) { func TestUninstallRun_UnreachableKubeClient(t *testing.T) {

@ -17,68 +17,44 @@ package common
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestVersionSet(t *testing.T) { func TestVersionSet(t *testing.T) {
vs := VersionSet{"v1", "apps/v1"} vs := VersionSet{"v1", "apps/v1"}
if d := len(vs); d != 2 { d := len(vs)
t.Errorf("Expected 2 versions, got %d", d) assert.Equalf(t, 2, d, "Expected 2 versions, got %d", d)
}
if !vs.Has("apps/v1") { assert.True(t, vs.Has("apps/v1"), "Expected to find apps/v1")
t.Error("Expected to find apps/v1")
}
if vs.Has("Spanish/inquisition") { assert.False(t, vs.Has("Spanish/inquisition"), "No one expects the Spanish/inquisition")
t.Error("No one expects the Spanish/inquisition")
}
} }
func TestDefaultVersionSet(t *testing.T) { func TestDefaultVersionSet(t *testing.T) {
if !DefaultVersionSet.Has("v1") { assert.True(t, DefaultVersionSet.Has("v1"), "Expected core v1 version set")
t.Error("Expected core v1 version set")
}
} }
func TestDefaultCapabilities(t *testing.T) { func TestDefaultCapabilities(t *testing.T) {
caps := DefaultCapabilities caps := DefaultCapabilities
kv := caps.KubeVersion kv := caps.KubeVersion
if kv.String() != "v1.20.0" { assert.Equalf(t, "v1.20.0", kv.String(), "Expected default KubeVersion.String() to be v1.20.0, got %q", kv.String())
t.Errorf("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)
if kv.Version != "v1.20.0" { assert.Equalf(t, "1", kv.Major, "Expected default KubeVersion.Major to be 1, got %q", kv.Major)
t.Errorf("Expected default KubeVersion.Version to be v1.20.0, got %q", kv.Version) assert.Equalf(t, "20", kv.Minor, "Expected default KubeVersion.Minor to be 20, got %q", kv.Minor)
}
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)
}
hv := caps.HelmVersion hv := caps.HelmVersion
if hv.Version != "v4.2" { assert.Equalf(t, "v4.2", hv.Version, "Expected default HelmVersion to be v4.2, got %q", hv.Version)
t.Errorf("Expected default HelmVersion to be v4.2, got %q", hv.Version)
}
} }
func TestParseKubeVersion(t *testing.T) { func TestParseKubeVersion(t *testing.T) {
kv, err := ParseKubeVersion("v1.16.0") kv, err := ParseKubeVersion("v1.16.0")
if err != nil { require.NoError(t, err, "Expected v1.16.0 to parse successfully")
t.Error("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)
if kv.Version != "v1.16.0" { assert.Equalf(t, "16", kv.Minor, "Expected parsed KubeVersion.Minor to be 16, got %q", kv.Minor)
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)
}
} }
func TestParseKubeVersionWithVendorSuffixes(t *testing.T) { func TestParseKubeVersionWithVendorSuffixes(t *testing.T) {
@ -101,21 +77,11 @@ func TestParseKubeVersionWithVendorSuffixes(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
kv, err := ParseKubeVersion(tt.input) kv, err := ParseKubeVersion(tt.input)
if err != nil { require.NoErrorf(t, err, "ParseKubeVersion()")
t.Fatalf("ParseKubeVersion() error = %v", err) 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)
if kv.Version != tt.wantVer { assert.Equalf(t, tt.wantMajor, kv.Major, "Major = %q, want %q", kv.Major, tt.wantMajor)
t.Errorf("Version = %q, want %q", kv.Version, tt.wantVer) assert.Equalf(t, tt.wantMinor, kv.Minor, "Minor = %q, want %q", kv.Minor, tt.wantMinor)
}
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)
}
}) })
} }
} }

@ -20,7 +20,6 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"time" "time"
@ -38,17 +37,11 @@ const templateTestBasedir = "./testdata/albatross"
func TestValidateAllowedExtension(t *testing.T) { func TestValidateAllowedExtension(t *testing.T) {
var failTest = []string{"/foo", "/test.toml"} var failTest = []string{"/foo", "/test.toml"}
for _, test := range failTest { for _, test := range failTest {
err := validateAllowedExtension(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)
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)
}
} }
var successTest = []string{"/foo.yaml", "foo.yaml", "foo.tpl", "/foo/bar/baz.yaml", "NOTES.txt"} var successTest = []string{"/foo.yaml", "foo.yaml", "foo.tpl", "/foo/bar/baz.yaml", "NOTES.txt"}
for _, test := range successTest { for _, test := range successTest {
err := validateAllowedExtension(test) assert.NoError(t, validateAllowedExtension(test), "validateAllowedExtension('%s') to return no error", test)
if err != nil {
t.Errorf("validateAllowedExtension('%s') to return no error but got \"%s\"", test, err.Error())
}
} }
} }
@ -65,13 +58,8 @@ func TestTemplateParsing(t *testing.T) {
TemplateLinterSkipSchemaValidation(false)) TemplateLinterSkipSchemaValidation(false))
res := linter.Messages res := linter.Messages
if len(res) != 1 { require.Len(t, res, 1, "Expected one error, got %d, %v", len(res), res)
t.Fatalf("Expected one error, got %d, %v", len(res), res) assert.ErrorContains(t, res[0].Err, "deliberateSyntaxError")
}
if !strings.Contains(res[0].Err.Error(), "deliberateSyntaxError") {
t.Errorf("Unexpected error: %s", res[0])
}
} }
var wrongTemplatePath = filepath.Join(templateTestBasedir, "templates", "fail.yaml") var wrongTemplatePath = filepath.Join(templateTestBasedir, "templates", "fail.yaml")
@ -92,9 +80,7 @@ func TestTemplateIntegrationHappyPath(t *testing.T) {
TemplateLinterSkipSchemaValidation(false)) TemplateLinterSkipSchemaValidation(false))
res := linter.Messages res := linter.Messages
if len(res) != 0 { require.Empty(t, res, "Expected no error, got %d, %v", len(res), res)
t.Fatalf("Expected no error, got %d, %v", len(res), res)
}
} }
func TestMultiTemplateFail(t *testing.T) { func TestMultiTemplateFail(t *testing.T) {
@ -106,13 +92,8 @@ func TestMultiTemplateFail(t *testing.T) {
TemplateLinterSkipSchemaValidation(false)) TemplateLinterSkipSchemaValidation(false))
res := linter.Messages res := linter.Messages
if len(res) != 1 { require.Len(t, res, 1, "Expected 1 error, got %d, %v", len(res), res)
t.Fatalf("Expected 1 error, got %d, %v", len(res), res) assert.ErrorContains(t, res[0].Err, "object name does not conform to Kubernetes naming requirements")
}
if !strings.Contains(res[0].Err.Error(), "object name does not conform to Kubernetes naming requirements") {
t.Errorf("Unexpected error: %s", res[0].Err)
}
} }
func TestValidateMetadataName(t *testing.T) { func TestValidateMetadataName(t *testing.T) {
@ -221,9 +202,7 @@ func TestDeprecatedAPIFails(t *testing.T) {
} }
tmpdir := t.TempDir() tmpdir := t.TempDir()
if err := chartutil.SaveDir(&mychart, tmpdir); err != nil { require.NoError(t, chartutil.SaveDir(&mychart, tmpdir))
t.Fatal(err)
}
linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())} linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())}
Templates( Templates(
@ -279,9 +258,7 @@ func TestStrictTemplateParsingMapError(t *testing.T) {
}, },
} }
dir := t.TempDir() dir := t.TempDir()
if err := chartutil.SaveDir(&ch, dir); err != nil { require.NoError(t, chartutil.SaveDir(&ch, dir))
t.Fatal(err)
}
linter := &support.Linter{ linter := &support.Linter{
ChartDir: filepath.Join(dir, ch.Metadata.Name), ChartDir: filepath.Join(dir, ch.Metadata.Name),
} }
@ -327,9 +304,7 @@ spec:
- name: nginx - name: nginx
image: nginx:1.14.2 image: nginx:1.14.2
` `
if err := validateMatchSelector(md, manifest); err != nil { require.NoError(t, validateMatchSelector(md, manifest))
t.Error(err)
}
manifest = ` manifest = `
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
@ -351,9 +326,7 @@ spec:
- name: nginx - name: nginx
image: nginx:1.14.2 image: nginx:1.14.2
` `
if err := validateMatchSelector(md, manifest); err != nil { require.NoError(t, validateMatchSelector(md, manifest))
t.Error(err)
}
manifest = ` manifest = `
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
@ -372,9 +345,7 @@ spec:
- name: nginx - name: nginx
image: nginx:1.14.2 image: nginx:1.14.2
` `
if err := validateMatchSelector(md, manifest); err == nil { assert.Error(t, validateMatchSelector(md, manifest), "expected Deployment with no selector to fail")
t.Error("expected Deployment with no selector to fail")
}
} }
func TestValidateTopIndentLevel(t *testing.T) { func TestValidateTopIndentLevel(t *testing.T) {
@ -413,9 +384,7 @@ func TestEmptyWithCommentsManifests(t *testing.T) {
} }
tmpdir := t.TempDir() tmpdir := t.TempDir()
if err := chartutil.SaveDir(&mychart, tmpdir); err != nil { require.NoError(t, chartutil.SaveDir(&mychart, tmpdir))
t.Fatal(err)
}
linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())} linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())}
Templates( Templates(
@ -448,10 +417,7 @@ items:
annotations: annotations:
helm.sh/resource-policy: keep helm.sh/resource-policy: keep
` `
require.Error(t, validateListAnnotations(md, manifest), "expected list with nested keep annotations to fail")
if err := validateListAnnotations(md, manifest); err == nil {
t.Fatal("expected list with nested keep annotations to fail")
}
manifest = ` manifest = `
apiVersion: v1 apiVersion: v1
@ -463,10 +429,7 @@ items:
- apiVersion: v1 - apiVersion: v1
kind: ConfigMap kind: ConfigMap
` `
require.NoErrorf(t, validateListAnnotations(md, manifest), "List objects keep annotations should pass. got")
if err := validateListAnnotations(md, manifest); err != nil {
t.Fatalf("List objects keep annotations should pass. got: %s", err)
}
} }
func TestIsYamlFileExtension(t *testing.T) { func TestIsYamlFileExtension(t *testing.T) {
@ -482,8 +445,6 @@ func TestIsYamlFileExtension(t *testing.T) {
for _, test := range tests { for _, test := range tests {
result := isYamlFileExtension(test.filename) result := isYamlFileExtension(test.filename)
if result != test.expected { assert.Equal(t, test.expected, result, "isYamlFileExtension(%s) = %v; want %v", test.filename, result, test.expected)
t.Errorf("isYamlFileExtension(%s) = %v; want %v", test.filename, result, test.expected)
}
} }
} }

@ -19,9 +19,11 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util" chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/provenance" "helm.sh/helm/v4/pkg/provenance"
"helm.sh/helm/v4/pkg/repo/v1" "helm.sh/helm/v4/pkg/repo/v1"
@ -39,15 +41,12 @@ func TestDependencyBuildCmd(t *testing.T) {
srv.LinkIndices() srv.LinkIndices()
ociSrv, err := repotest.NewOCIServer(t, srv.Root()) ociSrv, err := repotest.NewOCIServer(t, srv.Root())
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ociChartName := "oci-depending-chart" ociChartName := "oci-depending-chart"
c := createTestingMetadataForOCI(ociChartName, ociSrv.RegistryURL) c := createTestingMetadataForOCI(ociChartName, ociSrv.RegistryURL)
if _, err := chartutil.Save(c, ociSrv.Dir); err != nil { _, err = chartutil.Save(c, ociSrv.Dir)
t.Fatal(err) require.NoError(t, err)
}
ociSrv.Run(t, repotest.WithDependingChart(c)) ociSrv.Run(t, repotest.WithDependingChart(c))
dir := func(p ...string) string { dir := func(p ...string) string {
@ -67,25 +66,19 @@ func TestDependencyBuildCmd(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if !strings.Contains(out, `update from the "test" chart repository`) { assert.Contains(t, out, `update from the "test" chart repository`, "Repo did not get updated\n%s", out)
t.Errorf("Repo did not get updated\n%s", out)
}
// Make sure the actual file got downloaded. // Make sure the actual file got downloaded.
expect := filepath.Join(rootDir, chartname, "charts", "reqtest-0.1.0.tgz") expect := filepath.Join(rootDir, chartname, "charts", "reqtest-0.1.0.tgz")
if _, err := os.Stat(expect); err != nil { _, err = os.Stat(expect)
t.Fatal(err) require.NoError(t, err)
}
// In the second pass, we want to remove the chart's request dependency, // In the second pass, we want to remove the chart's request dependency,
// then see if it restores from the lock. // then see if it restores from the lock.
lockfile := filepath.Join(rootDir, chartname, "Chart.lock") lockfile := filepath.Join(rootDir, chartname, "Chart.lock")
if _, err := os.Stat(lockfile); err != nil { _, err = os.Stat(lockfile)
t.Fatal(err) require.NoError(t, err)
} require.NoError(t, os.RemoveAll(expect))
if err := os.RemoveAll(expect); err != nil {
t.Fatal(err)
}
_, out, err = executeActionCommand(cmd) _, out, err = executeActionCommand(cmd)
if err != nil { if err != nil {
@ -94,28 +87,21 @@ func TestDependencyBuildCmd(t *testing.T) {
} }
// Now repeat the test that the dependency exists. // Now repeat the test that the dependency exists.
if _, err := os.Stat(expect); err != nil { _, err = os.Stat(expect)
t.Fatal(err) require.NoError(t, err)
}
// Make sure that build is also fetching the correct version. // Make sure that build is also fetching the correct version.
hash, err := provenance.DigestFile(expect) hash, err := provenance.DigestFile(expect)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
i, err := repo.LoadIndexFile(filepath.Join(rootDir, "index.yaml")) i, err := repo.LoadIndexFile(filepath.Join(rootDir, "index.yaml"))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
reqver := i.Entries["reqtest"][0] reqver := i.Entries["reqtest"][0]
if h := reqver.Digest; h != hash { h := reqver.Digest
t.Errorf("Failed hash match: expected %s, got %s", hash, h) assert.Equalf(t, h, hash, "Failed hash match: expected %s, got %s", hash, h)
} v := reqver.Version
if v := reqver.Version; v != "0.1.0" { assert.Equalf(t, "0.1.0", v, "mismatched versions. Expected %q, got %q", "0.1.0", v)
t.Errorf("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) 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) _, out, err = executeActionCommand(skipRefreshCmd)
@ -126,14 +112,10 @@ func TestDependencyBuildCmd(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if strings.Contains(out, `update from the "test" chart repository`) { assert.NotContains(t, out, `update from the "test" chart repository`, "Repo did get updated\n%s", out)
t.Errorf("Repo did get updated\n%s", out)
}
// OCI dependencies // OCI dependencies
if err := chartutil.SaveDir(c, dir()); err != nil { require.NoError(t, chartutil.SaveDir(c, dir()))
t.Fatal(err)
}
cmd = fmt.Sprintf("dependency build '%s' --repository-config %s --repository-cache %s --registry-config %s/config.json --plain-http", cmd = fmt.Sprintf("dependency build '%s' --repository-config %s --repository-cache %s --registry-config %s/config.json --plain-http",
dir(ociChartName), dir(ociChartName),
dir("repositories.yaml"), dir("repositories.yaml"),
@ -145,9 +127,8 @@ func TestDependencyBuildCmd(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
expect = dir(ociChartName, "charts/oci-dependent-chart-0.1.0.tgz") expect = dir(ociChartName, "charts/oci-dependent-chart-0.1.0.tgz")
if _, err := os.Stat(expect); err != nil { _, err = os.Stat(expect)
t.Fatal(err) require.NoError(t, err)
}
} }
func TestDependencyBuildCmdWithHelmV2Hash(t *testing.T) { func TestDependencyBuildCmdWithHelmV2Hash(t *testing.T) {

@ -19,8 +19,10 @@ import (
"bytes" "bytes"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
// Common plugin.yaml content for v1 format tests // Common plugin.yaml content for v1 format tests
@ -43,14 +45,10 @@ func TestPluginPackageWithoutSigning(t *testing.T) {
// Create a test plugin directory // Create a test plugin directory
tempDir := t.TempDir() tempDir := t.TempDir()
pluginDir := filepath.Join(tempDir, "test-plugin") pluginDir := filepath.Join(tempDir, "test-plugin")
if err := os.MkdirAll(pluginDir, 0o755); err != nil { require.NoError(t, os.MkdirAll(pluginDir, 0o755))
t.Fatal(err)
}
// Create a plugin.yaml file // Create a plugin.yaml file
if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644); err != nil { require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644))
t.Fatal(err)
}
// Create package options with sign=false // Create package options with sign=false
o := &pluginPackageOptions{ o := &pluginPackageOptions{
@ -61,47 +59,34 @@ func TestPluginPackageWithoutSigning(t *testing.T) {
// Run the package command // Run the package command
out := &bytes.Buffer{} out := &bytes.Buffer{}
err := o.run(out)
// Should succeed without error // Should succeed without error
if err != nil { require.NoError(t, o.run(out))
t.Errorf("unexpected error: %v", err)
}
// Check that tarball was created with plugin name and version // Check that tarball was created with plugin name and version
tarballPath := filepath.Join(tempDir, "test-plugin-1.0.0.tgz") tarballPath := filepath.Join(tempDir, "test-plugin-1.0.0.tgz")
if _, err := os.Stat(tarballPath); os.IsNotExist(err) { _, err := os.Stat(tarballPath)
t.Error("tarball should exist when sign=false") assert.False(t, os.IsNotExist(err), "tarball should exist when sign=false")
}
// Check that no .prov file was created // Check that no .prov file was created
provPath := tarballPath + ".prov" provPath := tarballPath + ".prov"
if _, err := os.Stat(provPath); !os.IsNotExist(err) { _, err = os.Stat(provPath)
t.Error("provenance file should not exist when sign=false") assert.True(t, os.IsNotExist(err), "provenance file should not exist when sign=false")
}
// Output should contain warning about skipping signing // Output should contain warning about skipping signing
output := out.String() output := out.String()
if !strings.Contains(output, "WARNING: Skipping plugin signing") { assert.Contains(t, output, "WARNING: Skipping plugin signing", "should print warning when signing is skipped")
t.Error("should print warning when signing is skipped") assert.Contains(t, output, "Successfully packaged", "should print success message")
}
if !strings.Contains(output, "Successfully packaged") {
t.Error("should print success message")
}
} }
func TestPluginPackageDefaultRequiresSigning(t *testing.T) { func TestPluginPackageDefaultRequiresSigning(t *testing.T) {
// Create a test plugin directory // Create a test plugin directory
tempDir := t.TempDir() tempDir := t.TempDir()
pluginDir := filepath.Join(tempDir, "test-plugin") pluginDir := filepath.Join(tempDir, "test-plugin")
if err := os.MkdirAll(pluginDir, 0o755); err != nil { require.NoError(t, os.MkdirAll(pluginDir, 0o755))
t.Fatal(err)
}
// Create a plugin.yaml file // Create a plugin.yaml file
if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644); err != nil { require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644))
t.Fatal(err)
}
// Create package options with default sign=true and invalid keyring // Create package options with default sign=true and invalid keyring
o := &pluginPackageOptions{ o := &pluginPackageOptions{
@ -113,32 +98,24 @@ func TestPluginPackageDefaultRequiresSigning(t *testing.T) {
// Run the package command // Run the package command
out := &bytes.Buffer{} out := &bytes.Buffer{}
err := o.run(out)
// Should fail because signing is required by default // Should fail because signing is required by default
if err == nil { require.Error(t, o.run(out), "expected error when signing fails with default settings")
t.Error("expected error when signing fails with default settings")
}
// Check that no tarball was created // Check that no tarball was created
tarballPath := filepath.Join(tempDir, "test-plugin.tgz") tarballPath := filepath.Join(tempDir, "test-plugin.tgz")
if _, err := os.Stat(tarballPath); !os.IsNotExist(err) { _, err := os.Stat(tarballPath)
t.Error("tarball should not exist when signing fails") assert.True(t, os.IsNotExist(err), "tarball should not exist when signing fails")
}
} }
func TestPluginPackageSigningFailure(t *testing.T) { func TestPluginPackageSigningFailure(t *testing.T) {
// Create a test plugin directory // Create a test plugin directory
tempDir := t.TempDir() tempDir := t.TempDir()
pluginDir := filepath.Join(tempDir, "test-plugin") pluginDir := filepath.Join(tempDir, "test-plugin")
if err := os.MkdirAll(pluginDir, 0o755); err != nil { require.NoError(t, os.MkdirAll(pluginDir, 0o755))
t.Fatal(err)
}
// Create a plugin.yaml file // Create a plugin.yaml file
if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644); err != nil { require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644))
t.Fatal(err)
}
// Create package options with sign flag but invalid keyring // Create package options with sign flag but invalid keyring
o := &pluginPackageOptions{ o := &pluginPackageOptions{
@ -150,21 +127,15 @@ func TestPluginPackageSigningFailure(t *testing.T) {
// Run the package command // Run the package command
out := &bytes.Buffer{} out := &bytes.Buffer{}
err := o.run(out)
// Should get an error // Should get an error
if err == nil { require.Error(t, o.run(out), "expected error when signing fails, got nil")
t.Error("expected error when signing fails, got nil")
}
// Check that no tarball was created // Check that no tarball was created
tarballPath := filepath.Join(tempDir, "test-plugin.tgz") tarballPath := filepath.Join(tempDir, "test-plugin.tgz")
if _, err := os.Stat(tarballPath); !os.IsNotExist(err) { _, err := os.Stat(tarballPath)
t.Error("tarball should not exist when signing fails") assert.True(t, os.IsNotExist(err), "tarball should not exist when signing fails")
}
// Output should not contain success message // Output should not contain success message
if bytes.Contains(out.Bytes(), []byte("Successfully packaged")) { assert.False(t, bytes.Contains(out.Bytes(), []byte("Successfully packaged")), "should not print success message when signing fails")
t.Error("should not print success message when signing fails")
}
} }

@ -17,16 +17,16 @@ limitations under the License.
package cmd package cmd
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"sync" "sync"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"sigs.k8s.io/yaml" "sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/helmpath" "helm.sh/helm/v4/pkg/helmpath"
@ -50,9 +50,7 @@ func TestRepoAddCmd(t *testing.T) {
defer srv2.Stop() defer srv2.Stop()
tmpdir := filepath.Join(t.TempDir(), "path-component.yaml", "data") tmpdir := filepath.Join(t.TempDir(), "path-component.yaml", "data")
if err := os.MkdirAll(tmpdir, 0o777); err != nil { require.NoError(t, os.MkdirAll(tmpdir, 0o777))
t.Fatal(err)
}
repoFile := filepath.Join(tmpdir, "repositories.yaml") repoFile := filepath.Join(tmpdir, "repositories.yaml")
tests := []cmdTestCase{ tests := []cmdTestCase{
@ -101,37 +99,24 @@ func TestRepoAdd(t *testing.T) {
} }
t.Setenv(xdg.CacheHomeEnvVar, rootDir) t.Setenv(xdg.CacheHomeEnvVar, rootDir)
if err := o.run(io.Discard); err != nil { require.NoError(t, o.run(io.Discard))
t.Error(err)
}
f, err := repo.LoadFile(repoFile) f, err := repo.LoadFile(repoFile)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
if !f.Has(testRepoName) { assert.Truef(t, f.Has(testRepoName), "%s was not successfully inserted into %s", testRepoName, repoFile)
t.Errorf("%s was not successfully inserted into %s", testRepoName, repoFile)
}
idx := filepath.Join(helmpath.CachePath("repository"), helmpath.CacheIndexFile(testRepoName)) idx := filepath.Join(helmpath.CachePath("repository"), helmpath.CacheIndexFile(testRepoName))
if _, err := os.Stat(idx); errors.Is(err, fs.ErrNotExist) { _, err = os.Stat(idx)
t.Errorf("Error cache index file was not created for repository %s", testRepoName) 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)) idx = filepath.Join(helmpath.CachePath("repository"), helmpath.CacheChartsFile(testRepoName))
if _, err := os.Stat(idx); errors.Is(err, fs.ErrNotExist) { _, err = os.Stat(idx)
t.Errorf("Error cache charts file was not created for repository %s", testRepoName) require.NotErrorIsf(t, err, fs.ErrNotExist, "Error cache charts file was not created for repository %s", testRepoName)
}
o.forceUpdate = true o.forceUpdate = true
if err := o.run(io.Discard); err != nil { require.NoError(t, o.run(io.Discard), "Repository was not updated")
t.Errorf("Repository was not updated: %s", err) assert.NoError(t, o.run(io.Discard), "Duplicate repository name was added")
}
if err := o.run(io.Discard); err != nil {
t.Error("Duplicate repository name was added")
}
} }
func TestRepoAddCheckLegalName(t *testing.T) { func TestRepoAddCheckLegalName(t *testing.T) {
@ -156,14 +141,7 @@ func TestRepoAddCheckLegalName(t *testing.T) {
t.Setenv(xdg.CacheHomeEnvVar, rootDir) t.Setenv(xdg.CacheHomeEnvVar, rootDir)
wantErrorMsg := fmt.Sprintf("repository name (%s) contains '/', please specify a different name without '/'", testRepoName) wantErrorMsg := fmt.Sprintf("repository name (%s) contains '/', please specify a different name without '/'", testRepoName)
require.EqualError(t, o.run(io.Discard), wantErrorMsg)
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.")
}
} }
func TestRepoAddConcurrentGoRoutines(t *testing.T) { func TestRepoAddConcurrentGoRoutines(t *testing.T) {
@ -209,29 +187,21 @@ func repoAddConcurrent(t *testing.T, testName, repoFile string) {
forceUpdate: false, forceUpdate: false,
repoFile: repoFile, repoFile: repoFile,
} }
if err := o.run(io.Discard); err != nil { assert.NoError(t, o.run(io.Discard))
t.Error(err)
}
}(fmt.Sprintf("%s-%d", testName, i)) }(fmt.Sprintf("%s-%d", testName, i))
} }
wg.Wait() wg.Wait()
b, err := os.ReadFile(repoFile) b, err := os.ReadFile(repoFile)
if err != nil { require.NoError(t, err)
t.Error(err)
}
var f repo.File var f repo.File
if err := yaml.Unmarshal(b, &f); err != nil { require.NoError(t, yaml.Unmarshal(b, &f))
t.Error(err)
}
var name string var name string
for i := range 3 { for i := range 3 {
name = fmt.Sprintf("%s-%d", testName, i) name = fmt.Sprintf("%s-%d", testName, i)
if !f.Has(name) { assert.Truef(t, f.Has(name), "%s was not successfully inserted into %s: %s", name, repoFile, f.Repositories[0])
t.Errorf("%s was not successfully inserted into %s: %s", name, repoFile, f.Repositories[0])
}
} }
} }
@ -252,9 +222,7 @@ func TestRepoAddWithPasswordFromStdin(t *testing.T) {
defer resetEnv()() defer resetEnv()()
in, err := os.Open("testdata/password") in, err := os.Open("testdata/password")
if err != nil { require.NoError(t, err)
t.Errorf("unexpected error, got '%v'", err)
}
tmpdir := t.TempDir() tmpdir := t.TempDir()
repoFile := filepath.Join(tmpdir, "repositories.yaml") 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) 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 var result string
_, result, err = executeActionCommandStdinC(store, in, cmd) _, 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)) { require.NoError(t, err)
t.Errorf("Repo was not successfully added. Output: %s", result) assert.Contains(t, result, fmt.Sprintf("%q has been added to your repositories", testName), "Repo was not successfully added. Output: %s", result)
}
} }

Loading…
Cancel
Save