|
| 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 | +} |
0 commit comments