package web
import (
"regexp"
"strings"
"testing"
)
type maintRow = struct {
Store string `json:"store"`
Task string `json:"task"`
State string `json:"state"`
WaitingOn []string `json:"waitingOn"`
AgeMs int64 `json:"ageMs"`
Overdue bool `json:"overdue"`
Last *struct {
AgoMs int64 `json:"agoMs"`
DurationMs int64 `json:"durationMs"`
Error string `json:"error"`
} `json:"last"`
}
func maintPage(t *testing.T, rows ...maintRow) string {
t.Helper()
var d pageData
d.Ops.BudgetMs = 500
d.Ops.Maintenance = rows
var buf strings.Builder
if err := noHooks.template(opsPage).ExecuteTemplate(&buf, "content", d); err != nil {
t.Fatal(err)
}
return buf.String()
}
// The maintenance section carries one row per store and task, with the
// state, what a waiting task waits on, whether it is overdue, and the
// last run's duration and error as data hooks.
func TestMaintenanceSectionDrawsOneRowPerTask(t *testing.T) {
last := &struct {
AgoMs int64 `json:"agoMs"`
DurationMs int64 `json:"durationMs"`
Error string `json:"error"`
}{AgoMs: 60_000, DurationMs: 4_200, Error: "boom"}
body := maintPage(t,
maintRow{Store: "tcl", Task: "file history", State: "waiting", WaitingOn: []string{"deploy running", "memory pressure"}, AgeMs: 90_000_000, Overdue: true},
maintRow{Store: "sqlite", Task: "search check", State: "idle", Last: last},
maintRow{Store: "pkgsrc", Task: "warm reads", State: "queued"},
)
if n := strings.Count(body, `data-hook="maint-task"`); n != 3 {
t.Errorf("FAIL: drew %d task rows, want 3", n)
}
for _, want := range []string{
`id="maintenance"`,
`data-store="tcl"`, `data-task="file history"`, `data-state="waiting"`, `data-overdue="true"`,
`data-hook="maint-waiting-on"`, `data-hook="maint-overdue"`,
`data-state="idle"`, `data-hook="maint-last"`, `data-duration-ms="4200"`, `data-hook="maint-error"`,
`data-state="queued"`,
} {
if !strings.Contains(body, want) {
t.Errorf("FAIL: the section is missing %s", want)
}
}
if m := regexp.MustCompile(`data-overdue="true"`).FindAllString(body, -1); len(m) != 1 {
t.Errorf("FAIL: %d overdue rows, want 1", len(m))
}
if !t.Failed() {
t.Log("ok")
}
}
// No tasks, no section: a forge without a maintenance lane draws nothing.
func TestMaintenanceSectionIsAbsentWithoutTasks(t *testing.T) {
if strings.Contains(maintPage(t), `id="maintenance"`) {
t.Errorf("FAIL: an empty maintenance section was drawn")
}
if !t.Failed() {
t.Log("ok")
}
}