Merge pull request #32434 from mmorel-35/testifylint-manual-assert-pkg-18

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

@ -17,7 +17,6 @@ limitations under the License.
package action package action
import ( import (
"errors"
"os" "os"
"path" "path"
"testing" "testing"
@ -35,18 +34,12 @@ func TestPassphraseFileFetcher(t *testing.T) {
testPkg := NewPackage() testPkg := NewPackage()
fetcher, err := testPkg.passphraseFileFetcher(path.Join(directory, "passphrase-file"), nil) fetcher, err := testPkg.passphraseFileFetcher(path.Join(directory, "passphrase-file"), nil)
if err != nil { require.NoError(t, err, "Unable to create passphraseFileFetcher")
t.Fatal("Unable to create passphraseFileFetcher", err)
}
passphrase, err := fetcher("key") passphrase, err := fetcher("key")
if err != nil { require.NoError(t, err, "Unable to fetch passphrase")
t.Fatal("Unable to fetch passphrase")
}
if string(passphrase) != secret { assert.Equal(t, secret, string(passphrase), "Expected %s got %s", secret, string(passphrase))
t.Errorf("Expected %s got %s", secret, string(passphrase))
}
} }
func TestPassphraseFileFetcher_WithLineBreak(t *testing.T) { func TestPassphraseFileFetcher_WithLineBreak(t *testing.T) {
@ -55,18 +48,12 @@ func TestPassphraseFileFetcher_WithLineBreak(t *testing.T) {
testPkg := NewPackage() testPkg := NewPackage()
fetcher, err := testPkg.passphraseFileFetcher(path.Join(directory, "passphrase-file"), nil) fetcher, err := testPkg.passphraseFileFetcher(path.Join(directory, "passphrase-file"), nil)
if err != nil { require.NoError(t, err, "Unable to create passphraseFileFetcher")
t.Fatal("Unable to create passphraseFileFetcher", err)
}
passphrase, err := fetcher("key") passphrase, err := fetcher("key")
if err != nil { require.NoError(t, err, "Unable to fetch passphrase")
t.Fatal("Unable to fetch passphrase")
}
if string(passphrase) != secret { assert.Equal(t, secret, string(passphrase), "Expected %s got %s", secret, string(passphrase))
t.Errorf("Expected %s got %s", secret, string(passphrase))
}
} }
func TestPassphraseFileFetcher_WithInvalidStdin(t *testing.T) { func TestPassphraseFileFetcher_WithInvalidStdin(t *testing.T) {
@ -74,21 +61,16 @@ func TestPassphraseFileFetcher_WithInvalidStdin(t *testing.T) {
testPkg := NewPackage() testPkg := NewPackage()
stdin, err := os.CreateTemp(directory, "non-existing") stdin, err := os.CreateTemp(directory, "non-existing")
if err != nil { require.NoError(t, err, "Unable to create test file")
t.Fatal("Unable to create test file", err)
}
if _, err := testPkg.passphraseFileFetcher("-", stdin); err == nil { _, err = testPkg.passphraseFileFetcher("-", stdin)
t.Error("Expected passphraseFileFetcher returning an error") assert.Error(t, err, "Expected passphraseFileFetcher returning an error")
}
} }
func TestPassphraseFileFetcher_WithStdinAndMultipleFetches(t *testing.T) { func TestPassphraseFileFetcher_WithStdinAndMultipleFetches(t *testing.T) {
testPkg := NewPackage() testPkg := NewPackage()
stdin, w, err := os.Pipe() stdin, w, err := os.Pipe()
if err != nil { require.NoError(t, err, "Unable to create pipe")
t.Fatal("Unable to create pipe", err)
}
passphrase := "secret-from-stdin" passphrase := "secret-from-stdin"
@ -99,18 +81,12 @@ func TestPassphraseFileFetcher_WithStdinAndMultipleFetches(t *testing.T) {
for range 4 { for range 4 {
fetcher, err := testPkg.passphraseFileFetcher("-", stdin) fetcher, err := testPkg.passphraseFileFetcher("-", stdin)
if err != nil { require.NoError(t, err, "Expected passphraseFileFetcher to not return an error")
t.Errorf("Expected passphraseFileFetcher to not return an error, but got %v", err)
}
pass, err := fetcher("key") pass, err := fetcher("key")
if err != nil { require.NoError(t, err, "Expected passphraseFileFetcher invocation to succeed")
t.Errorf("Expected passphraseFileFetcher invocation to succeed, failed with %v", err)
}
if string(pass) != string(passphrase) { assert.Equal(t, string(passphrase), string(pass), "Expected multiple passphrase fetch to return %q, got %q", passphrase, pass)
t.Errorf("Expected multiple passphrase fetch to return %q, got %q", passphrase, pass)
}
} }
} }
@ -148,9 +124,7 @@ func TestValidateVersion(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) {
if err := validateVersion(tt.args.ver); err != nil { if err := validateVersion(tt.args.ver); err != nil {
if !errors.Is(err, tt.wantErr) { assert.ErrorIs(t, err, tt.wantErr)
t.Errorf("Expected {%v}, got {%v}", tt.wantErr, err)
}
} }
}) })
} }

