GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/news/tests

Test Signals Acid and 1 more file

A test in the tests folder of GlobalGrid2050 that checks Acid Live and Acid Report.

697 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 811 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Test Signals Acid test · globalgrid2050 / automation/news/tests/test_signals_acid.py lines 433–960
  2. Test Signals Official test · globalgrid2050 / automation/news/tests/test_signals_official.py lines 1–169

Test Signals Acid

A test in the tests folder of GlobalGrid2050 that checks Acid Live and Acid Report.

testglobalgrid2050 / automation/news/tests/test_signals_acid.py · lines 433–960 of 960 (continued from section 810) · Entry point · pattern combine (shared by 2 files)

What it does
It tests its inputs. Defines 82 functions or classes, including known, open_item, item, part, reviewed. Uses libraries __future__, datetime, json, re, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file projects.json; JSON file false_matches.json; JSON file dates.json; JSON file tester_cases.json; JSON file tester_false_matches.json; JSON file top200_solar.json; JSON file aliases.json; JSON file reviewed_signals.json.
Downstream impact
Used directly by 3 files: GlobalGrid2050 Agent1 Producer Strict Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the known step (`known`), the open item helper (`open_item`) and the item step (`item`). Acid suite for the project signals (top 200 solar): the combiner run end to end on fixtures, the collectors' matchers and date readers, the integrated workflow and the live checker. Its code works with 500 MW.
Why it matters
Run by GlobalGrid2050 Agent1 Producer Strict Workflow, GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Acid Live (import), Acid Report (import), __future__, datetime, json, re, subprocess, sys, pathlib, pytest
Used by
run by GlobalGrid2050 Agent1 Producer Strict Workflow (workflow run), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
known, open_item, item, part, reviewed, world, Run, combine, tiers, shown, reports, find
Defines here
test_R02_the_ninety_day_boundary_is_counted_from_the_date, test_R03_an_old_article_fetched_today_is_archive_not_recent_news, test_R03_the_same_parts_combined_again_do_not_move_generated_at, test_R03_recent_news_ages_out_by_its_date_when_the_feed_stays_the_same, test_R04_a_failed_part_is_marked_stale_and_its_items_keep_their_times, test_R04_with_no_part_at_all_every_project_still_has_its_planning_file, test_R09_nothing_collected_and_nothing_before_gives_no_generated_at, test_R09_generated_at_does_not_advance_when_every_collection_fails, test_R04_a_reviewed_entry_withdrawn_from_the_committed_file_is_not_carried_for_ever, test_R05_an_undated_item_never_outranks_a_dated_one, test_R05_an_undated_item_is_archive_and_labelled_undated, test_R05_a_recent_possible_item_is_not_pushed_out_by_five_older_confirmed_ones, test_R06_a_reviewed_item_duplicated_by_a_fetched_one_is_shown_once_as_fetched, test_R06_two_articles_whose_links_differ_in_a_meaningful_query_are_both_kept, test_R06_reviewed_items_follow_their_dates_like_any_other, test_R07_an_article_naming_two_projects_is_listed_on_both_and_says_so, test_R07_an_article_naming_one_project_is_not_listed_on_another, test_R07_real_reviewed_corpus_every_shared_link_is_declared, test_R08_a_sharp_drop_in_the_counts_is_not_published, test_R08_an_ordinary_second_run_is_published, test_R10_counts_are_by_tier_and_equal_what_the_items_give, test_R10_archive_and_official_items_never_reach_the_recent_news_count, test_R10_real_reviewed_corpus_passes_every_live_rule_and_its_headline_is_small, test_R11_a_register_search_is_not_labelled_as_a_planning_file, test_R12_one_event_reported_twice_is_shown_once_with_its_sources, test_R12_the_event_is_recorded_only_where_the_title_states_it, test_R13_every_item_says_where_it_came_from_and_when, test_R14_the_integrated_workflow_runs_every_signals_suite, test_R14_the_summary_table_counts_passed_failed_and_known_failing, good_item
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/tests/test_signals_acid.py:433-960 · blob 59a9f7536572e232bcbee5021a4105606731e3c7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
    got = got[:10] if isinstance(got, str) else got
    assert got == case["expected"], "%s calendar day (%r) gave %r, the tester expects %r" % (
        case["function"], case["value"], got, case["expected"])


@known("NL-019 finding 2 and acid tester 2", "no freshness boundary exists")
@pytest.mark.parametrize("date, where", [("2026-08-16", "recent_news"), ("2026-08-15", "archive")])
def test_R02_the_ninety_day_boundary_is_counted_from_the_date(tmp_path, date, where):
    run = combine(tmp_path, {"trade": part("trade", [item("90001", "edge", "Alderwick Solar Farm update", date)])})
    lists = tiers(run.project("90001"))
    assert [name for name, items in lists.items() if items] == [where], "an item dated %s (run on 2026-11-14)" % date


# ---------------------------------------------------------------- R03 stale feed

@known("NL-019 finding 2", "freshness is inherited from the run: an article of months ago, fetched today, counts as a news signal")
def test_R03_an_old_article_fetched_today_is_archive_not_recent_news(tmp_path):
    run = combine(tmp_path, {"trade": part("trade", [item("90007", "old", "Tarnside Solar Farm plan submitted", "2026-08-01")])})
    lists = tiers(run.project("90007"))
    assert [i["link"].rsplit("/", 1)[-1] for i in lists["archive"]] == ["old"] and not lists["recent_news"]
    assert lists["archive"][0]["freshness"] == "older" and lists["archive"][0]["year"] == 2026
    assert run.doc["counts"]["headline"]["value"] == 0 and run.doc["counts"]["by_tier"]["archive_only"] == 1


@known("NL-019 finding 3", "generated_at is the clock of the run: the same parts combined a day later look freshly collected")
def test_R03_the_same_parts_combined_again_do_not_move_generated_at(tmp_path):
    first = combine(tmp_path, base_parts(), name="first")
    again = combine(tmp_path, base_parts(), now=NEXT_DAY, previous=first.out, name="again")
    assert again.code == 0, again.text[-400:]
    assert again.doc["generated_at"] == first.doc["generated_at"], "generated_at moved from %s to %s with nothing collected" % (
        first.doc["generated_at"], again.doc["generated_at"])
    assert again.doc["generated_at"] == COLLECTED, "generated_at must be the newest successful collection (%s)" % COLLECTED
    for ref in ("90001", "90003", "90008"):
        before = {i["link"]: i.get("collected_at") for i in shown(first.project(ref))}
        after = {i["link"]: i.get("collected_at") for i in shown(again.project(ref))}
        assert before == after and all(before.values()), "collected_at of the items of %s changed or is missing" % ref


