From f1d5979e7d8b9d1e36b3cf703d150e8078c2e16e Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 20 Jul 2026 20:50:56 +0200 Subject: [PATCH] chore(internal): refactor: convert tests to testify assert/require part 5 refactor: convert tests to testify assert/require in internal/plugin/installer Signed-off-by: Matthieu MOREL --- internal/chart/v3/lint/rules/template_test.go | 27 ++- .../chart/v3/lint/support/message_test.go | 29 +-- internal/chart/v3/util/chartfile_test.go | 27 +-- internal/plugin/installer/installer_test.go | 26 +-- .../plugin/installer/plugin_structure_test.go | 31 +-- .../plugin/installer/verification_test.go | 181 +++++------------- internal/plugin/runtime_extismv1_test.go | 3 +- internal/plugin/subprocess_commands_test.go | 28 +-- internal/plugin/verify_test.go | 26 +-- 9 files changed, 118 insertions(+), 260 deletions(-) diff --git a/internal/chart/v3/lint/rules/template_test.go b/internal/chart/v3/lint/rules/template_test.go index 0b83e1cd5..b4fa2d311 100644 --- a/internal/chart/v3/lint/rules/template_test.go +++ b/internal/chart/v3/lint/rules/template_test.go @@ -37,13 +37,11 @@ const templateTestBasedir = "./testdata/albatross" func TestValidateAllowedExtension(t *testing.T) { var failTest = []string{"/foo", "/test.toml"} for _, test := range failTest { - err := validateAllowedExtension(test) - require.ErrorContains(t, err, "Valid extensions are .yaml, .yml, .tpl, or .txt", "validateAllowedExtension('%s') to return \"Valid extensions are .yaml, .yml, .tpl, or .txt\", got no error", test) + require.ErrorContains(t, validateAllowedExtension(test), "Valid extensions are .yaml, .yml, .tpl, or .txt", "validateAllowedExtension('%s') to return \"Valid extensions are .yaml, .yml, .tpl, or .txt\", got no error", test) } var successTest = []string{"/foo.yaml", "foo.yaml", "foo.tpl", "/foo/bar/baz.yaml", "NOTES.txt"} for _, test := range successTest { - err := validateAllowedExtension(test) - assert.NoError(t, err, "validateAllowedExtension('%s') to return no error", test) + assert.NoError(t, validateAllowedExtension(test), "validateAllowedExtension('%s') to return no error", test) } } @@ -58,8 +56,7 @@ func TestTemplateParsing(t *testing.T) { res := linter.Messages require.Len(t, res, 1, "Expected one error, got %d, %v", len(res), res) - - assert.ErrorContains(t, res[0].Err, "deliberateSyntaxError", "Unexpected error: %s", res[0]) + assert.ErrorContains(t, res[0].Err, "deliberateSyntaxError") } var wrongTemplatePath = filepath.Join(templateTestBasedir, "templates", "fail.yaml") @@ -86,7 +83,7 @@ func TestMultiTemplateFail(t *testing.T) { require.Len(t, res, 1, "Expected 1 error, got %d, %v", len(res), res) - assert.ErrorContains(t, res[0].Err, "object name does not conform to Kubernetes naming requirements", "Unexpected error: %s", res[0].Err) + assert.ErrorContains(t, res[0].Err, "object name does not conform to Kubernetes naming requirements") } func TestValidateMetadataName(t *testing.T) { @@ -292,8 +289,7 @@ spec: - name: nginx image: nginx:1.14.2 ` - err := validateMatchSelector(md, manifest) - require.NoError(t, err) + require.NoError(t, validateMatchSelector(md, manifest)) manifest = ` apiVersion: apps/v1 kind: Deployment @@ -315,8 +311,7 @@ spec: - name: nginx image: nginx:1.14.2 ` - err = validateMatchSelector(md, manifest) - require.NoError(t, err) + require.NoError(t, validateMatchSelector(md, manifest)) manifest = ` apiVersion: apps/v1 kind: Deployment @@ -335,8 +330,7 @@ spec: - name: nginx image: nginx:1.14.2 ` - err = validateMatchSelector(md, manifest) - assert.Error(t, err, "expected Deployment with no selector to fail") + assert.Error(t, validateMatchSelector(md, manifest), "expected Deployment with no selector to fail") } func TestValidateTopIndentLevel(t *testing.T) { @@ -349,8 +343,11 @@ func TestValidateTopIndentLevel(t *testing.T) { " apiVersion:foo": true, "\n\n apiVersion:foo\n\n": true, } { - if err := validateTopIndentLevel(doc); (err == nil) == shouldFail { - t.Errorf("Expected %t for %q", shouldFail, doc) + err := validateTopIndentLevel(doc) + if shouldFail { + assert.Errorf(t, err, "Expected %t for %q", shouldFail, doc) + } else { + assert.NoErrorf(t, err, "Expected %t for %q", shouldFail, doc) } } } diff --git a/internal/chart/v3/lint/support/message_test.go b/internal/chart/v3/lint/support/message_test.go index ce5b5e42e..4c3ed3a3f 100644 --- a/internal/chart/v3/lint/support/message_test.go +++ b/internal/chart/v3/lint/support/message_test.go @@ -19,6 +19,9 @@ package support import ( "errors" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var errLint = errors.New("lint failed") @@ -47,33 +50,19 @@ func TestRunLinterRule(t *testing.T) { linter := Linter{} for _, test := range tests { isValid := linter.RunLinterRule(test.Severity, "chart", test.LintError) - if len(linter.Messages) != test.ExpectedMessages { - t.Errorf("RunLinterRule(%d, \"chart\", %v), linter.Messages should now have %d message, we got %d", test.Severity, test.LintError, test.ExpectedMessages, len(linter.Messages)) - } - - if linter.HighestSeverity != test.ExpectedHighestSeverity { - t.Errorf("RunLinterRule(%d, \"chart\", %v), linter.HighestSeverity should be %d, we got %d", test.Severity, test.LintError, test.ExpectedHighestSeverity, linter.HighestSeverity) - } - - if isValid != test.ExpectedReturn { - t.Errorf("RunLinterRule(%d, \"chart\", %v), should have returned %t but returned %t", test.Severity, test.LintError, test.ExpectedReturn, isValid) - } + assert.Lenf(t, linter.Messages, test.ExpectedMessages, "RunLinterRule(%d, \"chart\", %v), linter.Messages should now have %d message, we got %d", test.Severity, test.LintError, test.ExpectedMessages, len(linter.Messages)) + assert.Equalf(t, test.ExpectedHighestSeverity, linter.HighestSeverity, "RunLinterRule(%d, \"chart\", %v), linter.HighestSeverity should be %d, we got %d", test.Severity, test.LintError, test.ExpectedHighestSeverity, linter.HighestSeverity) + assert.Equalf(t, test.ExpectedReturn, isValid, "RunLinterRule(%d, \"chart\", %v), should have returned %t but returned %t", test.Severity, test.LintError, test.ExpectedReturn, isValid) } } func TestMessage(t *testing.T) { m := Message{ErrorSev, "Chart.yaml", errors.New("Foo")} - if m.Error() != "[ERROR] Chart.yaml: Foo" { - t.Errorf("Unexpected output: %s", m.Error()) - } + require.EqualErrorf(t, m, "[ERROR] Chart.yaml: Foo", "Unexpected output: %s", m.Error()) m = Message{WarningSev, "templates/", errors.New("Bar")} - if m.Error() != "[WARNING] templates/: Bar" { - t.Errorf("Unexpected output: %s", m.Error()) - } + require.EqualErrorf(t, m, "[WARNING] templates/: Bar", "Unexpected output: %s", m.Error()) m = Message{InfoSev, "templates/rc.yaml", errors.New("FooBar")} - if m.Error() != "[INFO] templates/rc.yaml: FooBar" { - t.Errorf("Unexpected output: %s", m.Error()) - } + assert.EqualErrorf(t, m, "[INFO] templates/rc.yaml: FooBar", "Unexpected output: %s", m.Error()) } diff --git a/internal/chart/v3/util/chartfile_test.go b/internal/chart/v3/util/chartfile_test.go index c791930c1..0cc8a66af 100644 --- a/internal/chart/v3/util/chartfile_test.go +++ b/internal/chart/v3/util/chartfile_test.go @@ -29,10 +29,7 @@ const testfile = "testdata/chartfiletest.yaml" func TestLoadChartfile(t *testing.T) { f, err := LoadChartfile(testfile) - if err != nil { - t.Errorf("Failed to open %s: %s", testfile, err) - return - } + require.NoErrorf(t, err, "Failed to open %s", testfile) verifyChartfile(t, f, "frobnitz") } @@ -64,13 +61,11 @@ func verifyChartfile(t *testing.T, f *chart.Metadata, name string) { require.Len(t, f.Annotations, 2, "Unexpected annotations") - if want, got := "extravalue", f.Annotations["extrakey"]; want != got { - t.Errorf("Want %q, but got %q", want, got) - } + want, got := "extravalue", f.Annotations["extrakey"] + assert.Equalf(t, want, got, "Want %q, but got %q", want, got) - if want, got := "anothervalue", f.Annotations["anotherkey"]; want != got { - t.Errorf("Want %q, but got %q", want, got) - } + want, got = "anothervalue", f.Annotations["anotherkey"] + assert.Equalf(t, want, got, "Want %q, but got %q", want, got) kk := []string{"frobnitz", "sprocket", "dodad"} for i, k := range f.Keywords { @@ -80,13 +75,9 @@ func verifyChartfile(t *testing.T, f *chart.Metadata, name string) { func TestIsChartDir(t *testing.T) { validChartDir, err := IsChartDir("testdata/frobnitz") - if !validChartDir { - t.Errorf("unexpected error while reading chart-directory: (%v)", err) - return - } + require.NoError(t, err, "while reading chart-directory") + require.True(t, validChartDir, "expected valid chart directory") validChartDir, err = IsChartDir("testdata") - if validChartDir || err == nil { - t.Error("expected error but did not get any") - return - } + require.Error(t, err) + require.False(t, validChartDir, "expected invalid chart directory") } diff --git a/internal/plugin/installer/installer_test.go b/internal/plugin/installer/installer_test.go index 50e8e1ee2..620afc183 100644 --- a/internal/plugin/installer/installer_test.go +++ b/internal/plugin/installer/installer_test.go @@ -15,33 +15,27 @@ limitations under the License. package installer -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestIsRemoteHTTPArchive(t *testing.T) { srv := mockArchiveServer() defer srv.Close() source := srv.URL + "/plugins/fake-plugin-0.0.1.tar.gz" - if isRemoteHTTPArchive("/not/a/URL") { - t.Error("Expected non-URL to return false") - } + assert.False(t, isRemoteHTTPArchive("/not/a/URL"), "Expected non-URL to return false") // URLs with valid archive extensions are considered valid archives // even if the server is unreachable (optimization to avoid unnecessary HTTP requests) - if !isRemoteHTTPArchive("https://127.0.0.1:123/fake/plugin-1.2.3.tgz") { - t.Error("URL with .tgz extension should be considered a valid archive") - } + assert.True(t, isRemoteHTTPArchive("https://127.0.0.1:123/fake/plugin-1.2.3.tgz"), "URL with .tgz extension should be considered a valid archive") // Test with invalid extension and unreachable server - if isRemoteHTTPArchive("https://127.0.0.1:123/fake/plugin-1.2.3.notanarchive") { - t.Error("Bad URL without valid extension should not succeed") - } + assert.False(t, isRemoteHTTPArchive("https://127.0.0.1:123/fake/plugin-1.2.3.notanarchive"), "Bad URL without valid extension should not succeed") - if !isRemoteHTTPArchive(source) { - t.Errorf("Expected %q to be a valid archive URL", source) - } + assert.True(t, isRemoteHTTPArchive(source), "Expected %q to be a valid archive URL", source) - if isRemoteHTTPArchive(source + "-not-an-extension") { - t.Error("Expected media type match to fail") - } + assert.False(t, isRemoteHTTPArchive(source+"-not-an-extension"), "Expected media type match to fail") } diff --git a/internal/plugin/installer/plugin_structure_test.go b/internal/plugin/installer/plugin_structure_test.go index 182eb9bd8..187918a4b 100644 --- a/internal/plugin/installer/plugin_structure_test.go +++ b/internal/plugin/installer/plugin_structure_test.go @@ -19,6 +19,9 @@ import ( "os" "path/filepath" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDetectPluginRoot(t *testing.T) { @@ -73,26 +76,18 @@ func TestDetectPluginRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { dir := t.TempDir() - if err := tt.setup(dir); err != nil { - t.Fatalf("Setup failed: %v", err) - } + require.NoErrorf(t, tt.setup(dir), "Setup failed") root, err := detectPluginRoot(dir) if tt.expectError { - if err == nil { - t.Error("Expected error but got none") - } + assert.Error(t, err) } else { - if err != nil { - t.Errorf("Unexpected error: %v", err) - } + require.NoError(t, err) expectedPath := dir if tt.expectRoot != "." { expectedPath = filepath.Join(dir, tt.expectRoot) } - if root != expectedPath { - t.Errorf("Expected root %s but got %s", expectedPath, root) - } + assert.Equal(t, expectedPath, root, "Expected root %s but got %s", expectedPath, root) } }) } @@ -145,20 +140,14 @@ description: test` for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { dir := t.TempDir() - if err := tt.setup(dir); err != nil { - t.Fatalf("Setup failed: %v", err) - } + require.NoErrorf(t, tt.setup(dir), "Setup failed") pluginRoot := filepath.Join(dir, tt.pluginRoot) err := validatePluginName(pluginRoot, tt.expectedName) if tt.expectError { - if err == nil { - t.Error("Expected error but got none") - } + assert.Error(t, err) } else { - if err != nil { - t.Errorf("Unexpected error: %v", err) - } + assert.NoError(t, err) } }) } diff --git a/internal/plugin/installer/verification_test.go b/internal/plugin/installer/verification_test.go index d3824a0fc..1f8aa7ef4 100644 --- a/internal/plugin/installer/verification_test.go +++ b/internal/plugin/installer/verification_test.go @@ -23,6 +23,9 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "helm.sh/helm/v4/internal/plugin" "helm.sh/helm/v4/internal/test/ensure" ) @@ -37,29 +40,20 @@ func TestInstallWithOptions_VerifyMissingProvenance(t *testing.T) { // Create local installer installer, err := NewLocalInstaller(pluginTgz) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install with verification enabled should fail when .prov is missing result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: "dummy"}) // Should fail with a missing provenance error - if err == nil { - t.Fatal("Expected installation to fail when .prov file is missing and verification is enabled") - } - if !strings.Contains(err.Error(), "no provenance file") { - t.Errorf("Expected 'no provenance file' in error message, got: %v", err) - } - if result != nil { - t.Errorf("Expected nil verification result when .prov file is missing, got: %+v", result) - } + require.Error(t, err, "Expected installation to fail when .prov file is missing and verification is enabled") + require.ErrorContains(t, err, "no provenance file") + assert.Nil(t, result, "Expected nil verification result when .prov file is missing, got: %+v", result) // Plugin should NOT be installed - if _, err := os.Stat(installer.Path()); !os.IsNotExist(err) { - t.Error("Plugin should not be installed when verification fails due to missing .prov") - } + _, err = os.Stat(installer.Path()) + assert.True(t, os.IsNotExist(err), "Plugin should not be installed when verification fails due to missing .prov") } func TestInstallWithOptions_NoVerifyMissingProvenance(t *testing.T) { @@ -72,25 +66,18 @@ func TestInstallWithOptions_NoVerifyMissingProvenance(t *testing.T) { // Create local installer installer, err := NewLocalInstaller(pluginTgz) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install with verification explicitly disabled should succeed without .prov result, err := InstallWithOptions(installer, Options{Verify: false}) - if err != nil { - t.Fatalf("Expected installation to succeed with --verify=false, got error: %v", err) - } - if result != nil { - t.Errorf("Expected nil verification result when verification is disabled, got: %+v", result) - } + require.NoError(t, err, "Expected installation to succeed with --verify=false") + assert.Nil(t, result, "Expected nil verification result when verification is disabled, got: %+v", result) // Plugin should be installed - if _, err := os.Stat(installer.Path()); os.IsNotExist(err) { - t.Errorf("Plugin should be installed at %s", installer.Path()) - } + _, err = os.Stat(installer.Path()) + assert.Falsef(t, os.IsNotExist(err), "Plugin should be installed at %s", installer.Path()) } func TestInstallWithOptions_VerifyWithValidProvenance(t *testing.T) { @@ -110,9 +97,7 @@ func TestInstallWithOptions_VerifyWithValidProvenance(t *testing.T) { // Create local installer installer, err := NewLocalInstaller(pluginTgz) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install with verification enabled @@ -120,20 +105,13 @@ func TestInstallWithOptions_VerifyWithValidProvenance(t *testing.T) { result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) // Should fail due to invalid signature (empty keyring) but we test that it gets past the hash check - if err == nil { - t.Fatal("Expected installation to fail with empty keyring") - } - if !strings.Contains(err.Error(), "plugin verification failed") { - t.Errorf("Expected plugin verification failed error, got: %v", err) - } - if result != nil { - t.Errorf("Expected nil verification result when verification fails, got: %+v", result) - } + require.Error(t, err, "Expected installation to fail with empty keyring") + require.ErrorContains(t, err, "plugin verification failed") + assert.Nil(t, result, "Expected nil verification result when verification fails, got: %+v", result) // Plugin should not be installed due to verification failure - if _, err := os.Stat(installer.Path()); !os.IsNotExist(err) { - t.Error("Plugin should not be installed when verification fails") - } + _, err = os.Stat(installer.Path()) + assert.True(t, os.IsNotExist(err), "Plugin should not be installed when verification fails") } func TestInstallWithOptions_VerifyWithInvalidProvenance(t *testing.T) { @@ -154,32 +132,23 @@ func TestInstallWithOptions_VerifyWithInvalidProvenance(t *testing.T) { // Create local installer installer, err := NewLocalInstaller(pluginTgz) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install with verification enabled (should fail) result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) // Should fail with verification error - if err == nil { - t.Fatal("Expected installation with invalid .prov file to fail") - } - if result != nil { - t.Errorf("Expected nil verification result when verification fails, got: %+v", result) - } + require.Error(t, err, "Expected installation with invalid .prov file to fail") + assert.Nil(t, result, "Expected nil verification result when verification fails, got: %+v", result) // Should contain verification failure message expectedError := "plugin verification failed" - if !strings.Contains(err.Error(), expectedError) { - t.Errorf("Expected error message '%s', got: %s", expectedError, err.Error()) - } + require.ErrorContains(t, err, expectedError) // Plugin should not be installed - if _, err := os.Stat(installer.Path()); !os.IsNotExist(err) { - t.Error("Plugin should not be installed when verification fails") - } + _, err = os.Stat(installer.Path()) + assert.True(t, os.IsNotExist(err), "Plugin should not be installed when verification fails") } func TestInstallWithOptions_NoVerifyRequested(t *testing.T) { @@ -192,26 +161,19 @@ func TestInstallWithOptions_NoVerifyRequested(t *testing.T) { // Create local installer installer, err := NewLocalInstaller(pluginTgz) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install without verification (should succeed without any verification) result, err := InstallWithOptions(installer, Options{Verify: false}) // Should succeed with no verification - if err != nil { - t.Fatalf("Expected installation without verification to succeed, got error: %v", err) - } - if result != nil { - t.Errorf("Expected nil verification result when verification is disabled, got: %+v", result) - } + require.NoError(t, err, "Expected installation without verification to succeed") + assert.Nil(t, result, "Expected nil verification result when verification is disabled, got: %+v", result) // Plugin should be installed - if _, err := os.Stat(installer.Path()); os.IsNotExist(err) { - t.Errorf("Plugin should be installed at %s", installer.Path()) - } + _, err = os.Stat(installer.Path()) + assert.Falsef(t, os.IsNotExist(err), "Plugin should be installed at %s", installer.Path()) } func TestInstallWithOptions_VerifyDirectoryNotSupported(t *testing.T) { @@ -222,24 +184,16 @@ func TestInstallWithOptions_VerifyDirectoryNotSupported(t *testing.T) { // Create local installer for directory installer, err := NewLocalInstaller(pluginDir) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install with verification should fail (directories don't support verification) result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: "dummy"}) // Should fail with verification not supported error - if err == nil { - t.Fatal("Expected installation to fail with verification not supported error") - } - if !strings.Contains(err.Error(), "--verify is only supported for plugin tarballs") { - t.Errorf("Expected verification not supported error, got: %v", err) - } - if result != nil { - t.Errorf("Expected nil verification result when verification fails, got: %+v", result) - } + require.Error(t, err, "Expected installation to fail with verification not supported error") + require.ErrorContains(t, err, "--verify is only supported for plugin tarballs") + assert.Nil(t, result, "Expected nil verification result when verification fails, got: %+v", result) } func TestInstallWithOptions_VerifyMismatchedProvenance(t *testing.T) { @@ -261,24 +215,16 @@ func TestInstallWithOptions_VerifyMismatchedProvenance(t *testing.T) { // Create local installer installer, err := NewLocalInstaller(pluginTgz) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install with verification should fail due to hash mismatch result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) // Should fail with verification error - if err == nil { - t.Fatal("Expected installation to fail with hash mismatch") - } - if !strings.Contains(err.Error(), "plugin verification failed") { - t.Errorf("Expected plugin verification failed error, got: %v", err) - } - if result != nil { - t.Errorf("Expected nil verification result when verification fails, got: %+v", result) - } + require.Error(t, err, "Expected installation to fail with hash mismatch") + require.ErrorContains(t, err, "plugin verification failed") + assert.Nil(t, result, "Expected nil verification result when verification fails, got: %+v", result) } func TestInstallWithOptions_VerifyProvenanceAccessError(t *testing.T) { @@ -291,9 +237,7 @@ func TestInstallWithOptions_VerifyProvenanceAccessError(t *testing.T) { // Create a .prov file but make it inaccessible (simulate permission error) provFile := pluginTgz + ".prov" - if err := os.WriteFile(provFile, []byte("test"), 0o000); err != nil { - t.Fatalf("Failed to create inaccessible provenance file: %v", err) - } + require.NoErrorf(t, os.WriteFile(provFile, []byte("test"), 0o000), "Failed to create inaccessible provenance file") defer os.Remove(provFile) // Create keyring @@ -302,27 +246,21 @@ func TestInstallWithOptions_VerifyProvenanceAccessError(t *testing.T) { // Create local installer installer, err := NewLocalInstaller(pluginTgz) - if err != nil { - t.Fatalf("Failed to create installer: %v", err) - } + require.NoError(t, err, "Failed to create installer") defer os.RemoveAll(installer.Path()) // Install with verification should fail due to access error result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) // Should fail with access error (either at stat level or during verification) - if err == nil { - t.Fatal("Expected installation to fail with provenance file access error") - } + require.Error(t, err, "Expected installation to fail with provenance file access error") // The error could be either "failed to access provenance file" or "plugin verification failed" // depending on when the permission error occurs if !strings.Contains(err.Error(), "failed to access provenance file") && !strings.Contains(err.Error(), "plugin verification failed") { t.Errorf("Expected provenance file access or verification error, got: %v", err) } - if result != nil { - t.Errorf("Expected nil verification result when verification fails, got: %+v", result) - } + assert.Nil(t, result, "Expected nil verification result when verification fails, got: %+v", result) } // Helper functions for test setup @@ -333,9 +271,7 @@ func createTestPluginDir(t *testing.T) string { // Create temporary directory with plugin structure tmpDir := t.TempDir() pluginDir := filepath.Join(tmpDir, "test-plugin") - if err := os.MkdirAll(pluginDir, 0o755); err != nil { - t.Fatalf("Failed to create plugin directory: %v", err) - } + require.NoErrorf(t, os.MkdirAll(pluginDir, 0o755), "Failed to create plugin directory") // Create plugin.yaml using the standardized v1 format pluginYaml := `apiVersion: v1 @@ -346,9 +282,7 @@ version: 1.0.0 runtimeConfig: platformCommand: - command: echo` - if err := os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(pluginYaml), 0o644); err != nil { - t.Fatalf("Failed to create plugin.yaml: %v", err) - } + require.NoErrorf(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(pluginYaml), 0o644), "Failed to create plugin.yaml") return pluginDir } @@ -360,15 +294,10 @@ func createTarballFromPluginDir(t *testing.T, pluginDir string) string { tmpDir := filepath.Dir(pluginDir) tgzPath := filepath.Join(tmpDir, "test-plugin-1.0.0.tgz") tarFile, err := os.Create(tgzPath) - if err != nil { - t.Fatalf("Failed to create tarball file: %v", err) - } + require.NoError(t, err, "Failed to create tarball file") defer tarFile.Close() - if err := plugin.CreatePluginTarball(pluginDir, "test-plugin", tarFile); err != nil { - t.Fatalf("Failed to create tarball: %v", err) - } - + require.NoErrorf(t, plugin.CreatePluginTarball(pluginDir, "test-plugin", tarFile), "Failed to create tarball") return tgzPath } @@ -379,9 +308,7 @@ func createProvFile(t *testing.T, provFile, pluginTgz, hash string) { if hash == "" { // Calculate actual hash of the tarball for realistic testing data, err := os.ReadFile(pluginTgz) - if err != nil { - t.Fatalf("Failed to read tarball for hashing: %v", err) - } + require.NoError(t, err, "Failed to read tarball for hashing") hashSum := sha256.Sum256(data) hashStr = fmt.Sprintf("sha256:%x", hashSum) } else { @@ -404,9 +331,7 @@ Version: GnuPG v1 iQEcBAEBCAAGBQJktest... -----END PGP SIGNATURE----- `, hashStr) - if err := os.WriteFile(provFile, []byte(provContent), 0o644); err != nil { - t.Fatalf("Failed to create provenance file: %v", err) - } + require.NoErrorf(t, os.WriteFile(provFile, []byte(provContent), 0o644), "Failed to create provenance file") } func createProvFileInvalidFormat(t *testing.T, provFile string) { @@ -414,9 +339,7 @@ func createProvFileInvalidFormat(t *testing.T, provFile string) { // Create an invalid provenance file (not PGP signed format) invalidProv := "This is not a valid PGP signed message" - if err := os.WriteFile(provFile, []byte(invalidProv), 0o644); err != nil { - t.Fatalf("Failed to create invalid provenance file: %v", err) - } + require.NoErrorf(t, os.WriteFile(provFile, []byte(invalidProv), 0o644), "Failed to create invalid provenance file") } func createTestKeyring(t *testing.T) string { @@ -427,9 +350,7 @@ func createTestKeyring(t *testing.T) string { keyringPath := filepath.Join(tmpDir, "pubring.gpg") // Create empty keyring for testing - if err := os.WriteFile(keyringPath, []byte{}, 0o644); err != nil { - t.Fatalf("Failed to create test keyring: %v", err) - } + require.NoErrorf(t, os.WriteFile(keyringPath, []byte{}, 0o644), "Failed to create test keyring") return keyringPath } diff --git a/internal/plugin/runtime_extismv1_test.go b/internal/plugin/runtime_extismv1_test.go index 290d418ea..72a24d111 100644 --- a/internal/plugin/runtime_extismv1_test.go +++ b/internal/plugin/runtime_extismv1_test.go @@ -59,8 +59,7 @@ func buildLoadExtismPlugin(t *testing.T, dir string) pluginRaw { func TestRuntimeConfigExtismV1Validate(t *testing.T) { rc := RuntimeConfigExtismV1{} - err := rc.Validate() - assert.NoError(t, err, "expected no error for empty RuntimeConfigExtismV1") + assert.NoError(t, rc.Validate(), "expected no error for empty RuntimeConfigExtismV1") } func TestRuntimeExtismV1InvokePlugin(t *testing.T) { diff --git a/internal/plugin/subprocess_commands_test.go b/internal/plugin/subprocess_commands_test.go index 6aa0a7435..b2ac19c02 100644 --- a/internal/plugin/subprocess_commands_test.go +++ b/internal/plugin/subprocess_commands_test.go @@ -39,9 +39,7 @@ func TestPrepareCommand(t *testing.T) { cmd, args, err := PrepareCommands(platformCommand, true, []string{}, env) require.NoError(t, err) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) - if !reflect.DeepEqual(args, cmdArgs) { - t.Fatalf("Expected %v, got %v", cmdArgs, args) - } + require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args) } func TestPrepareCommandExtraArgs(t *testing.T) { @@ -113,9 +111,7 @@ func TestPrepareCommands(t *testing.T) { cmd, args, err := PrepareCommands(cmds, true, []string{}, env) require.NoError(t, err) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) - if !reflect.DeepEqual(args, cmdArgs) { - t.Fatalf("Expected %v, got %v", cmdArgs, args) - } + require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args) } func TestPrepareCommandsExtraArgs(t *testing.T) { @@ -136,9 +132,7 @@ func TestPrepareCommandsExtraArgs(t *testing.T) { cmd, args, err := PrepareCommands(cmds, true, extraArgs, env) require.NoError(t, err) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) - if !reflect.DeepEqual(args, expectedArgs) { - t.Fatalf("Expected %v, got %v", expectedArgs, args) - } + require.Truef(t, reflect.DeepEqual(args, expectedArgs), "Expected %v, got %v", expectedArgs, args) } func TestPrepareCommandsNoArch(t *testing.T) { @@ -155,9 +149,7 @@ func TestPrepareCommandsNoArch(t *testing.T) { cmd, args, err := PrepareCommands(cmds, true, []string{}, env) require.NoError(t, err) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) - if !reflect.DeepEqual(args, cmdArgs) { - t.Fatalf("Expected %v, got %v", cmdArgs, args) - } + require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args) } func TestPrepareCommandsNoOsNoArch(t *testing.T) { @@ -174,9 +166,7 @@ func TestPrepareCommandsNoOsNoArch(t *testing.T) { cmd, args, err := PrepareCommands(cmds, true, []string{}, env) require.NoError(t, err) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) - if !reflect.DeepEqual(args, cmdArgs) { - t.Fatalf("Expected %v, got %v", cmdArgs, args) - } + require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args) } func TestPrepareCommandsNoMatch(t *testing.T) { @@ -216,9 +206,7 @@ func TestPrepareCommandsExpand(t *testing.T) { cmd, args, err := PrepareCommands(cmds, true, []string{}, env) require.NoError(t, err) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) - if !reflect.DeepEqual(args, expectedArgs) { - t.Fatalf("Expected %v, got %v", expectedArgs, args) - } + require.Truef(t, reflect.DeepEqual(args, expectedArgs), "Expected %v, got %v", expectedArgs, args) } func TestPrepareCommandsNoExpand(t *testing.T) { @@ -235,7 +223,5 @@ func TestPrepareCommandsNoExpand(t *testing.T) { cmd, args, err := PrepareCommands(cmds, false, []string{}, env) require.NoError(t, err) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) - if !reflect.DeepEqual(args, cmdArgs) { - t.Fatalf("Expected %v, got %v", cmdArgs, args) - } + require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args) } diff --git a/internal/plugin/verify_test.go b/internal/plugin/verify_test.go index 5721e0414..4f5b26a97 100644 --- a/internal/plugin/verify_test.go +++ b/internal/plugin/verify_test.go @@ -44,11 +44,9 @@ func TestVerifyPlugin(t *testing.T) { // Create plugin directory pluginDir := filepath.Join(tempDir, "verify-test-plugin") - err := os.MkdirAll(pluginDir, 0o755) - require.NoError(t, err) + require.NoError(t, os.MkdirAll(pluginDir, 0o755)) - err = os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644) - require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644)) // Create tarball tarballPath := filepath.Join(tempDir, "verify-test-plugin.tar.gz") @@ -64,10 +62,9 @@ func TestVerifyPlugin(t *testing.T) { // Sign the plugin with source directory signer, err := provenance.NewFromKeyring(testKeyFile, "helm-test") require.NoError(t, err) - err = signer.DecryptKey(func(_ string) ([]byte, error) { + require.NoError(t, signer.DecryptKey(func(_ string) ([]byte, error) { return []byte(""), nil - }) - require.NoError(t, err) + })) // Read the tarball data tarballData, err := os.ReadFile(tarballPath) @@ -78,8 +75,7 @@ func TestVerifyPlugin(t *testing.T) { // Write the signature to .prov file provFile := tarballPath + ".prov" - err = os.WriteFile(provFile, []byte(sig), 0o644) - require.NoError(t, err) + require.NoError(t, os.WriteFile(provFile, []byte(sig), 0o644)) // Read the files for verification archiveData, err := os.ReadFile(tarballPath) @@ -105,11 +101,9 @@ func TestVerifyPluginBadSignature(t *testing.T) { // Create a plugin tarball pluginDir := filepath.Join(tempDir, "bad-plugin") - err := os.MkdirAll(pluginDir, 0o755) - require.NoError(t, err) + require.NoError(t, os.MkdirAll(pluginDir, 0o755)) - err = os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644) - require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644)) tarballPath := filepath.Join(tempDir, "bad-plugin.tar.gz") tarFile, err := os.Create(tarballPath) @@ -133,8 +127,7 @@ InvalidSignatureData -----END PGP SIGNATURE-----` provFile := tarballPath + ".prov" - err = os.WriteFile(provFile, []byte(badSig), 0o644) - require.NoError(t, err) + require.NoError(t, os.WriteFile(provFile, []byte(badSig), 0o644)) // Read the files archiveData, err := os.ReadFile(tarballPath) @@ -153,8 +146,7 @@ func TestVerifyPluginMissingProvenance(t *testing.T) { tarballPath := filepath.Join(tempDir, "no-prov.tar.gz") // Create a minimal tarball - err := os.WriteFile(tarballPath, []byte("dummy"), 0o644) - require.NoError(t, err) + require.NoError(t, os.WriteFile(tarballPath, []byte("dummy"), 0o644)) // Read the tarball data archiveData, err := os.ReadFile(tarballPath)