@ -19,6 +19,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
chart "helm.sh/helm/v4/pkg/chart/v2" chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/lint/support" "helm.sh/helm/v4/pkg/chart/v2/lint/support"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util" chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
@ -62,18 +65,12 @@ func chartWithBadDependencies() chart.Chart {
func TestValidateDependencyInChartsDir(t *testing.T) { func TestValidateDependencyInChartsDir(t *testing.T) {
c := chartWithBadDependencies() c := chartWithBadDependencies()
assert.Error(t, validateDependencyInChartsDir(&c), "chart should have been flagged for missing deps in chart directory")
if err := validateDependencyInChartsDir(&c); err == nil {
t.Error("chart should have been flagged for missing deps in chart directory")
}
} }
func TestValidateDependencyInMetadata(t *testing.T) { func TestValidateDependencyInMetadata(t *testing.T) {
c := chartWithBadDependencies() c := chartWithBadDependencies()
assert.Error(t, validateDependencyInMetadata(&c), "chart should have been flagged for missing deps in chart metadata")
if err := validateDependencyInMetadata(&c); err == nil {
t.Error("chart should have been flagged for missing deps in chart metadata")
}
} }
func TestValidateDependenciesUnique(t *testing.T) { func TestValidateDependenciesUnique(t *testing.T) {
@ -131,9 +128,7 @@ func TestValidateDependenciesUnique(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
if err := validateDependenciesUnique(&tt.chart); err == nil { assert.Error(t, validateDependenciesUnique(&tt.chart), "chart should have been flagged for dependency shadowing")
t.Error("chart should have been flagged for dependency shadowing")
}
} }
} }
@ -141,10 +136,7 @@ func TestDependencies(t *testing.T) {
tmp := t.TempDir() tmp := t.TempDir()
c := chartWithBadDependencies() c := chartWithBadDependencies()
err := chartutil.SaveDir(&c, tmp) require.NoError(t, chartutil.SaveDir(&c, tmp))
if err != nil {
t.Fatal(err)
}
linter := support.Linter{ChartDir: filepath.Join(tmp, c.Metadata.Name)} linter := support.Linter{ChartDir: filepath.Join(tmp, c.Metadata.Name)}
Dependencies(&linter) Dependencies(&linter)

@ -22,6 +22,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
chart "helm.sh/helm/v4/pkg/chart/v2" chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader" "helm.sh/helm/v4/pkg/chart/v2/loader"
) )
@ -30,20 +33,13 @@ func TestCreate(t *testing.T) {
tdir := t.TempDir() tdir := t.TempDir()
c, err := Create("foo", tdir) c, err := Create("foo", tdir)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
dir := filepath.Join(tdir, "foo") dir := filepath.Join(tdir, "foo")
mychart, err := loader.LoadDir(c) mychart, err := loader.LoadDir(c)
if err != nil { require.NoError(t, err, "Failed to load newly created chart %q", c)
t.Fatalf("Failed to load newly created chart %q: %s", c, err) assert.Equal(t, "foo", mychart.Name(), "Expected name to be 'foo', got %q", mychart.Name())
}
if mychart.Name() != "foo" {
t.Errorf("Expected name to be 'foo', got %q", mychart.Name())
}
for _, f := range []string{ for _, f := range []string{
ChartfileName, ChartfileName,
@ -58,9 +54,8 @@ func TestCreate(t *testing.T) {
TestConnectionName, TestConnectionName,
ValuesfileName, ValuesfileName,
} { } {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil { _, err := os.Stat(filepath.Join(dir, f))
t.Errorf("Expected %s file: %s", f, err) assert.NoErrorf(t, err, "Expected %s file", f)
}
} }
} }
@ -74,38 +69,26 @@ func TestCreateFrom(t *testing.T) {
} }
srcdir := "./testdata/frobnitz/charts/mariner" srcdir := "./testdata/frobnitz/charts/mariner"
if err := CreateFrom(cf, tdir, srcdir); err != nil { require.NoError(t, CreateFrom(cf, tdir, srcdir))
t.Fatal(err)
}
dir := filepath.Join(tdir, "foo") dir := filepath.Join(tdir, "foo")
c := filepath.Join(tdir, cf.Name) c := filepath.Join(tdir, cf.Name)
mychart, err := loader.LoadDir(c) mychart, err := loader.LoadDir(c)
if err != nil { require.NoError(t, err, "Failed to load newly created chart %q", c)
t.Fatalf("Failed to load newly created chart %q: %s", c, err) assert.Equal(t, "foo", mychart.Name(), "Expected name to be 'foo', got %q", mychart.Name())
}
if mychart.Name() != "foo" {
t.Errorf("Expected name to be 'foo', got %q", mychart.Name())
}
for _, f := range []string{ for _, f := range []string{
ChartfileName, ChartfileName,
ValuesfileName, ValuesfileName,
filepath.Join(TemplatesDir, "placeholder.tpl"), filepath.Join(TemplatesDir, "placeholder.tpl"),
} { } {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil { _, err := os.Stat(filepath.Join(dir, f))
t.Errorf("Expected %s file: %s", f, err) require.NoErrorf(t, err, "Expected %s file", f)
}
// Check each file to make sure <CHARTNAME> has been replaced // Check each file to make sure <CHARTNAME> has been replaced
b, err := os.ReadFile(filepath.Join(dir, f)) b, err := os.ReadFile(filepath.Join(dir, f))
if err != nil { require.NoError(t, err, "Unable to read file %s", f)
t.Errorf("Unable to read file %s: %s", f, err) assert.Falsef(t, bytes.Contains(b, []byte("<CHARTNAME>")), "File %s contains <CHARTNAME>", f)
}
if bytes.Contains(b, []byte("<CHARTNAME>")) {
t.Errorf("File %s contains <CHARTNAME>", f)
}
} }
} }
@ -115,9 +98,8 @@ func TestCreate_Overwrite(t *testing.T) {
var errlog bytes.Buffer var errlog bytes.Buffer
if _, err := Create("foo", tdir); err != nil { _, err := Create("foo", tdir)
t.Fatal(err) require.NoError(t, err)
}
dir := filepath.Join(tdir, "foo") dir := filepath.Join(tdir, "foo")
@ -126,22 +108,13 @@ func TestCreate_Overwrite(t *testing.T) {
// Now re-run the create // Now re-run the create
Stderr = &errlog Stderr = &errlog
if _, err := Create("foo", tdir); err != nil { _, err = Create("foo", tdir)
t.Fatal(err) require.NoError(t, err)
}
data, err := os.ReadFile(tplname) data, err := os.ReadFile(tplname)
if err != nil { require.NoError(t, err)
t.Fatal(err) require.NotEqual(t, "FOO", string(data), "File that should have been modified was not.")
} assert.NotEqual(t, 0, errlog.Len(), "Expected warnings about overwriting files.")
if string(data) == "FOO" {
t.Fatal("File that should have been modified was not.")
}
if errlog.Len() == 0 {
t.Error("Expected warnings about overwriting files.")
}
} }
func TestValidateChartName(t *testing.T) { func TestValidateChartName(t *testing.T) {

@ -21,6 +21,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/internal/plugin" "helm.sh/helm/v4/internal/plugin"
"helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/internal/test/ensure"
"helm.sh/helm/v4/pkg/cli" "helm.sh/helm/v4/pkg/cli"
@ -39,9 +42,7 @@ func TestPluginUninstallCleansUpVersionedFiles(t *testing.T) {
// Create plugin directory // Create plugin directory
pluginDir := filepath.Join(pluginsDir, pluginName) pluginDir := filepath.Join(pluginsDir, pluginName)
if err := os.MkdirAll(pluginDir, 0o755); err != nil { require.NoError(t, os.MkdirAll(pluginDir, 0o755))
t.Fatal(err)
}
// Create plugin.yaml // Create plugin.yaml
pluginYAML := `name: test-plugin pluginYAML := `name: test-plugin
@ -49,31 +50,21 @@ version: 1.2.3
description: Test plugin description: Test plugin
command: $HELM_PLUGIN_DIR/test-plugin command: $HELM_PLUGIN_DIR/test-plugin
` `
if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(pluginYAML), 0o644); err != nil { require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(pluginYAML), 0o644))
t.Fatal(err)
}
// Create versioned tarball and provenance files // Create versioned tarball and provenance files
tarballFile := filepath.Join(pluginsDir, "test-plugin-1.2.3.tgz") tarballFile := filepath.Join(pluginsDir, "test-plugin-1.2.3.tgz")
provFile := filepath.Join(pluginsDir, "test-plugin-1.2.3.tgz.prov") provFile := filepath.Join(pluginsDir, "test-plugin-1.2.3.tgz.prov")
otherVersionTarball := filepath.Join(pluginsDir, "test-plugin-2.0.0.tgz") otherVersionTarball := filepath.Join(pluginsDir, "test-plugin-2.0.0.tgz")
if err := os.WriteFile(tarballFile, []byte("fake tarball"), 0o644); err != nil { require.NoError(t, os.WriteFile(tarballFile, []byte("fake tarball"), 0o644))
t.Fatal(err) require.NoError(t, os.WriteFile(provFile, []byte("fake provenance"), 0o644))
}
if err := os.WriteFile(provFile, []byte("fake provenance"), 0o644); err != nil {
t.Fatal(err)
}
// Create another version that should NOT be removed // Create another version that should NOT be removed
if err := os.WriteFile(otherVersionTarball, []byte("other version"), 0o644); err != nil { require.NoError(t, os.WriteFile(otherVersionTarball, []byte("other version"), 0o644))
t.Fatal(err)
}
// Load the plugin // Load the plugin
p, err := plugin.LoadDir(pluginDir) p, err := plugin.LoadDir(pluginDir)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
// Create a test uninstall function that uses our test settings // Create a test uninstall function that uses our test settings
testUninstallPlugin := func(plugin plugin.Plugin) error { testUninstallPlugin := func(plugin plugin.Plugin) error {
@ -112,35 +103,26 @@ command: $HELM_PLUGIN_DIR/test-plugin
} }
// Verify files exist before uninstall // Verify files exist before uninstall
if _, err := os.Stat(tarballFile); os.IsNotExist(err) { _, err = os.Stat(tarballFile)
t.Fatal("tarball file should exist before uninstall") require.False(t, os.IsNotExist(err), "tarball file should exist before uninstall")
} _, err = os.Stat(provFile)
if _, err := os.Stat(provFile); os.IsNotExist(err) { require.False(t, os.IsNotExist(err), "provenance file should exist before uninstall")
t.Fatal("provenance file should exist before uninstall") _, err = os.Stat(otherVersionTarball)
} require.False(t, os.IsNotExist(err), "other version tarball should exist before uninstall")
if _, err := os.Stat(otherVersionTarball); os.IsNotExist(err) {
t.Fatal("other version tarball should exist before uninstall")
}
// Uninstall the plugin // Uninstall the plugin
if err := testUninstallPlugin(p); err != nil { require.NoError(t, testUninstallPlugin(p))
t.Fatal(err)
}
// Verify plugin directory is removed // Verify plugin directory is removed
if _, err := os.Stat(pluginDir); !os.IsNotExist(err) { _, err = os.Stat(pluginDir)
t.Error("plugin directory should be removed") assert.True(t, os.IsNotExist(err), "plugin directory should be removed")
}
// Verify only exact version files are removed // Verify only exact version files are removed
if _, err := os.Stat(tarballFile); !os.IsNotExist(err) { _, err = os.Stat(tarballFile)
t.Error("versioned tarball file should be removed") assert.True(t, os.IsNotExist(err), "versioned tarball file should be removed")
} _, err = os.Stat(provFile)
if _, err := os.Stat(provFile); !os.IsNotExist(err) { assert.True(t, os.IsNotExist(err), "versioned provenance file should be removed")
t.Error("versioned provenance file should be removed")
}
// Verify other version files are NOT removed // Verify other version files are NOT removed
if _, err := os.Stat(otherVersionTarball); os.IsNotExist(err) { _, err = os.Stat(otherVersionTarball)
t.Error("other version tarball should NOT be removed") assert.False(t, os.IsNotExist(err), "other version tarball should NOT be removed")
}
} }

