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

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

@ -64,12 +64,9 @@ command: "$HELM_PLUGIN_DIR/bin/%s"
Size: int64(len(pluginYAML)), Size: int64(len(pluginYAML)),
Typeflag: tar.TypeReg, Typeflag: tar.TypeReg,
} }
if err := tarWriter.WriteHeader(header); err != nil { require.NoError(t, tarWriter.WriteHeader(header))
t.Fatal(err) _, err := tarWriter.Write([]byte(pluginYAML))
} require.NoError(t, err)
if _, err := tarWriter.Write([]byte(pluginYAML)); err != nil {
t.Fatal(err)
}
// Add bin directory // Add bin directory
dirHeader := &tar.Header{ dirHeader := &tar.Header{
@ -77,9 +74,7 @@ command: "$HELM_PLUGIN_DIR/bin/%s"
Mode: 0o755, Mode: 0o755,
Typeflag: tar.TypeDir, Typeflag: tar.TypeDir,
} }
if err := tarWriter.WriteHeader(dirHeader); err != nil { require.NoError(t, tarWriter.WriteHeader(dirHeader))
t.Fatal(err)
}
// Add executable // Add executable
execContent := fmt.Sprintf("#!/bin/sh\necho '%s test plugin'", pluginName) execContent := fmt.Sprintf("#!/bin/sh\necho '%s test plugin'", pluginName)
@ -89,12 +84,9 @@ command: "$HELM_PLUGIN_DIR/bin/%s"
Size: int64(len(execContent)), Size: int64(len(execContent)),
Typeflag: tar.TypeReg, Typeflag: tar.TypeReg,
} }
if err := tarWriter.WriteHeader(execHeader); err != nil { require.NoError(t, tarWriter.WriteHeader(execHeader))
t.Fatal(err) _, err = tarWriter.Write([]byte(execContent))
} require.NoError(t, err)
if _, err := tarWriter.Write([]byte(execContent)); err != nil {
t.Fatal(err)
}
tarWriter.Close() tarWriter.Close()
gzWriter.Close() gzWriter.Close()
@ -135,9 +127,7 @@ func mockOCIRegistryWithArtifactType(t *testing.T, pluginName string) (*httptest
} }
manifestData, err := json.Marshal(manifest) manifestData, err := json.Marshal(manifest)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
manifestDigest := fmt.Sprintf("sha256:%x", sha256Sum(manifestData)) manifestDigest := fmt.Sprintf("sha256:%x", sha256Sum(manifestData))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -175,9 +165,7 @@ func mockOCIRegistryWithArtifactType(t *testing.T, pluginName string) (*httptest
// Parse server URL to get host:port format for OCI reference // Parse server URL to get host:port format for OCI reference
serverURL, err := url.Parse(server.URL) serverURL, err := url.Parse(server.URL)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
registryHost := serverURL.Host registryHost := serverURL.Host
return server, registryHost return server, registryHost
@ -240,42 +228,20 @@ func TestNewOCIInstaller(t *testing.T) {
installer, err := NewOCIInstaller(tt.source) installer, err := NewOCIInstaller(tt.source)
if tt.expectError { if tt.expectError {
if err == nil { require.Error(t, err)
t.Error("expected error but got none") } else {
} require.NoError(t, err)
return
}
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
// Check all fields thoroughly // Check all fields thoroughly
if installer.PluginName != tt.expectName { assert.Equal(t, tt.expectName, installer.PluginName, "expected plugin name %s, got %s", tt.expectName, installer.PluginName)
t.Errorf("expected plugin name %s, got %s", tt.expectName, installer.PluginName) assert.Equal(t, tt.source, installer.Source, "expected source %s, got %s", tt.source, installer.Source)
} assert.NotEmpty(t, installer.CacheDir, "expected non-empty cache directory")
assert.Contains(t, installer.CacheDir, "plugins", "expected cache directory to contain 'plugins', got %s", installer.CacheDir)
if installer.Source != tt.source { assert.NotNil(t, installer.settings, "expected settings to be initialized")
t.Errorf("expected source %s, got %s", tt.source, installer.Source)
}
if installer.CacheDir == "" {
t.Error("expected non-empty cache directory")
}
if !strings.Contains(installer.CacheDir, "plugins") {
t.Errorf("expected cache directory to contain 'plugins', got %s", installer.CacheDir)
}
if installer.settings == nil {
t.Error("expected settings to be initialized")
}
// Check that Path() method works // Check that Path() method works
expectedPath := helmpath.DataPath("plugins", tt.expectName) expectedPath := helmpath.DataPath("plugins", tt.expectName)
if installer.Path() != expectedPath { assert.Equal(t, expectedPath, installer.Path(), "expected path %s, got %s", expectedPath, installer.Path())
t.Errorf("expected path %s, got %s", expectedPath, installer.Path())
} }
}) })
} }
@ -311,9 +277,7 @@ func TestOCIInstaller_Path(t *testing.T) {
} }
path := installer.Path() path := installer.Path()
if path != tt.expectPath { assert.Equal(t, tt.expectPath, path, "expected path %s, got %s", tt.expectPath, path)
t.Errorf("expected path %s, got %s", tt.expectPath, path)
}
}) })
} }
} }
@ -331,39 +295,30 @@ func TestOCIInstaller_Install(t *testing.T) {
// Test with plain HTTP (since test server uses HTTP) // Test with plain HTTP (since test server uses HTTP)
installer, err := NewOCIInstaller(source, getter.WithPlainHTTP(true)) installer, err := NewOCIInstaller(source, getter.WithPlainHTTP(true))
if err != nil { require.NoError(t, err)
t.Fatalf("Expected no error, got %v", err)
}
// The OCI installer uses helmpath.DataPath, which is isolated by ensure.HelmHome(t) // The OCI installer uses helmpath.DataPath, which is isolated by ensure.HelmHome(t)
actualPath := installer.Path() actualPath := installer.Path()
t.Logf("Installer will use path: %s", actualPath) t.Logf("Installer will use path: %s", actualPath)
// Install the plugin // Install the plugin
if err := Install(installer); err != nil { require.NoErrorf(t, Install(installer), "Expected installation to succeed")
t.Fatalf("Expected installation to succeed, got error: %v", err)
}
// Verify plugin was installed to the correct location // Verify plugin was installed to the correct location
if !isPlugin(actualPath) { assert.Truef(t, isPlugin(actualPath), "Expected plugin directory %s to contain plugin.yaml", actualPath)
t.Errorf("Expected plugin directory %s to contain plugin.yaml", actualPath)
}
// Debug: list what was actually created // Debug: list what was actually created
if entries, err := os.ReadDir(actualPath); err != nil { entries, err := os.ReadDir(actualPath)
t.Fatalf("Could not read plugin directory %s: %v", actualPath, err) require.NoError(t, err, "Could not read plugin directory %s", actualPath)
} else {
t.Logf("Plugin directory %s contains:", actualPath) t.Logf("Plugin directory %s contains:", actualPath)
for _, entry := range entries { for _, entry := range entries {
t.Logf(" - %s", entry.Name()) t.Logf(" - %s", entry.Name())
} }
}
// Verify the plugin.yaml file exists and is valid // Verify the plugin.yaml file exists and is valid
pluginFile := filepath.Join(actualPath, "plugin.yaml") pluginFile := filepath.Join(actualPath, "plugin.yaml")
if _, err := os.Stat(pluginFile); err != nil { _, err = os.Stat(pluginFile)
t.Errorf("Expected plugin.yaml to exist, got error: %v", err) assert.NoErrorf(t, err, "Expected plugin.yaml to exist")
}
} }
func TestOCIInstaller_Install_WithGetterOptions(t *testing.T) { func TestOCIInstaller_Install_WithGetterOptions(t *testing.T) {
@ -404,11 +359,9 @@ func TestOCIInstaller_Install_WithGetterOptions(t *testing.T) {
source := fmt.Sprintf("oci://%s/%s:latest", registryHost, tc.pluginName) source := fmt.Sprintf("oci://%s/%s:latest", registryHost, tc.pluginName)
installer, err := NewOCIInstaller(source, tc.options...) installer, err := NewOCIInstaller(source, tc.options...)
if err != nil {
if !tc.wantErr { if !tc.wantErr {
t.Fatalf("Expected no error creating installer, got %v", err) require.NoError(t, err, "Expected no error creating installer")
}
return
} }
// The installer now uses our isolated test directory // The installer now uses our isolated test directory
@ -419,7 +372,7 @@ func TestOCIInstaller_Install_WithGetterOptions(t *testing.T) {
if tc.wantErr { if tc.wantErr {
require.Error(t, err, "Expected installation to fail, but it succeeded") require.Error(t, err, "Expected installation to fail, but it succeeded")
} else { } else {
require.NoError(t, err, "Expected installation to succeed, got error: %v", err) require.NoError(t, err, "Expected installation to succeed")
// Verify plugin was installed to the actual path // Verify plugin was installed to the actual path
assert.True(t, isPlugin(actualPath), "Expected plugin directory %s to contain plugin.yaml", actualPath) assert.True(t, isPlugin(actualPath), "Expected plugin directory %s to contain plugin.yaml", actualPath)
} }
@ -437,27 +390,16 @@ func TestOCIInstaller_Install_AlreadyExists(t *testing.T) {
source := fmt.Sprintf("oci://%s/%s:latest", registryHost, pluginName) source := fmt.Sprintf("oci://%s/%s:latest", registryHost, pluginName)
installer, err := NewOCIInstaller(source, getter.WithPlainHTTP(true)) installer, err := NewOCIInstaller(source, getter.WithPlainHTTP(true))
if err != nil { require.NoError(t, err)
t.Fatalf("Expected no error, got %v", err)
}
// First install should succeed // First install should succeed
if err := Install(installer); err != nil { require.NoErrorf(t, Install(installer), "Expected first installation to succeed")
t.Fatalf("Expected first installation to succeed, got error: %v", err)
}
// Verify plugin was installed // Verify plugin was installed
if !isPlugin(installer.Path()) { assert.Truef(t, isPlugin(installer.Path()), "Expected plugin directory %s to contain plugin.yaml", installer.Path())
t.Errorf("Expected plugin directory %s to contain plugin.yaml", installer.Path())
}
// Second install should fail with "plugin already exists" // Second install should fail with "plugin already exists"
err = Install(installer) assert.ErrorContains(t, Install(installer), "plugin already exists")
if err == nil {
t.Error("Expected error when installing plugin that already exists")
} else if !strings.Contains(err.Error(), "plugin already exists") {
t.Errorf("Expected 'plugin already exists' error, got: %v", err)
}
} }
func TestOCIInstaller_Update(t *testing.T) { func TestOCIInstaller_Update(t *testing.T) {
@ -470,38 +412,23 @@ func TestOCIInstaller_Update(t *testing.T) {
source := fmt.Sprintf("oci://%s/%s:latest", registryHost, pluginName) source := fmt.Sprintf("oci://%s/%s:latest", registryHost, pluginName)
installer, err := NewOCIInstaller(source, getter.WithPlainHTTP(true)) installer, err := NewOCIInstaller(source, getter.WithPlainHTTP(true))
if err != nil { require.NoError(t, err)
t.Fatalf("Expected no error, got %v", err)
}
// Test update when plugin does not exist - should fail // Test update when plugin does not exist - should fail
err = Update(installer) require.ErrorContains(t, Update(installer), "plugin does not exist")
if err == nil {
t.Error("Expected error when updating plugin that does not exist")
} else if !strings.Contains(err.Error(), "plugin does not exist") {
t.Errorf("Expected 'plugin does not exist' error, got: %v", err)
}
// Install plugin first // Install plugin first
if err := Install(installer); err != nil { require.NoErrorf(t, Install(installer), "Expected installation to succeed")
t.Fatalf("Expected installation to succeed, got error: %v", err)
}
// Verify plugin was installed // Verify plugin was installed
if !isPlugin(installer.Path()) { assert.Truef(t, isPlugin(installer.Path()), "Expected plugin directory %s to contain plugin.yaml", installer.Path())
t.Errorf("Expected plugin directory %s to contain plugin.yaml", installer.Path())
}
// Test update when plugin exists - should succeed // Test update when plugin exists - should succeed
// For OCI, Update() removes old version and reinstalls // For OCI, Update() removes old version and reinstalls
if err := Update(installer); err != nil { require.NoErrorf(t, Update(installer), "Expected update to succeed")
t.Errorf("Expected update to succeed, got error: %v", err)
}
// Verify plugin is still installed after update // Verify plugin is still installed after update
if !isPlugin(installer.Path()) { assert.Truef(t, isPlugin(installer.Path()), "Expected plugin directory %s to contain plugin.yaml after update", installer.Path())
t.Errorf("Expected plugin directory %s to contain plugin.yaml after update", installer.Path())
}
} }
func TestOCIInstaller_Install_ComponentExtraction(t *testing.T) { func TestOCIInstaller_Install_ComponentExtraction(t *testing.T) {
@ -513,35 +440,26 @@ func TestOCIInstaller_Install_ComponentExtraction(t *testing.T) {
pluginData := createTestPluginTarGz(t, pluginName) pluginData := createTestPluginTarGz(t, pluginName)
// Test extraction // Test extraction
err := extractTarGz(bytes.NewReader(pluginData), tempDir) require.NoError(t, extractTarGz(bytes.NewReader(pluginData), tempDir), "Failed to extract plugin")
if err != nil {
t.Fatalf("Failed to extract plugin: %v", err)
}
// Verify plugin.yaml exists // Verify plugin.yaml exists
pluginYAMLPath := filepath.Join(tempDir, "plugin.yaml") pluginYAMLPath := filepath.Join(tempDir, "plugin.yaml")
if _, err := os.Stat(pluginYAMLPath); os.IsNotExist(err) { _, err := os.Stat(pluginYAMLPath)
t.Error("plugin.yaml not found after extraction") assert.False(t, os.IsNotExist(err), "plugin.yaml not found after extraction")
}
// Verify bin directory exists // Verify bin directory exists
binPath := filepath.Join(tempDir, "bin") binPath := filepath.Join(tempDir, "bin")
if _, err := os.Stat(binPath); os.IsNotExist(err) { _, err = os.Stat(binPath)
t.Error("bin directory not found after extraction") assert.False(t, os.IsNotExist(err), "bin directory not found after extraction")
}
// Verify executable exists and has correct permissions // Verify executable exists and has correct permissions
execPath := filepath.Join(tempDir, "bin", pluginName) execPath := filepath.Join(tempDir, "bin", pluginName)
if info, err := os.Stat(execPath); err != nil { info, err := os.Stat(execPath)
t.Errorf("executable not found: %v", err) require.NoError(t, err, "executable not found")
} else if info.Mode()&0o111 == 0 { assert.NotEqual(t, 0, info.Mode()&0o111, "file is not executable")
t.Error("file is not executable")
}
// Verify this would be recognized as a plugin // Verify this would be recognized as a plugin
if !isPlugin(tempDir) { assert.True(t, isPlugin(tempDir), "extracted directory is not a valid plugin")
t.Error("extracted directory is not a valid plugin")
}
} }
func TestExtractTarGz(t *testing.T) { func TestExtractTarGz(t *testing.T) {
@ -561,13 +479,10 @@ func TestExtractTarGz(t *testing.T) {
Typeflag: tar.TypeReg, Typeflag: tar.TypeReg,
} }
if err := tarWriter.WriteHeader(header); err != nil { require.NoError(t, tarWriter.WriteHeader(header))
t.Fatal(err)
}
if _, err := tarWriter.Write([]byte(testContent)); err != nil { _, err := tarWriter.Write([]byte(testContent))
t.Fatal(err) require.NoError(t, err)
}
// Add a test directory // Add a test directory
dirHeader := &tar.Header{ dirHeader := &tar.Header{
@ -576,35 +491,25 @@ func TestExtractTarGz(t *testing.T) {
Typeflag: tar.TypeDir, Typeflag: tar.TypeDir,
} }
if err := tarWriter.WriteHeader(dirHeader); err != nil { require.NoError(t, tarWriter.WriteHeader(dirHeader))
t.Fatal(err)
}
tarWriter.Close() tarWriter.Close()
gzWriter.Close() gzWriter.Close()
// Test extraction // Test extraction
err := extractTarGz(bytes.NewReader(buf.Bytes()), tempDir) require.NoError(t, extractTarGz(bytes.NewReader(buf.Bytes()), tempDir), "extractTarGz failed")
if err != nil {
t.Errorf("extractTarGz failed: %v", err)
}
// Verify extracted file // Verify extracted file
extractedFile := filepath.Join(tempDir, "test-file.txt") extractedFile := filepath.Join(tempDir, "test-file.txt")
content, err := os.ReadFile(extractedFile) content, err := os.ReadFile(extractedFile)
if err != nil { require.NoError(t, err, "failed to read extracted file")
t.Errorf("failed to read extracted file: %v", err)
}
if string(content) != testContent { assert.Equal(t, testContent, string(content), "expected content %s, got %s", testContent, string(content))
t.Errorf("expected content %s, got %s", testContent, string(content))
}
// Verify extracted directory // Verify extracted directory
extractedDir := filepath.Join(tempDir, "test-dir") extractedDir := filepath.Join(tempDir, "test-dir")
if _, err := os.Stat(extractedDir); os.IsNotExist(err) { _, err = os.Stat(extractedDir)
t.Errorf("extracted directory does not exist: %s", extractedDir) assert.Falsef(t, os.IsNotExist(err), "extracted directory does not exist: %s", extractedDir)
}
} }
func TestExtractTarGz_InvalidGzip(t *testing.T) { func TestExtractTarGz_InvalidGzip(t *testing.T) {
@ -612,10 +517,7 @@ func TestExtractTarGz_InvalidGzip(t *testing.T) {
// Test with invalid gzip data // Test with invalid gzip data
invalidGzipData := []byte("not gzip data") invalidGzipData := []byte("not gzip data")
err := extractTarGz(bytes.NewReader(invalidGzipData), tempDir) assert.Error(t, extractTarGz(bytes.NewReader(invalidGzipData), tempDir), "expected error for invalid gzip data")
if err == nil {
t.Error("expected error for invalid gzip data")
}
} }
func TestExtractTar_UnknownFileType(t *testing.T) { func TestExtractTar_UnknownFileType(t *testing.T) {
@ -634,13 +536,10 @@ func TestExtractTar_UnknownFileType(t *testing.T) {
Typeflag: tar.TypeReg, Typeflag: tar.TypeReg,
} }
if err := tarWriter.WriteHeader(header); err != nil { require.NoError(t, tarWriter.WriteHeader(header))
t.Fatal(err)
}
if _, err := tarWriter.Write([]byte(testContent)); err != nil { _, err := tarWriter.Write([]byte(testContent))
t.Fatal(err) require.NoError(t, err)
}
// Test unknown file type // Test unknown file type
unknownHeader := &tar.Header{ unknownHeader := &tar.Header{
@ -649,21 +548,12 @@ func TestExtractTar_UnknownFileType(t *testing.T) {
Typeflag: tar.TypeSymlink, // Use a type that's not handled Typeflag: tar.TypeSymlink, // Use a type that's not handled
} }
if err := tarWriter.WriteHeader(unknownHeader); err != nil { require.NoError(t, tarWriter.WriteHeader(unknownHeader))
t.Fatal(err)
}
tarWriter.Close() tarWriter.Close()
// Test extraction - should fail due to unknown type // Test extraction - should fail due to unknown type
err := extractTar(bytes.NewReader(buf.Bytes()), tempDir) assert.ErrorContains(t, extractTar(bytes.NewReader(buf.Bytes()), tempDir), "unknown type")
if err == nil {
t.Error("expected error for unknown tar file type")
}
if !strings.Contains(err.Error(), "unknown type") {
t.Errorf("expected 'unknown type' error, got: %v", err)
}
} }
func TestExtractTar_SuccessfulExtraction(t *testing.T) { func TestExtractTar_SuccessfulExtraction(t *testing.T) {
@ -686,32 +576,22 @@ func TestExtractTar_SuccessfulExtraction(t *testing.T) {
Typeflag: tar.TypeReg, Typeflag: tar.TypeReg,
} }
if err := tarWriter.WriteHeader(header); err != nil { require.NoError(t, tarWriter.WriteHeader(header))
t.Fatal(err)
}
if _, err := tarWriter.Write([]byte(testContent)); err != nil { _, err := tarWriter.Write([]byte(testContent))
t.Fatal(err) require.NoError(t, err)
}
tarWriter.Close() tarWriter.Close()
// Test extraction // Test extraction
err := extractTar(bytes.NewReader(buf.Bytes()), tempDir) require.NoError(t, extractTar(bytes.NewReader(buf.Bytes()), tempDir), "extractTar failed")
if err != nil {
t.Errorf("extractTar failed: %v", err)
}
// Verify the regular file was extracted // Verify the regular file was extracted
extractedFile := filepath.Join(tempDir, "test-file.txt") extractedFile := filepath.Join(tempDir, "test-file.txt")
content, err := os.ReadFile(extractedFile) content, err := os.ReadFile(extractedFile)
if err != nil { require.NoError(t, err, "failed to read extracted file")
t.Errorf("failed to read extracted file: %v", err)
}
if string(content) != testContent { assert.Equal(t, testContent, string(content), "expected content %s, got %s", testContent, string(content))
t.Errorf("expected content %s, got %s", testContent, string(content))
}
} }
func TestOCIInstaller_Install_PlainHTTPOption(t *testing.T) { func TestOCIInstaller_Install_PlainHTTPOption(t *testing.T) {
@ -720,41 +600,25 @@ func TestOCIInstaller_Install_PlainHTTPOption(t *testing.T) {
// Test with PlainHTTP=false (default) // Test with PlainHTTP=false (default)
installer1, err := NewOCIInstaller(source) installer1, err := NewOCIInstaller(source)
if err != nil { require.NoError(t, err, "failed to create installer")
t.Fatalf("failed to create installer: %v", err) assert.NotNil(t, installer1.getter, "getter should be initialized")
}
if installer1.getter == nil {
t.Error("getter should be initialized")
}
// Test with PlainHTTP=true // Test with PlainHTTP=true
installer2, err := NewOCIInstaller(source, getter.WithPlainHTTP(true)) installer2, err := NewOCIInstaller(source, getter.WithPlainHTTP(true))
if err != nil { require.NoError(t, err, "failed to create installer with PlainHTTP=true")
t.Fatalf("failed to create installer with PlainHTTP=true: %v", err) assert.NotNil(t, installer2.getter, "getter should be initialized with PlainHTTP=true")
}
if installer2.getter == nil {
t.Error("getter should be initialized with PlainHTTP=true")
}
// Both installers should have the same basic properties // Both installers should have the same basic properties
if installer1.PluginName != installer2.PluginName { assert.Equal(t, installer2.PluginName, installer1.PluginName, "plugin names should match")
t.Error("plugin names should match") assert.Equal(t, installer2.Source, installer1.Source, "sources should match")
}
if installer1.Source != installer2.Source {
t.Error("sources should match")
}
// Test with multiple options // Test with multiple options
installer3, err := NewOCIInstaller(source, installer3, err := NewOCIInstaller(source,
getter.WithPlainHTTP(true), getter.WithPlainHTTP(true),
getter.WithBasicAuth("user", "pass"), getter.WithBasicAuth("user", "pass"),
) )
if err != nil { require.NoError(t, err, "failed to create installer with multiple options")
t.Fatalf("failed to create installer with multiple options: %v", err) assert.NotNil(t, installer3.getter, "getter should be initialized with multiple options")
}
if installer3.getter == nil {
t.Error("getter should be initialized with multiple options")
}
} }
func TestOCIInstaller_Install_ValidationErrors(t *testing.T) { func TestOCIInstaller_Install_ValidationErrors(t *testing.T) {
@ -789,12 +653,8 @@ func TestOCIInstaller_Install_ValidationErrors(t *testing.T) {
// Test the gzip validation logic that's used in the Install method // Test the gzip validation logic that's used in the Install method
if len(tt.layerData) < 2 || tt.layerData[0] != 0x1f || tt.layerData[1] != 0x8b { if len(tt.layerData) < 2 || tt.layerData[0] != 0x1f || tt.layerData[1] != 0x8b {
// This matches the validation in the Install method // This matches the validation in the Install method
if !tt.expectError { assert.True(t, tt.expectError, "expected valid gzip data")
t.Error("expected valid gzip data") assert.Contains(t, tt.errorMsg, "is not a gzip compressed archive")
}
if !strings.Contains(tt.errorMsg, "is not a gzip compressed archive") {
t.Error("expected error message to contain 'is not a gzip compressed archive'")
}
} }
}) })
} }

@ -23,6 +23,7 @@ import (
"testing" "testing"
"github.com/Masterminds/vcs" "github.com/Masterminds/vcs"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/internal/test/ensure" "helm.sh/helm/v4/internal/test/ensure"
"helm.sh/helm/v4/pkg/helmpath" "helm.sh/helm/v4/pkg/helmpath"
@ -52,9 +53,7 @@ func (r *testRepo) UpdateVersion(version string) error {
func TestVCSInstaller(t *testing.T) { func TestVCSInstaller(t *testing.T) {
ensure.HelmHome(t) ensure.HelmHome(t)
if err := os.MkdirAll(helmpath.DataPath("plugins"), 0o755); err != nil { require.NoErrorf(t, os.MkdirAll(helmpath.DataPath("plugins"), 0o755), "Could not create %s", helmpath.DataPath("plugins"))
t.Fatalf("Could not create %s: %s", helmpath.DataPath("plugins"), err)
}
source := "https://github.com/adamreese/helm-env" source := "https://github.com/adamreese/helm-env"
testRepoPath, _ := filepath.Abs("../testdata/plugdir/good/echo-v1") testRepoPath, _ := filepath.Abs("../testdata/plugdir/good/echo-v1")
@ -64,43 +63,27 @@ func TestVCSInstaller(t *testing.T) {
} }
i, err := NewForSource(source, "~0.1.0") i, err := NewForSource(source, "~0.1.0")
if err != nil { require.NoError(t, err)
t.Fatalf("unexpected error: %s", err)
}
// ensure a VCSInstaller was returned // ensure a VCSInstaller was returned
vcsInstaller, ok := i.(*VCSInstaller) vcsInstaller, ok := i.(*VCSInstaller)
if !ok { require.True(t, ok, "expected a VCSInstaller")
t.Fatal("expected a VCSInstaller")
}
// set the testRepo in the VCSInstaller // set the testRepo in the VCSInstaller
vcsInstaller.Repo = repo vcsInstaller.Repo = repo
if err := Install(i); err != nil { require.NoError(t, Install(i))
t.Fatal(err) require.Equal(t, "0.1.1", repo.current, "expected version '0.1.1', got %q", repo.current)
}
if repo.current != "0.1.1" {
t.Fatalf("expected version '0.1.1', got %q", repo.current)
}
expectedPath := helmpath.DataPath("plugins", "helm-env") expectedPath := helmpath.DataPath("plugins", "helm-env")
if i.Path() != expectedPath { require.Equal(t, expectedPath, i.Path(), "expected path %q, got %q", expectedPath, i.Path())
t.Fatalf("expected path %q, got %q", expectedPath, i.Path())
}
// Install again to test plugin exists error // Install again to test plugin exists error
if err := Install(i); err == nil { require.EqualErrorf(t, Install(i), "plugin already exists", "expected error for plugin exists")
t.Fatal("expected error for plugin exists, got none")
} else if err.Error() != "plugin already exists" {
t.Fatalf("expected error for plugin exists, got (%v)", err)
}
// Testing FindSource method, expect error because plugin code is not a cloned repository // Testing FindSource method, expect error because plugin code is not a cloned repository
if _, err := FindSource(i.Path()); err == nil { _, err = FindSource(i.Path())
t.Fatal("expected error for inability to find plugin source, got none") require.Error(t, err, "expected error for inability to find plugin source, got none")
} else if err.Error() != "cannot get information about plugin source" { require.EqualErrorf(t, err, "cannot get information about plugin source", "expected error for inability to find plugin source")
t.Fatalf("expected error for inability to find plugin source, got (%v)", err)
}
} }
func TestVCSInstallerNonExistentVersion(t *testing.T) { func TestVCSInstallerNonExistentVersion(t *testing.T) {
@ -110,21 +93,18 @@ func TestVCSInstallerNonExistentVersion(t *testing.T) {
version := "0.2.0" version := "0.2.0"
i, err := NewForSource(source, version) i, err := NewForSource(source, version)
if err != nil { require.NoError(t, err)
t.Fatalf("unexpected error: %s", err)
}
// ensure a VCSInstaller was returned // ensure a VCSInstaller was returned
if _, ok := i.(*VCSInstaller); !ok { _, ok := i.(*VCSInstaller)
t.Fatal("expected a VCSInstaller") require.True(t, ok, "expected a VCSInstaller")
}
if err := Install(i); err == nil { if err := Install(i); err == nil {
t.Fatal("expected error for version does not exists, got none") t.Fatal("expected error for version does not exists, got none")
} else if strings.Contains(err.Error(), "Could not resolve host: github.com") { } else if strings.Contains(err.Error(), "Could not resolve host: github.com") {
t.Skip("Unable to run test without Internet access") t.Skip("Unable to run test without Internet access")
} else if err.Error() != fmt.Sprintf("requested version %q does not exist for plugin %q", version, source) { } else {
t.Fatalf("expected error for version does not exists, got (%v)", err) require.EqualErrorf(t, err, fmt.Sprintf("requested version %q does not exist for plugin %q", version, source), "expected error for version does not exists")
} }
} }
func TestVCSInstallerUpdate(t *testing.T) { func TestVCSInstallerUpdate(t *testing.T) {
@ -133,20 +113,13 @@ func TestVCSInstallerUpdate(t *testing.T) {
source := "https://github.com/adamreese/helm-env" source := "https://github.com/adamreese/helm-env"
i, err := NewForSource(source, "") i, err := NewForSource(source, "")
if err != nil { require.NoError(t, err)
t.Fatalf("unexpected error: %s", err)
}
// ensure a VCSInstaller was returned // ensure a VCSInstaller was returned
if _, ok := i.(*VCSInstaller); !ok { _, ok := i.(*VCSInstaller)
t.Fatal("expected a VCSInstaller") require.True(t, ok, "expected a VCSInstaller")
}
if err := Update(i); err == nil { require.EqualErrorf(t, Update(i), "plugin does not exist", "expected error for plugin does not exist")
t.Fatal("expected error for plugin does not exist, got none")
} else if err.Error() != "plugin does not exist" {
t.Fatalf("expected error for plugin does not exist, got (%v)", err)
}
// Install plugin before update // Install plugin before update
if err := Install(i); err != nil { if err := Install(i); err != nil {
@ -159,30 +132,18 @@ func TestVCSInstallerUpdate(t *testing.T) {
// Test FindSource method for positive result // Test FindSource method for positive result
pluginInfo, err := FindSource(i.Path()) pluginInfo, err := FindSource(i.Path())
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
vcsInstaller := pluginInfo.(*VCSInstaller) vcsInstaller := pluginInfo.(*VCSInstaller)
repoRemote := vcsInstaller.Repo.Remote() repoRemote := vcsInstaller.Repo.Remote()
if repoRemote != source { require.Equal(t, source, repoRemote, "invalid source found, expected %q got %q", source, repoRemote)
t.Fatalf("invalid source found, expected %q got %q", source, repoRemote)
}
// Update plugin // Update plugin
if err := Update(i); err != nil { require.NoError(t, Update(i))
t.Fatal(err)
}
// Test update failure // Test update failure
if err := os.Remove(filepath.Join(vcsInstaller.Repo.LocalPath(), "plugin.yaml")); err != nil { require.NoError(t, os.Remove(filepath.Join(vcsInstaller.Repo.LocalPath(), "plugin.yaml")))
t.Fatal(err)
}
// Testing update for error // Testing update for error
if err := Update(vcsInstaller); err == nil { require.EqualErrorf(t, Update(vcsInstaller), "plugin repo was modified", "expected error for plugin modified")
t.Fatal("expected error for plugin modified, got none")
} else if err.Error() != "plugin repo was modified" {
t.Fatalf("expected error for plugin modified, got (%v)", err)
}
} }

Loading…
Cancel
Save