Skip to content
quarry Artifact [1639c4ed81]
Login

Artifact [1639c4ed81]

Artifact 1639c4ed81ec5e1de725c5fb95412f9fdc37c4118a2bbc01bf3c00197e5bcc7b:


package api

import (
	"context"
	"errors"
	"testing"

	"craftdesign.group/quarry/internal/ops"
)

// #499: ci.rerun is an admin command at its own route, and answers with
// the new run's id from the engine hook. A refusal from the hook is the
// caller's refusal, unchanged.
func TestCIRerunIsAnAdminCommandThatReturnsTheNewRun(t *testing.T) {
	var asked [3]string
	d := Deps{Version: "v", Repos: testRepos(wikiIndex(t)),
		CIRerun: func(repo, runID, by string) (string, error) {
			asked = [3]string{repo, runID, by}
			if runID == "going" {
				return "", ops.ErrInvalid
			}
			if runID == "nope" {
				return "", ops.ErrNotFound
			}
			return "new-run", nil
		}}
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	desc, ok := r.Lookup("ci.rerun")
	if !ok {
		t.Fatalf("FAIL: ci.rerun is not registered")
	}
	if desc.Caps != "a" || desc.Method != "POST" || desc.Pattern != "/api/v1/r/{repo}/ci/runs/{runId}/rerun" {
		t.Errorf("FAIL: caps %q route %s %s, want a and the rerun route", desc.Caps, desc.Method, desc.Pattern)
	}
	if c, ok := r.Lookup("ci.cancel"); !ok || c.Auth != desc.Auth || c.Kind != desc.Kind {
		t.Errorf("FAIL: ci.rerun's auth and kind differ from ci.cancel's")
	}
	ctx := ops.WithUser(context.Background(), "dan")
	out, err := r.Invoke(ctx, "ci.rerun", ciRerunIn{Repo: "test", RunID: "old1"})
	if err != nil {
		t.Fatalf("FAIL: rerun: %v", err)
	}
	if got := out.(ciRerunOut); got.RunID != "new-run" || !got.OK {
		t.Errorf("FAIL: answered %+v, want ok with run new-run", got)
	}
	if asked != [3]string{"test", "old1", "dan"} {
		t.Errorf("FAIL: the hook was asked %v", asked)
	}
	if _, err := r.Invoke(ctx, "ci.rerun", ciRerunIn{Repo: "test", RunID: "going"}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: an unfinished run answered %v, want invalid", err)
	}
	if _, err := r.Invoke(ctx, "ci.rerun", ciRerunIn{Repo: "test", RunID: "nope"}); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: an unknown run answered %v, want not found", err)
	}
	if _, err := RegisterAndInvokeWithout(t, ciRerunIn{Repo: "test", RunID: "x"}); !errors.Is(err, ops.ErrUnavailable) {
		t.Errorf("FAIL: with no engine answered %v, want unavailable", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func RegisterAndInvokeWithout(t *testing.T, in ciRerunIn) (any, error) {
	t.Helper()
	r := ops.NewRegistry()
	if err := RegisterAll(r, Deps{Version: "v", Repos: testRepos(wikiIndex(t))}); err != nil {
		t.Fatal(err)
	}
	return r.Invoke(ops.WithUser(context.Background(), "dan"), "ci.rerun", in)
}