In this section
- Test Collect test · lightning / tests/test_collect.py lines 1–218
- Test Collector Health test · lightning / tests/test_collector_health.py lines 1–243
Test Collect
A test in the tests folder of Lightning that checks Collect. It sets up (`setUp`) and runs record tests (`RunRecordTests`).
testlightning / tests/test_collect.py · lines 1–218 of 218 · Entry point
- What it does
- It tests its inputs. Defines 27 functions or classes, including product_for, UKLightningTests, test_uk_extent_and_neighbouring_waters, test_utc_normalisation, test_feature_timestamp_and_provenance. Uses libraries json, os, sys, tempfile, unittest. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file status.json; GeoJSON file feed.geojson; JSON file run.json. Out: JSON file index.json; JSON file status.json.
- Downstream impact
- Used directly by 4 files: Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Update Lightning Workflow (lightning).
- What it achieves
- Defines `product_for`, `UKLightningTests`, `test_uk_extent_and_neighbouring_waters` and 24 more. It reads `status.json`.
- Why it matters
- Run by Backfill Lightning Workflow, Backfill Parallel Lightning Workflow and Update Lightning Workflow. Checked by Test Lightning Workflow.
- Application
- lightning · tests · test
- Uses
- Collect (import), json, os, sys, tempfile, unittest, datetime, pathlib
- Used by
- run by Backfill Lightning Workflow (workflow run), run by Backfill Parallel Lightning Workflow (workflow run), run by Test Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run)
- Produces
- product_for, UKLightningTests, LookbackWindowTests, ProductSlotTests, RunRecordTests
- Defines here
- product_for, UKLightningTests, test_uk_extent_and_neighbouring_waters, test_utc_normalisation, test_feature_timestamp_and_provenance, test_no_outside_points, test_deduplicate_and_retention, test_empty_collection_has_no_synthetic_strikes, test_iso_utc_keeps_whole_seconds_and_strips_only_fractional_zeros, LookbackWindowTests, setUp, test_defaults_to_six_hours_without_history, test_recent_success_keeps_the_six_hour_minimum, test_gap_since_last_success_plus_margin_wins_over_minimum, test_gap_is_capped_at_48_hours_and_flagged, test_exactly_at_the_cap_is_not_flagged, test_last_success_comes_from_status_then_index_then_default, ProductSlotTests, test_real_product_name_yields_its_sensing_slot, test_adjacent_slots_merge_and_clip_to_the_query_window, test_missing_middle_slot_is_a_source_gap, test_long_tail_is_also_reported_as_a_gap, test_unparseable_names_fall_back_to_the_query_window_and_say_so, test_merge_ranges_tolerates_one_second_seams, RunRecordTests, test_run_record_carries_window_slots_and_uncapped_features, test_main_without_credentials_writes_a_failure_record_and_raises
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 tests/test_collect.py:1-218 · blob b6b1e98b2a78dd3c5cd59744b4d44a1684baf8c5 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
import json
import os
import sys
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import collect
from collect import (
LOOKBACK_MAX_HOURS, LOOKBACK_MIN_HOURS, assemble, build_feature, build_run_record, inside_uk_view, iso_utc,
lookback_window, merge_ranges, parse_utc, product_slot, read_last_success, scanned_ranges, unscanned_ranges,
)
# A genuine product name from data/uk_lightning.geojson (sensing slot 12:30:09-12:40:09 UTC, 21 Oct 2026).
REAL_PRODUCT = ("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_20261021124026_L2PF_OPE_"
"20261021123009_20261021124009_N__O_0076_0000")
def product_for(slot_start: datetime) -> str:
"""Build an LFL-style product name for a 10-minute slot starting at slot_start."""
end = slot_start + timedelta(minutes=10)
return ("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_"
f"{end:%Y%m%d%H%M%S}_L2PF_OPE_{slot_start:%Y%m%d%H%M%S}_{end:%Y%m%d%H%M%S}_N__O_0001_0000")
class UKLightningTests(unittest.TestCase):
def test_uk_extent_and_neighbouring_waters(self):
self.assertTrue(inside_uk_view(-3.2, 55.9))
self.assertTrue(inside_uk_view(-6.5, 54.5))
self.assertFalse(inside_uk_view(20, 55.9))
self.assertFalse(inside_uk_view(-3, float("nan")))
def test_utc_normalisation(self):
self.assertEqual(parse_utc("2026-10-22T15:00:00+01:00").isoformat(), "2026-10-22T14:00:00+00:00")
def test_feature_timestamp_and_provenance(self):
point = build_feature(-1.3, 52.1, datetime(2026, 10, 22, 12, tzinfo=timezone.utc), "product1", 1)
self.assertEqual(point["geometry"]["coordinates"], [-1.3, 52.1])
self.assertIn("not a confirmed ground strike", point["properties"]["raw_tech"])
self.assertEqual(point["properties"]["source_product"], "MTG LI L2-LFL")
def test_no_outside_points(self):
self.assertIsNone(build_feature(15, 52, datetime.now(timezone.utc), "x", 1))
def test_deduplicate_and_retention(self):
now = datetime(2026, 10, 22, 17, tzinfo=timezone.utc)
recent = build_feature(-1, 51, now - timedelta(hours=1), "recent", 1)
old = build_feature(-1, 51, now - timedelta(days=9), "old", 1)
result = assemble([old, recent], [recent], now, retention_days=7)
self.assertEqual(len(result["features"]), 1)
self.assertEqual(result["features"][0]["id"], recent["id"])
def test_empty_collection_has_no_synthetic_strikes(self):
output = assemble([], [], datetime.now(timezone.utc))
self.assertEqual(output["features"], [])
self.assertEqual(output["metadata"]["total_before_display_cap"], 0)
def test_iso_utc_keeps_whole_seconds_and_strips_only_fractional_zeros(self):
# Latent bug found by the archive audit: "12:32:20" used to become "12:32:2Z".
self.assertEqual(iso_utc("2026-10-21T12:32:20"), "2026-10-21T12:32:20Z")
self.assertEqual(iso_utc("2026-10-21T12:32:19.282000"), "2026-10-21T12:32:19.282Z")
self.assertEqual(iso_utc("2026-10-21T12:32:19.000000"), "2026-10-21T12:32:19Z")
self.assertEqual(iso_utc("2026-10-21T12:32:19.282Z"), "2026-10-21T12:32:19.282Z")
self.assertEqual(iso_utc(datetime(2026, 10, 21, 12, 32, 19, 282000, tzinfo=timezone.utc)), "2026-10-21T12:32:19.282Z")
class LookbackWindowTests(unittest.TestCase):
"""window = max(6 h, now - last successful scan end + 30 min) capped at 48 h."""
def setUp(self):
self.now = datetime(2026, 10, 26, 14, 17, tzinfo=timezone.utc)
def test_defaults_to_six_hours_without_history(self):
window, capped = lookback_window(self.now, None)
self.assertEqual(window, timedelta(hours=LOOKBACK_MIN_HOURS))
self.assertFalse(capped)
def test_recent_success_keeps_the_six_hour_minimum(self):
window, capped = lookback_window(self.now, self.now - timedelta(hours=1, minutes=17))
self.assertEqual(window, timedelta(hours=6))
self.assertFalse(capped)
def test_gap_since_last_success_plus_margin_wins_over_minimum(self):
window, capped = lookback_window(self.now, self.now - timedelta(hours=10))
self.assertEqual(window, timedelta(hours=10, minutes=30))
self.assertFalse(capped)
def test_gap_is_capped_at_48_hours_and_flagged(self):
window, capped = lookback_window(self.now, self.now - timedelta(days=3))
self.assertEqual(window, timedelta(hours=LOOKBACK_MAX_HOURS))
self.assertTrue(capped)
def test_exactly_at_the_cap_is_not_flagged(self):
window, capped = lookback_window(self.now, self.now - timedelta(hours=47, minutes=30))
self.assertEqual(window, timedelta(hours=48))
self.assertFalse(capped)
def test_last_success_comes_from_status_then_index_then_default(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
self.assertEqual(read_last_success(root / "status.json", root / "history"), (None, "default"))
(root / "history").mkdir()
(root / "history" / "index.json").write_text(json.dumps({
"scan_windows": [{"start_utc": "2026-10-26T01:00:00Z", "end_utc": "2026-10-26T04:40:09Z"},
{"start_utc": "2026-10-25T01:00:00Z", "end_utc": "2026-10-25T04:00:00Z"}]}))
value, source = read_last_success(root / "status.json", root / "history")
self.assertEqual((value.isoformat(), source), ("2026-10-26T04:40:09+00:00", "index"))
(root / "status.json").write_text(json.dumps({"last_successful_scan_end_utc": "2026-10-26T13:00:09Z"}))
value, source = read_last_success(root / "status.json", root / "history")
self.assertEqual((value.isoformat(), source), ("2026-10-26T13:00:09+00:00", "status"))
class ProductSlotTests(unittest.TestCase):
"""Only examined 10-minute slots count as searched; the tail is unobserved."""
def test_real_product_name_yields_its_sensing_slot(self):
start, end = product_slot(REAL_PRODUCT)
self.assertEqual(start.isoformat(), "2026-10-21T12:30:09+00:00")
self.assertEqual(end.isoformat(), "2026-10-21T12:40:09+00:00")
self.assertIsNone(product_slot("not-a-product"))
self.assertIsNone(product_slot(""))
def test_adjacent_slots_merge_and_clip_to_the_query_window(self):
beginning = datetime(2026, 10, 26, 10, 5, 58, tzinfo=timezone.utc)
now = datetime(2026, 10, 26, 13, 5, 58, tzinfo=timezone.utc)
first = datetime(2026, 10, 26, 10, 0, 9, tzinfo=timezone.utc)
names = [product_for(first + timedelta(minutes=10 * i)) for i in range(18)] # 10:00:09 .. 13:00:09
ranges, slots, parsed = scanned_ranges(names, beginning, now)
self.assertTrue(parsed)
self.assertEqual(len(slots), 18)
self.assertEqual(ranges, [(beginning, datetime(2026, 10, 26, 13, 0, 9, tzinfo=timezone.utc))])
gaps, tail = unscanned_ranges(ranges, beginning, now)
self.assertEqual(gaps, [])
self.assertEqual(tail, 349) # 13:00:09 -> 13:05:58 not yet published: unknown, not zero
def test_missing_middle_slot_is_a_source_gap(self):
beginning = datetime(2026, 10, 26, 10, 0, 9, tzinfo=timezone.utc)
now = datetime(2026, 10, 26, 11, 0, 9, tzinfo=timezone.utc)
names = [product_for(beginning + timedelta(minutes=10 * i)) for i in (0, 1, 3, 4, 5)] # slot 2 missing
ranges, slots, parsed = scanned_ranges(names, beginning, now)
self.assertEqual(len(ranges), 2)
gaps, tail = unscanned_ranges(ranges, beginning, now)
self.assertEqual(gaps, [(datetime(2026, 10, 26, 10, 20, 9, tzinfo=timezone.utc),
datetime(2026, 10, 26, 10, 30, 9, tzinfo=timezone.utc))])
self.assertEqual(tail, 0)
def test_long_tail_is_also_reported_as_a_gap(self):
beginning = datetime(2026, 10, 26, 10, 0, 9, tzinfo=timezone.utc)
now = datetime(2026, 10, 26, 12, 0, 9, tzinfo=timezone.utc)
names = [product_for(beginning)]
ranges, _, _ = scanned_ranges(names, beginning, now)
gaps, tail = unscanned_ranges(ranges, beginning, now)
self.assertEqual(tail, 6600)
self.assertEqual(gaps, [(datetime(2026, 10, 26, 10, 10, 9, tzinfo=timezone.utc), now)])
def test_unparseable_names_fall_back_to_the_query_window_and_say_so(self):
beginning = datetime(2026, 10, 26, 10, tzinfo=timezone.utc)
now = datetime(2026, 10, 26, 13, tzinfo=timezone.utc)
ranges, slots, parsed = scanned_ranges(["opaque-product"], beginning, now)
self.assertFalse(parsed)
self.assertEqual(ranges, [(beginning, now)])
self.assertEqual(slots, [])
def test_merge_ranges_tolerates_one_second_seams(self):
a = datetime(2026, 1, 1, 0, 0, tzinfo=timezone.utc)
merged = merge_ranges([(a, a + timedelta(minutes=10)), (a + timedelta(minutes=10, seconds=1), a + timedelta(minutes=20))])
self.assertEqual(merged, [(a, a + timedelta(minutes=20))])
class RunRecordTests(unittest.TestCase):
def test_run_record_carries_window_slots_and_uncapped_features(self):
now = datetime(2026, 10, 26, 13, 5, 58, tzinfo=timezone.utc)
beginning = now - timedelta(hours=6)
names = [product_for(datetime(2026, 10, 26, 7, 0, 9, tzinfo=timezone.utc) + timedelta(minutes=10 * i)) for i in range(36)]
incoming = [build_feature(-2, 52, now - timedelta(hours=1), names[0], 7)]
existing = [build_feature(-2, 52, now - timedelta(days=2), "older", 1)]
feed = assemble(existing, incoming, now)
record = build_run_record(now=now, beginning=beginning, lookback_source="status", lookback_capped=False,
last_success_before=now - timedelta(hours=1), product_names=names,
products_examined=36, incoming=incoming, existing=existing, feed=feed)
self.assertEqual(record["schema"], "uk-lightning-run-record.v1")
self.assertEqual(record["outcome"], "success")
self.assertEqual(record["lookback_hours"], 6)
self.assertEqual(record["slots_examined"], 36)
self.assertEqual(record["scanned_ranges"], [{"start_utc": "2026-10-26T07:05:58.000Z", "end_utc": "2026-10-26T13:00:09.000Z"}])
self.assertEqual(record["scanned_end_utc"], "2026-10-26T13:00:09.000Z")
self.assertEqual(record["tail_unobserved_seconds"], 349)
self.assertEqual(record["incoming_features"], 1)
self.assertEqual(len(record["features"]), 2)
self.assertEqual(record["feed_features"], 2)
def test_main_without_credentials_writes_a_failure_record_and_raises(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
env = {k: v for k, v in os.environ.items() if not k.startswith("EUMETSAT_")}
saved = dict(os.environ)
os.environ.clear()
os.environ.update(env)
try:
with self.assertRaises(RuntimeError):
collect.main(["--auto-window", "--out", str(root / "feed.geojson"), "--status", str(root / "status.json"),
"--history-dir", str(root / "history"), "--run-record", str(root / "run.json")])
finally:
os.environ.clear()
os.environ.update(saved)
record = json.loads((root / "run.json").read_text())
self.assertEqual(record["outcome"], "failure")
self.assertIn("EUMETSAT_CONSUMER_KEY", record["error"])
self.assertEqual(record["lookback_hours"], 6)
self.assertEqual(record["lookback_source"], "default")
self.assertEqual(record["features"], [])
self.assertFalse((root / "feed.geojson").exists(), "a failed run must not write the feed")
if __name__ == "__main__":
unittest.main()Test Collector Health
A test in the tests folder of Lightning that checks CI Collector Health. It opens issues (`open_issues`), creates issue (`create_issue`) and updates issue (`update_issue`).
testlightning / tests/test_collector_health.py · lines 1–243 of 243 · Entry point · pattern create_issue (shared by 2 files)
- What it does
- It tests its inputs. Defines 39 functions or classes, including status, FakeGitHub, __init__, open_issues, ensure_label. Uses libraries io, json, sys, tempfile, unittest. Side effects: reads or writes files; makes network requests.
- Inputs & outputs
- In: JSON file status.json; JSON file index.json.
- Downstream impact
- Used directly by 4 files: Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Update Lightning Workflow (lightning).
- What it achieves
- The collector-stale verdict, the issue sync and the workflow wiring.
- Why it matters
- Run by Backfill Lightning Workflow, Backfill Parallel Lightning Workflow and Update Lightning Workflow. Checked by Test Lightning Workflow.
- Application
- lightning · tests · test
- Uses
- CI Collector Health (sys.path import), io, json, sys, tempfile, unittest, contextlib, datetime, pathlib
- Used by
- run by Backfill Lightning Workflow (workflow run), run by Backfill Parallel Lightning Workflow (workflow run), run by Test Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run)
- Produces
- status, FakeGitHub, EvaluateTests, SyncIssueTests, RawProbeTests, CliTests, WorkflowWiringTests
- Defines here
- status, FakeGitHub, __init__, open_issues, ensure_label, create_issue, update_issue, comment, EvaluateTests, test_on_time_heartbeat_is_ok, test_past_late_after_but_within_grace_is_late_not_an_issue, test_past_late_after_plus_grace_is_stale, test_grace_zero_alerts_exactly_at_late_after, test_missing_or_unreadable_status_is_stale, test_heartbeat_block_missing_falls_back_to_attempt_plus_90_min, test_repeated_failures_are_failing_even_with_a_fresh_heartbeat, test_stale_freshness_is_failing, test_stale_wins_over_failing_and_keeps_both_reasons, test_the_committed_status_json_is_readable, SyncIssueTests, sync, test_opens_one_issue_with_the_label, test_second_unhealthy_check_updates_without_a_comment, test_a_state_change_comments_once, test_recovery_closes_with_a_comment, test_raced_duplicates_are_closed_onto_the_oldest, test_issue_text_names_the_threshold_and_runbook, RawProbeTests, fetcher, fetch
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 tests/test_collector_health.py:1-243 · blob acb992eb467a3bc63ba18c74cdc55e7875ad7eab · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
"""ci/collector_health.py: the collector-stale verdict, the issue sync and the workflow wiring.
No network and no GitHub: the issue sync runs against an in-memory fake of the
four REST calls, and the raw probe against a fake fetch.
"""
import io
import json
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "ci"))
import collector_health as ch # noqa: E402
WORKFLOWS = ROOT / ".github" / "workflows"
NOW = datetime(2026, 10, 29, 12, 0, tzinfo=timezone.utc)
def status(attempt="2026-10-29T11:31:00Z", late_after="2026-10-29T13:01:00Z", outcome="success",
failures=0, freshness="ok", error=None):
return {"last_attempt_utc": attempt, "last_attempt_outcome": outcome, "consecutive_failures": failures,
"freshness": freshness, "last_error": error, "last_successful_scan_end_utc": "2026-10-29T11:20:05Z",
"heartbeat": {"late_after_utc": late_after}}
class FakeGitHub:
def __init__(self, issues=None):
self.issues = {i["number"]: dict(i) for i in (issues or [])}
self.comments, self.labels, self.next = [], [], 100
def open_issues(self, label):
return [dict(i) for n, i in sorted(self.issues.items())
if i.get("state", "open") == "open" and label in i.get("labels", [])]
def ensure_label(self, label, color, description):
self.labels.append(label)
def create_issue(self, title, body, label):
self.next += 1
self.issues[self.next] = {"number": self.next, "title": title, "body": body, "labels": [label], "state": "open"}
return self.issues[self.next]
def update_issue(self, number, **fields):
self.issues[number].update(fields)
return self.issues[number]
def comment(self, number, body):
self.comments.append((number, body))
class EvaluateTests(unittest.TestCase):
def test_on_time_heartbeat_is_ok(self):
self.assertEqual(ch.evaluate(status(), now=NOW)["state"], "ok")
def test_past_late_after_but_within_grace_is_late_not_an_issue(self):
v = ch.evaluate(status(), now=datetime(2026, 10, 29, 13, 30, tzinfo=timezone.utc))
self.assertEqual(v["state"], "late")
self.assertNotIn(v["state"], ch.UNHEALTHY)
def test_past_late_after_plus_grace_is_stale(self):
v = ch.evaluate(status(), now=datetime(2026, 10, 29, 14, 32, tzinfo=timezone.utc))
self.assertEqual(v["state"], "stale")
self.assertEqual(v["stale_after_utc"], "2026-10-29T14:31:00Z")
self.assertIn("late_after_utc 2026-10-29T13:01:00Z", v["reasons"][0])
def test_grace_zero_alerts_exactly_at_late_after(self):
v = ch.evaluate(status(), now=datetime(2026, 10, 29, 13, 2, tzinfo=timezone.utc), grace_minutes=0)
self.assertEqual(v["state"], "stale")
def test_missing_or_unreadable_status_is_stale(self):
self.assertEqual(ch.evaluate(None, now=NOW)["state"], "stale")
with tempfile.TemporaryDirectory() as tmp:
bad = Path(tmp) / "status.json"
bad.write_text("{not json")
self.assertIsNone(ch.load_status(bad))
def test_heartbeat_block_missing_falls_back_to_attempt_plus_90_min(self):
s = status()
del s["heartbeat"]
self.assertEqual(ch.evaluate(s, now=NOW)["late_after_utc"], "2026-10-29T13:01:00Z")
def test_repeated_failures_are_failing_even_with_a_fresh_heartbeat(self):
v = ch.evaluate(status(outcome="failure", failures=3, error="401 invalid_client"), now=NOW)
self.assertEqual(v["state"], "failing")
self.assertIn("401 invalid_client", v["reasons"][0])
self.assertEqual(ch.evaluate(status(outcome="failure", failures=2), now=NOW)["state"], "ok")
def test_stale_freshness_is_failing(self):
self.assertEqual(ch.evaluate(status(freshness="stopped"), now=NOW)["state"], "failing")
def test_stale_wins_over_failing_and_keeps_both_reasons(self):
v = ch.evaluate(status(failures=5), now=datetime(2026, 10, 30, tzinfo=timezone.utc))
self.assertEqual(v["state"], "stale")
self.assertEqual(len(v["reasons"]), 2)
def test_the_committed_status_json_is_readable(self):
committed = ch.load_status(ROOT / "data" / "status.json")
if committed is None:
self.skipTest("no data/status.json in this checkout")
v = ch.evaluate(committed, now=NOW)
self.assertIsNotNone(v["late_after_utc"])
class SyncIssueTests(unittest.TestCase):
def sync(self, gh, unhealthy, state="stale", body="b"):
return ch.sync_issue(gh, label=ch.STALE_LABEL, unhealthy=unhealthy, state=state, title="t", body=body,
recovery="recovered")
def test_opens_one_issue_with_the_label(self):
gh = FakeGitHub()
self.assertEqual(self.sync(gh, True), "opened #101")
self.assertEqual(gh.labels, [ch.STALE_LABEL])
self.assertEqual(gh.issues[101]["labels"], ["collector-stale"])
self.assertIn("state=stale", gh.issues[101]["body"])
def test_second_unhealthy_check_updates_without_a_comment(self):
gh = FakeGitHub()
self.sync(gh, True, body="first")
self.assertEqual(self.sync(gh, True, body="second"), "updated #101")
self.assertEqual(len(gh.issues), 1)
self.assertTrue(gh.issues[101]["body"].endswith("second"))
self.assertEqual(gh.comments, [])
def test_a_state_change_comments_once(self):
gh = FakeGitHub()
self.sync(gh, True, state="failing")
self.assertIn("commented", self.sync(gh, True, state="stale"))
self.sync(gh, True, state="stale")
self.assertEqual(len(gh.comments), 1)
def test_recovery_closes_with_a_comment(self):
gh = FakeGitHub()
self.sync(gh, True)
self.assertEqual(self.sync(gh, False, state="ok"), "closed #101")
self.assertEqual(gh.issues[101]["state"], "closed")
self.assertEqual(gh.comments, [(101, "recovered")])
self.assertEqual(self.sync(gh, False, state="ok"), "none open; nothing to do")
def test_raced_duplicates_are_closed_onto_the_oldest(self):
gh = FakeGitHub([{"number": 7, "labels": ["collector-stale"], "body": ""},
{"number": 9, "labels": ["collector-stale"], "body": ""},
{"number": 8, "labels": ["bug"], "body": ""}])
self.sync(gh, True)
self.assertEqual(gh.issues[7].get("state", "open"), "open")
self.assertEqual(gh.issues[9]["state"], "closed")
self.assertEqual(gh.issues[8].get("state", "open"), "open") # other labels untouched
def test_issue_text_names_the_threshold_and_runbook(self):
v = ch.evaluate(status(), now=datetime(2026, 10, 29, 15, tzinfo=timezone.utc))
title, body = ch.stale_issue(v, source="test", now=NOW)
self.assertIn("no heartbeat since 2026-10-29T11:31:00Z", title)
self.assertIn("late_after_utc", body)
self.assertIn("docs/OPERATIONS.md", body)
class RawProbeTests(unittest.TestCase):
def fetcher(self, served_status, codes=None):
codes = codes or {}
def fetch(url, method="GET", **_):
rel = url.split(ch.RAW_BASE, 1)[1].split("?", 1)[0]
code = codes.get(rel, 200)
body = json.dumps(served_status).encode() if rel == "data/status.json" and code == 200 else b""
return code, body, "" if code == 200 else f"HTTP {code}"
return fetch
def test_ok_when_raw_serves_current_bytes(self):
s = status()
self.assertEqual(ch.probe_raw(s, fetch=self.fetcher(s))["state"], "ok")
def test_failing_on_http_errors(self):
s = status()
p = ch.probe_raw(s, fetch=self.fetcher(s, {"data/history/index.json": 429}))
self.assertEqual(p["state"], "failing")
self.assertIn("data/history/index.json: HTTP 429", p["reasons"])
def test_failing_when_raw_is_far_behind_main(self):
p = ch.probe_raw(status(), fetch=self.fetcher(status(attempt="2026-10-29T08:00:00Z")))
self.assertEqual(p["state"], "failing")
self.assertIn("min behind main", p["reasons"][0])
class CliTests(unittest.TestCase):
def test_report_only_exit_codes(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "status.json"
path.write_text(json.dumps(status()))
out = io.StringIO()
with redirect_stdout(out):
self.assertEqual(ch.main(["--status", str(path), "--now", "2026-10-29T12:00:00Z",
"--fail-when-unhealthy"]), 0)
self.assertEqual(ch.main(["--status", str(path), "--now", "2026-10-29T18:00:00Z",
"--fail-when-unhealthy"]), 1)
self.assertEqual(ch.main(["--status", str(path), "--now", "2026-10-29T18:00:00Z"]), 0)
self.assertIn("::error title=collector stale::", out.getvalue())
class WorkflowWiringTests(unittest.TestCase):
"""The check runs inside the existing workflows and the watchdog stays tiny."""
def test_hourly_collector_syncs_the_issue_after_its_commit_without_changing_the_outcome(self):
text = (WORKFLOWS / "update-lightning.yml").read_text()
self.assertIn("issues: write", text.split("\nconcurrency:", 1)[0])
step = text.split("- name: Collector health issue (collector-stale)", 1)[1].split("\n - name:", 1)[0]
self.assertIn("if: always()", step)
self.assertIn("continue-on-error: true", step)
self.assertIn("python ci/collector_health.py", step)
self.assertIn("--issue", step)
order = [text.index(n) for n in ("- name: Commit archive and status (archive commit)",
"- name: Collector health issue (collector-stale)",
"- name: Surface collection, archive or integrity failure")]
self.assertEqual(order, sorted(order))
def test_data_verifier_has_a_health_job_with_issue_write_only_there(self):
text = (WORKFLOWS / "verify-lightning-data.yml").read_text()
top = text.split("\njobs:", 1)[0]
self.assertNotIn("issues: write", top)
health = text.split("\n health:\n", 1)[1]
self.assertIn("issues: write", health)
self.assertIn("ci/collector_health.py", health)
self.assertIn("--issue", health)
def test_watchdog_is_read_only_scheduled_and_never_in_a_writer_group(self):
text = (WORKFLOWS / "collector-watchdog.yml").read_text()
self.assertIn("schedule:", text)
self.assertIn("contents: read", text)
self.assertIn("issues: write", text)
self.assertNotIn("contents: write", text)
for group in ("uk-lightning-update", "uk-lightning-backfill"):
self.assertNotIn(group, text)
self.assertIn("--fail-when-unhealthy", text)
self.assertIn("--raw", text)
self.assertIn("timeout-minutes: 5", text)
self.assertNotIn("pip install", text)
if __name__ == "__main__":
unittest.main()