@known("NL-019 finding 2", "no freshness status is computed from the date")
def test_R03_recent_news_ages_out_by_its_date_when_the_feed_stays_the_same(tmp_path):
    first = combine(tmp_path, base_parts(), name="first")
    assert [i["link"].rsplit("/", 1)[-1] for i in tiers(first.project("90003"))["recent_news"]] == ["t-mill"]
    later = combine(tmp_path, base_parts(), now="2027-03-01T12:00:00Z", previous=first.out, name="later")
    assert later.code == 0, later.text[-400:]
    lists = tiers(later.project("90003"))
    assert not lists["recent_news"] and [i["freshness"] for i in lists["archive"]] == ["older"]
    assert later.doc["counts"]["headline"]["value"] == 0


# ---------------------------------------------------------------- R04 source failure, R09 generated_at

ALL_FAILED = part("trade", [], NEXT_COLLECTED, sources=[{"id": "trade-source", "url": "https://news.example.co.uk/",
                                                           "status": "failed", "requests": 4, "failures": 4, "items": 0,
                                                           "error": "URLError: timed out"}])
BROKEN = {"missing": None, "unreadable": "{\"schema\": \"project-signals-part.v1\", \"items\": [", "raised": "Traceback (most recent call last):\n",
          "wrong-schema": json.dumps({"schema": "something-else", "items": []}), "every-source-failed": ALL_FAILED,
          "items-not-a-list": json.dumps({"schema": PART_SCHEMA, "generated_at": NEXT_COLLECTED, "items": None})}


@known("NL-019 finding 3", "a part that failed is recorded as absent, or as ok with 0 items, and never as stale; its items lose their collection time")
@pytest.mark.parametrize("how", list(BROKEN))
def test_R04_a_failed_part_is_marked_stale_and_its_items_keep_their_times(tmp_path, how):
    first = combine(tmp_path, base_parts(), name="first")
    parts = base_parts(NEXT_COLLECTED)
    parts["trade"] = BROKEN[how]
    second = combine(tmp_path, parts, now=NEXT_DAY, previous=first.out, name="second")
    assert second.code == 0, second.text[-400:]
    kept = find(second.project("90003"), "t-mill")
    assert kept, "the trade item published before was lost when the trade part failed (%s)" % how
    state = second.doc["parts"]["trade"]
    assert state["status"] == "stale", "parts.trade.status is %r after a failed collection (%s)" % (state["status"], how)
    assert state.get("collected_at") == COLLECTED and kept[0].get("collected_at") == COLLECTED
    assert second.doc.get("stale") is True
    assert second.doc["generated_at"] == NEXT_COLLECTED, "the official and index parts did succeed at %s" % NEXT_COLLECTED


def test_R04_with_no_part_at_all_every_project_still_has_its_planning_file(tmp_path):
    run = combine(tmp_path, {})
    assert run.code == 0, run.text[-400:]
    assert all(isinstance(p.get("planning_file"), dict) and p["planning_file"]["url"].startswith("https://")
               for p in run.doc["projects"].values())
    assert not any(shown(p) for p in run.doc["projects"].values())


@known("NL-019 finding 3", "a file built from nothing still carries the time of the run as generated_at")
def test_R09_nothing_collected_and_nothing_before_gives_no_generated_at(tmp_path):
    run = combine(tmp_path, {})
    assert run.code == 0, run.text[-400:]
    assert run.doc["generated_at"] is None, "generated_at is %r though nothing was ever collected" % run.doc["generated_at"]
    assert run.doc.get("stale") is True


@known("NL-019 finding 3", "every fetch failing republishes the previous items under a new generated_at")
@pytest.mark.parametrize("how", ["missing", "unreadable", "every-source-failed"])
def test_R09_generated_at_does_not_advance_when_every_collection_fails(tmp_path, how):
    first = combine(tmp_path, base_parts(), name="first")
    broken = BROKEN[how]
    parts = {team: (dict(broken, team=team) if isinstance(broken, dict) else broken) for team in ("official", "trade", "index")}
    second = combine(tmp_path, parts, now=NEXT_DAY, previous=first.out, name="second")
    assert second.doc is not None
    assert second.doc["generated_at"] == first.doc["generated_at"], "generated_at went from %s to %s although every collection failed (%s)" % (
        first.doc["generated_at"], second.doc["generated_at"], how)
    if second.code == 0:
        assert second.doc.get("stale") is True
        assert total_items(second.doc) == total_items(first.doc), "items were lost or added by a run that collected nothing"
        assert L.failures(second.doc, "2026-11-20T12:00:00Z").get("generated-at") is None, "six days later the file must still say it is stale"


@known("acid tester 5 (publishing)", "every signal of the previous file is carried for ever, so a reviewed entry that was withdrawn is republished")
def test_R04_a_reviewed_entry_withdrawn_from_the_committed_file_is_not_carried_for_ever(tmp_path):
    parts = base_parts()
    parts["reviewed"] = reviewed([item("90006", "r-wrong", "Henwick Solar Park approved", "2026-10-01", "regional")])
    first = combine(tmp_path, parts, name="first")
    assert find(first.project("90006"), "r-wrong")
    second = combine(tmp_path, base_parts(NEXT_COLLECTED), now=NEXT_DAY, previous=first.out, name="second")
    assert second.code == 0, second.text[-400:]
    assert not find(second.project("90006"), "r-wrong"), "the withdrawn reviewed entry is still published"


# ---------------------------------------------------------------- R05 undated against dated, ordering

@known("NL-019 finding 2", "confirmed first, then date: an undated or 2014 confirmed item outranks a timely uncertain one")
def test_R05_an_undated_item_never_outranks_a_dated_one(tmp_path):
    run = combine(tmp_path, {"index": part("index", [
        item("90001", "undated", "Alderwick Solar Farm: what we know", None, "regional"),
        item("90001", "old", "Alderwick Solar Farm first proposed", "2019-03-01", "regional"),
        item("90001", "fresh", "Alderwick Solar Farm decision due this week", "2026-11-12", "regional", "uncertain")])})
    order = [i["link"].rsplit("/", 1)[-1] for i in shown(run.project("90001"))]
    assert order == ["fresh", "old", "undated"], "shown in the order %s" % order
    assert not L.failures(run.doc, NOW).get("undated-order")


