package runner
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"craftdesign.group/quarry/internal/runner/install"
)
// A FIRST ARGUMENT THAT IS A URL OR A FLAG RUNS THE RUNNER AS TODAY;
// ONLY THE THREE WORDS ARE SETUP COMMANDS.
func TestOnlyTheThreeWordsAreSetupCommands(t *testing.T) {
for _, w := range []string{"install", "doctor", "uninstall"} {
if got, ok := setupCommand([]string{w, "x"}); !ok || got != w {
t.Errorf("FAIL: %q is not routed to setup: %q %v", w, got, ok)
}
}
for _, args := range [][]string{
nil,
{"https://forge.example/r/dmestas/suit"},
{"--max-tasks", "2", "https://forge.example/r/x"},
{"-h"},
{"--version"},
{"http://127.0.0.1:1/r/install"},
{"Install"},
} {
if got, ok := setupCommand(args); ok {
t.Errorf("FAIL: %v was routed to setup %q", args, got)
}
}
if !t.Failed() {
t.Log("ok")
}
}
func TestAURLFirstArgumentStillRunsTheRunner(t *testing.T) {
t.Setenv("QUARRY_RUNNER_TOKEN", "")
err := Main([]string{"https://forge.example/r/dmestas/suit"}, "quarry-runner", "dev")
var ee *install.ExitError
if err == nil || errors.As(err, &ee) {
t.Errorf("FAIL: the runner path answered %v, want its own error", err)
}
// A setup word does reach setup, which refuses a bare `install`
// before it touches the machine.
err = Main([]string{"install"}, "quarry-runner", "dev")
if !errors.As(err, &ee) || ee.Code != 2 {
t.Errorf("FAIL: `install` with no URL answered %v, want a usage exit", err)
}
if !t.Failed() {
t.Log("ok")
}
}
// DOCTOR'S TRUNK CHECK ASKS THE FORGE FOR THE LISTING OF ci/; IT NEVER
// FETCHES OR UNPACKS AN ARCHIVE (it runs as root).
func TestTrunkCheckReadsTheListingAndUnpacksNothing(t *testing.T) {
var paths []string
answer := ""
status := 200
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.Path)
w.WriteHeader(status)
w.Write([]byte(answer))
}))
defer srv.Close()
url := srv.URL + "/r/dmestas/suit"
answer = `{"entries":[{"name":"runner.json"}]}`
if has, err := trunkHasCI(context.Background(), url); err != nil || !has {
t.Errorf("FAIL: a ci/ with files: %v %v", has, err)
}
answer = `{"entries":[]}`
if has, err := trunkHasCI(context.Background(), url); err != nil || has {
t.Errorf("FAIL: an empty ci/: %v %v", has, err)
}
status = 404
if has, err := trunkHasCI(context.Background(), url); err == nil || has {
t.Errorf("FAIL: an unreadable trunk answered %v %v", has, err)
}
for _, p := range paths {
if !strings.HasPrefix(p, "/api/v1/r/suit/tree/trunk/ci") {
t.Errorf("FAIL: asked for %s", p)
}
}
if !t.Failed() {
t.Log("ok")
}
}