Change NewCLIInstance() and NewCLIInstanceWithFs() to return (*Instance, error) instead of panicking on DetermineStateDir failure. Callers in RunE contexts propagate the error. Callers in command construction (for shell completion) use log.Fatalf. Test callers use t.Fatalf. Addresses review feedback on PR #18.
67 lines
1.7 KiB
Go
67 lines
1.7 KiB
Go
package cli
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"git.eeqj.de/sneak/secret/internal/secret"
|
|
"github.com/spf13/afero"
|
|
)
|
|
|
|
func TestCLIInstanceStateDir(t *testing.T) {
|
|
// Test the CLI instance state directory functionality
|
|
fs := afero.NewMemMapFs()
|
|
|
|
// Create a test state directory
|
|
testStateDir := "/test-state-dir"
|
|
cli := NewCLIInstanceWithStateDir(fs, testStateDir)
|
|
|
|
if cli.GetStateDir() != testStateDir {
|
|
t.Errorf("Expected state directory %q, got %q", testStateDir, cli.GetStateDir())
|
|
}
|
|
}
|
|
|
|
func TestCLIInstanceWithFs(t *testing.T) {
|
|
// Test creating CLI instance with custom filesystem
|
|
fs := afero.NewMemMapFs()
|
|
cli, err := NewCLIInstanceWithFs(fs)
|
|
if err != nil {
|
|
t.Fatalf("failed to initialize CLI: %v", err)
|
|
}
|
|
|
|
// The state directory should be determined automatically
|
|
stateDir := cli.GetStateDir()
|
|
if stateDir == "" {
|
|
t.Error("Expected non-empty state directory")
|
|
}
|
|
}
|
|
|
|
func TestDetermineStateDir(t *testing.T) {
|
|
// Test the determineStateDir function from the secret package
|
|
|
|
// Test with environment variable set
|
|
testEnvDir := "/test-env-dir"
|
|
t.Setenv(secret.EnvStateDir, testEnvDir)
|
|
|
|
stateDir, err := secret.DetermineStateDir("")
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if stateDir != testEnvDir {
|
|
t.Errorf("Expected state directory %q from environment, got %q", testEnvDir, stateDir)
|
|
}
|
|
|
|
// Test with custom config dir
|
|
_ = os.Unsetenv(secret.EnvStateDir)
|
|
customConfigDir := "/custom-config"
|
|
stateDir, err = secret.DetermineStateDir(customConfigDir)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
expectedDir := filepath.Join(customConfigDir, secret.AppID)
|
|
if stateDir != expectedDir {
|
|
t.Errorf("Expected state directory %q with custom config, got %q", expectedDir, stateDir)
|
|
}
|
|
}
|