@known("definition 1", "an undated item carries no label saying so")
def test_R05_an_undated_item_is_archive_and_labelled_undated(tmp_path):
    run = combine(tmp_path, {"index": part("index", [item("90008", "undated", "Oxley Green Solar Farm: what we know", None, "regional"),
                                                      item("90008", "undated-official", "Oxley Green Solar Farm notice", None, "official")])})
    lists = tiers(run.project("90008"))
    assert not lists["recent_news"] and not lists["official"] and len(lists["archive"]) == 2
    assert all(i["date"] is None and i["year"] is None and i["freshness"] == "undated" for i in lists["archive"])


@known("acid tester 6 (recent news)", "the newest event is hidden: an uncertain recent item ranks below confirmed older ones and the cap of five cuts it")
def test_R05_a_recent_possible_item_is_not_pushed_out_by_five_older_confirmed_ones(tmp_path):
    older = [item("90001", "y%d" % n, "Alderwick Solar Farm report %d" % n, "2025-0%d-10" % n) for n in range(1, 8)]
    run = combine(tmp_path, {"trade": part("trade", older + [
        item("90001", "sale", "Developer sells 500MW solar NSIP in Norfolk", "2026-11-13", confidence="uncertain")])})
    kept = find(run.project("90001"), "sale")
    assert kept and shown(run.project("90001"))[0]["link"].endswith("/sale"), "the newest item is missing or not first"
    assert not confirmed(kept[0]), "an uncertain match must never be shown as fact"


# ---------------------------------------------------------------- R06 reviewed item duplicated by a fetched one

@pytest.mark.parametrize("fetched_link", [
    "https://news.example.co.uk/same?utm_source=rss&utm_medium=feed",
    "https://news.example.co.uk/same?ito=1&at_medium=rss",
    "http://news.example.co.uk/same",
    "https://NEWS.example.co.uk/same#comments"], ids=["utm", "ito-at", "http", "host-case-fragment"])
def test_R06_a_reviewed_item_duplicated_by_a_fetched_one_is_shown_once_as_fetched(tmp_path, fetched_link):
    title = "Alderwick Solar Farm granted development consent"
    run = combine(tmp_path, {
        "reviewed": reviewed([item("90001", "same", title, "2026-11-11", publisher="Example News")]),
        "trade": part("trade", [item("90001", "same", title, "2026-11-11", link=fetched_link)])})
    kept = [i for i in shown(run.project("90001")) if "/same" in i["link"]]
    assert len(kept) == 1, "the same article is listed %d times" % len(kept)
    assert kept[0]["link"] == "https://news.example.co.uk/same"
    if VERSION_1:
        assert not kept[0]["basis"].startswith("reviewed")
    else:
        assert kept[0]["obtained"] == "fetched" and kept[0]["source"] == "trade"


def test_R06_two_articles_whose_links_differ_in_a_meaningful_query_are_both_kept(tmp_path):
    run = combine(tmp_path, {"trade": part("trade", [
        item("90001", "a", "Alderwick Solar Farm granted development consent", "2026-11-11", link="https://news.example.co.uk/?p=35578"),
        item("90001", "b", "Alderwick Solar Farm: residents respond", "2026-10-02", link="https://news.example.co.uk/?p=35579")])})
    assert len(shown(run.project("90001"))) == 2


@known("NL-019 finding 2", "reviewed research is one undifferentiated pile: 326 items, 113 undated, 4 dated since 31 October 2026")
def test_R06_reviewed_items_follow_their_dates_like_any_other(tmp_path):
    run = combine(tmp_path, {"reviewed": reviewed([
        item("90007", "r-recent", "Tarnside Solar Farm approved by committee", "2026-11-06", "regional"),
        item("90007", "r-2021", "Tarnside Solar Farm plan revealed", "2021-06-01", "regional"),
        item("90007", "r-undated", "Tarnside Solar Farm: the story so far", None, "regional")])})
    lists = tiers(run.project("90007"))
    assert [(i["link"].rsplit("/", 1)[-1], i["obtained"]) for i in lists["recent_news"]] == [("r-recent", "reviewed")]
    assert [i["link"].rsplit("/", 1)[-1] for i in lists["archive"]] == ["r-2021", "r-undated"]
    assert [i["year"] for i in lists["archive"]] == [2021, None]


# ---------------------------------------------------------------- R07 multi-project articles

BOTH = "Alderwick and Brantley Moor solar farms both granted development consent"
ONE = "Alderwick Solar Farm granted development consent"


@known("NL-019 finding 6", "a link on several projects is not recorded as one article about several projects")
def test_R07_an_article_naming_two_projects_is_listed_on_both_and_says_so(tmp_path):
    run = combine(tmp_path, {"reviewed": reviewed([item("90001", "both", BOTH, "2026-11-11"), item("90002", "both", BOTH, "2026-11-11")])})
    first, second = find(run.project("90001"), "both"), find(run.project("90002"), "both")
    assert first and second, "a valid two-project story must stay on both projects"
    assert first[0].get("also_projects") == ["90002"] and second[0].get("also_projects") == ["90001"]


@known("NL-019 finding 6", "five links sit on more than one project whatever their titles say")
@pytest.mark.parametrize("obtained", ["fetched", "reviewed"])
def test_R07_an_article_naming_one_project_is_not_listed_on_another(tmp_path, obtained):
    """Definition 4: on several projects only when the title or the reviewer's evidence names each. Being in the
    reviewed file is not by itself evidence that the article names the second project (acid tester 4: one link
    is on REPD 6071 and 7630 although the reviewer's note says the article was not opened)."""
    both = [item("90001", "one", ONE, "2026-11-11"), item("90002", "one", ONE, "2026-11-11")]
    run = combine(tmp_path, {"reviewed": reviewed(both)} if obtained == "reviewed" else {"trade": part("trade", both)})
    assert find(run.project("90001"), "one"), "the article was lost from the project it names"
    assert not find(run.project("90002"), "one"), "the article is also listed on a project its title does not name"


