package cmd import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) // execute runs the root command with args against a fresh output buffer, after // resetting the shared flag globals so tests don't leak state into each other. func execute(t *testing.T, args ...string) (string, string, error) { t.Helper() // Reset globals touched by these tests. flagJSON = false flagHost = "" flagToken = "" repoListUser = "" repoListOrg = "" pageFlag = 0 perPageFlag = 0 issueTitle = "" issueBody = "" issueRepo = "" issueState = "open" milestoneRepo = "" milestoneState = "open" milestoneTitle = "" milestoneDue = "" milestoneDescription = "" runRepo = "" runWatchInterval = "2s" runWatchTimeout = "30m" runWatchLogs = false authLoginScope = "all" authLoginNoBrowser = false var out, errBuf bytes.Buffer rootCmd.SetOut(&out) rootCmd.SetErr(&errBuf) rootCmd.SetArgs(args) err := rootCmd.Execute() return out.String(), errBuf.String(), err } func repoListServer(t *testing.T) *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/v1/users/ricktester/repos" { w.WriteHeader(http.StatusNotFound) w.Write([]byte(`{"error":{"code":"not_found","message":"no"}}`)) return } json.NewEncoder(w).Encode(map[string]any{ "page": 1, "per_page": 30, "has_next": false, "items": []map[string]any{ {"full_name": "ricktester/alpha", "visibility": "public", "description": "first"}, {"full_name": "ricktester/beta", "visibility": "private", "description": ""}, }, }) })) } func TestRepoListTable(t *testing.T) { srv := repoListServer(t) defer srv.Close() t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("RICKUB_HOST", srv.URL) t.Setenv("RICKUB_TOKEN", "rickub_pat_test") out, _, err := execute(t, "repo", "list", "--user", "ricktester") if err != nil { t.Fatalf("execute: %v", err) } if !strings.Contains(out, "NAME") || !strings.Contains(out, "VISIBILITY") { t.Errorf("missing table header:\n%s", out) } if !strings.Contains(out, "ricktester/alpha") || !strings.Contains(out, "ricktester/beta") { t.Errorf("missing rows:\n%s", out) } // Empty description rendered as a dash. if !strings.Contains(out, "-") { t.Errorf("expected dash for empty description:\n%s", out) } } func TestRepoListJSONPassthrough(t *testing.T) { srv := repoListServer(t) defer srv.Close() t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("RICKUB_HOST", srv.URL) t.Setenv("RICKUB_TOKEN", "rickub_pat_test") out, _, err := execute(t, "repo", "list", "--user", "ricktester", "--json") if err != nil { t.Fatalf("execute: %v", err) } var decoded struct { Items []struct { FullName string `json:"full_name"` } `json:"items"` } if err := json.Unmarshal([]byte(out), &decoded); err != nil { t.Fatalf("output is not JSON: %v\n%s", err, out) } if len(decoded.Items) != 2 || decoded.Items[0].FullName != "ricktester/alpha" { t.Errorf("unexpected JSON items: %+v", decoded.Items) } } func TestRepoViewNotFoundError(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) w.Write([]byte(`{"error":{"code":"not_found","message":"repository not found"}}`)) })) defer srv.Close() t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("RICKUB_HOST", srv.URL) t.Setenv("RICKUB_TOKEN", "rickub_pat_test") _, _, err := execute(t, "repo", "view", "ghost/repo") if err == nil { t.Fatal("expected error for 404") } if !strings.Contains(err.Error(), "not_found") { t.Errorf("error should surface code: %v", err) } } func TestHumanTime(t *testing.T) { cases := map[string]string{ "": "-", // empty -> dash "2026-07-21T00:07:53.58474Z": "2026-07-21 00:07 UTC", // sub-second RFC3339 "2026-07-21T00:07:53Z": "2026-07-21 00:07 UTC", // whole-second RFC3339 "2026-07-21T02:07:53+02:00": "2026-07-21 00:07 UTC", // offset normalized to UTC "not-a-timestamp": "not-a-timestamp", // unparseable -> unchanged } for in, want := range cases { if got := humanTime(in); got != want { t.Errorf("humanTime(%q) = %q, want %q", in, got, want) } } } // TestRepoViewHumanizesTimestamp verifies the default output humanizes created_at // while --json passes the raw timestamp through unchanged. func TestRepoViewHumanizesTimestamp(t *testing.T) { const raw = "2026-07-21T00:07:53.58474Z" srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"owner":"ricktester","name":"demo","full_name":"ricktester/demo","visibility":"public","default_branch":"main","created_at":"` + raw + `"}`)) })) defer srv.Close() t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("RICKUB_HOST", srv.URL) t.Setenv("RICKUB_TOKEN", "rickub_pat_test") // Default (human) output: humanized, and NOT the raw nanosecond string. out, _, err := execute(t, "repo", "view", "ricktester/demo") if err != nil { t.Fatalf("execute: %v", err) } if !strings.Contains(out, "2026-07-21 00:07 UTC") { t.Errorf("human output not humanized:\n%s", out) } if strings.Contains(out, raw) { t.Errorf("human output still contains the raw timestamp:\n%s", out) } // --json output: raw timestamp preserved verbatim. jsonOut, _, err := execute(t, "repo", "view", "ricktester/demo", "--json") if err != nil { t.Fatalf("execute --json: %v", err) } if !strings.Contains(jsonOut, raw) { t.Errorf("--json output should keep the raw timestamp:\n%s", jsonOut) } } func TestParseOwnerRepo(t *testing.T) { o, r, err := parseOwnerRepo("ricktester/demo.git") if err != nil || o != "ricktester" || r != "demo" { t.Errorf("got %q/%q err=%v", o, r, err) } if _, _, err := parseOwnerRepo("nope"); err == nil { t.Error("expected error for missing slash") } } func TestOwnerRepoFromRemote(t *testing.T) { cases := map[string][2]string{ "http://localhost:8080/ricktester/demo.git": {"ricktester", "demo"}, "ssh://git@localhost:2222/ricktester/demo": {"ricktester", "demo"}, "git@rickub.com:acme/api.git": {"acme", "api"}, } for url, want := range cases { o, r, err := ownerRepoFromRemote(url) if err != nil || o != want[0] || r != want[1] { t.Errorf("%s => %q/%q err=%v, want %v", url, o, r, err, want) } } }