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 <matthieu.morel35@gmail.com>
pull/32409/head
Matthieu MOREL 2 months ago
parent 06978bd8c5
commit f1d5979e7d

@ -37,13 +37,11 @@ const templateTestBasedir = "./testdata/albatross"
func TestValidateAllowedExtension(t *testing.T) { func TestValidateAllowedExtension(t *testing.T) {
var failTest = []string{"/foo", "/test.toml"} var failTest = []string{"/foo", "/test.toml"}
for _, test := range failTest { for _, test := range failTest {
err := validateAllowedExtension(test) require.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)
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)
} }
var successTest = []string{"/foo.yaml", "foo.yaml", "foo.tpl", "/foo/bar/baz.yaml", "NOTES.txt"} var successTest = []string{"/foo.yaml", "foo.yaml", "foo.tpl", "/foo/bar/baz.yaml", "NOTES.txt"}
for _, test := range successTest { for _, test := range successTest {
err := validateAllowedExtension(test) assert.NoError(t, validateAllowedExtension(test), "validateAllowedExtension('%s') to return no error", test)
assert.NoError(t, err, "validateAllowedExtension('%s') to return no error", test)
} }
} }
@ -58,8 +56,7 @@ func TestTemplateParsing(t *testing.T) {
res := linter.Messages res := linter.Messages
require.Len(t, res, 1, "Expected one error, got %d, %v", len(res), res) require.Len(t, res, 1, "Expected one error, got %d, %v", len(res), res)
assert.ErrorContains(t, res[0].Err, "deliberateSyntaxError")
assert.ErrorContains(t, res[0].Err, "deliberateSyntaxError", "Unexpected error: %s", res[0])
} }
var wrongTemplatePath = filepath.Join(templateTestBasedir, "templates", "fail.yaml") 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) 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) { func TestValidateMetadataName(t *testing.T) {
@ -292,8 +289,7 @@ spec:
- name: nginx - name: nginx
image: nginx:1.14.2 image: nginx:1.14.2
` `
err := validateMatchSelector(md, manifest) require.NoError(t, validateMatchSelector(md, manifest))
require.NoError(t, err)
manifest = ` manifest = `
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
@ -315,8 +311,7 @@ spec:
- name: nginx - name: nginx
image: nginx:1.14.2 image: nginx:1.14.2
` `
err = validateMatchSelector(md, manifest) require.NoError(t, validateMatchSelector(md, manifest))
require.NoError(t, err)
manifest = ` manifest = `
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
@ -335,8 +330,7 @@ spec:
- name: nginx - name: nginx
image: nginx:1.14.2 image: nginx:1.14.2
` `
err = validateMatchSelector(md, manifest) assert.Error(t, validateMatchSelector(md, manifest), "expected Deployment with no selector to fail")
assert.Error(t, err, "expected Deployment with no selector to fail")
} }
func TestValidateTopIndentLevel(t *testing.T) { func TestValidateTopIndentLevel(t *testing.T) {
@ -349,8 +343,11 @@ func TestValidateTopIndentLevel(t *testing.T) {
" apiVersion:foo": true, " apiVersion:foo": true,
"\n\n apiVersion:foo\n\n": true, "\n\n apiVersion:foo\n\n": true,
} { } {
if err := validateTopIndentLevel(doc); (err == nil) == shouldFail { err := validateTopIndentLevel(doc)
t.Errorf("Expected %t for %q", shouldFail, doc) if shouldFail {
assert.Errorf(t, err, "Expected %t for %q", shouldFail, doc)
} else {
assert.NoErrorf(t, err, "Expected %t for %q", shouldFail, doc)
} }
} }
} }