@known("NL-019 finding 6", "the reviewed corpus has links on two projects each; the published file does not say so")
def test_R07_real_reviewed_corpus_every_shared_link_is_declared(tmp_path):
    run = combine(tmp_path, {"reviewed": REVIEWED}, top200=SIGNALS / "top200_solar.json", aliases=SIGNALS / "aliases.json")
    where = {}
    for ref, project in run.doc["projects"].items():
        for one in shown(project):
            where.setdefault(one["link"], []).append((ref, one))
    shared = {link: places for link, places in where.items() if len(places) > 1}
    undeclared = sorted(link for link, places in shared.items()
                        if any(sorted(one.get("also_projects") or []) != sorted(r for r, _ in places if r != ref) for ref, one in places))
    assert not undeclared, "%d link(s) on more than one project without also_projects: %s" % (len(undeclared), undeclared[:5])


# ---------------------------------------------------------------- R08 a sharp drop in the counts

@known("definition 5 and acid tester 5", "nothing stops publication when the counts fall sharply; the only gate (nothing == 0) cannot fire")
def test_R08_a_sharp_drop_in_the_counts_is_not_published(tmp_path):
    first = combine(tmp_path, base_parts(), name="first")
    before = first.out.read_bytes()
    had, had_items = projects_with_items(first.doc), total_items(first.doc)
    assert had >= 6
    wipe = {ref: {"exclude": ["solar"]} for ref in WORLD["aliases"]["projects"] if ref != "90001"}
    second = combine(tmp_path, base_parts(NEXT_COLLECTED), now=NEXT_DAY, previous=first.out, name="second", aliases_patch=wipe)
    if second.code == 0:
        assert projects_with_items(second.doc) * 3 >= had * 2 and total_items(second.doc) * 3 >= had_items * 2, \
            "published with %d of %d projects and %d of %d items left" % (
                projects_with_items(second.doc), had, total_items(second.doc), had_items)
    else:
        assert second.code == 3, "refusal must be exit code 3, got %d: %s" % (second.code, second.text[-300:])
        assert second.out.read_bytes() == before, "the combiner refused but still changed the published file"
        assert re.search(r"drop|fell|fall|third", second.text, re.I), "the refusal does not say why"


def test_R08_an_ordinary_second_run_is_published(tmp_path):
    first = combine(tmp_path, base_parts(), name="first")
    second = combine(tmp_path, base_parts(NEXT_COLLECTED), now=NEXT_DAY, previous=first.out, name="second")
    assert second.code == 0 and total_items(second.doc) >= total_items(first.doc), second.text[-400:]


# ---------------------------------------------------------------- R10 tiers and counts

@known("NL-019 findings 1, 2 and 8", "'161 of 200 with a signal' mixes recent news, old articles, official notices and reviewed research")
def test_R10_counts_are_by_tier_and_equal_what_the_items_give(tmp_path):
    run = combine(tmp_path, base_parts())
    assert not L.failures(run.doc, NOW), L.failures(run.doc, NOW)
    counts = run.doc["counts"]
    assert {ref: p["tier"] for ref, p in run.doc["projects"].items()} == {
        "90001": "recent_news", "90002": "official", "90003": "recent_news", "90004": "planning_file_only",
        "90005": "planning_file_only", "90006": "planning_file_only", "90007": "recent_news", "90008": "archive_only",
        "9050": "archive_only"}
    assert counts["by_tier"] == {"recent_news": 3, "official": 1, "archive_only": 2, "planning_file_only": 3, "nothing": 0}
    assert counts["headline"] == {"label": "projects with recent candidate news (independent evidence pending)", "value": 3}
    assert not {"with_signal", "with_confirmed_signal", "split"} & set(counts)


@known("NL-019 finding 2", "old and undated articles are counted with the news")
def test_R10_archive_and_official_items_never_reach_the_recent_news_count(tmp_path):
    run = combine(tmp_path, {
        "official": part("official", [item("90002", "o1", "Brantley Moor Solar Farm: decision", "2026-11-12", "official")]),
        "trade": part("trade", [item("90008", "t-2021", "Oxley Green Solar Farm proposed", "2021-05-04"),
                                item("90007", "t-possible", "Tarnside Solar Farm sold", "2026-11-12", confidence="uncertain"),
                                item("90001", "dev", "Alderwick Solar Farm: our plans", "2026-11-12", "developer",
                                     link="https://www.lightsourcebp.com/alderwick")])})
    counts = run.doc["counts"]
    assert counts["headline"]["value"] == 0 and counts["by_tier"]["recent_news"] == 0
    assert counts["by_tier"]["official"] == 1 and counts.get("with_possible_recent_news") == 1
    assert tiers(run.project("90001"))["archive"] and not tiers(run.project("90001"))["recent_news"], \
        "a developer's own page is not news, whatever its date"
    assert not L.failures(run.doc, NOW), L.failures(run.doc, NOW)


@known("NL-019 finding 2", "the committed reviewed corpus is shown as current signals")
def test_R10_real_reviewed_corpus_passes_every_live_rule_and_its_headline_is_small(tmp_path):
    run = combine(tmp_path, {"reviewed": REVIEWED}, top200=SIGNALS / "top200_solar.json", aliases=SIGNALS / "aliases.json")
    assert run.code == 0, run.text[-400:]
    problems = L.failures(run.doc, NOW)
    problems.pop("generated-at", None)          # nothing live was collected in this run: stale by design
    assert not problems, {rule: lines[:3] for rule, lines in problems.items()}
    cutoff = (dt.date(2026, 11, 14) - dt.timedelta(days=90)).isoformat()
    recent = {str(i["repd_ref"]) for i in REVIEWED["items"]
              if i.get("family") in NEWS_FAMILIES and isinstance(i.get("date"), str) and cutoff <= i["date"][:10] <= "2026-11-15"}
    value = run.doc["counts"]["headline"]["value"]
    assert value <= len(recent), "headline %d, but only %d projects have a reviewed publisher article since %s" % (value, len(recent), cutoff)


# ---------------------------------------------------------------- R11 planning file labels

@known("NL-019 finding 7", "every kind of link is labelled 'planning file', including an unverified search page")
def test_R11_a_register_search_is_not_labelled_as_a_planning_file(tmp_path):
    run = combine(tmp_path, {})
    for ref, project in run.doc["projects"].items():
        file = project["planning_file"]
        assert file["label"] in L.LABELS, "REPD %s: label %r" % (ref, file["label"])
        if file["kind"] == "search_page":
            assert file["label"].startswith("planning register") and file["link_type"] == "search" and file["verified"] is False
        else:
            assert file["label"].startswith("planning file (") and file["link_type"] == "direct"
        assert (file["label"] == "planning file (verified link)") == (file["verified"] is True)
    assert run.project("90006")["planning_file"]["label"].startswith("planning register")
    assert set(run.doc["counts"]["planning_file"]) == {"verified_direct", "unverified_direct", "register_search", "register_finder"}
    assert sum(run.doc["counts"]["planning_file"].values()) == len(run.doc["projects"])


