package runner
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"slices"
"testing"
)
// failingCheckout is a checkout that must not be used.
type failingCheckout struct{ called bool }
func (f *failingCheckout) Checkout(context.Context, string, string) error {
f.called = true
return errors.New("no account to fetch trunk as")
}
// A RUNNER NAMES ITS TASK TYPES AT START-UP FROM THE FORGE, with its
// worker token alone: it needs no account to read trunk's manifest, and
// a forge that cannot say leaves the runner reading trunk itself.
func TestARunnerReadsItsTaskTypesFromTheForgeAtStartUp(t *testing.T) {
var bearer string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/trunk/tasks" {
http.NotFound(w, r)
return
}
bearer = r.Header.Get("Authorization")
json.NewEncoder(w).Encode(map[string][]string{"tasks": {"lint", "test"}})
}))
defer srv.Close()
co := &failingCheckout{}
got, err := startupTasks(context.Background(), nil, srv.URL, "WT", "demo", co, t.TempDir())
if err != nil || co.called || bearer != "Bearer WT" {
t.Fatalf("FAIL: %v, checkout used %v, bearer %q; want the forge's answer by the worker token, no checkout", err, co.called, bearer)
}
if !slices.Contains(got, "lint") || !slices.Contains(got, "test") || len(got) != 3 {
t.Errorf("FAIL: the task types are %v; want the two names and the repository's job type", got)
}
// A forge without the route: trunk is read with the runner's own checkout.
old := httptest.NewServer(http.NotFoundHandler())
defer old.Close()
manifest := `{"tasks":{"fmt":["true"]}}`
got, err = startupTasks(context.Background(), nil, old.URL, "WT", "demo", fakeCheckout{map[string]string{"trunk": manifest}}, t.TempDir())
if err != nil || len(got) != 2 || !slices.Contains(got, "fmt") {
t.Errorf("FAIL: an older forge: %v, %v; want fmt and the job type from trunk", got, err)
}
if _, err := startupTasks(context.Background(), nil, old.URL, "WT", "demo", &failingCheckout{}, t.TempDir()); err == nil {
t.Errorf("FAIL: an older forge and a checkout that cannot read trunk started a runner")
}
// A forge that answers with a fault does not start it on a guess.
sick := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "busy", http.StatusServiceUnavailable)
}))
defer sick.Close()
co = &failingCheckout{}
if _, err := startupTasks(context.Background(), nil, sick.URL, "WT", "demo", co, t.TempDir()); err == nil || co.called {
t.Errorf("FAIL: a forge's fault was %v (checkout used %v); want an error and no fallback", err, co.called)
}
}