Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions cmd/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,51 @@ func TestEnvironmentVariablePrecedence(t *testing.T) {
assert.Equal(t, "env-key", apiKey)
}

func TestCompletionAPIKeyPrecedence(t *testing.T) {
// Create temp directory
tempDir, err := os.MkdirTemp("", "cloudamqp-test")
assert.NoError(t, err)
defer os.RemoveAll(tempDir)

// Override home directory for test
originalHome := os.Getenv("HOME")
os.Setenv("HOME", tempDir)
defer os.Setenv("HOME", originalHome)

// Clear any existing env var
originalEnvKey := os.Getenv("CLOUDAMQP_APIKEY")
os.Unsetenv("CLOUDAMQP_APIKEY")
defer func() {
if originalEnvKey != "" {
os.Setenv("CLOUDAMQP_APIKEY", originalEnvKey)
}
}()

t.Run("returns error when no key configured", func(t *testing.T) {
_, err := completionAPIKey()
assert.Error(t, err)
assert.Contains(t, err.Error(), "API key not configured")
})

t.Run("returns key from config file", func(t *testing.T) {
err := saveMainAPIKey("file-key")
assert.NoError(t, err)

apiKey, err := completionAPIKey()
assert.NoError(t, err)
assert.Equal(t, "file-key", apiKey)
})

t.Run("env var takes precedence over config file", func(t *testing.T) {
os.Setenv("CLOUDAMQP_APIKEY", "env-key")
defer os.Unsetenv("CLOUDAMQP_APIKEY")

apiKey, err := completionAPIKey()
assert.NoError(t, err)
assert.Equal(t, "env-key", apiKey)
})
}

func TestInstanceActionsCommand(t *testing.T) {
cmd := instanceCmd

Expand Down
7 changes: 7 additions & 0 deletions cmd/completion_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"encoding/json"
"fmt"
"os"
"strconv"

"cloudamqp-cli/client"
Expand All @@ -11,6 +12,12 @@ import (

// completionAPIKey retrieves the API key without prompting the user
func completionAPIKey() (string, error) {
// First, check environment variable
if apiKey := os.Getenv("CLOUDAMQP_APIKEY"); apiKey != "" {
return apiKey, nil
}

// Second, check config file
apiKey, err := loadAPIKey()
if apiKey != "" {
return apiKey, nil
Expand Down
Loading