rickub/clipublic Fork 0
main
Commits
Clone
git clone https://git.rickub.com/rickub/cli.git
git clone ssh://git@rickub.com/rickub/cli.git
Initial import of the rickub CLI as a standalone public project 1a1d430Unverified · on main · Olivier Girardot · 8h ago
repo_test.go · 203 lines · 6.3 KBGo Blame HistoryRaw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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)
		}
	}
}