@ -19,6 +19,9 @@ package support
import ( import (
"errors" "errors"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
var errLint = errors.New("lint failed") var errLint = errors.New("lint failed")
@ -47,33 +50,19 @@ func TestRunLinterRule(t *testing.T) {
linter := Linter{} linter := Linter{}
for _, test := range tests { for _, test := range tests {
isValid := linter.RunLinterRule(test.Severity, "chart", test.LintError) isValid := linter.RunLinterRule(test.Severity, "chart", test.LintError)
if len(linter.Messages) != test.ExpectedMessages { 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))
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)) 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)
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)
}
} }
} }
func TestMessage(t *testing.T) { func TestMessage(t *testing.T) {
m := Message{ErrorSev, "Chart.yaml", errors.New("Foo")} m := Message{ErrorSev, "Chart.yaml", errors.New("Foo")}
if m.Error() != "[ERROR] Chart.yaml: Foo" { require.EqualErrorf(t, m, "[ERROR] Chart.yaml: Foo", "Unexpected output: %s", m.Error())
t.Errorf("Unexpected output: %s", m.Error())
}
m = Message{WarningSev, "templates/", errors.New("Bar")} m = Message{WarningSev, "templates/", errors.New("Bar")}
if m.Error() != "[WARNING] templates/: Bar" { require.EqualErrorf(t, m, "[WARNING] templates/: Bar", "Unexpected output: %s", m.Error())
t.Errorf("Unexpected output: %s", m.Error())
}
m = Message{InfoSev, "templates/rc.yaml", errors.New("FooBar")} m = Message{InfoSev, "templates/rc.yaml", errors.New("FooBar")}
if m.Error() != "[INFO] templates/rc.yaml: FooBar" { assert.EqualErrorf(t, m, "[INFO] templates/rc.yaml: FooBar", "Unexpected output: %s", m.Error())
t.Errorf("Unexpected output: %s", m.Error())
}
} }

