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

refactor: convert tests to testify assert/require in internal/plugin
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
pull/32410/head
Matthieu MOREL 2 months ago
parent 06978bd8c5
commit f3402c1cd6

@ -32,7 +32,7 @@ func TestValidateNoDeprecations(t *testing.T) {
require.Error(t, err, "Expected deprecated extension to be flagged") require.Error(t, err, "Expected deprecated extension to be flagged")
var depErr deprecatedAPIError var depErr deprecatedAPIError
require.ErrorAs(t, err, &depErr, "Expected error to be of type deprecatedAPIError") require.ErrorAs(t, err, &depErr, "Expected error to be of type deprecatedAPIError")
require.NotEmpty(t, depErr.Message, "Expected error message to be non-blank: %v", err) require.NotEmpty(t, depErr.Message, "Expected error message to be non-blank")
assert.NoError(t, validateNoDeprecations(&k8sYamlStruct{ assert.NoError(t, validateNoDeprecations(&k8sYamlStruct{
APIVersion: "v1", APIVersion: "v1",
Kind: "Pod", Kind: "Pod",

@ -56,8 +56,7 @@ func TestValidateValuesYamlNotDirectory(t *testing.T) {
_ = os.Mkdir(nonExistingValuesFilePath, os.ModePerm) _ = os.Mkdir(nonExistingValuesFilePath, os.ModePerm)
defer os.Remove(nonExistingValuesFilePath) defer os.Remove(nonExistingValuesFilePath)
err := validateValuesFileExistence(nonExistingValuesFilePath) assert.Error(t, validateValuesFileExistence(nonExistingValuesFilePath), "validateValuesFileExistence to return a linter error, got no error")
assert.Error(t, err, "validateValuesFileExistence to return a linter error, got no error")
} }
func TestValidateValuesFileWellFormed(t *testing.T) { func TestValidateValuesFileWellFormed(t *testing.T) {
@ -150,7 +149,7 @@ func TestValidateValuesFile(t *testing.T) {
require.NoError(t, err, "Failed validation") require.NoError(t, err, "Failed validation")
} else { } else {
require.Error(t, err, "expected values file to fail parsing") require.Error(t, err, "expected values file to fail parsing")
assert.ErrorContains(t, err, tt.errorMessage, "Failed with unexpected error") assert.ErrorContains(t, err, tt.errorMessage)
} }
}) })
} }

@ -16,7 +16,11 @@ limitations under the License.
package util package util
import "testing" import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestValidateReleaseName is a regression test for ValidateName // TestValidateReleaseName is a regression test for ValidateName
// //
@ -46,12 +50,11 @@ func TestValidateReleaseName(t *testing.T) {
"a1111111111111111111111111111111111111111111111111111111111z": false, "a1111111111111111111111111111111111111111111111111111111111z": false,
} }
for input, expectPass := range names { for input, expectPass := range names {
if err := ValidateReleaseName(input); (err == nil) != expectPass { err := ValidateReleaseName(input)
st := "fail" if expectPass {
if expectPass { assert.NoErrorf(t, err, "Expected release name %q to pass validation", input)
st = "succeed" } else {
} assert.Errorf(t, err, "Expected release name %q to fail validation, but it passed", input)
t.Errorf("Expected %q to %s", input, st)
} }
} }
} }
@ -80,12 +83,11 @@ func TestValidateMetadataName(t *testing.T) {
"a1111111111111111111111111111111111111111111111111111111111z": false, "a1111111111111111111111111111111111111111111111111111111111z": false,
} }
for input, expectPass := range names { for input, expectPass := range names {
if err := ValidateMetadataName(input); (err == nil) != expectPass { err := ValidateMetadataName(input)
st := "fail" if expectPass {
if expectPass { assert.NoError(t, err, "Expected %q to succeed", input)
st = "succeed" } else {
} assert.Error(t, err, "Expected %q to fail", input)
t.Errorf("Expected %q to %s", input, st)
} }
} }
} }

