package pickupclient
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
const apiTestToken = "tok_api_test_value"
type apiForge struct {
srv *httptest.Server
mu sync.Mutex
method string
uri string
auth string
ctype string
body string
hits int
status int
reply string
}
func newAPIForge(t *testing.T) *apiForge {
f := &apiForge{status: 200, reply: `{"ok":true,"say":"café \"q\""}`}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
if strings.HasSuffix(r.URL.Path, "/events/stream") {
return
}
b, _ := io.ReadAll(r.Body)
f.method, f.uri, f.auth, f.ctype, f.body = r.Method, r.URL.RequestURI(), r.Header.Get("Authorization"), r.Header.Get("Content-Type"), string(b)
f.hits++
w.WriteHeader(f.status)
io.WriteString(w, f.reply)
}))
t.Cleanup(f.srv.Close)
return f
}
func (f *apiForge) env(t *testing.T, out, errw *bytes.Buffer, stdin string) *Env {
st := &fakeStore{}
st.Put(strings.TrimPrefix(f.srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
e := loginEnv(t, out, errw, st)
e.Stdin = strings.NewReader(stdin)
return e
}
func (f *apiForge) run(t *testing.T, stdin string, args ...string) (int, string, string) {
var out, errw bytes.Buffer
code := API(context.Background(), append([]string{"--host", f.srv.URL}, args...), f.env(t, &out, &errw, stdin))
return code, out.String(), errw.String()
}
func pretty(t *testing.T, raw string) string {
var b bytes.Buffer
if err := json.Indent(&b, []byte(raw), "", " "); err != nil {
t.Fatal(err)
}
return b.String() + "\n"
}
func TestAPIStdoutIsExactlyTheBodyIndentedAndTokenIsABearer(t *testing.T) {
f := newAPIForge(t)
code, out, errw := f.run(t, "", "GET", "/r/alex/site/landing")
if code != 0 || out != pretty(t, f.reply) || errw != "" {
t.Errorf("FAIL: exit %d stdout %q stderr %q", code, out, errw)
}
if f.method != "GET" || f.uri != "/api/v1/r/alex/site/landing" || f.auth != "Bearer "+apiTestToken {
t.Errorf("FAIL: request %s %s %q", f.method, f.uri, f.auth)
}
if strings.Contains(out+errw, apiTestToken) {
t.Errorf("FAIL: the token was printed")
}
}
func TestAPIBodiesRoundTripThroughFileAndStdin(t *testing.T) {
text := "line one\n\"quoted\" and 'single'\ttab\n\\back\\slash\nnaïve 日本語 🚀\n\nlast"
f := newAPIForge(t)
file := filepath.Join(t.TempDir(), "body.md")
os.WriteFile(file, []byte(text), 0o600)
for name, c := range map[string]struct{ stdin, arg string }{
"file": {"", "body=@" + file},
"stdin": {text, "body=@-"},
} {
if code, _, errw := f.run(t, c.stdin, "POST", "/r/alex/site/forum", "-f", "title=T", "-f", c.arg); code != 0 {
t.Fatalf("FAIL: %s exit %d %s", name, code, errw)
}
var got map[string]any
if err := json.Unmarshal([]byte(f.body), &got); err != nil || got["body"] != text || got["title"] != "T" || len(got) != 2 {
t.Errorf("FAIL: %s body %q (%v)", name, f.body, err)
}
if f.ctype != "application/json" || f.method != "POST" {
t.Errorf("FAIL: %s %s %q", name, f.method, f.ctype)
}
}
}
func TestAPITypedFields(t *testing.T) {
f := newAPIForge(t)
code, _, errw := f.run(t, "", "POST", "/x", "-f", "n:=3", "-f", "b:=true", "-f", `a:=[1,"x"]`, "-f", `o:={"k":null}`, "-f", "s=3", "-f", "z:=null")
if code != 0 {
t.Fatalf("FAIL: %d %s", code, errw)
}
var got map[string]any
json.Unmarshal([]byte(f.body), &got)
arr, _ := got["a"].([]any)
obj, _ := got["o"].(map[string]any)
if got["n"] != float64(3) || got["b"] != true || len(arr) != 2 || arr[1] != "x" || obj == nil || got["s"] != "3" {
t.Errorf("FAIL: %v", got)
}
if _, ok := got["z"]; !ok {
t.Errorf("FAIL: null field dropped: %v", got)
}
if code, _, _ := f.run(t, "", "POST", "/x", "-f", "n:=nope"); code != 2 {
t.Errorf("FAIL: bad JSON exit %d", code)
}
}
func TestAPIGetFieldsAreAProperlyEncodedQuery(t *testing.T) {
f := newAPIForge(t)
code, _, errw := f.run(t, "", "GET", "/search?x=1", "-f", "q=a b&c=d#e é", "-f", "n:=2", "-f", `k:=["a","b"]`)
if code != 0 {
t.Fatalf("FAIL: %d %s", code, errw)
}
if f.method != "GET" || f.body != "" {
t.Errorf("FAIL: %s body %q", f.method, f.body)
}
u := "http://x" + f.uri
pu, _ := url.Parse(u)
q := pu.Query()
if pu.Path != "/api/v1/search" || q.Get("x") != "1" || q.Get("q") != "a b&c=d#e é" || q.Get("n") != "2" || strings.Join(q["k"], ",") != "a,b" {
t.Errorf("FAIL: %s", f.uri)
}
if strings.ContainsAny(strings.SplitN(f.uri, "?", 2)[1], " #é") {
t.Errorf("FAIL: query not encoded: %s", f.uri)
}
}
func TestAPIUsageErrorsExit2AndSendNothing(t *testing.T) {
f := newAPIForge(t)
for name, args := range map[string][]string{
"f with d": {"POST", "/x", "-f", "a=b", "-d", "{}"},
"d not json": {"POST", "/x", "-d", "nope"},
"d on get": {"GET", "/x", "-d", "{}"},
"no path": {"GET"},
"bad method": {"FETCH", "/x"},
"unknown flag": {"GET", "/x", "--as", "bot"},
"stdin twice": {"POST", "/x", "-f", "a=@-", "-f", "b=@-"},
"missing file": {"POST", "/x", "-f", "a=@/no/such/file"},
"field no name": {"POST", "/x", "-f", "=v"},
} {
if code, out, _ := f.run(t, "", args...); code != 2 || out != "" {
t.Errorf("FAIL: %s exit %d stdout %q", name, code, out)
}
}
if f.hits != 0 {
t.Errorf("FAIL: %d requests were sent", f.hits)
}
}
func TestAPIStdinIsReadOnlyWhenAsked(t *testing.T) {
f := newAPIForge(t)
var out, errw bytes.Buffer
e := f.env(t, &out, &errw, "")
e.Stdin = failReader{t}
if code := API(context.Background(), []string{"--host", f.srv.URL, "POST", "/x", "-f", "a=b"}, e); code != 0 {
t.Errorf("FAIL: exit %d", code)
}
if code := API(context.Background(), []string{"--host", f.srv.URL, "GET", "/x"}, e); code != 0 {
t.Errorf("FAIL: exit %d", code)
}
}
type failReader struct{ t *testing.T }
func (r failReader) Read([]byte) (int, error) {
r.t.Error("FAIL: standard input was read")
return 0, io.EOF
}
func TestAPIDataFromFileAndStdin(t *testing.T) {
f := newAPIForge(t)
file := filepath.Join(t.TempDir(), "d.json")
os.WriteFile(file, []byte(`{"a":"é"}`), 0o600)
if code, _, _ := f.run(t, "", "POST", "/x", "-d", "@"+file); code != 0 || f.body != `{"a":"é"}` {
t.Errorf("FAIL: %d %q", code, f.body)
}
if code, _, _ := f.run(t, `{"b":1}`, "POST", "/x", "-d", "-"); code != 0 || f.body != `{"b":1}` {
t.Errorf("FAIL: %d %q", code, f.body)
}
}
func TestAPIPathSmugglingIsRefused(t *testing.T) {
f := newAPIForge(t)
for _, p := range []string{
"http://evil.example/x", "https://evil.example/", "//evil.example/x", "x/y", "",
"/../me", "/r/../../x", "/r/%2e%2e/x", "/r/%2E%2e/x", "/a/./b", `/a\b`, "/x#frag",
"/x\r\nHost: evil", "/x\x1b[2J", "/r%5c..%5cx", "/a b",
} {
if code, out, _ := f.run(t, "", "GET", p); code != 2 || out != "" {
t.Errorf("FAIL: %q exit %d", p, code)
}
}
if f.hits != 0 {
t.Errorf("FAIL: %d requests were sent", f.hits)
}
// A path that merely looks odd stays on the forge.
if code, _, _ := f.run(t, "", "GET", "/r/a/b/x?u=http://evil.example"); code != 0 || !strings.HasPrefix(f.uri, "/api/v1/r/a/b/x?") {
t.Errorf("FAIL: %d %s", code, f.uri)
}
}
func TestAPIRedirectIsRefusedAndTheTokenNeverFollows(t *testing.T) {
var elsewhere int
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { elsewhere++ }))
defer other.Close()
redir := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, other.URL+"/steal", http.StatusFound)
}))
defer redir.Close()
st := &fakeStore{}
st.Put(strings.TrimPrefix(redir.URL, "http://"), Record{Token: apiTestToken})
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, st)
code := API(context.Background(), []string{"--host", redir.URL, "GET", "/x"}, e)
if code != 1 || elsewhere != 0 || out.Len() != 0 || strings.Contains(errw.String(), apiTestToken) {
t.Errorf("FAIL: exit %d followed %d stdout %q", code, elsewhere, out.String())
}
}
func TestAPIExitCodes(t *testing.T) {
f := newAPIForge(t)
f.status, f.reply = 404, `{"code":"not_found","error":"no such thing","next":{"say":"Look it up.","cmd":"quarry api GET /","ask":false}}`
code, out, errw := f.run(t, "", "GET", "/x")
if code != 1 || out != pretty(t, f.reply) || !strings.Contains(errw, "quarry api GET /") || !strings.Contains(errw, "Look it up.") {
t.Errorf("FAIL: 4xx exit %d stdout %q stderr %q", code, out, errw)
}
// --json: the body is on stdout, and stderr says nothing.
code, out, errw = f.run(t, "", "GET", "/x", "--json")
if code != 1 || out != pretty(t, f.reply) || errw != "" {
t.Errorf("FAIL: --json exit %d stderr %q", code, errw)
}
f.status, f.reply = 401, `{"code":"no_login","error":"sign in","next":{"say":"Log in.","cmd":"quarry auth login","ask":false}}`
if code, _, _ := f.run(t, "", "GET", "/x"); code != 4 {
t.Errorf("FAIL: forge no_login exit %d", code)
}
f.status, f.reply = 204, ``
if code, out, _ := f.run(t, "", "DELETE", "/x"); code != 0 || out != "" {
t.Errorf("FAIL: 204 exit %d %q", code, out)
}
f.status, f.reply = 200, `plain text`
if code, out, _ := f.run(t, "", "GET", "/x"); code != 0 || out != "plain text\n" {
t.Errorf("FAIL: text exit %d %q", code, out)
}
}
func TestAPIWithNoLoginExits4AndSendsNothing(t *testing.T) {
f := newAPIForge(t)
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, &fakeStore{})
if code := API(context.Background(), []string{"--host", f.srv.URL, "GET", "/x"}, e); code != 4 || out.Len() != 0 || !strings.Contains(errw.String(), "quarry auth login") {
t.Errorf("FAIL: exit %d stdout %q stderr %q", code, out.String(), errw.String())
}
out.Reset()
e = loginEnv(t, &out, &errw, &fakeStore{})
code := API(context.Background(), []string{"--host", f.srv.URL, "GET", "/x", "--json"}, e)
m := oneObject(t, out.String())
if code != 4 || m["ok"] != false || m["code"] != "no_login" || nextOf(m)["cmd"] != "quarry auth login" || f.hits != 0 {
t.Errorf("FAIL: exit %d %v hits %d", code, m, f.hits)
}
}
const browserOnlyReply = `{"code":"browser_only","error":"a token does not change branch protection","next":{"say":"Change it signed in at a browser.","open":"/r/alex/site/settings","ask":false}}`
func TestAPIBrowserOnlyRendersOpenAndOpensOnlyOnATerminalOnTheSameOrigin(t *testing.T) {
f := newAPIForge(t)
f.status, f.reply = 403, browserOnlyReply
code, out, errw := f.run(t, "", "POST", "/r/alex/site/branch/protection", "-d", "{}")
if code != 1 || out != pretty(t, f.reply) || !strings.Contains(errw, "/r/alex/site/settings") {
t.Errorf("FAIL: exit %d stdout %q stderr %q", code, out, errw)
}
var opened []string
run := func(tty bool, reply string) {
opened = nil
f.reply = reply
var o, er bytes.Buffer
e := f.env(t, &o, &er, "")
e.IsTerminal = func(io.Writer) bool { return tty }
e.Open = func(u string) error { opened = append(opened, u); return nil }
API(context.Background(), []string{"--host", f.srv.URL, "--open", "POST", "/x", "-d", "{}"}, e)
}
run(false, browserOnlyReply)
if len(opened) != 0 {
t.Errorf("FAIL: opened with no terminal: %v", opened)
}
run(true, browserOnlyReply)
if len(opened) != 1 || opened[0] != f.srv.URL+"/r/alex/site/settings" {
t.Errorf("FAIL: opened %v", opened)
}
run(true, strings.Replace(browserOnlyReply, "/r/alex/site/settings", "https://evil.example/x", 1))
if len(opened) != 0 {
t.Errorf("FAIL: opened another origin: %v", opened)
}
}
func TestAPIWaitRetriesWhenTheRepositoryEventsChange(t *testing.T) {
var mu sync.Mutex
changed := false
var streamPath, streamAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/events/stream") {
streamPath, streamAuth = r.URL.Path, r.Header.Get("Authorization")
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "event: live\ndata: {}\n\n")
w.(http.Flusher).Flush()
time.Sleep(50 * time.Millisecond)
mu.Lock()
changed = true
mu.Unlock()
io.WriteString(w, ": keepalive\n\nid: 5\ndata: {\"kind\":\"settings.changed\"}\n\n")
w.(http.Flusher).Flush()
return
}
mu.Lock()
defer mu.Unlock()
if !changed {
w.WriteHeader(403)
io.WriteString(w, browserOnlyReply)
return
}
io.WriteString(w, `{"ok":true}`)
}))
defer srv.Close()
st := &fakeStore{}
st.Put(strings.TrimPrefix(srv.URL, "http://"), Record{Token: apiTestToken})
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, st)
code := API(context.Background(), []string{"--host", srv.URL, "--wait", "POST", "/r/alex/site/branch/protection", "-d", "{}"}, e)
if code != 0 || out.String() != pretty(t, `{"ok":true}`) {
t.Errorf("FAIL: exit %d stdout %q stderr %q", code, out.String(), errw.String())
}
if streamPath != "/api/v1/r/alex/site/events/stream" || streamAuth != "Bearer "+apiTestToken {
t.Errorf("FAIL: stream %s %q", streamPath, streamAuth)
}
}
func TestAPIWaitThatRunsOutExits3(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/events/stream") {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "event: live\ndata: {}\n\n")
w.(http.Flusher).Flush()
<-r.Context().Done()
return
}
w.WriteHeader(403)
io.WriteString(w, browserOnlyReply)
}))
defer srv.Close()
st := &fakeStore{}
st.Put(strings.TrimPrefix(srv.URL, "http://"), Record{Token: apiTestToken})
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, st)
e.WaitMax = 150 * time.Millisecond
if code := API(context.Background(), []string{"--host", srv.URL, "--wait", "POST", "/r/a/b/x", "-d", "{}"}, e); code != 3 {
t.Errorf("FAIL: exit %d stderr %q", code, errw.String())
}
}
func TestAPIEncodedPathsAreSentAsWritten(t *testing.T) {
f := newAPIForge(t)
for in, want := range map[string]string{
"/wiki/My%20Page": "/api/v1/wiki/My%20Page",
"/wiki/caf%C3%A9": "/api/v1/wiki/caf%C3%A9",
"/wiki/café": "/api/v1/wiki/caf%C3%A9",
"/wiki/a%3Fb": "/api/v1/wiki/a%3Fb",
"/wiki/日本語?x=a%20b": "/api/v1/wiki/%E6%97%A5%E6%9C%AC%E8%AA%9E?x=a%20b",
} {
if code, _, errw := f.run(t, "", "GET", in); code != 0 || f.uri != want {
t.Errorf("FAIL: %q exit %d sent %q want %q (%s)", in, code, f.uri, want, errw)
}
}
// A %2F inside a segment is refused, not sent: it would name another path.
before := f.hits
for _, p := range []string{"/wiki/a%2Fb", "/wiki/a%2fb", "/wiki/%2e%2e%2fx"} {
if code, _, _ := f.run(t, "", "GET", p); code != 2 {
t.Errorf("FAIL: %q exit %d", p, code)
}
}
if f.hits != before {
t.Errorf("FAIL: an encoded slash was sent")
}
}
type repoForge struct {
*apiForge
remote string
}
func (f repoForge) runIn(t *testing.T, args ...string) (int, string) {
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, ".zit-checkout"), nil, 0o600)
var out, errw bytes.Buffer
e := f.env(t, &out, &errw, "")
e.Getwd = func() (string, error) { return dir, nil }
e.Run = func(context.Context, string, []string, []string) (string, error) { return f.remote + "\n", nil }
return API(context.Background(), args, e), errw.String()
}
func TestAPIFillsRepoFromTheCheckoutAndRefusesOddNames(t *testing.T) {
f := newAPIForge(t)
f.reply = `{"name":"site","handle":"site","namespace":"alex","address":"alex/site"}`
rf := repoForge{f, f.srv.URL + "/r/alex/site"}
// A namespaced remote is resolved to the forge's key.
if code, errw := rf.runIn(t, "GET", "/r/{repo}/landing"); code != 0 || f.uri != "/api/v1/r/site/landing" {
t.Errorf("FAIL: exit %d sent %q (%s)", code, f.uri, errw)
}
// A flat remote is the key, and costs no lookup.
f.hits = 0
rf.remote = f.srv.URL + "/r/site"
if code, errw := rf.runIn(t, "GET", "/r/{repo}/landing"); code != 0 || f.uri != "/api/v1/r/site/landing" || f.hits != 1 {
t.Errorf("FAIL: flat: exit %d sent %q, %d calls (%s)", code, f.uri, f.hits, errw)
}
rf.remote = f.srv.URL + "/r/alex/site"
f.hits = 0
for _, tail := range []string{"/r/alex/site%3Fx=1", "/r/alex/site%2Fmore", "/r/alex/.site", "/r/alex/s%20x", "/r/a%2e%2e/site"} {
rf.remote = f.srv.URL + tail
code, errw := rf.runIn(t, "GET", "/r/{repo}/landing")
if code != 2 || errw == "" {
t.Errorf("FAIL: %q exit %d stderr %q", tail, code, errw)
}
}
if f.hits != 0 {
t.Errorf("FAIL: %d requests were sent", f.hits)
}
}
func TestAPITokenIsNeverSentToAnotherHost(t *testing.T) {
a, b := newAPIForge(t), newAPIForge(t)
st := &fakeStore{}
st.Put(strings.TrimPrefix(a.srv.URL, "http://"), Record{Token: apiTestToken})
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, st)
e.Getenv = envOf(map[string]string{"QUARRY_TOKEN": "env-token-for-a", "QUARRY_HOST": a.srv.URL})
if code := API(context.Background(), []string{"--host", b.srv.URL, "GET", "/x"}, e); code != 4 || b.hits != 0 {
t.Errorf("FAIL: exit %d, other forge saw %d requests (auth %q)", code, b.hits, b.auth)
}
// With the environment's host, the environment's token goes to it.
if code := API(context.Background(), []string{"GET", "/x"}, e); code != 0 || a.auth != "Bearer env-token-for-a" {
t.Errorf("FAIL: exit %d auth %q", code, a.auth)
}
}
func TestAPIWaitHasOneOverallDeadline(t *testing.T) {
var mu sync.Mutex
posts := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/events/stream") {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "event: live\ndata: {}\n\n")
w.(http.Flusher).Flush()
for r.Context().Err() == nil {
io.WriteString(w, "data: {\"kind\":\"landing.updated\"}\n\n")
w.(http.Flusher).Flush()
time.Sleep(10 * time.Millisecond)
}
return
}
mu.Lock()
posts++
mu.Unlock()
w.WriteHeader(403)
io.WriteString(w, browserOnlyReply)
}))
defer srv.Close()
st := &fakeStore{}
st.Put(strings.TrimPrefix(srv.URL, "http://"), Record{Token: apiTestToken})
for _, asJSON := range []bool{false, true} {
var out, errw bytes.Buffer
e := loginEnv(t, &out, &errw, st)
e.WaitMax = 300 * time.Millisecond
args := []string{"--host", srv.URL, "--wait", "POST", "/r/a/b/x", "-d", "{}"}
if asJSON {
args = append(args, "--json")
}
start := time.Now()
code := API(context.Background(), args, e)
if code != 3 || time.Since(start) > 3*time.Second {
t.Errorf("FAIL: json=%v exit %d after %v", asJSON, code, time.Since(start))
}
if asJSON && errw.Len() != 0 {
t.Errorf("FAIL: --json wrote to stderr: %q", errw.String())
}
if !asJSON && !strings.Contains(errw.String(), "still waiting") {
t.Errorf("FAIL: no waiting line: %q", errw.String())
}
}
if posts < 3 {
t.Errorf("FAIL: the call was retried %d times", posts)
}
}
func TestAPITerminalOutputIsCleanedAndAFileIsNot(t *testing.T) {
f := newAPIForge(t)
f.reply = "{\"a\":\"x\u0085y\u202ez\"}"
run := func(tty bool) string {
var out, errw bytes.Buffer
e := f.env(t, &out, &errw, "")
e.IsTerminal = func(io.Writer) bool { return tty }
API(context.Background(), []string{"--host", f.srv.URL, "GET", "/x"}, e)
return out.String()
}
if got := run(false); got != pretty(t, f.reply) {
t.Errorf("FAIL: piped output changed: %q", got)
}
if got := run(true); strings.ContainsAny(got, "\u0085\u202e") || !strings.Contains(got, "\n \"a\"") {
t.Errorf("FAIL: terminal output %q", got)
}
f.reply = "plain \x1b[2Jtext"
if got := run(true); strings.Contains(got, "\x1b") || got != "plain text\n" {
t.Errorf("FAIL: terminal text %q", got)
}
}
func TestAPIAnswerOverTheLimitIsRefusedNotCut(t *testing.T) {
old := apiBodyLimit
apiBodyLimit = 64
defer func() { apiBodyLimit = old }()
f := newAPIForge(t)
f.reply = `{"x":"` + strings.Repeat("a", 200) + `"}`
code, out, errw := f.run(t, "", "GET", "/x")
if code != 1 || out != "" || errw == "" {
t.Errorf("FAIL: exit %d stdout %q stderr %q", code, out, errw)
}
f.reply = `{"x":"y"}`
if code, _, _ := f.run(t, "", "GET", "/x"); code != 0 {
t.Errorf("FAIL: small answer exit %d", code)
}
}
type syncBuf struct {
mu sync.Mutex
b bytes.Buffer
}
func (s *syncBuf) Write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.Write(p)
}
func (s *syncBuf) String() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.String()
}
func streamEnv(t *testing.T, srv *httptest.Server, out, errw io.Writer) *Env {
st := &fakeStore{}
st.Put(strings.TrimPrefix(srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
var ob, eb bytes.Buffer
e := loginEnv(t, &ob, &eb, st)
e.Stdout, e.Stderr = out, errw
e.Client = &http.Client{Timeout: 50 * time.Millisecond}
return e
}
func waitFor(t *testing.T, what string, ok func() bool) {
t.Helper()
dl := time.Now().Add(5 * time.Second)
for !ok() {
if time.Now().After(dl) {
t.Fatalf("FAIL: timed out waiting for %s", what)
}
time.Sleep(2 * time.Millisecond)
}
}
func TestAPIStreamPrintsEventsAsTheyArriveAndKeepsLiveOffStdout(t *testing.T) {
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, ": keepalive\n\nevent: live\ndata: {}\n\nid: 7\nevent: ci.completed\ndata: {\"runId\": 9}\n\n")
w.(http.Flusher).Flush()
select {
case <-release:
case <-r.Context().Done():
}
}))
defer srv.Close()
var out, errw syncBuf
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
done := make(chan int, 1)
go func() {
done <- API(ctx, []string{"--host", srv.URL, "GET", "/events/stream"}, streamEnv(t, srv, &out, &errw))
}()
waitFor(t, "the first event on stdout", func() bool { return out.String() != "" })
if got := out.String(); got != "{\"runId\":9}\n" {
t.Errorf("FAIL: stdout %q", got)
}
if strings.Contains(out.String(), "live") || !strings.Contains(errw.String(), "live") {
t.Errorf("FAIL: live reached stdout or not stderr: %q / %q", out.String(), errw.String())
}
cancel()
close(release)
select {
case code := <-done:
if code != 0 {
t.Errorf("FAIL: exit %d on cancel", code)
}
case <-time.After(5 * time.Second):
t.Fatal("FAIL: stream did not end on cancel")
}
if !t.Failed() {
t.Log("ok")
}
}
func TestAPIStreamReconnectsWithLastEventID(t *testing.T) {
var mu sync.Mutex
var seen []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
seen = append(seen, r.Header.Get("Last-Event-ID")+"|"+r.Header.Get("Authorization"))
n := len(seen)
mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
if n == 1 {
io.WriteString(w, "id: 41\nevent: a\ndata: {\"n\":1}\n\nid: 42\nevent: a\ndata: {\"n\":2}\n\n")
return // the drop
}
io.WriteString(w, "id: 43\nevent: a\ndata: {\"n\":3}\n\n")
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
defer srv.Close()
var out, errw syncBuf
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
done := make(chan int, 1)
go func() {
done <- API(ctx, []string{"--host", srv.URL, "GET", "/r/alex/site/events/stream"}, streamEnv(t, srv, &out, &errw))
}()
waitFor(t, "the event after the drop", func() bool { return strings.Contains(out.String(), `"n":3`) })
cancel()
<-done
if got := out.String(); got != "{\"n\":1}\n{\"n\":2}\n{\"n\":3}\n" {
t.Errorf("FAIL: stdout %q", got)
}
mu.Lock()
defer mu.Unlock()
if len(seen) < 2 || seen[0] != "|Bearer "+apiTestToken || seen[1] != "42|Bearer "+apiTestToken {
t.Errorf("FAIL: requests %q", seen)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestAPIStreamRefusalOnReconnectExitsOne(t *testing.T) {
var mu sync.Mutex
hits := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
hits++
n := hits
mu.Unlock()
if n == 1 {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "id: 1\ndata: {\"n\":1}\n\n")
return
}
w.WriteHeader(403)
io.WriteString(w, `{"code":"forbidden","error":"no"}`)
}))
defer srv.Close()
var out, errw syncBuf
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if code := API(ctx, []string{"--host", srv.URL, "GET", "/events/stream"}, streamEnv(t, srv, &out, &errw)); code != 1 {
t.Errorf("FAIL: exit %d", code)
}
if !t.Failed() {
t.Log("ok")
}
}
// askForge answers a browser-only call with a 202 request when Quarry-Ask
// is sent, then reports the request pending a few polls and then final.
type askForge struct {
srv *httptest.Server
mu sync.Mutex
askHdr string
final string
polls int
pendFor int
askedOps int
}
func newAskForge(t *testing.T, final string) *askForge {
f := &askForge{final: final, pendFor: 2}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
switch {
case r.Method == "POST":
f.askHdr = r.Header.Get("Quarry-Ask")
if f.askHdr == "" {
w.WriteHeader(403)
io.WriteString(w, `{"code":"browser_only","error":"for a browser"}`)
return
}
f.askedOps++
w.WriteHeader(202)
io.WriteString(w, `{"signoff":{"id":"S1","state":"pending"}}`)
case r.URL.Path == "/api/v1/signoffs/S1":
f.polls++
state := "pending"
if f.polls > f.pendFor {
state = f.final
}
io.WriteString(w, `{"request":{"id":"S1","state":"`+state+`"},"result":{"ok":true}}`)
}
}))
t.Cleanup(f.srv.Close)
return f
}
func (f *askForge) run(t *testing.T, args ...string) (int, string, string) {
var out, errw bytes.Buffer
st := &fakeStore{}
st.Put(strings.TrimPrefix(f.srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
e := loginEnv(t, &out, &errw, st)
code := API(context.Background(), append([]string{"--host", f.srv.URL}, args...), e)
return code, out.String(), errw.String()
}
func TestAPIAskSendsTheHeaderAndWaitsForApproval(t *testing.T) {
f := newAskForge(t, "approved")
code, out, errw := f.run(t, "POST", "/r/a/b/ci/required-checks", "-f", "branch=trunk", "--ask", "gate trunk")
if code != 0 || f.askHdr != "gate trunk" || f.polls < 3 {
t.Errorf("FAIL: exit %d header %q polls %d stderr %q", code, f.askHdr, f.polls, errw)
}
if !strings.Contains(errw, f.srv.URL+"/me/signoffs/S1") || !strings.Contains(out, `"approved"`) {
t.Errorf("FAIL: page not named or result not printed: out %q err %q", out, errw)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestAPIAskDeniedExitsOne(t *testing.T) {
f := newAskForge(t, "denied")
code, out, _ := f.run(t, "POST", "/r/a/b/ci/required-checks", "--ask", "why")
if code != 1 || !strings.Contains(out, `"denied"`) {
t.Errorf("FAIL: exit %d out %q", code, out)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestAPIAskGivesUpAtItsDeadline(t *testing.T) {
f := newAskForge(t, "approved")
f.pendFor = 1 << 30
code, _, _ := f.run(t, "POST", "/r/a/b/ci/required-checks", "--ask", "why", "--ask-wait", "50ms")
if code != 3 {
t.Errorf("FAIL: exit %d", code)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestAPIBrowserOnlyWithoutAskSaysAskWorks(t *testing.T) {
f := newAskForge(t, "approved")
code, _, errw := f.run(t, "POST", "/r/a/b/ci/required-checks")
if code != 1 || !strings.Contains(errw, "--ask") || f.askedOps != 0 {
t.Errorf("FAIL: exit %d asked %d stderr %q", code, f.askedOps, errw)
}
if !t.Failed() {
t.Log("ok")
}
}