# ---------------------------------------------------------------- R12 events and clusters

@known("definition 8 and NL-019 finding 6", "no event type; the same story from two publishers is two headlines, or one is silently dropped")
def test_R12_one_event_reported_twice_is_shown_once_with_its_sources(tmp_path):
    run = combine(tmp_path, {"trade": part("trade", [
        item("90001", "a", "Alderwick Solar Farm granted development consent", "2026-11-10", publisher="Example News"),
        item("90001", "b", "Alderwick Solar Farm wins development consent from Secretary of State", "2026-11-12", publisher="Other Press"),
        item("90002", "c", "Brantley Moor Solar Farm refused development consent", "2026-11-10")])})
    recent = tiers(run.project("90001"))["recent_news"]
    assert len(recent) == 1, "one consent, two reports: %d headlines shown" % len(recent)
    assert recent[0]["event"] == "consent" and recent[0]["link"].endswith("/b"), "the item shown is the newest dated confirmed one"
    assert recent[0].get("cluster") == "90001:consent:2026-11-10"
    assert [s["link"].rsplit("/", 1)[-1] for s in recent[0].get("sources") or []] == ["a"]
    assert tiers(run.project("90002"))["recent_news"][0]["event"] == "refusal"


@known("definition 8", "no event type is recorded")
@pytest.mark.parametrize("title, event", [
    ("Alderwick Solar Farm granted development consent", "consent"),
    ("Alderwick Solar Farm refused by Secretary of State", "refusal"),
    ("Alderwick Solar Farm appeal lodged", "appeal"),
    ("Alderwick Solar Farm reaches financial close", "financial_close"),
    ("Construction starts at Alderwick Solar Farm", "construction_start"),
    ("Alderwick Solar Farm energised", "energisation"),
    ("Alderwick Solar Farm: residents' views", None)])
def test_R12_the_event_is_recorded_only_where_the_title_states_it(tmp_path, title, event):
    run = combine(tmp_path, {"trade": part("trade", [item("90001", "e", title, "2026-11-10")])})
    kept = find(run.project("90001"), "e")
    assert kept and "event" in kept[0] and kept[0]["event"] == event, "event %r for %r" % (kept[0].get("event") if kept else None, title)


# ---------------------------------------------------------------- R13 provenance on every item

@known("definition 1 and NL-019 finding 1", "items carry no provenance: not how obtained, not which part, not when collected")
def test_R13_every_item_says_where_it_came_from_and_when(tmp_path):
    parts = base_parts()
    parts["reviewed"] = reviewed([item("90006", "r1", "Henwick Solar Park approved", "2026-10-01", "regional")])
    run = combine(tmp_path, parts)
    assert not L.failures(run.doc, NOW).get("schema"), L.failures(run.doc, NOW).get("schema")[:5]
    got = {i["link"].rsplit("/", 1)[-1]: (i["source"], i["obtained"], i["collected_at"]) for p in run.doc["projects"].values() for i in shown(p)}
    assert got["t-mill"] == ("trade", "fetched", COLLECTED) and got["o-consent"] == ("official", "fetched", COLLECTED)
    assert got["r1"][:2] == ("reviewed", "reviewed")
    assert set(run.doc["parts"]) >= {"official", "trade", "index", "reviewed", "planning"}
    assert run.doc["generated_at"] == COLLECTED and run.doc["run_at"] == NOW and run.doc["stale"] is False


# ---------------------------------------------------------------- R14 the integrated workflow

WORKFLOW = REPO / ".github" / "workflows" / "project-signals-acid.yml"


def test_R14_the_integrated_workflow_runs_every_signals_suite():
    text = WORKFLOW.read_text(encoding="utf-8")
    suites = sorted(str(p.relative_to(REPO)).replace("\\", "/") for p in
                    list(TESTS.glob("test_signals_*.py")) + list((SIGNALS / "tests").glob("test_*.py")))
    assert len(suites) >= 6
    missing = [s for s in suites if s not in text]
    assert not missing, "not run by the integrated workflow: %s" % missing
    assert "schedule:" in text and "pull_request:" in text and "automation/news/signals/**" in text
    assert "acid_report.py" in text and "acid_live.py" in text and "GITHUB_STEP_SUMMARY" in text
    assert "contents: read" in text and "contents: write" not in text, "the acid workflow must not be able to write"


def test_R14_the_summary_table_counts_passed_failed_and_known_failing(tmp_path):
    (tmp_path / "combiner.xml").write_text(
        '<testsuites><testsuite><testcase classname="a.b" name="ok"/><testcase classname="a.b" name="bad"><failure message="boom"/></testcase>'
        '<testcase classname="a.b" name="known"><skipped type="pytest.xfail" message="NL-019 finding 3: x"/></testcase>'
        '<testcase classname="a.b" name="open"><skipped type="pytest.xfail" message="OPEN, outside contract v2: y"/></testcase>'
        '<testcase classname="a.b" name="skip"><skipped type="pytest.skip" message="s"/></testcase></testsuite></testsuites>', encoding="utf-8")
    code = acid_report.main([str(tmp_path), "--expect", "combiner,trade", "--summary", str(tmp_path / "s.md"), "--json", str(tmp_path / "s.json")])
    text = (tmp_path / "s.md").read_text(encoding="utf-8")
    assert code == 1 and "| combiner | 5 | 1 | **1** | 1 | 1 | 1 |" in text
    assert "| trade | 0 | 0 | **1** | 0 | 0 | 0 |" in text, "a suite that did not run must count as failed"
    assert "NL-019 finding 3: x" in text and "| suite | tests | passed | failed |" in text
    (tmp_path / "combiner.xml").write_text('<testsuites><testsuite><testcase classname="a.b" name="ok"/></testsuite></testsuites>', encoding="utf-8")
    assert acid_report.main([str(tmp_path), "--expect", "combiner"]) == 0


# ---------------------------------------------------------------- R15 the live checker

