Skip to content
quarry Artifact [d4062b463c]
Login

Artifact [d4062b463c]

Artifact d4062b463cf9e4d0b79cfac9baa743f03ebcbcbbbf295fda51bb6405fffd9bca:


package pickupclient

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func rerunForge(t *testing.T, seen *[]string) *httptest.Server {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		*seen = append(*seen, r.Method+" "+r.URL.RequestURI())
		if r.Header.Get("Authorization") != "Bearer "+apiTestToken {
			w.WriteHeader(401)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		if r.URL.Path == "/api/v1/r/alex/site/ci/runs/old123/rerun" {
			w.Write([]byte(`{"ok":true,"runId":"new456"}`))
			return
		}
		w.WriteHeader(400)
		w.Write([]byte(`{"error":"run is still going","next":{"say":"cancel it first","ask":false}}`))
	}))
	t.Cleanup(srv.Close)
	return srv
}

func runCIRerun(t *testing.T, srv *httptest.Server, 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(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 srv.URL + "/r/alex/site\n", nil
	}
	e.Getenv = func(k string) string {
		if k == envHostVar {
			return srv.URL
		}
		return ""
	}
	code := CIRerun(context.Background(), args, e)
	return code, out.String(), errw.String()
}

// #499: quarry ci rerun posts to the run's rerun route and prints the
// new run's id; a refusal exits 1 and prints no id.
func TestCIRerunPostsToTheRunAndPrintsTheNewID(t *testing.T) {
	var seen []string
	srv := rerunForge(t, &seen)

	code, out, errw := runCIRerun(t, srv, "old123")
	if code != 0 {
		t.Fatalf("FAIL: exit %d (%s)", code, errw)
	}
	if got := seen[len(seen)-1]; got != "POST /api/v1/r/alex/site/ci/runs/old123/rerun" {
		t.Errorf("FAIL: asked %q", got)
	}
	if strings.TrimSpace(out) != "new456" {
		t.Errorf("FAIL: printed %q, want the new run id alone", out)
	}

	seen = nil
	code, out, _ = runCIRerun(t, srv, "old123", "-R", "alex/site", "--json")
	var m map[string]any
	if code != 0 || json.Unmarshal([]byte(out), &m) != nil || m["runId"] != "new456" || m["ok"] != true {
		t.Errorf("FAIL: --json gave %d %q", code, out)
	}

	code, out, _ = runCIRerun(t, srv, "going1")
	if code != 1 || strings.Contains(out, "new456") {
		t.Errorf("FAIL: a refused rerun exits %d printing %q, want 1 and no id", code, out)
	}
	for _, args := range [][]string{{}, {"a", "b"}, {"x/y"}, {"old123", "-R"}, {"old123", "--nope"}} {
		if code, _, _ := runCIRerun(t, srv, args...); code != 2 {
			t.Errorf("FAIL: %v exits %d, want 2", args, code)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}