Files
uptimesebi/internal/statuspage/statuspage_test.go
T
Sebastian UnterschützandClaude Opus 5.5 43b0a35f20 feat: maintenance windows and Markdown descriptions
Monitors and groups get one-off or recurring maintenance. While it is in
progress, failures neither open incidents nor alert, so the SLA is not
affected; successes still resolve earlier incidents. The console shows
monitors under maintenance and lists windows on a new page and on
monitor pages. Status pages announce maintenance in progress and planned
for the next two weeks and mark affected components; the occurrences are
part of the snapshot and evaluated when the page is shown, so this also
works from cache during an API outage. Maintenance and status page
descriptions are rendered as Markdown.

Closes #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 10:38:31 +01:00

302 lines
10 KiB
Go

package statuspage
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
type fakeSource struct {
mu sync.Mutex
calls int
err error
delay time.Duration
pages map[string]agentapi.PageSnapshot
}
func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
f.mu.Lock()
f.calls++
err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false
if _, exists := f.pages[host+"|"+slug]; exists {
ok = true
}
f.mu.Unlock()
if delay > 0 {
select {
case <-time.After(delay):
case <-ctx.Done():
return p, ctx.Err()
}
}
if err != nil {
return agentapi.PageSnapshot{}, err
}
if !ok {
return p, agentapi.ErrNotFound
}
return p, nil
}
func (f *fakeSource) set(fn func(*fakeSource)) {
f.mu.Lock()
defer f.mu.Unlock()
fn(f)
}
func (f *fakeSource) callCount() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls
}
type harness struct {
srv *Server
src *fakeSource
r *gin.Engine
now *time.Time
}
func newHarness(t *testing.T, src *fakeSource, dir string, now *time.Time) harness {
t.Helper()
cat, err := i18n.Load()
if err != nil {
t.Fatal(err)
}
s, err := New(src, cat, slog.New(slog.DiscardHandler), Options{Hosts: []string{"status.example.test"}, CacheDir: dir})
if err != nil {
t.Fatal(err)
}
s.now = func() time.Time { return *now }
gin.SetMode(gin.TestMode)
r := gin.New()
s.Mount(r)
return harness{srv: s, src: src, r: r, now: now}
}
func newSource() *fakeSource {
return &fakeSource{pages: map[string]agentapi.PageSnapshot{
"|acme": {Title: "Acme status", Status: agentapi.PageOperational},
"status.acme.test|": {Title: "Acme on own domain", Status: agentapi.PageOutage},
}}
}
func (h harness) get(host, path string) (int, string) {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Host = host
req.Header.Set("Accept-Language", "de")
w := httptest.NewRecorder()
h.r.ServeHTTP(w, req)
return w.Code, w.Body.String()
}
func TestRouting(t *testing.T) {
now := time.Now()
h := newHarness(t, newSource(), t.TempDir(), &now)
tests := []struct {
host, path string
want int
contains string
}{
{"status.example.test", "/acme", 200, "Acme status"},
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
{"status.example.test", "/missing", 404, ""},
{"status.example.test", "/", 404, ""},
{"status.acme.test", "/", 200, "Acme on own domain"},
{"status.acme.test", "/acme", 404, ""},
{"other.test", "/", 404, ""},
}
for _, tt := range tests {
code, body := h.get(tt.host, tt.path)
if code != tt.want || !strings.Contains(body, tt.contains) {
t.Errorf("GET %s%s = %d (contains %q: %t), want %d", tt.host, tt.path, code, tt.contains, strings.Contains(body, tt.contains), tt.want)
}
}
}
// TestSurvivesAPIOutageAndRestart is the reason this package keeps state:
// the page must stay up while the API is down, also across restarts.
func TestSurvivesAPIOutageAndRestart(t *testing.T) {
dir := t.TempDir()
now := time.Now()
h := newHarness(t, newSource(), dir, &now)
if code, _ := h.get("status.example.test", "/acme"); code != 200 {
t.Fatalf("first GET = %d", code)
}
down := &fakeSource{err: errors.New("connection refused")}
now = now.Add(time.Minute)
restarted := newHarness(t, down, dir, &now)
if code, body := restarted.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
t.Errorf("GET after restart with API down = %d, want cached page without stale notice", code)
}
if err := restarted.srv.Ready(context.Background(), func(context.Context) error { return errors.New("api down") }); err != nil {
t.Errorf("Ready() with cached pages and API down = %v, want ready", err)
}
now = now.Add(72 * time.Hour)
code, body := restarted.get("status.example.test", "/acme")
if code != 200 || !strings.Contains(body, "Live-Aktualisierung") {
t.Errorf("GET three days into the outage = %d, want cached page with stale notice", code)
}
}
func TestReadyWithoutCacheNeedsAPI(t *testing.T) {
now := time.Now()
h := newHarness(t, newSource(), t.TempDir(), &now)
if err := h.srv.Ready(context.Background(), func(context.Context) error { return errors.New("api down") }); err == nil {
t.Error("Ready() with empty cache and API down = nil, want error")
}
}
func TestCachedPagesDoNotWaitForAPI(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, t.TempDir(), &now)
h.get("status.example.test", "/acme")
src.set(func(f *fakeSource) { f.delay = 5 * time.Second })
now = now.Add(time.Minute)
start := time.Now()
if code, _ := h.get("status.example.test", "/acme"); code != 200 {
t.Fatalf("GET = %d", code)
}
if took := time.Since(start); took > time.Second {
t.Errorf("GET with a hanging API took %v, want an immediate cached answer", took)
}
}
func TestBackgroundRefresh(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, t.TempDir(), &now)
h.get("status.example.test", "/acme")
src.set(func(f *fakeSource) {
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational}
})
now = now.Add(time.Minute)
h.get("status.example.test", "/acme") // served from cache, triggers refresh
deadline := time.Now().Add(2 * time.Second)
for {
_, body := h.get("status.example.test", "/acme")
if strings.Contains(body, "Renamed") {
break
}
if time.Now().After(deadline) {
t.Fatal("cached page was not refreshed in the background")
}
time.Sleep(20 * time.Millisecond)
}
}
func TestDeletedPageDisappears(t *testing.T) {
dir := t.TempDir()
now := time.Now()
src := newSource()
h := newHarness(t, src, dir, &now)
h.get("status.example.test", "/acme")
src.set(func(f *fakeSource) { delete(f.pages, "|acme") })
now = now.Add(time.Minute)
h.srv.refresh(context.Background(), "slug:acme", "", "acme")
if code, _ := h.get("status.example.test", "/acme"); code != 404 {
t.Errorf("GET after the API reported the page gone = %d, want 404", code)
}
restarted := newHarness(t, &fakeSource{err: errors.New("down")}, dir, &now)
if code, _ := restarted.get("status.example.test", "/acme"); code != 404 {
t.Errorf("GET after restart = %d, want 404 (removed from disk too)", code)
}
}
func TestLegalDocuments(t *testing.T) {
now := time.Now()
src := newSource()
legal := []agentapi.LegalDoc{
{Kind: "imprint", Markdown: "# Impressum\n\nAcme GmbH <script>alert(1)</script> [x](javascript:alert(1))"},
{Kind: "privacy", URL: "https://acme.example/privacy"},
}
src.pages["|acme"] = agentapi.PageSnapshot{Title: "Acme status", Status: agentapi.PageOperational, Legal: legal}
src.pages["status.acme.test|"] = agentapi.PageSnapshot{Title: "Acme on own domain", Status: agentapi.PageOperational, Legal: legal}
h := newHarness(t, src, t.TempDir(), &now)
_, page := h.get("status.example.test", "/acme")
if !strings.Contains(page, `href="/acme/imprint"`) || !strings.Contains(page, `href="https://acme.example/privacy"`) {
t.Error("status page does not link its legal documents")
}
if _, page := h.get("status.acme.test", "/"); !strings.Contains(page, `href="/imprint"`) {
t.Error("custom domain page does not link /imprint")
}
// The API goes away; the documents stay reachable from the cache.
src.mu.Lock()
src.err = errors.New("connection refused")
src.mu.Unlock()
now = now.Add(time.Hour)
for _, tc := range []struct{ host, path string }{{"status.example.test", "/acme/imprint"}, {"status.acme.test", "/imprint"}} {
code, body := h.get(tc.host, tc.path)
if code != http.StatusOK || !strings.Contains(body, "<h1>Impressum</h1>") || !strings.Contains(body, "Acme GmbH") {
t.Errorf("GET %s%s = %d, lacks the rendered imprint", tc.host, tc.path, code)
}
if strings.Contains(body, "<script>alert") || strings.Contains(body, "javascript:") {
t.Errorf("GET %s%s renders unsafe markup", tc.host, tc.path)
}
}
req := httptest.NewRequest(http.MethodGet, "/acme/privacy", nil)
req.Host = "status.example.test"
w := httptest.NewRecorder()
h.r.ServeHTTP(w, req)
if w.Code != http.StatusFound || w.Header().Get("Location") != "https://acme.example/privacy" {
t.Errorf("privacy link = %d %s, want redirect", w.Code, w.Header().Get("Location"))
}
if code, _ := h.get("status.example.test", "/acme/other"); code != http.StatusNotFound {
t.Errorf("unknown document = %d, want 404", code)
}
}
// Maintenance in a cached snapshot starts on time even without the API.
func TestMaintenanceStartsWhileAPIIsDown(t *testing.T) {
now := time.Now()
src := newSource()
src.pages["|acme"] = agentapi.PageSnapshot{
Title: "Acme status", Status: agentapi.PageOperational, Description: "Run by **Acme**",
Sections: []agentapi.Section{{Components: []agentapi.Component{{Name: "Database", Status: agentapi.PageOperational}, {Name: "Web", Status: agentapi.PageOperational}}}},
Maintenance: []agentapi.PageMaintenance{{
Title: "DB upgrade", Description: "Expect <b>short</b> _gaps_.", Components: []string{"Database"},
Start: now.Add(30 * time.Minute), End: now.Add(90 * time.Minute),
}},
}
h := newHarness(t, src, t.TempDir(), &now)
_, page := h.get("status.example.test", "/acme")
if !strings.Contains(page, "Geplante Wartung") || strings.Contains(page, "Laufende Wartung") {
t.Error("upcoming maintenance is not announced as planned")
}
if !strings.Contains(page, "<strong>Acme</strong>") || !strings.Contains(page, "<em>gaps</em>") || strings.Contains(page, "<b>short</b>") {
t.Error("descriptions are not rendered as safe Markdown")
}
src.mu.Lock()
src.err = errors.New("connection refused")
src.mu.Unlock()
now = now.Add(45 * time.Minute)
_, page = h.get("status.example.test", "/acme")
if !strings.Contains(page, "Laufende Wartung") || !strings.Contains(page, "Geplante Wartung läuft") {
t.Error("maintenance in progress is not shown from the cache")
}
now = now.Add(time.Hour)
if _, page = h.get("status.example.test", "/acme"); strings.Contains(page, "Wartung") {
t.Error("ended maintenance is still shown")
}
}