Skip to content

Commit 5da0a92

Browse files
committed
api-key command tests
1 parent 5dbbc4c commit 5da0a92

2 files changed

Lines changed: 85 additions & 0 deletions

File tree

cmd/api_key_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package cmd
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"strings"
7+
"testing"
8+
9+
"github.com/loops-so/cli/internal/api"
10+
)
11+
12+
func TestAPIKeyCmd(t *testing.T) {
13+
t.Run("text: shows team name", func(t *testing.T) {
14+
serveJSON(t, http.StatusOK, `{"teamName":"Acme Corp"}`)
15+
out, err := runCmd(t, "api-key")
16+
if err != nil {
17+
t.Fatalf("unexpected error: %v", err)
18+
}
19+
if !strings.Contains(out, "Acme Corp") {
20+
t.Errorf("output %q should contain team name", out)
21+
}
22+
})
23+
24+
t.Run("json: valid json with team name", func(t *testing.T) {
25+
serveJSON(t, http.StatusOK, `{"teamName":"Acme Corp"}`)
26+
out, err := runCmd(t, "--output=json", "api-key")
27+
if err != nil {
28+
t.Fatalf("unexpected error: %v", err)
29+
}
30+
var result api.APIKeyResponse
31+
if err := json.Unmarshal([]byte(out), &result); err != nil {
32+
t.Fatalf("output is not valid JSON: %v\n%s", err, out)
33+
}
34+
if result.TeamName != "Acme Corp" {
35+
t.Errorf("TeamName = %q, want %q", result.TeamName, "Acme Corp")
36+
}
37+
})
38+
39+
t.Run("api error propagates", func(t *testing.T) {
40+
serveJSON(t, http.StatusUnauthorized, `{"error":"Invalid API key"}`)
41+
_, err := runCmd(t, "api-key")
42+
if err == nil {
43+
t.Fatal("expected error, got nil")
44+
}
45+
})
46+
}

cmd/helpers_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package cmd
2+
3+
import (
4+
"bytes"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
9+
"github.com/zalando/go-keyring"
10+
)
11+
12+
// runCmd executes rootCmd with the given args and returns captured stdout.
13+
// outputFormat is reset to "text" before and after each call.
14+
func runCmd(t *testing.T, args ...string) (string, error) {
15+
t.Helper()
16+
outputFormat = "text"
17+
t.Cleanup(func() { outputFormat = "text" })
18+
19+
buf := &bytes.Buffer{}
20+
rootCmd.SetOut(buf)
21+
rootCmd.SetErr(&bytes.Buffer{})
22+
rootCmd.SetArgs(args)
23+
err := rootCmd.Execute()
24+
return buf.String(), err
25+
}
26+
27+
// serveJSON starts a test server that responds with the given status and JSON
28+
// body, sets LOOPS_API_KEY and LOOPS_ENDPOINT_URL, and registers cleanup.
29+
func serveJSON(t *testing.T, status int, body string) {
30+
t.Helper()
31+
keyring.MockInit()
32+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
33+
w.WriteHeader(status)
34+
w.Write([]byte(body))
35+
}))
36+
t.Cleanup(srv.Close)
37+
t.Setenv("LOOPS_API_KEY", "test-key")
38+
t.Setenv("LOOPS_ENDPOINT_URL", srv.URL)
39+
}

0 commit comments

Comments
 (0)