secret/internal/cli/test_helpers.go
sneak 6fe49344e2 fix: resolve errcheck, gosec, and mnd linter errors
- Fixed unhandled errors in init.go (os.Setenv/Unsetenv)
- Fixed unhandled errors in test_helpers.go (os.Setenv/Unsetenv)
- Replaced magic numbers with named constants:
  - defaultSecretLength = 16
  - mnemonicEntropyBits = 128
  - tabWriterPadding = 2
2025-07-09 06:59:01 -07:00

64 lines
1.3 KiB
Go

package cli
import (
"bytes"
"os"
"strings"
"git.eeqj.de/sneak/secret/internal/secret"
)
// ExecuteCommandInProcess executes a CLI command in-process for testing
func ExecuteCommandInProcess(args []string, stdin string, env map[string]string) (string, error) {
secret.Debug("ExecuteCommandInProcess called", "args", args)
// Save current environment
savedEnv := make(map[string]string)
for k := range env {
savedEnv[k] = os.Getenv(k)
}
// Set test environment
for k, v := range env {
_ = os.Setenv(k, v)
}
// Create root command
rootCmd := newRootCmd()
// Capture output
var buf bytes.Buffer
rootCmd.SetOut(&buf)
rootCmd.SetErr(&buf)
// Set stdin if provided
if stdin != "" {
rootCmd.SetIn(strings.NewReader(stdin))
}
// Set args
rootCmd.SetArgs(args)
// Execute command
err := rootCmd.Execute()
output := buf.String()
secret.Debug("Command execution completed", "error", err, "outputLength", len(output), "output", output)
// Add debug info for troubleshooting
if len(output) == 0 && err == nil {
secret.Debug("Warning: Command executed successfully but produced no output", "args", args)
}
// Restore environment
for k, v := range savedEnv {
if v == "" {
_ = os.Unsetenv(k)
} else {
_ = os.Setenv(k, v)
}
}
return output, err
}