def good_item(slug, date, tier, family="trade", confidence="confirmed", title=None):
    day = L.parse_day(date)
    fresh = "undated" if day is None else "recent" if day >= dt.date(2026, 8, 16) else "older"
    return {"title": title or "Example Solar Farm %s" % slug, "link": "https://news.example.co.uk/%s" % slug, "publisher": "Example News",
            "date": date, "year": day.year if day else None, "tier": tier, "event": None, "obtained": "fetched", "source": "trade",
            "family": family, "collected_at": COLLECTED, "confidence": confidence, "freshness": fresh, "basis": "exact phrase in title"}


def good_file():
    def project(ref, tier, recent=(), official=(), archive=(), label="planning register search"):
        return {"repd_ref": ref, "rank": 1, "site_name": "Example", "alias": "Example Solar Farm", "alias_standing": "confirmed",
                "tier": tier, "recent_news": list(recent), "official": list(official), "archive": list(archive),
                "planning_file": {"label": label, "link_type": "direct" if label.startswith("planning file") else "search",
                                  "authority": "Example", "reference": "1/2", "url": "https://register.example.gov.uk/", "kind":
                                  "application" if label.startswith("planning file") else "search_page",
                                  "verified": label == "planning file (verified link)", "note": ""}}
    projects = {
        "1": project("1", "recent_news", [good_item("a", "2026-11-10", "recent_news")], [], [good_item("b", "2021-01-05", "archive"),
                                                                                             good_item("c", None, "archive")]),
        "2": project("2", "official", [], [good_item("d", "2025-02-01", "official", "official")], label="planning file (verified link)"),
        "9050": project("9050", "archive_only", [], [], [good_item("e", "2021-02-17", "archive", "regional", title="Solar farm at Foston wins approval")]),
        "4": project("4", "planning_file_only")}
    ok = {"status": "ok", "collected_at": COLLECTED, "items": 1, "note": ""}
    return {"schema": "project-signals.v2", "generated_at": COLLECTED, "run_at": NOW, "stale": False, "scope": "test", "recent_days": 90,
            "parts": {"official": dict(ok), "trade": dict(ok), "index": dict(ok), "reviewed": dict(ok), "planning": dict(ok)},
            "counts": {"projects": 4, "headline": {"label": "projects with recent candidate news (independent evidence pending)", "value": 1},
                       "by_tier": {"recent_news": 1, "official": 1, "archive_only": 1, "planning_file_only": 1, "nothing": 0},
                       "possible_only": 0, "with_recent_news": 1, "with_official": 1, "with_archive": 2, "with_possible_recent_news": 0,
                       "items": {"recent_news": 1, "official": 1, "archive": 3},
                       "planning_file": {"verified_direct": 1, "unverified_direct": 0, "register_search": 3, "register_finder": 0}},
            "dropped": {}, "sources": [], "projects": projects}


def test_R15_live_checker_passes_a_file_that_meets_the_contract():
    assert L.failures(good_file(), NOW) == {}


def test_R15_new_v2_must_not_call_uncleared_project_news_verified():
    doc = good_file()
    # Changing only the wording to the historical label must be rejected even
    # if all other dates, tiers and synthetic fixture values are consistent.
    doc["counts"]["headline"]["label"] = "projects with recent verified news"
    failures = L.failures(doc, NOW)
    assert "schema" in failures
    assert any("candidate news" in message for message in failures["schema"])
    # Source-history readback belongs to its own pinned old revision; it is
    # never used as an exception in the current producer's publication gate.


def _diode(doc):
    doc["projects"]["9050"]["archive"][0]["title"] = "New bypass diode design cuts shading losses in PV modules"


def _undated_first(doc):
    doc["projects"]["1"]["archive"].reverse()


def _headline(doc):
    doc["counts"]["headline"]["value"] = 3


def _by_tier(doc):
    doc["counts"]["by_tier"].update(recent_news=2, archive_only=0)


def _old_as_recent(doc):
    moved = doc["projects"]["1"]["archive"].pop(0)
    doc["projects"]["1"]["recent_news"].append(dict(moved, tier="recent_news"))


def _nothing(doc):
    doc["projects"]["4"]["planning_file"] = None


def _future(doc):
    doc["projects"]["1"]["recent_news"][0].update(date="2027-01-01", year=2027)


def _impossible(doc):
    doc["projects"]["1"]["recent_news"][0].update(date="2026-02-30")


def _old_stamp(doc):
    doc["generated_at"] = "2026-11-10T05:00:00Z"
    for name in ("official", "trade", "index"):
        doc["parts"][name]["collected_at"] = "2026-11-10T05:00:00Z"


def _fresh_stamp_over_stale_parts(doc):
    for name in ("official", "trade", "index"):
        doc["parts"][name].update(status="stale", collected_at="2026-11-10T05:00:00Z")
    doc["stale"] = True


def _version_1(doc):
    doc["schema"] = "project-signals.v1"


@pytest.mark.parametrize("damage, rule", [
    (_diode, "repd-9050"), (_undated_first, "undated-order"), (_headline, "tier-counts"), (_by_tier, "tier-counts"),
    (_old_as_recent, "tier-purity"), (_nothing, "nothing"), (_future, "dates"), (_impossible, "dates"),
    (_old_stamp, "generated-at"), (_version_1, "schema")], ids=lambda v: getattr(v, "__name__", v))
def test_R15_live_checker_names_the_rule_that_is_broken(damage, rule):
    doc = good_file()
    damage(doc)
    assert rule in L.failures(doc, NOW), "the checker did not report %r" % rule


def test_R15_live_checker_accepts_an_old_generated_at_only_when_the_file_says_stale():
    doc = good_file()
    _old_stamp(doc)
    _fresh_stamp_over_stale_parts(doc)
    assert "generated-at" not in L.failures(doc, NOW)
    doc["stale"] = False
    assert "generated-at" in L.failures(doc, NOW)


def test_R15_live_checker_exit_code_and_summary_name_the_rule(tmp_path):
    doc = good_file()
    _diode(doc)
    path, summary = tmp_path / "project_signals.json", tmp_path / "summary.md"
    path.write_text(json.dumps(doc), encoding="utf-8")
    assert L.main([str(path), "--now", NOW, "--summary", str(summary)]) == 1
    assert "Failed: repd-9050" in summary.read_text(encoding="utf-8")
    path.write_text(json.dumps(good_file()), encoding="utf-8")
    assert L.main([str(path), "--now", NOW]) == 0
    path.write_text("not json", encoding="utf-8")
    assert L.main([str(path), "--now", NOW]) == 1

