package main
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"craftdesign.group/quarry/internal/health"
)
// A forge that does not know its own public address cannot check what
// readers receive, and health.New skips a dep with no URL — so "" is
// how the check turns itself off rather than probing something wrong.
func TestTheOriginCheckIsSkippedWithoutAPublicAddress(t *testing.T) {
for _, in := range []string{"", " "} {
if got := originCheckURL(in); got != "" {
t.Errorf("FAIL: originCheckURL(%q) = %q, want empty", in, got)
}
}
}
// One slash, however the operator wrote the origin.
func TestTheOriginCheckBuildsOneCleanURL(t *testing.T) {
for _, tc := range []struct{ in, want string }{
{"https://zeitforge.app", "https://zeitforge.app/"},
{"https://zeitforge.app/", "https://zeitforge.app/"},
{" https://zeitforge.app/ ", "https://zeitforge.app/"},
{"http://127.0.0.1:8950", "http://127.0.0.1:8950/"},
} {
if got := originCheckURL(tc.in); got != tc.want {
t.Errorf("FAIL: originCheckURL(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
// A 502 or network error during a deploy restart is a probe read failure,
// not a third-party script injection; only an actual foreign host keeps
// the injection headline and Cloudflare Web Analytics guidance — in both
// the watcher's reported fault and its live Down() state.
func TestOriginDepDistinguishesReadFailureFromInjection(t *testing.T) {
var probeErr error
dep := originDep("https://zeitforge.app")
dep.Probe = func(context.Context, health.Dep) error { return probeErr }
var reported []health.Dep
w := health.New([]health.Dep{dep}, func(d health.Dep, up bool, err error) {
if !up {
reported = append(reported, d)
}
})
probeErr = errors.New("the public page answered 502 Bad Gateway, so this check could not run")
w.Check(context.Background())
if len(reported) != 1 || reported[0].Broken != "the public page could not be checked" {
t.Fatalf("FAIL: 502 reported = %+v, want probe-unreadable headline", reported)
}
if strings.Contains(strings.ToLower(reported[0].Fix), "cloudflare") {
t.Errorf("FAIL: 502 fix blamed Cloudflare Web Analytics: %q", reported[0].Fix)
}
if down := w.Down(); len(down) != 1 || !strings.Contains(down[0].Why, "could not confirm") {
t.Errorf("FAIL: 502 Down() state still blamed third-party injection: %+v", down)
}
// Recover, then inject a real foreign resource.
probeErr = nil
w.Check(context.Background())
probeErr = fmt.Errorf("injected: %w", health.ErrForeignResource)
w.Check(context.Background())
if len(reported) != 2 || reported[1].Broken != dep.Broken || !strings.Contains(strings.ToLower(reported[1].Fix), "cloudflare") {
t.Errorf("FAIL: real injection lost its headline/fix: %+v", reported)
}
}