@ -29,10 +29,7 @@ const testfile = "testdata/chartfiletest.yaml"
func TestLoadChartfile(t *testing.T) { func TestLoadChartfile(t *testing.T) {
f, err := LoadChartfile(testfile) f, err := LoadChartfile(testfile)
if err != nil { require.NoErrorf(t, err, "Failed to open %s", testfile)
t.Errorf("Failed to open %s: %s", testfile, err)
return
}
verifyChartfile(t, f, "frobnitz") 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") require.Len(t, f.Annotations, 2, "Unexpected annotations")
if want, got := "extravalue", f.Annotations["extrakey"]; want != got { want, got := "extravalue", f.Annotations["extrakey"]
t.Errorf("Want %q, but got %q", want, got) assert.Equalf(t, want, got, "Want %q, but got %q", want, got)
}
if want, got := "anothervalue", f.Annotations["anotherkey"]; want != got { want, got = "anothervalue", f.Annotations["anotherkey"]
t.Errorf("Want %q, but got %q", want, got) assert.Equalf(t, want, got, "Want %q, but got %q", want, got)
}
kk := []string{"frobnitz", "sprocket", "dodad"} kk := []string{"frobnitz", "sprocket", "dodad"}
for i, k := range f.Keywords { 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) { func TestIsChartDir(t *testing.T) {
validChartDir, err := IsChartDir("testdata/frobnitz") validChartDir, err := IsChartDir("testdata/frobnitz")
if !validChartDir { require.NoError(t, err, "while reading chart-directory")
t.Errorf("unexpected error while reading chart-directory: (%v)", err) require.True(t, validChartDir, "expected valid chart directory")
return
}
validChartDir, err = IsChartDir("testdata") validChartDir, err = IsChartDir("testdata")
if validChartDir || err == nil { require.Error(t, err)
t.Error("expected error but did not get any") require.False(t, validChartDir, "expected invalid chart directory")
return
}
} }

@ -15,33 +15,27 @@ limitations under the License.
package installer package installer
import "testing" import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsRemoteHTTPArchive(t *testing.T) { func TestIsRemoteHTTPArchive(t *testing.T) {
srv := mockArchiveServer() srv := mockArchiveServer()
defer srv.Close() defer srv.Close()
source := srv.URL + "/plugins/fake-plugin-0.0.1.tar.gz" source := srv.URL + "/plugins/fake-plugin-0.0.1.tar.gz"
if isRemoteHTTPArchive("/not/a/URL") { assert.False(t, isRemoteHTTPArchive("/not/a/URL"), "Expected non-URL to return false")
t.Error("Expected non-URL to return false")
}
// URLs with valid archive extensions are considered valid archives // URLs with valid archive extensions are considered valid archives
// even if the server is unreachable (optimization to avoid unnecessary HTTP requests) // 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") { 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")
t.Error("URL with .tgz extension should be considered a valid archive")
}
// Test with invalid extension and unreachable server // Test with invalid extension and unreachable server
if isRemoteHTTPArchive("https://127.0.0.1:123/fake/plugin-1.2.3.notanarchive") { assert.False(t, isRemoteHTTPArchive("https://127.0.0.1:123/fake/plugin-1.2.3.notanarchive"), "Bad URL without valid extension should not succeed")
t.Error("Bad URL without valid extension should not succeed")
}
if !isRemoteHTTPArchive(source) { assert.True(t, isRemoteHTTPArchive(source), "Expected %q to be a valid archive URL", source)
t.Errorf("Expected %q to be a valid archive URL", source)
}
if isRemoteHTTPArchive(source + "-not-an-extension") { assert.False(t, isRemoteHTTPArchive(source+"-not-an-extension"), "Expected media type match to fail")
t.Error("Expected media type match to fail")
}
} }

@ -19,6 +19,9 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestDetectPluginRoot(t *testing.T) { func TestDetectPluginRoot(t *testing.T) {
@ -73,26 +76,18 @@ func TestDetectPluginRoot(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) {
dir := t.TempDir() dir := t.TempDir()
if err := tt.setup(dir); err != nil { require.NoErrorf(t, tt.setup(dir), "Setup failed")
t.Fatalf("Setup failed: %v", err)
}
root, err := detectPluginRoot(dir) root, err := detectPluginRoot(dir)
if tt.expectError { if tt.expectError {
if err == nil { assert.Error(t, err)
t.Error("Expected error but got none")
}
} else { } else {
if err != nil { require.NoError(t, err)
t.Errorf("Unexpected error: %v", err)
}
expectedPath := dir expectedPath := dir
if tt.expectRoot != "." { if tt.expectRoot != "." {
expectedPath = filepath.Join(dir, tt.expectRoot) expectedPath = filepath.Join(dir, tt.expectRoot)
} }
if root != expectedPath { assert.Equal(t, expectedPath, root, "Expected root %s but got %s", expectedPath, root)
t.Errorf("Expected root %s but got %s", expectedPath, root)
}
} }
}) })
} }
@ -145,20 +140,14 @@ description: test`
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
if err := tt.setup(dir); err != nil { require.NoErrorf(t, tt.setup(dir), "Setup failed")
t.Fatalf("Setup failed: %v", err)
}
pluginRoot := filepath.Join(dir, tt.pluginRoot) pluginRoot := filepath.Join(dir, tt.pluginRoot)
err := validatePluginName(pluginRoot, tt.expectedName) err := validatePluginName(pluginRoot, tt.expectedName)
if tt.expectError { if tt.expectError {
if err == nil { assert.Error(t, err)
t.Error("Expected error but got none")
}
} else { } else {
if err != nil { assert.NoError(t, err)
t.Errorf("Unexpected error: %v", err)
}
} }
}) })
} }

@ -23,6 +23,9 @@ import (
"strings" "strings"
"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"
) )
@ -37,29 +40,20 @@ func TestInstallWithOptions_VerifyMissingProvenance(t *testing.T) {
// Create local installer // Create local installer
installer, err := NewLocalInstaller(pluginTgz) installer, err := NewLocalInstaller(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install with verification enabled should fail when .prov is missing // Install with verification enabled should fail when .prov is missing
result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: "dummy"}) result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: "dummy"})
// Should fail with a missing provenance error // Should fail with a missing provenance error
if err == nil { require.Error(t, err, "Expected installation to fail when .prov file is missing and verification is enabled")
t.Fatal("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)
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)
}
// Plugin should NOT be installed // Plugin should NOT be installed
if _, err := os.Stat(installer.Path()); !os.IsNotExist(err) { _, err = os.Stat(installer.Path())
t.Error("Plugin should not be installed when verification fails due to missing .prov") assert.True(t, os.IsNotExist(err), "Plugin should not be installed when verification fails due to missing .prov")
}
} }
func TestInstallWithOptions_NoVerifyMissingProvenance(t *testing.T) { func TestInstallWithOptions_NoVerifyMissingProvenance(t *testing.T) {
@ -72,25 +66,18 @@ func TestInstallWithOptions_NoVerifyMissingProvenance(t *testing.T) {
// Create local installer // Create local installer
installer, err := NewLocalInstaller(pluginTgz) installer, err := NewLocalInstaller(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install with verification explicitly disabled should succeed without .prov // Install with verification explicitly disabled should succeed without .prov
result, err := InstallWithOptions(installer, Options{Verify: false}) result, err := InstallWithOptions(installer, Options{Verify: false})
if err != nil { require.NoError(t, err, "Expected installation to succeed with --verify=false")
t.Fatalf("Expected installation to succeed with --verify=false, got error: %v", err) assert.Nil(t, result, "Expected nil verification result when verification is disabled, got: %+v", result)
}
if result != nil {
t.Errorf("Expected nil verification result when verification is disabled, got: %+v", result)
}
// Plugin should be installed // Plugin should be installed
if _, err := os.Stat(installer.Path()); os.IsNotExist(err) { _, err = os.Stat(installer.Path())
t.Errorf("Plugin should be installed at %s", installer.Path()) assert.Falsef(t, os.IsNotExist(err), "Plugin should be installed at %s", installer.Path())
}
} }
func TestInstallWithOptions_VerifyWithValidProvenance(t *testing.T) { func TestInstallWithOptions_VerifyWithValidProvenance(t *testing.T) {
@ -110,9 +97,7 @@ func TestInstallWithOptions_VerifyWithValidProvenance(t *testing.T) {
// Create local installer // Create local installer
installer, err := NewLocalInstaller(pluginTgz) installer, err := NewLocalInstaller(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install with verification enabled // Install with verification enabled
@ -120,20 +105,13 @@ func TestInstallWithOptions_VerifyWithValidProvenance(t *testing.T) {
result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) 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 // Should fail due to invalid signature (empty keyring) but we test that it gets past the hash check
if err == nil { require.Error(t, err, "Expected installation to fail with empty keyring")
t.Fatal("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)
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)
}
// Plugin should not be installed due to verification failure // Plugin should not be installed due to verification failure
if _, err := os.Stat(installer.Path()); !os.IsNotExist(err) { _, err = os.Stat(installer.Path())
t.Error("Plugin should not be installed when verification fails") assert.True(t, os.IsNotExist(err), "Plugin should not be installed when verification fails")
}
} }
func TestInstallWithOptions_VerifyWithInvalidProvenance(t *testing.T) { func TestInstallWithOptions_VerifyWithInvalidProvenance(t *testing.T) {
@ -154,32 +132,23 @@ func TestInstallWithOptions_VerifyWithInvalidProvenance(t *testing.T) {
// Create local installer // Create local installer
installer, err := NewLocalInstaller(pluginTgz) installer, err := NewLocalInstaller(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install with verification enabled (should fail) // Install with verification enabled (should fail)
result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring})
// Should fail with verification error // Should fail with verification error
if err == nil { require.Error(t, err, "Expected installation with invalid .prov file to fail")
t.Fatal("Expected installation with invalid .prov file to fail") assert.Nil(t, result, "Expected nil verification result when verification fails, got: %+v", result)
}
if result != nil {
t.Errorf("Expected nil verification result when verification fails, got: %+v", result)
}
// Should contain verification failure message // Should contain verification failure message
expectedError := "plugin verification failed" expectedError := "plugin verification failed"
if !strings.Contains(err.Error(), expectedError) { require.ErrorContains(t, err, expectedError)
t.Errorf("Expected error message '%s', got: %s", expectedError, err.Error())
}
// Plugin should not be installed // Plugin should not be installed
if _, err := os.Stat(installer.Path()); !os.IsNotExist(err) { _, err = os.Stat(installer.Path())
t.Error("Plugin should not be installed when verification fails") assert.True(t, os.IsNotExist(err), "Plugin should not be installed when verification fails")
}
} }
func TestInstallWithOptions_NoVerifyRequested(t *testing.T) { func TestInstallWithOptions_NoVerifyRequested(t *testing.T) {
@ -192,26 +161,19 @@ func TestInstallWithOptions_NoVerifyRequested(t *testing.T) {
// Create local installer // Create local installer
installer, err := NewLocalInstaller(pluginTgz) installer, err := NewLocalInstaller(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install without verification (should succeed without any verification) // Install without verification (should succeed without any verification)
result, err := InstallWithOptions(installer, Options{Verify: false}) result, err := InstallWithOptions(installer, Options{Verify: false})
// Should succeed with no verification // Should succeed with no verification
if err != nil { require.NoError(t, err, "Expected installation without verification to succeed")
t.Fatalf("Expected installation without verification to succeed, got error: %v", err) assert.Nil(t, result, "Expected nil verification result when verification is disabled, got: %+v", result)
}
if result != nil {
t.Errorf("Expected nil verification result when verification is disabled, got: %+v", result)
}
// Plugin should be installed // Plugin should be installed
if _, err := os.Stat(installer.Path()); os.IsNotExist(err) { _, err = os.Stat(installer.Path())
t.Errorf("Plugin should be installed at %s", installer.Path()) assert.Falsef(t, os.IsNotExist(err), "Plugin should be installed at %s", installer.Path())
}
} }
func TestInstallWithOptions_VerifyDirectoryNotSupported(t *testing.T) { func TestInstallWithOptions_VerifyDirectoryNotSupported(t *testing.T) {
@ -222,24 +184,16 @@ func TestInstallWithOptions_VerifyDirectoryNotSupported(t *testing.T) {
// Create local installer for directory // Create local installer for directory
installer, err := NewLocalInstaller(pluginDir) installer, err := NewLocalInstaller(pluginDir)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install with verification should fail (directories don't support verification) // Install with verification should fail (directories don't support verification)
result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: "dummy"}) result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: "dummy"})
// Should fail with verification not supported error // Should fail with verification not supported error
if err == nil { require.Error(t, err, "Expected installation to fail with verification not supported error")
t.Fatal("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)
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)
}
} }
func TestInstallWithOptions_VerifyMismatchedProvenance(t *testing.T) { func TestInstallWithOptions_VerifyMismatchedProvenance(t *testing.T) {
@ -261,24 +215,16 @@ func TestInstallWithOptions_VerifyMismatchedProvenance(t *testing.T) {
// Create local installer // Create local installer
installer, err := NewLocalInstaller(pluginTgz) installer, err := NewLocalInstaller(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install with verification should fail due to hash mismatch // Install with verification should fail due to hash mismatch
result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring})
// Should fail with verification error // Should fail with verification error
if err == nil { require.Error(t, err, "Expected installation to fail with hash mismatch")
t.Fatal("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)
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)
}
} }
func TestInstallWithOptions_VerifyProvenanceAccessError(t *testing.T) { 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) // Create a .prov file but make it inaccessible (simulate permission error)
provFile := pluginTgz + ".prov" provFile := pluginTgz + ".prov"
if err := os.WriteFile(provFile, []byte("test"), 0o000); err != nil { require.NoErrorf(t, os.WriteFile(provFile, []byte("test"), 0o000), "Failed to create inaccessible provenance file")
t.Fatalf("Failed to create inaccessible provenance file: %v", err)
}
defer os.Remove(provFile) defer os.Remove(provFile)
// Create keyring // Create keyring
@ -302,27 +246,21 @@ func TestInstallWithOptions_VerifyProvenanceAccessError(t *testing.T) {
// Create local installer // Create local installer
installer, err := NewLocalInstaller(pluginTgz) installer, err := NewLocalInstaller(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to create installer")
t.Fatalf("Failed to create installer: %v", err)
}
defer os.RemoveAll(installer.Path()) defer os.RemoveAll(installer.Path())
// Install with verification should fail due to access error // Install with verification should fail due to access error
result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring}) result, err := InstallWithOptions(installer, Options{Verify: true, Keyring: keyring})
// Should fail with access error (either at stat level or during verification) // Should fail with access error (either at stat level or during verification)
if err == nil { require.Error(t, err, "Expected installation to fail with provenance file access error")
t.Fatal("Expected installation to fail with provenance file access error")
}
// The error could be either "failed to access provenance file" or "plugin verification failed" // The error could be either "failed to access provenance file" or "plugin verification failed"
// depending on when the permission error occurs // depending on when the permission error occurs
if !strings.Contains(err.Error(), "failed to access provenance file") && if !strings.Contains(err.Error(), "failed to access provenance file") &&
!strings.Contains(err.Error(), "plugin verification failed") { !strings.Contains(err.Error(), "plugin verification failed") {
t.Errorf("Expected provenance file access or verification error, got: %v", err) t.Errorf("Expected provenance file access or verification error, got: %v", err)
} }
if result != nil { assert.Nil(t, result, "Expected nil verification result when verification fails, got: %+v", result)
t.Errorf("Expected nil verification result when verification fails, got: %+v", result)
}
} }
// Helper functions for test setup // Helper functions for test setup
@ -333,9 +271,7 @@ func createTestPluginDir(t *testing.T) string {
// Create temporary directory with plugin structure // Create temporary directory with plugin structure
tmpDir := t.TempDir() tmpDir := t.TempDir()
pluginDir := filepath.Join(tmpDir, "test-plugin") pluginDir := filepath.Join(tmpDir, "test-plugin")
if err := os.MkdirAll(pluginDir, 0o755); err != nil { require.NoErrorf(t, os.MkdirAll(pluginDir, 0o755), "Failed to create plugin directory")
t.Fatalf("Failed to create plugin directory: %v", err)
}
// Create plugin.yaml using the standardized v1 format // Create plugin.yaml using the standardized v1 format
pluginYaml := `apiVersion: v1 pluginYaml := `apiVersion: v1
@ -346,9 +282,7 @@ 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.NoErrorf(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(pluginYaml), 0o644), "Failed to create plugin.yaml")
t.Fatalf("Failed to create plugin.yaml: %v", err)
}
return pluginDir return pluginDir
} }
@ -360,15 +294,10 @@ func createTarballFromPluginDir(t *testing.T, pluginDir string) string {
tmpDir := filepath.Dir(pluginDir) tmpDir := filepath.Dir(pluginDir)
tgzPath := filepath.Join(tmpDir, "test-plugin-1.0.0.tgz") tgzPath := filepath.Join(tmpDir, "test-plugin-1.0.0.tgz")
tarFile, err := os.Create(tgzPath) tarFile, err := os.Create(tgzPath)
if err != nil { require.NoError(t, err, "Failed to create tarball file")
t.Fatalf("Failed to create tarball file: %v", err)
}
defer tarFile.Close() defer tarFile.Close()
if err := plugin.CreatePluginTarball(pluginDir, "test-plugin", tarFile); err != nil { require.NoErrorf(t, plugin.CreatePluginTarball(pluginDir, "test-plugin", tarFile), "Failed to create tarball")
t.Fatalf("Failed to create tarball: %v", err)
}
return tgzPath return tgzPath
} }
@ -379,9 +308,7 @@ func createProvFile(t *testing.T, provFile, pluginTgz, hash string) {
if hash == "" { if hash == "" {
// Calculate actual hash of the tarball for realistic testing // Calculate actual hash of the tarball for realistic testing
data, err := os.ReadFile(pluginTgz) data, err := os.ReadFile(pluginTgz)
if err != nil { require.NoError(t, err, "Failed to read tarball for hashing")
t.Fatalf("Failed to read tarball for hashing: %v", err)
}
hashSum := sha256.Sum256(data) hashSum := sha256.Sum256(data)
hashStr = fmt.Sprintf("sha256:%x", hashSum) hashStr = fmt.Sprintf("sha256:%x", hashSum)
} else { } else {
@ -404,9 +331,7 @@ Version: GnuPG v1
iQEcBAEBCAAGBQJktest... iQEcBAEBCAAGBQJktest...
-----END PGP SIGNATURE----- -----END PGP SIGNATURE-----
`, hashStr) `, hashStr)
if err := os.WriteFile(provFile, []byte(provContent), 0o644); err != nil { require.NoErrorf(t, os.WriteFile(provFile, []byte(provContent), 0o644), "Failed to create provenance file")
t.Fatalf("Failed to create provenance file: %v", err)
}
} }
func createProvFileInvalidFormat(t *testing.T, provFile string) { 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) // Create an invalid provenance file (not PGP signed format)
invalidProv := "This is not a valid PGP signed message" invalidProv := "This is not a valid PGP signed message"
if err := os.WriteFile(provFile, []byte(invalidProv), 0o644); err != nil { require.NoErrorf(t, os.WriteFile(provFile, []byte(invalidProv), 0o644), "Failed to create invalid provenance file")
t.Fatalf("Failed to create invalid provenance file: %v", err)
}
} }
func createTestKeyring(t *testing.T) string { func createTestKeyring(t *testing.T) string {
@ -427,9 +350,7 @@ func createTestKeyring(t *testing.T) string {
keyringPath := filepath.Join(tmpDir, "pubring.gpg") keyringPath := filepath.Join(tmpDir, "pubring.gpg")
// Create empty keyring for testing // Create empty keyring for testing
if err := os.WriteFile(keyringPath, []byte{}, 0o644); err != nil { require.NoErrorf(t, os.WriteFile(keyringPath, []byte{}, 0o644), "Failed to create test keyring")
t.Fatalf("Failed to create test keyring: %v", err)
}
return keyringPath return keyringPath
} }

@ -59,8 +59,7 @@ func buildLoadExtismPlugin(t *testing.T, dir string) pluginRaw {
func TestRuntimeConfigExtismV1Validate(t *testing.T) { func TestRuntimeConfigExtismV1Validate(t *testing.T) {
rc := RuntimeConfigExtismV1{} rc := RuntimeConfigExtismV1{}
err := rc.Validate() assert.NoError(t, rc.Validate(), "expected no error for empty RuntimeConfigExtismV1")
assert.NoError(t, err, "expected no error for empty RuntimeConfigExtismV1")
} }
func TestRuntimeExtismV1InvokePlugin(t *testing.T) { func TestRuntimeExtismV1InvokePlugin(t *testing.T) {

@ -39,9 +39,7 @@ func TestPrepareCommand(t *testing.T) {
cmd, args, err := PrepareCommands(platformCommand, true, []string{}, env) cmd, args, err := PrepareCommands(platformCommand, true, []string{}, env)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd)
if !reflect.DeepEqual(args, cmdArgs) { require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args)
t.Fatalf("Expected %v, got %v", cmdArgs, args)
}
} }
func TestPrepareCommandExtraArgs(t *testing.T) { func TestPrepareCommandExtraArgs(t *testing.T) {
@ -113,9 +111,7 @@ func TestPrepareCommands(t *testing.T) {
cmd, args, err := PrepareCommands(cmds, true, []string{}, env) cmd, args, err := PrepareCommands(cmds, true, []string{}, env)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd)
if !reflect.DeepEqual(args, cmdArgs) { require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args)
t.Fatalf("Expected %v, got %v", cmdArgs, args)
}
} }
func TestPrepareCommandsExtraArgs(t *testing.T) { func TestPrepareCommandsExtraArgs(t *testing.T) {
@ -136,9 +132,7 @@ func TestPrepareCommandsExtraArgs(t *testing.T) {
cmd, args, err := PrepareCommands(cmds, true, extraArgs, env) cmd, args, err := PrepareCommands(cmds, true, extraArgs, env)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd)
if !reflect.DeepEqual(args, expectedArgs) { require.Truef(t, reflect.DeepEqual(args, expectedArgs), "Expected %v, got %v", expectedArgs, args)
t.Fatalf("Expected %v, got %v", expectedArgs, args)
}
} }
func TestPrepareCommandsNoArch(t *testing.T) { func TestPrepareCommandsNoArch(t *testing.T) {
@ -155,9 +149,7 @@ func TestPrepareCommandsNoArch(t *testing.T) {
cmd, args, err := PrepareCommands(cmds, true, []string{}, env) cmd, args, err := PrepareCommands(cmds, true, []string{}, env)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd)
if !reflect.DeepEqual(args, cmdArgs) { require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args)
t.Fatalf("Expected %v, got %v", cmdArgs, args)
}
} }
func TestPrepareCommandsNoOsNoArch(t *testing.T) { func TestPrepareCommandsNoOsNoArch(t *testing.T) {
@ -174,9 +166,7 @@ func TestPrepareCommandsNoOsNoArch(t *testing.T) {
cmd, args, err := PrepareCommands(cmds, true, []string{}, env) cmd, args, err := PrepareCommands(cmds, true, []string{}, env)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd)
if !reflect.DeepEqual(args, cmdArgs) { require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args)
t.Fatalf("Expected %v, got %v", cmdArgs, args)
}
} }
func TestPrepareCommandsNoMatch(t *testing.T) { func TestPrepareCommandsNoMatch(t *testing.T) {
@ -216,9 +206,7 @@ func TestPrepareCommandsExpand(t *testing.T) {
cmd, args, err := PrepareCommands(cmds, true, []string{}, env) cmd, args, err := PrepareCommands(cmds, true, []string{}, env)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd)
if !reflect.DeepEqual(args, expectedArgs) { require.Truef(t, reflect.DeepEqual(args, expectedArgs), "Expected %v, got %v", expectedArgs, args)
t.Fatalf("Expected %v, got %v", expectedArgs, args)
}
} }
func TestPrepareCommandsNoExpand(t *testing.T) { func TestPrepareCommandsNoExpand(t *testing.T) {
@ -235,7 +223,5 @@ func TestPrepareCommandsNoExpand(t *testing.T) {
cmd, args, err := PrepareCommands(cmds, false, []string{}, env) cmd, args, err := PrepareCommands(cmds, false, []string{}, env)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd) require.Equal(t, cmdMain, cmd, "Expected %q, got %q", cmdMain, cmd)
if !reflect.DeepEqual(args, cmdArgs) { require.Truef(t, reflect.DeepEqual(args, cmdArgs), "Expected %v, got %v", cmdArgs, args)
t.Fatalf("Expected %v, got %v", cmdArgs, args)
}
} }

@ -44,11 +44,9 @@ func TestVerifyPlugin(t *testing.T) {
// Create plugin directory // Create plugin directory
pluginDir := filepath.Join(tempDir, "verify-test-plugin") pluginDir := filepath.Join(tempDir, "verify-test-plugin")
err := os.MkdirAll(pluginDir, 0o755) require.NoError(t, os.MkdirAll(pluginDir, 0o755))
require.NoError(t, err)
err = os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644) require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644))
require.NoError(t, err)
// Create tarball // Create tarball
tarballPath := filepath.Join(tempDir, "verify-test-plugin.tar.gz") tarballPath := filepath.Join(tempDir, "verify-test-plugin.tar.gz")
@ -64,10 +62,9 @@ func TestVerifyPlugin(t *testing.T) {
// Sign the plugin with source directory // Sign the plugin with source directory
signer, err := provenance.NewFromKeyring(testKeyFile, "helm-test") signer, err := provenance.NewFromKeyring(testKeyFile, "helm-test")
require.NoError(t, err) require.NoError(t, err)
err = signer.DecryptKey(func(_ string) ([]byte, error) { require.NoError(t, signer.DecryptKey(func(_ string) ([]byte, error) {
return []byte(""), nil return []byte(""), nil
}) }))
require.NoError(t, err)
// Read the tarball data // Read the tarball data
tarballData, err := os.ReadFile(tarballPath) tarballData, err := os.ReadFile(tarballPath)
@ -78,8 +75,7 @@ func TestVerifyPlugin(t *testing.T) {
// Write the signature to .prov file // Write the signature to .prov file
provFile := tarballPath + ".prov" provFile := tarballPath + ".prov"
err = os.WriteFile(provFile, []byte(sig), 0o644) require.NoError(t, os.WriteFile(provFile, []byte(sig), 0o644))
require.NoError(t, err)
// Read the files for verification // Read the files for verification
archiveData, err := os.ReadFile(tarballPath) archiveData, err := os.ReadFile(tarballPath)
@ -105,11 +101,9 @@ func TestVerifyPluginBadSignature(t *testing.T) {
// Create a plugin tarball // Create a plugin tarball
pluginDir := filepath.Join(tempDir, "bad-plugin") pluginDir := filepath.Join(tempDir, "bad-plugin")
err := os.MkdirAll(pluginDir, 0o755) require.NoError(t, os.MkdirAll(pluginDir, 0o755))
require.NoError(t, err)
err = os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644) require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.yaml"), []byte(testPluginYAML), 0o644))
require.NoError(t, err)
tarballPath := filepath.Join(tempDir, "bad-plugin.tar.gz") tarballPath := filepath.Join(tempDir, "bad-plugin.tar.gz")
tarFile, err := os.Create(tarballPath) tarFile, err := os.Create(tarballPath)
@ -133,8 +127,7 @@ InvalidSignatureData
-----END PGP SIGNATURE-----` -----END PGP SIGNATURE-----`
provFile := tarballPath + ".prov" provFile := tarballPath + ".prov"
err = os.WriteFile(provFile, []byte(badSig), 0o644) require.NoError(t, os.WriteFile(provFile, []byte(badSig), 0o644))
require.NoError(t, err)
// Read the files // Read the files
archiveData, err := os.ReadFile(tarballPath) archiveData, err := os.ReadFile(tarballPath)
@ -153,8 +146,7 @@ func TestVerifyPluginMissingProvenance(t *testing.T) {
tarballPath := filepath.Join(tempDir, "no-prov.tar.gz") tarballPath := filepath.Join(tempDir, "no-prov.tar.gz")
// Create a minimal tarball // Create a minimal tarball
err := os.WriteFile(tarballPath, []byte("dummy"), 0o644) require.NoError(t, os.WriteFile(tarballPath, []byte("dummy"), 0o644))
require.NoError(t, err)
// Read the tarball data // Read the tarball data
archiveData, err := os.ReadFile(tarballPath) archiveData, err := os.ReadFile(tarballPath)

Loading…
Cancel
Save