secret/internal/cli/stdout_stderr_test.go
sneak 18fb79e971 Fix 'secret get' to output to stdout instead of stderr
- Add Print method to CLI Instance that uses cmd.OutOrStdout()
- Update GetSecretWithVersion to use cli.Print instead of cmd.Print
- Add test to verify secret values go to stdout, not stderr
- Store command reference in Instance for proper output handling
2025-07-29 20:01:10 +02:00

73 lines
2.1 KiB
Go

package cli_test
import (
"bytes"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestGetCommandOutputsToStdout tests that 'secret get' outputs the secret value to stdout, not stderr
func TestGetCommandOutputsToStdout(t *testing.T) {
// Create a temporary directory for our vault
tempDir := t.TempDir()
// Set environment variables for the test
t.Setenv("SB_SECRET_STATE_DIR", tempDir)
// Find the secret binary path
wd, err := filepath.Abs("../..")
require.NoError(t, err, "should get working directory")
secretPath := filepath.Join(wd, "secret")
testMnemonic := "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
testPassphrase := "test-passphrase"
// Initialize vault
cmd := exec.Command(secretPath, "init")
cmd.Env = []string{
"SB_SECRET_STATE_DIR=" + tempDir,
"SB_SECRET_MNEMONIC=" + testMnemonic,
"SB_UNLOCK_PASSPHRASE=" + testPassphrase,
"PATH=" + "/usr/bin:/bin",
}
output, err := cmd.CombinedOutput()
require.NoError(t, err, "init should succeed: %s", string(output))
// Add a secret
cmd = exec.Command(secretPath, "add", "test/secret")
cmd.Env = []string{
"SB_SECRET_STATE_DIR=" + tempDir,
"SB_SECRET_MNEMONIC=" + testMnemonic,
"PATH=" + "/usr/bin:/bin",
}
cmd.Stdin = strings.NewReader("test-secret-value")
output, err = cmd.CombinedOutput()
require.NoError(t, err, "add should succeed: %s", string(output))
// Test that 'secret get' outputs to stdout, not stderr
cmd = exec.Command(secretPath, "get", "test/secret")
cmd.Env = []string{
"SB_SECRET_STATE_DIR=" + tempDir,
"SB_SECRET_MNEMONIC=" + testMnemonic,
"PATH=" + "/usr/bin:/bin",
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
require.NoError(t, err, "get should succeed")
// The secret value should be in stdout
assert.Equal(t, "test-secret-value", strings.TrimSpace(stdout.String()), "secret value should be in stdout")
// Nothing should be in stderr
assert.Empty(t, stderr.String(), "stderr should be empty")
}