chore(internal): refactor: convert tests to testify assert/require part 3

refactor: convert tests to testify assert/require in internal/chart/v3/lint/rules
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
pull/32343/head
Matthieu MOREL 2 months ago
parent ad93b7df63
commit caac755f19

@ -21,6 +21,7 @@ import (
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/pkg/chart/common" "helm.sh/helm/v4/pkg/chart/common"
) )
@ -76,15 +77,12 @@ func TestSaveChartNoRawData(t *testing.T) {
} }
is := assert.New(t) is := assert.New(t)
req := require.New(t)
data, err := json.Marshal(chrt) data, err := json.Marshal(chrt)
if err != nil { req.NoError(err)
t.Fatal(err)
}
res := &Chart{} res := &Chart{}
if err := json.Unmarshal(data, res); err != nil { req.NoError(json.Unmarshal(data, res))
t.Fatal(err)
}
is.Equal([]*common.File(nil), res.Raw) is.Equal([]*common.File(nil), res.Raw)
} }

@ -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/internal/chart/v3" chart "helm.sh/helm/v4/internal/chart/v3"
"helm.sh/helm/v4/internal/chart/v3/lint/support" "helm.sh/helm/v4/internal/chart/v3/lint/support"
chartutil "helm.sh/helm/v4/internal/chart/v3/util" chartutil "helm.sh/helm/v4/internal/chart/v3/util"
@ -63,17 +66,13 @@ func chartWithBadDependencies() chart.Chart {
func TestValidateDependencyInChartsDir(t *testing.T) { func TestValidateDependencyInChartsDir(t *testing.T) {
c := chartWithBadDependencies() c := chartWithBadDependencies()
if err := validateDependencyInChartsDir(&c); err == nil { assert.Error(t, validateDependencyInChartsDir(&c), "chart should have been flagged for missing deps in chart directory")
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()
if err := validateDependencyInMetadata(&c); err == nil { assert.Error(t, validateDependencyInMetadata(&c), "chart should have been flagged for missing deps in chart metadata")
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 +130,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,15 +138,11 @@ 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)
if l := len(linter.Messages); l != 2 { if !assert.Len(t, linter.Messages, 2, "expected 2 linter errors for bad chart dependencies") {
t.Errorf("expected 2 linter errors for bad chart dependencies. Got %d.", l)
for i, msg := range linter.Messages { for i, msg := range linter.Messages {
t.Logf("Message: %d, Error: %#v", i, msg) t.Logf("Message: %d, Error: %#v", i, msg)
} }

@ -22,6 +22,7 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/internal/test/ensure"
) )
@ -56,9 +57,7 @@ func TestValidateValuesYamlNotDirectory(t *testing.T) {
defer os.Remove(nonExistingValuesFilePath) defer os.Remove(nonExistingValuesFilePath)
err := validateValuesFileExistence(nonExistingValuesFilePath) err := validateValuesFileExistence(nonExistingValuesFilePath)
if err == nil { assert.Error(t, err, "validateValuesFileExistence to return a linter error, got no error")
t.Error("validateValuesFileExistence to return a linter error, got no error")
}
} }
func TestValidateValuesFileWellFormed(t *testing.T) { func TestValidateValuesFileWellFormed(t *testing.T) {
@ -67,9 +66,7 @@ func TestValidateValuesFileWellFormed(t *testing.T) {
` `
tmpdir := ensure.TempFile(t, "values.yaml", []byte(badYaml)) tmpdir := ensure.TempFile(t, "values.yaml", []byte(badYaml))
valfile := filepath.Join(tmpdir, "values.yaml") valfile := filepath.Join(tmpdir, "values.yaml")
if err := validateValuesFile(valfile, map[string]any{}, false); err == nil { require.Error(t, validateValuesFile(valfile, map[string]any{}, false), "expected values file to fail parsing")
t.Fatal("expected values file to fail parsing")
}
} }
func TestValidateValuesFileSchema(t *testing.T) { func TestValidateValuesFileSchema(t *testing.T) {
@ -78,9 +75,7 @@ func TestValidateValuesFileSchema(t *testing.T) {
createTestingSchema(t, tmpdir) createTestingSchema(t, tmpdir)
valfile := filepath.Join(tmpdir, "values.yaml") valfile := filepath.Join(tmpdir, "values.yaml")
if err := validateValuesFile(valfile, map[string]any{}, false); err != nil { require.NoError(t, validateValuesFile(valfile, map[string]any{}, false), "Failed validation")
t.Fatalf("Failed validation with %s", err)
}
} }
func TestValidateValuesFileSchemaFailure(t *testing.T) { func TestValidateValuesFileSchemaFailure(t *testing.T) {
@ -91,8 +86,7 @@ func TestValidateValuesFileSchemaFailure(t *testing.T) {
valfile := filepath.Join(tmpdir, "values.yaml") valfile := filepath.Join(tmpdir, "values.yaml")
err := validateValuesFile(valfile, map[string]any{}, false) assert.ErrorContains(t, validateValuesFile(valfile, map[string]any{}, false), "- at '/username': got number, want string")
assert.ErrorContains(t, err, "- at '/username': got number, want string")
} }
func TestValidateValuesFileSchemaFailureButWithSkipSchemaValidation(t *testing.T) { func TestValidateValuesFileSchemaFailureButWithSkipSchemaValidation(t *testing.T) {
@ -103,10 +97,7 @@ func TestValidateValuesFileSchemaFailureButWithSkipSchemaValidation(t *testing.T
valfile := filepath.Join(tmpdir, "values.yaml") valfile := filepath.Join(tmpdir, "values.yaml")
err := validateValuesFile(valfile, map[string]any{}, true) require.NoError(t, validateValuesFile(valfile, map[string]any{}, true), "expected values file to pass parsing because of skipSchemaValidation")
if err != nil {
t.Fatal("expected values file to pass parsing because of skipSchemaValidation")
}
} }
func TestValidateValuesFileSchemaOverrides(t *testing.T) { func TestValidateValuesFileSchemaOverrides(t *testing.T) {
@ -118,9 +109,7 @@ func TestValidateValuesFileSchemaOverrides(t *testing.T) {
createTestingSchema(t, tmpdir) createTestingSchema(t, tmpdir)
valfile := filepath.Join(tmpdir, "values.yaml") valfile := filepath.Join(tmpdir, "values.yaml")
if err := validateValuesFile(valfile, overrides, false); err != nil { require.NoError(t, validateValuesFile(valfile, overrides, false), "Failed validation")
t.Fatalf("Failed validation with %s", err)
}
} }
func TestValidateValuesFile(t *testing.T) { func TestValidateValuesFile(t *testing.T) {
@ -157,12 +146,10 @@ func TestValidateValuesFile(t *testing.T) {
err := validateValuesFile(valfile, tt.overrides, false) err := validateValuesFile(valfile, tt.overrides, false)
switch { if tt.errorMessage == "" {
case err != nil && tt.errorMessage == "": require.NoError(t, err, "Failed validation")
t.Errorf("Failed validation with %s", err) } else {
case err == nil && tt.errorMessage != "": require.Error(t, err, "expected values file to fail parsing")
t.Error("expected values file to fail parsing")
case err != nil && tt.errorMessage != "":
assert.ErrorContains(t, err, tt.errorMessage, "Failed with unexpected error") assert.ErrorContains(t, err, tt.errorMessage, "Failed with unexpected error")
} }
}) })
@ -172,8 +159,6 @@ func TestValidateValuesFile(t *testing.T) {
func createTestingSchema(t *testing.T, dir string) string { func createTestingSchema(t *testing.T, dir string) string {
t.Helper() t.Helper()
schemafile := filepath.Join(dir, "values.schema.json") schemafile := filepath.Join(dir, "values.schema.json")
if err := os.WriteFile(schemafile, []byte(testSchema), 0o700); err != nil { require.NoError(t, os.WriteFile(schemafile, []byte(testSchema), 0o700), "Failed to write schema to tmpdir")
t.Fatalf("Failed to write schema to tmpdir: %s", err)
}
return schemafile return schemafile
} }

@ -31,6 +31,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
chart "helm.sh/helm/v4/internal/chart/v3" chart "helm.sh/helm/v4/internal/chart/v3"
@ -690,9 +691,7 @@ func verifyChartFileAndTemplate(t *testing.T, c *chart.Chart, name string) {
if dep.Templates[0].Name != "templates/alpine-pod.yaml" { if dep.Templates[0].Name != "templates/alpine-pod.yaml" {
t.Errorf("Unexpected template: %s", dep.Templates[0].Name) t.Errorf("Unexpected template: %s", dep.Templates[0].Name)
} }
if len(dep.Templates[0].Data) == 0 { assert.NotEmpty(t, dep.Templates[0].Data, "No template data.")
t.Error("No template data.")
}
if len(dep.Files) != 1 { if len(dep.Files) != 1 {
t.Fatalf("Expected 1 Files, got %d", len(dep.Files)) t.Fatalf("Expected 1 Files, got %d", len(dep.Files))
} }

@ -16,8 +16,10 @@ limitations under the License.
package v3 package v3
import ( import (
"errors"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestValidate(t *testing.T) { func TestValidate(t *testing.T) {
@ -192,21 +194,13 @@ func TestValidate(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
result := tt.md.Validate() result := tt.md.Validate()
if !errors.Is(result, tt.err) { assert.ErrorIsf(t, result, tt.err, "expected %q, got %q in test %q", tt.err, result, tt.name)
t.Errorf("expected %q, got %q in test %q", tt.err, result, tt.name)
}
} }
} }
func TestValidate_sanitize(t *testing.T) { func TestValidate_sanitize(t *testing.T) {
md := &Metadata{APIVersion: "3", Name: "test", Version: "1.0", Description: "\adescr\u0081iption\rtest", Maintainers: []*Maintainer{{Name: "\r"}}} md := &Metadata{APIVersion: "3", Name: "test", Version: "1.0", Description: "\adescr\u0081iption\rtest", Maintainers: []*Maintainer{{Name: "\r"}}}
if err := md.Validate(); err != nil { require.NoError(t, md.Validate())
t.Fatalf("unexpected error: %s", err) require.Equalf(t, "description test", md.Description, "description was not sanitized: %q", md.Description)
} require.Equal(t, " ", md.Maintainers[0].Name, "maintainer name was not sanitized")
if md.Description != "description test" {
t.Fatalf("description was not sanitized: %q", md.Description)
}
if md.Maintainers[0].Name != " " {
t.Fatal("maintainer name was not sanitized")
}
} }

@ -17,7 +17,11 @@ limitations under the License.
// Package version represents the current version of the project. // Package version represents the current version of the project.
package util package util
import "testing" import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsCompatibleRange(t *testing.T) { func TestIsCompatibleRange(t *testing.T) {
tests := []struct { tests := []struct {
@ -36,8 +40,6 @@ func TestIsCompatibleRange(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
if IsCompatibleRange(tt.constraint, tt.ver) != tt.expected { assert.Equalf(t, tt.expected, IsCompatibleRange(tt.constraint, tt.ver), "expected constraint %s to be %v for %s", tt.constraint, tt.expected, tt.ver)
t.Errorf("expected constraint %s to be %v for %s", tt.constraint, tt.expected, tt.ver)
}
} }
} }

@ -18,9 +18,11 @@ package plugin
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/pkg/provenance" "helm.sh/helm/v4/pkg/provenance"
) )
@ -28,9 +30,7 @@ func TestSignPlugin(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
pluginYAML := `apiVersion: v1 pluginYAML := `apiVersion: v1
@ -41,16 +41,12 @@ version: 1.0.0
runtimeConfig: runtimeConfig:
platformCommand: platformCommand:
- command: echo` - command: echo`
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 a tarball // Create a tarball
tarballPath := filepath.Join(tempDir, "test-plugin.tgz") tarballPath := filepath.Join(tempDir, "test-plugin.tgz")
tarFile, err := os.Create(tarballPath) tarFile, err := os.Create(tarballPath)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
if err := CreatePluginTarball(pluginDir, "test-plugin", tarFile); err != nil { if err := CreatePluginTarball(pluginDir, "test-plugin", tarFile); err != nil {
tarFile.Close() tarFile.Close()
t.Fatal(err) t.Fatal(err)
@ -60,39 +56,25 @@ runtimeConfig:
// Create a test key for signing // Create a test key for signing
keyring := "../../pkg/cmd/testdata/helm-test-key.secret" keyring := "../../pkg/cmd/testdata/helm-test-key.secret"
signer, err := provenance.NewFromKeyring(keyring, "helm-test") signer, err := provenance.NewFromKeyring(keyring, "helm-test")
if err != nil { require.NoError(t, err)
t.Fatal(err) require.NoError(t, signer.DecryptKey(func(_ string) ([]byte, error) {
}
if err := signer.DecryptKey(func(_ string) ([]byte, error) {
return []byte(""), nil return []byte(""), nil
}); err != nil { }))
t.Fatal(err)
}
// Read the tarball data // Read the tarball data
tarballData, err := os.ReadFile(tarballPath) tarballData, err := os.ReadFile(tarballPath)
if err != nil { require.NoError(t, err, "failed to read tarball")
t.Fatalf("failed to read tarball: %v", err)
}
// Sign the plugin tarball // Sign the plugin tarball
sig, err := SignPlugin(tarballData, filepath.Base(tarballPath), signer) sig, err := SignPlugin(tarballData, filepath.Base(tarballPath), signer)
if err != nil { require.NoError(t, err, "failed to sign plugin")
t.Fatalf("failed to sign plugin: %v", err)
}
// Verify the signature contains the expected content // Verify the signature contains the expected content
if !strings.Contains(sig, "-----BEGIN PGP SIGNED MESSAGE-----") { assert.Contains(t, sig, "-----BEGIN PGP SIGNED MESSAGE-----", "signature does not contain PGP header")
t.Error("signature does not contain PGP header")
}
// Verify the tarball hash is in the signature // Verify the tarball hash is in the signature
expectedHash, err := provenance.DigestFile(tarballPath) expectedHash, err := provenance.DigestFile(tarballPath)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
// The signature should contain the tarball hash // The signature should contain the tarball hash
if !strings.Contains(sig, "sha256:"+expectedHash) { assert.Contains(t, sig, "sha256:"+expectedHash, "signature does not contain expected tarball hash: sha256:%s", expectedHash)
t.Errorf("signature does not contain expected tarball hash: sha256:%s", expectedHash)
}
} }

Loading…
Cancel
Save