@ -21,9 +21,11 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/pkg/helmpath" "helm.sh/helm/v4/pkg/helmpath"
"helm.sh/helm/v4/pkg/repo/v1" "helm.sh/helm/v4/pkg/repo/v1"
"helm.sh/helm/v4/pkg/repo/v1/repotest" "helm.sh/helm/v4/pkg/repo/v1/repotest"
@ -49,41 +51,29 @@ func TestRepoRemove(t *testing.T) {
repoCache: rootDir, repoCache: rootDir,
} }
if err := rmOpts.run(os.Stderr); err == nil { require.Errorf(t, rmOpts.run(os.Stderr), "Expected error removing %s, but did not get one.", testRepoName)
t.Errorf("Expected error removing %s, but did not get one.", testRepoName)
}
o := &repoAddOptions{ o := &repoAddOptions{
name: testRepoName, name: testRepoName,
url: ts.URL(), url: ts.URL(),
repoFile: repoFile, repoFile: repoFile,
} }
if err := o.run(os.Stderr); err != nil { require.NoError(t, o.run(os.Stderr))
t.Error(err)
}
cacheIndexFile, cacheChartsFile := createCacheFiles(rootDir, testRepoName) cacheIndexFile, cacheChartsFile := createCacheFiles(rootDir, testRepoName)
// Reset the buffer before running repo remove // Reset the buffer before running repo remove
b.Reset() b.Reset()
if err := rmOpts.run(b); err != nil { require.NoErrorf(t, rmOpts.run(b), "Error removing %s from repositories", testRepoName)
t.Errorf("Error removing %s from repositories", testRepoName) assert.Contains(t, b.String(), "has been removed", "Unexpected output: %s", b.String())
}
if !strings.Contains(b.String(), "has been removed") {
t.Errorf("Unexpected output: %s", b.String())
}
testCacheFiles(t, cacheIndexFile, cacheChartsFile, testRepoName) testCacheFiles(t, cacheIndexFile, cacheChartsFile, testRepoName)
f, err := repo.LoadFile(repoFile) f, err := repo.LoadFile(repoFile)
if err != nil { require.NoError(t, err)
t.Error(err)
}
if f.Has(testRepoName) { assert.Falsef(t, f.Has(testRepoName), "%s was not successfully removed from repositories list", testRepoName)
t.Errorf("%s was not successfully removed from repositories list", testRepoName)
}
// Test removal of multiple repos in one go // Test removal of multiple repos in one go
var testRepoNames = []string{"foo", "bar", "baz"} var testRepoNames = []string{"foo", "bar", "baz"}
@ -97,9 +87,7 @@ func TestRepoRemove(t *testing.T) {
repoFile: repoFile, repoFile: repoFile,
} }
if err := o.run(os.Stderr); err != nil { require.NoError(t, o.run(os.Stderr))
t.Error(err)
}
cacheIndex, cacheChart := createCacheFiles(rootDir, repoName) cacheIndex, cacheChart := createCacheFiles(rootDir, repoName)
cacheFiles[repoName] = []string{cacheIndex, cacheChart} cacheFiles[repoName] = []string{cacheIndex, cacheChart}
@ -116,23 +104,15 @@ func TestRepoRemove(t *testing.T) {
b.Reset() b.Reset()
// Run repo remove command // Run repo remove command
if err := multiRmOpts.run(b); err != nil { require.NoErrorf(t, multiRmOpts.run(b), "Error removing list of repos from repositories: %q", testRepoNames)
t.Errorf("Error removing list of repos from repositories: %q", testRepoNames)
}
// Check that stuff were removed // Check that stuff were removed
if !strings.Contains(b.String(), "has been removed") { assert.Contains(t, b.String(), "has been removed", "Unexpected output: %s", b.String())
t.Errorf("Unexpected output: %s", b.String())
}
for _, repoName := range testRepoNames { for _, repoName := range testRepoNames {
f, err := repo.LoadFile(repoFile) f, err := repo.LoadFile(repoFile)
if err != nil { require.NoError(t, err)
t.Error(err) assert.Falsef(t, f.Has(repoName), "%s was not successfully removed from repositories list", repoName)
}
if f.Has(repoName) {
t.Errorf("%s was not successfully removed from repositories list", repoName)
}
cacheIndex := cacheFiles[repoName][0] cacheIndex := cacheFiles[repoName][0]
cacheChart := cacheFiles[repoName][1] cacheChart := cacheFiles[repoName][1]
testCacheFiles(t, cacheIndex, cacheChart, repoName) testCacheFiles(t, cacheIndex, cacheChart, repoName)
@ -153,12 +133,10 @@ func createCacheFiles(rootDir string, repoName string) (cacheIndexFile string, c
func testCacheFiles(t *testing.T, cacheIndexFile string, cacheChartsFile string, repoName string) { func testCacheFiles(t *testing.T, cacheIndexFile string, cacheChartsFile string, repoName string) {
t.Helper() t.Helper()
if _, err := os.Stat(cacheIndexFile); err == nil { _, err := os.Stat(cacheIndexFile)
t.Errorf("Error cache index file was not removed for repository %s", repoName) require.Errorf(t, err, "Error cache index file was not removed for repository %s", repoName)
} _, err = os.Stat(cacheChartsFile)
if _, err := os.Stat(cacheChartsFile); err == nil { assert.Errorf(t, err, "Error cache chart file was not removed for repository %s", repoName)
t.Errorf("Error cache chart file was not removed for repository %s", repoName)
}
} }
func TestRepoRemoveCompletion(t *testing.T) { func TestRepoRemoveCompletion(t *testing.T) {
@ -183,9 +161,7 @@ func TestRepoRemoveCompletion(t *testing.T) {
repoFile: repoFile, repoFile: repoFile,
} }
if err := o.run(os.Stderr); err != nil { require.NoError(t, o.run(os.Stderr))
t.Error(err)
}
} }
repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache) repoSetup := fmt.Sprintf("--repository-config %s --repository-cache %s", repoFile, repoCache)

@ -24,6 +24,9 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/internal/test/ensure"
"helm.sh/helm/v4/pkg/getter" "helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/repo/v1" "helm.sh/helm/v4/pkg/repo/v1"
@ -44,9 +47,7 @@ func TestUpdateCmd(t *testing.T) {
update: updater, update: updater,
repoFile: "testdata/repositories.yaml", repoFile: "testdata/repositories.yaml",
} }
if err := o.run(&out); err != nil { require.NoError(t, o.run(&out))
t.Fatal(err)
}
if got := out.String(); !strings.Contains(got, "charts") || if got := out.String(); !strings.Contains(got, "charts") ||
!strings.Contains(got, "firstexample") || !strings.Contains(got, "firstexample") ||
@ -70,9 +71,7 @@ func TestUpdateCmdMultiple(t *testing.T) {
repoFile: "testdata/repositories.yaml", repoFile: "testdata/repositories.yaml",
names: []string{"firstexample", "charts"}, names: []string{"firstexample", "charts"},
} }
if err := o.run(&out); err != nil { require.NoError(t, o.run(&out))
t.Fatal(err)
}
if got := out.String(); !strings.Contains(got, "charts") || if got := out.String(); !strings.Contains(got, "charts") ||
!strings.Contains(got, "firstexample") || !strings.Contains(got, "firstexample") ||
@ -96,9 +95,7 @@ func TestUpdateCmdInvalid(t *testing.T) {
repoFile: "testdata/repositories.yaml", repoFile: "testdata/repositories.yaml",
names: []string{"firstexample", "invalid"}, names: []string{"firstexample", "invalid"},
} }
if err := o.run(&out); err == nil { require.Error(t, o.run(&out), "expected error but did not get one")
t.Fatal("expected error but did not get one")
}
} }
func TestUpdateCustomCacheCmd(t *testing.T) { func TestUpdateCustomCacheCmd(t *testing.T) {
@ -119,12 +116,9 @@ func TestUpdateCustomCacheCmd(t *testing.T) {
repoCache: cachePath, repoCache: cachePath,
} }
b := io.Discard b := io.Discard
if err := o.run(b); err != nil { require.NoError(t, o.run(b))
t.Fatal(err) _, err := os.Stat(filepath.Join(cachePath, "test-index.yaml"))
} require.NoErrorf(t, err, "error finding created index file in custom cache")
if _, err := os.Stat(filepath.Join(cachePath, "test-index.yaml")); err != nil {
t.Fatalf("error finding created index file in custom cache: %v", err)
}
} }
func TestUpdateCharts(t *testing.T) { func TestUpdateCharts(t *testing.T) {
@ -140,20 +134,14 @@ func TestUpdateCharts(t *testing.T) {
Name: "charts", Name: "charts",
URL: ts.URL(), URL: ts.URL(),
}, getter.All(settings)) }, getter.All(settings))
if err != nil { require.NoError(t, err)
t.Error(err)
}
b := bytes.NewBuffer(nil) b := bytes.NewBuffer(nil)
updateCharts([]*repo.ChartRepository{r}, b) updateCharts([]*repo.ChartRepository{r}, b)
got := b.String() got := b.String()
if strings.Contains(got, "Unable to get an update") { assert.NotContains(t, got, "Unable to get an update", "Failed to get a repo: %q", got)
t.Errorf("Failed to get a repo: %q", got) assert.Contains(t, got, "Update Complete.", "Update was not successful")
}
if !strings.Contains(got, "Update Complete.") {
t.Error("Update was not successful")
}
} }
func TestRepoUpdateFileCompletion(t *testing.T) { func TestRepoUpdateFileCompletion(t *testing.T) {
@ -176,37 +164,22 @@ func TestUpdateChartsFailWithError(t *testing.T) {
Name: "charts", Name: "charts",
URL: invalidURL, URL: invalidURL,
}, getter.All(settings)) }, getter.All(settings))
if err != nil { require.NoError(t, err)
t.Error(err)
}
r2, err := repo.NewChartRepository(&repo.Entry{ r2, err := repo.NewChartRepository(&repo.Entry{
Name: "charts", Name: "charts",
URL: invalidURL, URL: invalidURL,
}, getter.All(settings)) }, getter.All(settings))
if err != nil { require.NoError(t, err)
t.Error(err)
}
b := bytes.NewBuffer(nil) b := bytes.NewBuffer(nil)
err = updateCharts([]*repo.ChartRepository{r1, r2}, b) err = updateCharts([]*repo.ChartRepository{r1, r2}, b)
if err == nil { require.Error(t, err, "Repo update should return error because update of repository fails and 'fail-on-repo-update-fail' flag set")
t.Error("Repo update should return error because update of repository fails and 'fail-on-repo-update-fail' flag set")
return
}
var expectedErr = "failed to update the following repositories" var expectedErr = "failed to update the following repositories"
var receivedErr = err.Error() var receivedErr = err.Error()
if !strings.Contains(receivedErr, expectedErr) { require.ErrorContains(t, err, expectedErr, "Expected error (%s) but got (%s) instead", expectedErr, receivedErr)
t.Errorf("Expected error (%s) but got (%s) instead", expectedErr, receivedErr) require.ErrorContains(t, err, invalidURL, "Expected invalid URL (%s) in error message but got (%s) instead", invalidURL, receivedErr)
}
if !strings.Contains(receivedErr, invalidURL) {
t.Errorf("Expected invalid URL (%s) in error message but got (%s) instead", invalidURL, receivedErr)
}
got := b.String() got := b.String()
if !strings.Contains(got, "Unable to get an update") { assert.Contains(t, got, "Unable to get an update", "Repo should have failed update but instead got: %q", got)
t.Errorf("Repo should have failed update but instead got: %q", got) assert.NotContains(t, got, "Update Complete.", "Update was not successful and should return error message because 'fail-on-repo-update-fail' flag set")
}
if strings.Contains(got, "Update Complete.") {
t.Error("Update was not successful and should return error message because 'fail-on-repo-update-fail' flag set")
}
} }

