package pickupclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
// statusForge answers the ops quarry status composes. Landings are
// served exactly as set; the client may not add words to them.
type statusForge struct {
srv *httptest.Server
mu sync.Mutex
landings []map[string]any // landing.get answers, with "author"
rows []map[string]any
paths []string
methods map[string]bool
}
func newStatusForge(t *testing.T) *statusForge {
f := &statusForge{methods: map[string]bool{}}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
f.paths = append(f.paths, r.URL.RequestURI())
f.methods[r.Method] = true
if r.Header.Get("Authorization") != "Bearer "+apiTestToken {
w.WriteHeader(401)
return
}
p := strings.TrimPrefix(r.URL.Path, "/api/v1")
switch {
case p == "/me":
w.Write([]byte(`{"name":"alex","token":{"label":"mac","may":"m","mayNot":[]},"repos":[]}`))
case p == "/r/alex/site/landing":
var ls []map[string]any
for _, l := range f.landings {
lv := l["landing"].(map[string]any)
ls = append(ls, map[string]any{"id": lv["id"], "number": lv["number"], "branch": lv["branch"], "author": lv["author"]})
}
json.NewEncoder(w).Encode(map[string]any{"landings": ls})
case strings.HasPrefix(p, "/r/alex/site/landing/"):
id := strings.TrimPrefix(p, "/r/alex/site/landing/")
for _, l := range f.landings {
if l["landing"].(map[string]any)["id"] == id {
json.NewEncoder(w).Encode(l)
return
}
}
w.WriteHeader(404)
case strings.HasSuffix(p, "/log"):
w.Write([]byte(`{"runId":"9153","status":"failed","steps":[{"step":"s-ok","failed":false,"text":"fine"},{"step":"s-bad","failed":true,"text":"line one\nline two"}]}`))
case p == "/me/inbox":
json.NewEncoder(w).Encode(map[string]any{"rows": f.rows})
default:
w.WriteHeader(404)
}
}))
t.Cleanup(f.srv.Close)
return f
}
func landingAnswer(id string, number int, author, on, say, nextSay, cmd, ci string) map[string]any {
return map[string]any{
"landing": map[string]any{"id": id, "number": number, "branch": "br-" + id, "target": "trunk",
"title": "t", "state": "open", "ci": ci, "author": author},
"checks": []map[string]any{{"runId": "9153", "pipeline": "test"}},
"waiting": map[string]any{"on": on, "say": say, "who": "", "next": map[string]any{"say": nextSay, "cmd": cmd, "ask": false}},
}
}
func (f *statusForge) run(t *testing.T, args ...string) (int, string, string) {
t.Helper()
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, ".zit-checkout"), nil, 0o600)
st := &fakeStore{}
st.Put(strings.TrimPrefix(f.srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, st)
e.Getwd = func() (string, error) { return dir, nil }
e.Run = func(context.Context, string, []string, []string) (string, error) {
return f.srv.URL + "/r/alex/site\n", nil
}
code := Status(context.Background(), args, e)
return code, out.String(), errw.String()
}
func (f *statusForge) object(t *testing.T, args ...string) map[string]any {
t.Helper()
code, out, errw := f.run(t, append(args, "--json")...)
if code != 0 {
t.Fatalf("FAIL: exit %d (%s)", code, errw)
}
var m map[string]any
if err := json.Unmarshal([]byte(out), &m); err != nil || strings.Count(strings.TrimSpace(out), "\n") != 0 {
t.Fatalf("FAIL: stdout is not exactly one object: %q", out)
}
return m
}
var allWaits = []string{"checks", "conflict", "stale", "never_ran", "stack", "protection", "nothing"}
func TestStatusPrintsTheServersWordsForEachState(t *testing.T) {
f := newStatusForge(t)
for i, on := range allWaits {
f.landings = append(f.landings, landingAnswer(fmt.Sprintf("id%d", i), 40+i, "alex", on,
"SAY-"+on, "NEXT-"+on, "run-"+on, ""))
}
code, out, errw := f.run(t)
if code != 0 {
t.Fatalf("FAIL: exit %d (%s)", code, errw)
}
for _, on := range allWaits {
for _, w := range []string{"SAY-" + on, "NEXT-" + on, "run-" + on} {
if !strings.Contains(out, w) {
t.Errorf("FAIL: the forge's %q is not printed", w)
}
}
}
for i := range allWaits {
if !strings.Contains(out, fmt.Sprintf("!%d", 40+i)) {
t.Errorf("FAIL: landing %d is not named", 40+i)
}
}
if strings.Contains(out, apiTestToken) {
t.Errorf("FAIL: the token was printed")
}
if !t.Failed() {
t.Log("ok")
}
}
func TestStatusListsOnlyMyLandingsAndASelectorPicksAnyone(t *testing.T) {
f := newStatusForge(t)
f.landings = []map[string]any{
landingAnswer("a", 41, "alex", "nothing", "SAY-a", "n", "", ""),
landingAnswer("b", 42, "sam", "checks", "SAY-b", "n", "", ""),
}
m := f.object(t)
ls := m["landings"].([]any)
if len(ls) != 1 || ls[0].(map[string]any)["number"].(float64) != 41 {
t.Errorf("FAIL: landings %v", ls)
}
m = f.object(t, "!42")
ls = m["landings"].([]any)
if len(ls) != 1 || ls[0].(map[string]any)["branch"] != "br-b" {
t.Errorf("FAIL: !42 gave %v", ls)
}
m = f.object(t, "br-a")
if ls = m["landings"].([]any); len(ls) != 1 {
t.Errorf("FAIL: a branch selector gave %v", ls)
}
if code, _, _ := f.run(t, "!99"); code != 1 {
t.Errorf("FAIL: an unknown landing exits %d, want 1", code)
}
}
func TestStatusJSONShape(t *testing.T) {
f := newStatusForge(t)
f.landings = []map[string]any{landingAnswer("a", 41, "alex", "checks", "SAY", "NEXT", "quarry status !41 --log", "ci-fail")}
m := f.object(t)
for _, k := range []string{"ok", "host", "repo", "account", "landings", "inbox", "next"} {
if _, ok := m[k]; !ok {
t.Errorf("FAIL: no key %q in %v", k, m)
}
}
if m["ok"] != true || m["repo"] != "alex/site" || m["account"] != "alex" {
t.Errorf("FAIL: %v", m)
}
l := m["landings"].([]any)[0].(map[string]any)
for _, k := range []string{"number", "id", "branch", "target", "title", "state", "ci", "waiting"} {
if _, ok := l[k]; !ok {
t.Errorf("FAIL: landing has no key %q", k)
}
}
w := l["waiting"].(map[string]any)
for _, k := range []string{"on", "say", "who", "next"} {
if _, ok := w[k]; !ok {
t.Errorf("FAIL: waiting has no key %q", k)
}
}
if n := m["next"].(map[string]any); n["say"] != "NEXT" {
t.Errorf("FAIL: top next is %v, want the first landing's", n)
}
in := m["inbox"].(map[string]any)
if _, ok := in["unread"]; !ok || in["rows"] == nil {
t.Errorf("FAIL: inbox %v", in)
}
}
func inboxRow(id, repo string, read bool) map[string]any {
return map[string]any{"id": id, "reason": "mention", "repo": repo, "from": "sam", "summary": "S-" + id,
"link": "/r/" + repo + "/x", "at": "t", "read": read}
}
func TestStatusEmptyInboxAndNothingWaiting(t *testing.T) {
f := newStatusForge(t)
m := f.object(t)
in := m["inbox"].(map[string]any)
if rows := in["rows"].([]any); len(rows) != 0 || in["unread"].(float64) != 0 {
t.Errorf("FAIL: inbox %v", in)
}
if ls := m["landings"].([]any); ls == nil || len(ls) != 0 {
t.Errorf("FAIL: landings %v", m["landings"])
}
f.rows = []map[string]any{inboxRow("r1", "alex/site", true)}
code, out, _ := f.run(t)
if code != 0 || strings.Contains(out, "S-r1") {
t.Errorf("FAIL: exit %d; a read row was listed: %q", code, out)
}
if m = f.object(t); m["inbox"].(map[string]any)["unread"].(float64) != 0 {
t.Errorf("FAIL: a read row counted as unread")
}
}
func TestStatusInboxIsCappedAtFiveThisRepositorysFirstAndNeverMarksRead(t *testing.T) {
f := newStatusForge(t)
for i := 0; i < 4; i++ {
f.rows = append(f.rows, inboxRow(fmt.Sprintf("o%d", i), "sam/other", false))
}
f.rows = append(f.rows, inboxRow("done", "alex/site", true))
for i := 0; i < 3; i++ {
f.rows = append(f.rows, inboxRow(fmt.Sprintf("h%d", i), "alex/site", false))
}
m := f.object(t)
in := m["inbox"].(map[string]any)
rows := in["rows"].([]any)
if len(rows) != 5 || in["unread"].(float64) != 7 {
t.Fatalf("FAIL: %d rows, unread %v", len(rows), in["unread"])
}
for i := 0; i < 3; i++ {
if r := rows[i].(map[string]any); r["repo"] != "alex/site" {
t.Errorf("FAIL: row %d is %v, this repository's come first", i, r["repo"])
}
}
for _, r := range rows {
if r.(map[string]any)["id"] == "done" {
t.Errorf("FAIL: a read row is listed")
}
}
_, out, _ := f.run(t)
if strings.Count(out, "S-") != 5 || !strings.Contains(out, "/r/alex/site/x") {
t.Errorf("FAIL: text lists %d rows: %q", strings.Count(out, "S-"), out)
}
for _, p := range f.paths {
if strings.Contains(p, "mark") {
t.Errorf("FAIL: %s was called", p)
}
}
if len(f.methods) != 1 || !f.methods["GET"] {
t.Errorf("FAIL: methods used %v, want GET only", f.methods)
}
}
func TestStatusLogPrintsFailedStepsOnly(t *testing.T) {
f := newStatusForge(t)
f.landings = []map[string]any{landingAnswer("a", 41, "alex", "checks", "SAY", "NEXT", "", "ci-fail")}
_, out, _ := f.run(t)
if strings.Contains(out, "line one") {
t.Errorf("FAIL: a log without --log")
}
m := f.object(t, "--log")
logs := m["landings"].([]any)[0].(map[string]any)["logs"].([]any)
if len(logs) != 1 || logs[0].(map[string]any)["step"] != "s-bad" || logs[0].(map[string]any)["runId"] != "9153" {
t.Errorf("FAIL: logs %v", logs)
}
_, out, _ = f.run(t, "--log")
if !strings.Contains(out, "line two") || strings.Contains(out, "fine") {
t.Errorf("FAIL: log text %q", out)
}
if !strings.Contains(strings.Join(f.paths, " "), "tail=20") {
t.Errorf("FAIL: the log was not asked for a tail")
}
}
func TestStatusErrors(t *testing.T) {
f := newStatusForge(t)
if code, _, _ := f.run(t, "--nope"); code != 2 {
t.Errorf("FAIL: usage exits %d", code)
}
if code, _, _ := f.run(t, "a", "b"); code != 2 {
t.Errorf("FAIL: two selectors exit %d", code)
}
// No login: exit 4 and nothing sent.
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, ".zit-checkout"), nil, 0o600)
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, &fakeStore{})
e.Getwd = func() (string, error) { return dir, nil }
e.Run = func(context.Context, string, []string, []string) (string, error) {
return f.srv.URL + "/r/alex/site\n", nil
}
f.paths = nil
if code := Status(context.Background(), nil, e); code != 4 || len(f.paths) != 0 {
t.Errorf("FAIL: no login exits %d with %d calls", code, len(f.paths))
}
// Not a checkout: refused before any call.
e.Getwd = func() (string, error) { return t.TempDir(), nil }
if code := Status(context.Background(), nil, e); code != 1 || len(f.paths) != 0 {
t.Errorf("FAIL: no checkout exits %d", code)
}
}