Test Signals Official

A test in the tests folder of GlobalGrid2050 that checks Official. It is built from the project step (`project`), the fake fetcher class (`FakeFetcher`) and the get step (`get`).

testglobalgrid2050 / automation/news/tests/test_signals_official.py · lines 1–169 of 169 · Entry point · pattern opener (shared by 2 files)

What it does
It tests solar. Defines 15 functions or classes, including project, FakeFetcher, __init__, get, test_derive_alias_strips_place_prefix_and_storage_tail. Uses libraries __future__, json, sys, urllib.error, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
Inputs & outputs
In: JSON file aliases.json.
Downstream impact
Used directly by 4 files: Test Signals Planning File (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Project Signals Official Workflow (globalgrid2050).
What it achieves
Tests for `automation/news/signals/official.py`. Offline: synthetic responses in the shape each source returns.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow, GlobalGrid2050 Project Signals Acid Workflow and GlobalGrid2050 Project Signals Official Workflow. Checked by Test Signals Planning File.
Application
globalgrid2050 · automation/news/tests · test
Uses
Official (sys.path import), __future__, json, sys, urllib.error, pathlib, pytest
Used by
imported by Test Signals Planning File (import), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 Project Signals Official Workflow (workflow run)
Produces
project, FakeFetcher, test_derive_alias_strips_place_prefix_and_storage_tail, test_match_needs_the_alias_in_the_title_or_summary_with_a_second_fact, test_match_whole_words_exclusions_and_uncertain_aliases, test_pins_csv_gives_the_newest_past_milestone_by_reference, test_pins_lookup_by_alias_only_for_inspectorate_rows_without_a_national_reference, test_govuk_search_keeps_matching_results_only, test_one_failing_source_never_stops_a_run, test_fetcher_throttles_per_host_retries_once_on_429_and_caps, test_shipped_tables_cover_the_200
Defines here
project, FakeFetcher, __init__, get, test_derive_alias_strips_place_prefix_and_storage_tail, test_match_needs_the_alias_in_the_title_or_summary_with_a_second_fact, test_match_whole_words_exclusions_and_uncertain_aliases, test_pins_csv_gives_the_newest_past_milestone_by_reference, test_pins_lookup_by_alias_only_for_inspectorate_rows_without_a_national_reference, test_govuk_search_keeps_matching_results_only, test_one_failing_source_never_stops_a_run, test_fetcher_throttles_per_host_retries_once_on_429_and_caps, opener, sleep, test_shipped_tables_cover_the_200
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/tests/test_signals_official.py:1-169 · blob 5cfb3810309c515b25852a82c58c033645cdd353 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Tests for automation/news/signals/official.py. Offline: synthetic responses in the shape each source returns."""
from __future__ import annotations

import json
import sys
import urllib.error
from pathlib import Path

import pytest

SIG = Path(__file__).resolve().parents[1] / "signals"
sys.path.insert(0, str(SIG))

import official as O  # noqa: E402

NOW = "2026-11-14T12:00:00Z"
PINS_CSV = (
    "Project reference,Project name,Applicant name,Stage,Date of application,Date of decision,"
    "Anticipated submission date\r\n"
    "EN010147,Botley West Solar Farm,SolarFive Ltd,Decided,15/11/2024,10/11/2026,\r\n"
    "EN010148,Tween Bridge Solar Farm,RWE,Recommendation,2025-08-01,,\r\n"
    "EN010999,Hedgehog Grove Solar Farm,Example,Pre-application,,,01/03/2027\r\n"
    "EN020001,Some Power Line,National Grid,Decided,01/01/2020,01/01/2022,\r\n").encode()
GOVUK = {"results": [
    {"title": "Botley West Solar Farm: development consent decision", "link": "/government/publications/botley-west",
     "public_timestamp": "2026-11-10T15:00:00.000+00:00", "organisations": [{"title": "Department for Energy Security and Net Zero"}],
     "format": "decision", "description": "Decision on the application for development consent."},
    {"title": "Planning decisions this week", "link": "/government/news/decisions",
     "public_timestamp": "2026-11-11T09:00:00Z", "organisations": [], "format": "news",
     "description": "Includes Botley West Solar Farm in Oxfordshire."},
    {"title": "Botley village hall grant", "link": "/government/news/botley-hall",
     "public_timestamp": "2026-10-01T09:00:00Z", "organisations": [], "format": "news", "description": "A grant."},
]}


def project(ref="12588", alias="Botley West Solar Farm", pref="EN010147", authority="The Planning Inspectorate - National Infrastructure",
            status="confirmed", **extra):
    base = {"repd_ref": ref, "rank": 1, "site_name": alias, "operator": "Photovolt Development Partners & SolarFive",
            "mw": 840.0, "county": "Oxfordshire", "country": "England", "planning_authority": authority,
            "planning_ref": pref, "aliases": [alias], "alias_status": status, "exclude": [], "planning_file": None}
    base.update(extra)
    return base


class FakeFetcher:
    def __init__(self, routes):
        self.routes, self.calls = routes, []

    def get(self, url, accept="*/*"):
        self.calls.append(url)
        for prefix, value in self.routes.items():
            if url.startswith(prefix):
                if isinstance(value, Exception):
                    raise value
                return url, "text/plain", value(url) if callable(value) else value
        raise O.FetchError("HTTP 404", 404)


def test_derive_alias_strips_place_prefix_and_storage_tail():
    assert O.derive_alias("Springwell, Lincoln - Springwell Solar Farm & Battery Storage") == "Springwell Solar Farm"
    assert O.derive_alias("Bolt Hall Farm, Lark Hill Road - Solar Photovoltaic Farm") == "Bolt Hall Farm Solar Farm"
    assert O.derive_alias("Longfield") == "Longfield Solar Farm"
    assert O.derive_alias("The Tween Bridge Solar Farm ") == "Tween Bridge Solar Farm"


def test_match_needs_the_alias_in_the_title_or_summary_with_a_second_fact():
    p = project()
    assert O.match(p, "Botley West Solar Farm refused consent")[1] == "confirmed"
    assert O.match(p, "Planning decisions", "Includes Botley West Solar Farm in Oxfordshire.")
    assert O.match(p, "Planning decisions", "Includes Botley West Solar Farm.") is None
    assert O.match(p, "Botley village hall grant", "A grant.") is None
    assert O.match(p, "Decision letter EN010147") [0].startswith("planning reference")
    assert O.match(p, "Botley West: solar scheme decision")           # core of the alias plus a solar term


def test_match_whole_words_exclusions_and_uncertain_aliases():
    p = project(alias="Longfield Solar Farm", status="uncertain", exclude=["Longfield Academy"])
    assert O.match(p, "Longfield Solar Farm approved")[1] == "uncertain"
    assert O.match(p, "Longfields Solar Farm approved") is None
    assert O.match(p, "Longfield Solar Farm visit by Longfield Academy") is None
    generic = project(alias="Cowley Complex", pref="20/2131/FUL", authority="Stockton-on-Tees")
    assert O.match(generic, "Cowley Complex opens") is None           # no solar or energy word anywhere
    assert O.match(generic, "Cowley Complex solar farm opens")


def test_pins_csv_gives_the_newest_past_milestone_by_reference():
    rows = O.parse_pins_csv(PINS_CSV)
    assert [r["ref"] for r in rows] == ["EN010147", "EN010148", "EN010999", "EN020001"]
    items, found = O.pins_items([project(), project("12926", "Tween Bridge Solar Farm", "EN010148")], rows, "2026-11-14")
    assert items[0]["date"] == "2026-11-10" and items[0]["title"] == "Botley West Solar Farm: decision (stage: Decided)"
    assert items[0]["link"].endswith("/projects/EN010147") and items[0]["family"] == "official"
    assert items[0]["confidence"] == "confirmed" and items[0]["publisher"] == "Planning Inspectorate"
    assert items[1]["date"] == "2025-08-01" and "application" in items[1]["title"]
    assert set(found) == {"12588", "12926"}


def test_pins_lookup_by_alias_only_for_inspectorate_rows_without_a_national_reference():
    rows = O.parse_pins_csv(PINS_CSV)
    hedgehog = project("18870", "Hedgehog Grove Solar Farm", "26/00440/FUL")
    items, _ = O.pins_items([hedgehog], rows, "2026-11-14")
    assert items[0]["date"] is None and items[0]["confidence"] == "uncertain" and "EN010999" in items[0]["link"]
    local = project("1", "Tween Bridge Solar Farm", "21/0001/FUL", authority="Doncaster")
    assert O.pins_items([local], rows, "2026-11-14")[0] == []
    with pytest.raises(ValueError):
        O.parse_pins_csv(b"a,b\n1,2\n")


def test_govuk_search_keeps_matching_results_only():
    fetcher = FakeFetcher({O.GOVUK_SEARCH: json.dumps(GOVUK).encode()})
    items, record = O.source_govuk([project()], fetcher)
    assert [i["link"] for i in items] == ["https://www.gov.uk/government/news/decisions",
                                          "https://www.gov.uk/government/publications/botley-west"]
    assert items[1]["publisher"] == "Department for Energy Security and Net Zero" and items[1]["date"] == "2026-11-10"
    assert record["status"] == "ok" and record["requests"] == 2 and record["items"] == 2
    assert "%22Botley+West+Solar+Farm%22" in fetcher.calls[0] and "q=EN010147" in fetcher.calls[1]


def test_one_failing_source_never_stops_a_run():
    fetcher = FakeFetcher({O.PINS_CSV: O.FetchError("HTTP 503", 503), O.GOVUK_SEARCH: json.dumps(GOVUK).encode(),
                           "https://www.energyconsents.scot/": b"<html><title>Case</title>ECU00005085 Bowshiel Solar Farm</html>"})
    scottish = project("17779", "Bowshiel Solar Farm", "ECU00005085", authority="Scottish Government (S36)")
    items, records, _ = O.run([project(), scottish], fetcher, "2026-11-14")
    status = {r["id"]: r["status"] for r in records}
    assert status == {"pins-register": "failed", "govuk-search": "ok", "ecu-case": "ok"}
    ecu = [i for i in items if i["repd_ref"] == "17779"]
    assert ecu and ecu[0]["date"] is None and ecu[0]["confidence"] == "confirmed" and "ECU00005085" in ecu[0]["link"]
    part = O.build_part(items, records, NOW)
    assert part["schema"] == "project-signals-part.v1" and part["team"] == "official"
    for it in part["items"]:
        assert set(it) >= {"repd_ref", "title", "link", "publisher", "date", "family", "basis", "confidence"}
        assert it["family"] == "official" and it["link"].startswith("https://") and len(it["title"]) <= 300
    report = O.probe_report([project(), scottish], items, records, NOW)
    assert "2 of 2 projects" in report and "pins-register" in report


def test_fetcher_throttles_per_host_retries_once_on_429_and_caps():
    slept, clock, calls = [], [0.0], []

    def opener(url, accept):
        calls.append(url)
        if len(calls) == 2:
            raise urllib.error.HTTPError(url, 429, "Too Many", {}, None)
        return 200, url, "text/plain", b"ok"

    def sleep(seconds):
        slept.append(seconds)
        clock[0] += seconds

    f = O.Fetcher(opener=opener, sleep=sleep, clock=lambda: clock[0], host_cap=4)
    assert f.get("https://a.example/1")[2] == b"ok"
    assert f.get("https://a.example/2")[2] == b"ok"            # 429, wait ten seconds, one retry
    assert 10 in slept and slept[0] == pytest.approx(1.0)
    assert f.get("https://b.example/1")[2] == b"ok"            # another host: its own allowance
    f.get("https://a.example/3")
    with pytest.raises(O.FetchError):
        f.get("https://a.example/4")                           # cap of four requests for the host
    with pytest.raises(O.FetchError):
        f.get("http://a.example/plain")


def test_shipped_tables_cover_the_200():
    projects = O.load_projects()
    assert len(projects) == 200 and len({p["repd_ref"] for p in projects}) == 200
    table = json.loads((SIG / "aliases.json").read_text(encoding="utf-8"))
    assert table["schema"] == "project-signal-aliases.v1" and set(table["projects"]) == {p["repd_ref"] for p in projects}
    for p in projects:
        assert p["aliases"] and all(len(a) >= 4 for a in p["aliases"]) and p["alias_status"] in ("confirmed", "uncertain", "derived")
    text = (SIG / "aliases.json").read_text(encoding="utf-8")
    assert "@" not in text.replace("@id", "") and "/home/" not in text