@ -19,6 +19,7 @@ package kube
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/resource" "k8s.io/cli-runtime/pkg/resource"
@ -37,27 +38,17 @@ func TestResourceList(t *testing.T) {
r1 = []*resource.Info{info("foo"), info("bar")} r1 = []*resource.Info{info("foo"), info("bar")}
r2 = []*resource.Info{info("bar")} r2 = []*resource.Info{info("bar")}
if r1.Get(info("bar")).Mapping.Resource.Resource != "pod" { assert.Equal(t, "pod", r1.Get(info("bar")).Mapping.Resource.Resource, "expected get pod")
t.Error("expected get pod")
}
diff := r1.Difference(r2) diff := r1.Difference(r2)
if len(diff) != 1 { assert.Len(t, diff, 1, "expected 1 result")
t.Error("expected 1 result")
}
if !diff.Contains(info("foo")) { assert.True(t, diff.Contains(info("foo")), "expected diff to return foo")
t.Error("expected diff to return foo")
}
inter := r1.Intersect(r2) inter := r1.Intersect(r2)
if len(inter) != 1 { assert.Len(t, inter, 1, "expected 1 result")
t.Error("expected 1 result")
}
if !inter.Contains(info("bar")) { assert.True(t, inter.Contains(info("bar")), "expected intersect to return bar")
t.Error("expected intersect to return bar")
}
} }
func TestIsMatchingInfo(t *testing.T) { func TestIsMatchingInfo(t *testing.T) {
@ -66,35 +57,23 @@ func TestIsMatchingInfo(t *testing.T) {
gvkDiffGroup := schema.GroupVersionKind{Group: "diff", Version: "version1", Kind: "pod"} gvkDiffGroup := schema.GroupVersionKind{Group: "diff", Version: "version1", Kind: "pod"}
resourceInfoDiffGroup := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffGroup}} resourceInfoDiffGroup := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffGroup}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffGroup) { assert.False(t, isMatchingInfo(&resourceInfo, &resourceInfoDiffGroup), "expected resources not equal")
t.Error("expected resources not equal")
}
gvkDiffVersion := schema.GroupVersionKind{Group: "group1", Version: "diff", Kind: "pod"} gvkDiffVersion := schema.GroupVersionKind{Group: "group1", Version: "diff", Kind: "pod"}
resourceInfoDiffVersion := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffVersion}} resourceInfoDiffVersion := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffVersion}}
if !isMatchingInfo(&resourceInfo, &resourceInfoDiffVersion) { assert.True(t, isMatchingInfo(&resourceInfo, &resourceInfoDiffVersion), "expected resources with different versions but same group and kind to be equal")
t.Error("expected resources with different versions but same group and kind to be equal")
}
gvkDiffKind := schema.GroupVersionKind{Group: "group1", Version: "version1", Kind: "deployment"} gvkDiffKind := schema.GroupVersionKind{Group: "group1", Version: "version1", Kind: "deployment"}
resourceInfoDiffKind := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffKind}} resourceInfoDiffKind := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffKind}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffKind) { assert.False(t, isMatchingInfo(&resourceInfo, &resourceInfoDiffKind), "expected resources not equal")
t.Error("expected resources not equal")
}
resourceInfoDiffName := resource.Info{Name: "diff", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvk}} resourceInfoDiffName := resource.Info{Name: "diff", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvk}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffName) { assert.False(t, isMatchingInfo(&resourceInfo, &resourceInfoDiffName), "expected resources not equal")
t.Error("expected resources not equal")
}
resourceInfoDiffNamespace := resource.Info{Name: "name1", Namespace: "diff", Mapping: &meta.RESTMapping{GroupVersionKind: gvk}} resourceInfoDiffNamespace := resource.Info{Name: "name1", Namespace: "diff", Mapping: &meta.RESTMapping{GroupVersionKind: gvk}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffNamespace) { assert.False(t, isMatchingInfo(&resourceInfo, &resourceInfoDiffNamespace), "expected resources not equal")
t.Error("expected resources not equal")
}
gvkEqual := schema.GroupVersionKind{Group: "group1", Version: "version1", Kind: "pod"} gvkEqual := schema.GroupVersionKind{Group: "group1", Version: "version1", Kind: "pod"}
resourceInfoEqual := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkEqual}} resourceInfoEqual := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkEqual}}
if !isMatchingInfo(&resourceInfo, &resourceInfoEqual) { assert.True(t, isMatchingInfo(&resourceInfo, &resourceInfoEqual), "expected resources to be equal")
t.Error("expected resources to be equal")
}
} }

Loading…
Cancel
Save