@ -37,8 +37,7 @@ func TestAtomicWriteFile(t *testing.T) {
reader := bytes.NewReader([]byte(stringContent)) reader := bytes.NewReader([]byte(stringContent))
mode := os.FileMode(0o644) mode := os.FileMode(0o644)
err := AtomicWriteFile(testpath, reader, mode) require.NoError(t, AtomicWriteFile(testpath, reader, mode))
require.NoError(t, err)
got, err := os.ReadFile(testpath) got, err := os.ReadFile(testpath)
require.NoError(t, err) require.NoError(t, err)
@ -58,8 +57,7 @@ func TestAtomicWriteFile_CreateTempError(t *testing.T) {
reader := bytes.NewReader([]byte("test content")) reader := bytes.NewReader([]byte("test content"))
mode := os.FileMode(0o644) mode := os.FileMode(0o644)
err := AtomicWriteFile(invalidPath, reader, mode) assert.Error(t, AtomicWriteFile(invalidPath, reader, mode), "Expected error when CreateTemp fails")
assert.Error(t, err, "Expected error when CreateTemp fails")
} }
// TestAtomicWriteFile_EmptyContent tests with empty content // TestAtomicWriteFile_EmptyContent tests with empty content
@ -70,8 +68,7 @@ func TestAtomicWriteFile_EmptyContent(t *testing.T) {
reader := bytes.NewReader([]byte("")) reader := bytes.NewReader([]byte(""))
mode := os.FileMode(0o644) mode := os.FileMode(0o644)
err := AtomicWriteFile(testpath, reader, mode) require.NoError(t, AtomicWriteFile(testpath, reader, mode), "AtomicWriteFile error with empty content")
require.NoError(t, err, "AtomicWriteFile error with empty content")
got, err := os.ReadFile(testpath) got, err := os.ReadFile(testpath)
require.NoError(t, err) require.NoError(t, err)
@ -89,8 +86,7 @@ func TestAtomicWriteFile_LargeContent(t *testing.T) {
reader := bytes.NewReader([]byte(largeContent)) reader := bytes.NewReader([]byte(largeContent))
mode := os.FileMode(0o644) mode := os.FileMode(0o644)
err := AtomicWriteFile(testpath, reader, mode) require.NoError(t, AtomicWriteFile(testpath, reader, mode), "AtomicWriteFile error with large content")
require.NoError(t, err, "AtomicWriteFile error with large content")
got, err := os.ReadFile(testpath) got, err := os.ReadFile(testpath)
require.NoError(t, err) require.NoError(t, err)

@ -197,9 +197,8 @@ func TestDebugCheckHandler_Handle(t *testing.T) {
} }
record := slog.NewRecord(time.Now(), slog.LevelInfo, "test message", 0) record := slog.NewRecord(time.Now(), slog.LevelInfo, "test message", 0)
err := handler.Handle(t.Context(), record)
require.NoError(t, err) require.NoError(t, handler.Handle(t.Context(), record))
assert.Contains(t, buf.String(), "test message") assert.Contains(t, buf.String(), "test message")
}) })
@ -214,9 +213,8 @@ func TestDebugCheckHandler_Handle(t *testing.T) {
type testKey string type testKey string
ctx := context.WithValue(t.Context(), testKey("test"), "value") ctx := context.WithValue(t.Context(), testKey("test"), "value")
record := slog.NewRecord(time.Now(), slog.LevelInfo, "context test", 0) record := slog.NewRecord(time.Now(), slog.LevelInfo, "context test", 0)
err := handler.Handle(ctx, record)
require.NoError(t, err) require.NoError(t, handler.Handle(ctx, record))
assert.Contains(t, buf.String(), "context test") assert.Contains(t, buf.String(), "context test")
}) })
} }

@ -15,6 +15,8 @@ package installer
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestPath(t *testing.T) { func TestPath(t *testing.T) {
@ -38,8 +40,6 @@ func TestPath(t *testing.T) {
t.Setenv("HELM_PLUGINS", tt.helmPluginsDir) t.Setenv("HELM_PLUGINS", tt.helmPluginsDir)
baseIns := newBase(tt.source) baseIns := newBase(tt.source)
baseInsPath := baseIns.Path() baseInsPath := baseIns.Path()
if baseInsPath != tt.expectPath { assert.Equal(t, tt.expectPath, baseInsPath, "expected name %s, got %s", tt.expectPath, baseInsPath)
t.Errorf("expected name %s, got %s", tt.expectPath, baseInsPath)
}
} }
} }

