package main import ( "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" ) func TestCredentialPrecedence(t *testing.T) { cases := []struct { name string args []string wantAuth string wantKey string }{ {"persisted key sent", []string{"cms", "nodes", "list"}, "", "persisted-key"}, {"explicit token beats persisted key", []string{"--token", "flag-token", "cms", "nodes", "list"}, "Bearer flag-token", ""}, {"explicit api-key flag wins", []string{"--api-key", "flag-key", "cms", "nodes", "list"}, "", "flag-key"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { var gotAuth, gotKey string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotAuth = r.Header.Get("Authorization") gotKey = r.Header.Get("X-API-Key") _, _ = w.Write([]byte(`{"data":[]}`)) })) defer srv.Close() cfgPath := filepath.Join(t.TempDir(), "config.json") cfg := defaultConfig() cfg.BaseURL = srv.URL cfg.APIKey = "persisted-key" if err := saveConfig(cfgPath, cfg); err != nil { t.Fatal(err) } var stdout, stderr strings.Builder full := append([]string{"--config", cfgPath, "--base-url", srv.URL}, tc.args...) if err := runWithStdin(full, strings.NewReader(""), &stdout, &stderr); err != nil { t.Fatalf("run: %v (stderr=%s)", err, stderr.String()) } if gotAuth != tc.wantAuth || gotKey != tc.wantKey { t.Fatalf("auth=%q key=%q, want auth=%q key=%q", gotAuth, gotKey, tc.wantAuth, tc.wantKey) } }) } } func TestMain(m *testing.M) { os.Exit(m.Run()) }