@ -194,13 +194,9 @@ func TestDetectDuplicates(t *testing.T) {
mockSubprocessCLIPlugin(t, "foo"), mockSubprocessCLIPlugin(t, "foo"),
mockSubprocessCLIPlugin(t, "bar"), mockSubprocessCLIPlugin(t, "bar"),
} }
if err := detectDuplicates(plugs); err != nil { require.NoError(t, detectDuplicates(plugs), "no duplicates in the first set")
t.Error("no duplicates in the first set")
}
plugs = append(plugs, mockSubprocessCLIPlugin(t, "foo")) plugs = append(plugs, mockSubprocessCLIPlugin(t, "foo"))
if err := detectDuplicates(plugs); err == nil { assert.Error(t, detectDuplicates(plugs), "duplicates in the second set")
t.Error("duplicates in the second set")
}
} }
func TestLoadAllDir_Empty(t *testing.T) { func TestLoadAllDir_Empty(t *testing.T) {

@ -66,7 +66,7 @@ func TestValidatePluginData(t *testing.T) {
t.Run(strconv.Itoa(i), func(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) {
err := item.plug.Metadata().Validate() err := item.plug.Metadata().Validate()
if item.pass { if item.pass {
require.NoError(t, err, "failed to validate case %d: %s", i, err) require.NoError(t, err, "failed to validate case %d", i)
} else { } else {
require.Error(t, err, "expected case %d to fail", i) require.Error(t, err, "expected case %d to fail", i)
assert.ErrorContains(t, err, item.errString, "expected case %d error to contain %q", i, item.errString) assert.ErrorContains(t, err, item.errString, "expected case %d error to contain %q", i, item.errString)
@ -97,8 +97,7 @@ func TestMetadataValidateVersion(t *testing.T) {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
m := mockSubprocessCLIPlugin(t, "testplugin") m := mockSubprocessCLIPlugin(t, "testplugin")
m.metadata.Version = tc.version m.metadata.Version = tc.version
err := m.Metadata().Validate() assert.NoError(t, m.Metadata().Validate())
assert.NoError(t, err)
}) })
} }
@ -106,8 +105,7 @@ func TestMetadataValidateVersion(t *testing.T) {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
m := mockSubprocessCLIPlugin(t, "testplugin") m := mockSubprocessCLIPlugin(t, "testplugin")
m.metadata.Version = tc.version m.metadata.Version = tc.version
err := m.Metadata().Validate() assert.ErrorContains(t, m.Metadata().Validate(), "invalid plugin version")
assert.ErrorContains(t, err, "invalid plugin version")
}) })
} }
} }
@ -139,7 +137,7 @@ func TestMetadataValidateMultipleErrors(t *testing.T) {
} }
for _, expectedErr := range expectedErrors { for _, expectedErr := range expectedErrors {
assert.Contains(t, errStr, expectedErr, "expected error to contain %q, but got: %v", expectedErr, errStr) require.ErrorContains(t, err, expectedErr)
} }
// Verify that the error contains the correct number of error messages // Verify that the error contains the correct number of error messages

@ -77,8 +77,7 @@ func TestMetadataV1ValidateVersion(t *testing.T) {
t.Run("invalid/"+name, func(t *testing.T) { t.Run("invalid/"+name, func(t *testing.T) {
m := base() m := base()
m.Version = tc.version m.Version = tc.version
err := m.Validate() assert.ErrorContains(t, m.Validate(), tc.errMsg)
assert.ErrorContains(t, err, tc.errMsg)
}) })
} }
} }

@ -18,6 +18,8 @@ package plugin
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/internal/plugin/schema" "helm.sh/helm/v4/internal/plugin/schema"
) )
@ -34,9 +36,7 @@ func TestValidPluginName(t *testing.T) {
for name, pluginName := range validNames { for name, pluginName := range validNames {
t.Run("valid/"+name, func(t *testing.T) { t.Run("valid/"+name, func(t *testing.T) {
if !validPluginName.MatchString(pluginName) { assert.Truef(t, validPluginName.MatchString(pluginName), "expected %q to match validPluginName regex", pluginName)
t.Errorf("expected %q to match validPluginName regex", pluginName)
}
}) })
} }
@ -52,9 +52,7 @@ func TestValidPluginName(t *testing.T) {
for name, pluginName := range invalidNames { for name, pluginName := range invalidNames {
t.Run("invalid/"+name, func(t *testing.T) { t.Run("invalid/"+name, func(t *testing.T) {
if validPluginName.MatchString(pluginName) { assert.Falsef(t, validPluginName.MatchString(pluginName), "expected %q to not match validPluginName regex", pluginName)
t.Errorf("expected %q to not match validPluginName regex", pluginName)
}
}) })
} }
} }

@ -170,12 +170,12 @@ func TestHookExecutionUnmarshalJSON(t *testing.T) {
err := json.Unmarshal([]byte(tt.input), &exec) err := json.Unmarshal([]byte(tt.input), &exec)
if tt.wantErr { if tt.wantErr {
assert.Error(t, err) assert.Error(t, err)
return } else {
require.NoError(t, err)
assert.Equal(t, tt.expected.StartedAt.Unix(), exec.StartedAt.Unix())
assert.Equal(t, tt.expected.CompletedAt.Unix(), exec.CompletedAt.Unix())
assert.Equal(t, tt.expected.Phase, exec.Phase)
} }
require.NoError(t, err)
assert.Equal(t, tt.expected.StartedAt.Unix(), exec.StartedAt.Unix())
assert.Equal(t, tt.expected.CompletedAt.Unix(), exec.CompletedAt.Unix())
assert.Equal(t, tt.expected.Phase, exec.Phase)
}) })
} }
} }
@ -194,8 +194,7 @@ func TestHookExecutionRoundTrip(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
var decoded HookExecution var decoded HookExecution
err = json.Unmarshal(data, &decoded) require.NoError(t, json.Unmarshal(data, &decoded))
require.NoError(t, err)
assert.Equal(t, original.StartedAt.Unix(), decoded.StartedAt.Unix()) assert.Equal(t, original.StartedAt.Unix(), decoded.StartedAt.Unix())
assert.Equal(t, original.CompletedAt.Unix(), decoded.CompletedAt.Unix()) assert.Equal(t, original.CompletedAt.Unix(), decoded.CompletedAt.Unix())
@ -208,12 +207,11 @@ func TestHookExecutionEmptyStringRoundTrip(t *testing.T) {
input := `{"started_at":"","completed_at":"","phase":"Succeeded"}` input := `{"started_at":"","completed_at":"","phase":"Succeeded"}`
var exec HookExecution var exec HookExecution
err := json.Unmarshal([]byte(input), &exec) require.NoError(t, json.Unmarshal([]byte(input), &exec))
require.NoError(t, err)
// Verify time fields are zero values // Verify time fields are zero values
assert.True(t, exec.StartedAt.IsZero()) assert.Zero(t, exec.StartedAt)
assert.True(t, exec.CompletedAt.IsZero()) assert.Zero(t, exec.CompletedAt)
assert.Equal(t, HookPhaseSucceeded, exec.Phase) assert.Equal(t, HookPhaseSucceeded, exec.Phase)
// Marshal back and verify empty time fields are omitted // Marshal back and verify empty time fields are omitted
@ -221,8 +219,7 @@ func TestHookExecutionEmptyStringRoundTrip(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
var result map[string]any var result map[string]any
err = json.Unmarshal(data, &result) require.NoError(t, json.Unmarshal(data, &result))
require.NoError(t, err)
// Zero time values should be omitted // Zero time values should be omitted
assert.NotContains(t, result, "started_at") assert.NotContains(t, result, "started_at")

@ -132,8 +132,7 @@ func TestWalk(t *testing.T) {
return mark(info, err, &errors, true) return mark(info, err, &errors, true)
} }
// Expect no errors. // Expect no errors.
err := Walk(tree.name, markFn) require.NoError(t, Walk(tree.name, markFn))
require.NoError(t, err)
require.Empty(t, errors, "unexpected errors") require.Empty(t, errors, "unexpected errors")
checkMarks(t, true) checkMarks(t, true)

Loading…
Cancel
Save