GLOBALGRID2050 / EXPLORE CODE

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

Test Index and 1 more file

A test in the tests folder of GlobalGrid2050. It is built from the rss step (`rss`), the projects step (`projects`) and the fetch step (`fetch`).

560 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 797 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 Gate test · globalgrid2050 / automation/news/signals/tests/test_gate.py lines 1–258
  2. Test Index test · globalgrid2050 / automation/news/signals/tests/test_index.py lines 1–302

Test Gate

A test in the tests folder of GlobalGrid2050.

testglobalgrid2050 / automation/news/signals/tests/test_gate.py · lines 1–258 of 258 · Entry point

What it does
It tests its inputs. Defines 14 functions or classes, including test_gate_verdicts_on_the_plain_cases, test_no_false_headline_is_confirmed_by_the_gate_beyond_the_known_few, test_true_headlines_survive_the_gate, test_east_yorkshire_alias_is_not_a_wrong_county, test_weak_development_candidates_never_become_confirmed_from_place_or_developer_alone. Uses libraries __future__, datetime, json, sys, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file gate_cases.json; JSON file exclusions.json; JSON file aliases.json; JSON file top200_solar.json; JSON file alias_standings.json; JSON file reviewed_signals.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Offline tests for the shared title gate (`gate.py`) and date rule (`dates.py`), through all three collectors. Its code works with 400 MW, 840 MW and 49.99 MW.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/signals/tests · test
Uses
__future__, datetime, json, sys, pathlib, combine, dates, gate
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
test_gate_verdicts_on_the_plain_cases, test_no_false_headline_is_confirmed_by_the_gate_beyond_the_known_few, test_true_headlines_survive_the_gate, test_east_yorkshire_alias_is_not_a_wrong_county, test_weak_development_candidates_never_become_confirmed_from_place_or_developer_alone, test_all_three_collectors_reject_the_false_headlines, test_collectors_still_match_the_true_headlines, test_combiner_purges_a_carried_false_match_and_keeps_reviewed_items, test_shared_links_follow_the_reviewers_findings, test_link_key_recognises_copies_of_one_page, test_one_date_rule_for_collectors_and_combiner, test_year_is_kept_for_an_undated_item_when_the_link_or_the_reviewer_gives_it
Defines here
test_gate_verdicts_on_the_plain_cases, test_no_false_headline_is_confirmed_by_the_gate_beyond_the_known_few, test_true_headlines_survive_the_gate, test_east_yorkshire_alias_is_not_a_wrong_county, test_weak_development_candidates_never_become_confirmed_from_place_or_developer_alone, test_all_three_collectors_reject_the_false_headlines, test_collectors_still_match_the_true_headlines, test_combiner_purges_a_carried_false_match_and_keeps_reviewed_items, test_shared_links_follow_the_reviewers_findings, on, test_link_key_recognises_copies_of_one_page, test_one_date_rule_for_collectors_and_combiner, test_year_is_kept_for_an_undated_item_when_the_link_or_the_reviewer_gives_it, test_a_part_file_older_than_two_days_is_stale_not_ok
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/signals/tests/test_gate.py:1-258 · blob edc212c9a9287833a4c2ea36b8e872913fc708f7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Offline tests for the shared title gate (gate.py) and date rule (dates.py), through all three collectors."""
from __future__ import annotations

import datetime as dt
import json
import sys
from pathlib import Path

SIGNALS = Path(__file__).resolve().parents[1]
for path in (str(SIGNALS.parent), str(SIGNALS)):
    if path not in sys.path:
        sys.path.insert(0, path)

import combine as C  # noqa: E402
import dates as DATES  # noqa: E402
import gate as G  # noqa: E402
import index as I  # noqa: E402
import official as O  # noqa: E402
import trade as T  # noqa: E402

CASES = json.loads((SIGNALS / "tests" / "fixtures" / "gate_cases.json").read_text(encoding="utf-8"))
EXCLUSIONS = json.loads((SIGNALS / "exclusions.json").read_text(encoding="utf-8"))["projects"]
TODAY = dt.date(2026, 11, 14)


def test_gate_verdicts_on_the_plain_cases():
    for ref, title, verdict in (
            ("12588", "UK government refuses 840MW Botley West Solar Farm", "ok"),
            ("12588", "Botley West footpath closed after landslip", "drop"),              # a distinctive name alone
            ("12588", "Miliband refuses Botley West", "possible"),                        # planning word, no solar term
            ("12588", "Decision on EN010147 published", "ok"),                            # the reference is enough
            ("12588", "Huge solar farm refused in Oxfordshire", "none"),                  # the title does not name it
            ("9050", "Contractor named for £60m Lincolnshire bypass", "drop"),            # name and county, no solar term
            ("9050", "Bypass diodes: why solar modules fail in the field", "drop"),
            ("17429", "Fosse Way near Leamington now clear after earlier accident", "drop"),
            ("12117", "The new pavements installed on Cardiff's Cowbridge Road and how they work", "drop"),
            ("8483", "Belvoir Castle sees visitor numbers rise as it opens for the new season", "drop"),
            ("10529", "New life for Red House", "drop"),
            ("11678", "East Yorkshire bus drivers vote to strike", "drop"),
            ("7945", "Cornwell solar panels on village hall", "drop"),                    # panels are not a solar farm
            ("19007", "Thornton solar farm plan in Lancashire", "drop"),                  # another county
            ("11476", "Helios Solar Farm reaches financial close in Spain", "drop"),      # abroad
            ("6012", "Kells solar farm plan in County Meath", "drop"),
            ("8479", "Octopus Energy fined for breach of supply rules", "drop"),          # a developer and an everyday word
            ("15252", "RES wins permit for 450MW Steeple solar farm", "ok"),
            ("7188", "500MW Sunnica permit call hit by fresh delay", "ok"),               # the project's own capacity
            ("9904", "Windel, Canadian Solar file Mallard Pass paperwork", "ok"),         # "Canadian" is the developer here
            ("14096", "Cubico opens Frodsham consultation", "possible")):                 # developer only
        assert G.judge(ref, title)[0] == verdict, (ref, title, G.judge(ref, title))
    assert G.judge("15793", "Green Hill Solar Farm development consent decision announced", official=True)[0] == "ok"
    assert G.judge("99999", "Anything") == ("none", "")


def test_no_false_headline_is_confirmed_by_the_gate_beyond_the_known_few():
    verdicts = [G.judge(ref, title)[0] for ref, title, _real in CASES["false"]]
    assert len(verdicts) == 240
    assert verdicts.count("ok") <= 12, verdicts.count("ok")            # was 168 "confirmed" before the gate
    assert verdicts.count("drop") >= 190
    real = [G.judge(ref, title)[0] for ref, title, is_real in CASES["false"] if is_real]
    assert real == ["drop"] * 7                                        # the seven real published headlines


def test_true_headlines_survive_the_gate():
    # Independent Agent2 ruling: these nine titles are plausible candidates,
    # but the title ALONE does not establish full project/site or publisher proof.
    # In particular, a road name, BOOM developer or county is not conclusive.
    candidate_only = {
        ("13043", "EDF and Luminous tweak Springwell solar design"),
        ("15149", "Great North Road solar nears decision"),
        ("17699", "Green Nation unveils 750MW Whitestone solar"),
        ("8162", "METLEN to deliver EPC work at EDF’s 400MW Longfield solar PV farm"),
        ("15252", "RES submits 600MW Steeple solar for DCO"),
        ("11678", "Government grants consent for Boom Power's 400MW East Yorkshire solar NSIP"),
        ("14098", "Boom Power wins Fenwick solar approval"),
        ("14098", "BOOM Power’s Fenwick solar NSIP closes examination phase early"),
        ("6557", "UK gives go-ahead for 50MW Little Crow solar"),
    }
    results = [(ref, title, G.judge(ref, title, official=team == "official")[0])
               for ref, title, team in CASES["true"]]
    lost = [(ref, title, verdict) for ref, title, verdict in results
            if verdict != "ok" and not ((ref, title) in candidate_only and verdict == "possible")]
    assert len(CASES["true"]) >= 80 and sum(verdict == "ok" for _, _, verdict in results) >= 81
    assert lost == []


def test_east_yorkshire_alias_is_not_a_wrong_county():
    assert G.judge("11678", "Government grants consent for Boom Power's 400MW East Yorkshire solar NSIP")[0] in ("ok", "possible")
    # An actual different county remains an explicit contradiction, not a synonym.
    assert G.judge("11678", "Boom Power's 400MW East Yorkshire solar project approved in West Yorkshire")[0] != "ok"


def test_weak_development_candidates_never_become_confirmed_from_place_or_developer_alone():
    # The new candidate path must not turn roadworks, a different Boom Power
    # solar project or roof-panel coverage into a verified REPD project event.
    for ref, title in (
        ("15149", "Great North Road solar street lights planning granted"),
        ("15149", "Great North Road residents discuss road resurfacing"),
        ("14098", "Boom Power solar contract in another county"),
        ("11678", "Boom Power 49.99MW Drove Lane solar farm approved in East Yorkshire"),
        ("14098", "Fenwick solar panels installed on library roof"),
    ):
        assert G.judge(ref, title)[0] != "ok", (ref, title, G.judge(ref, title))



def test_all_three_collectors_reject_the_false_headlines():
    trade = {p.ref: p for p in T.load_projects(str(SIGNALS / "aliases.json"))}
    official = {p["repd_ref"]: p for p in O.load_projects()}
    index = {p["repd_ref"]: p for p in I.load_projects(str(SIGNALS / "top200_solar.json"), str(SIGNALS / "aliases.json"))}
    counts = {"trade": 0, "trade confirmed": 0, "official": 0, "index": 0, "index strong": 0, "confirmed and not excluded": 0}
    for ref, title, _real in CASES["false"]:
        t, o, i = trade[ref].match(title), O.match(official[ref], title), I.match_item(index[ref], title)
        counts["trade"] += bool(t)
        counts["trade confirmed"] += bool(t and t[1] == "confirmed")
        counts["official"] += bool(o)
        counts["index"] += bool(i)
        counts["index strong"] += bool(i and i[0] == "strong")
        confirmed = (t and t[1] == "confirmed") or (o and o[1] == "confirmed") or (i and i[0] == "strong")
        excluded = C.exclusion_reason({"title": title, "link": "https://example.co.uk/x"}, EXCLUSIONS.get(ref) or {})
        counts["confirmed and not excluded"] += bool(confirmed and not excluded)
    # before the gate (the tester's run of the same file): trade 229, index 85, official 45, 168 confirmed
    assert counts["trade"] <= 50 and counts["trade confirmed"] <= 12, counts
    assert counts["official"] <= 16 and counts["index"] <= 20, counts
    assert counts["confirmed and not excluded"] <= 18, counts


def test_collectors_still_match_the_true_headlines():
    trade = {p.ref: p for p in T.load_projects(str(SIGNALS / "aliases.json"))}
    official = {p["repd_ref"]: p for p in O.load_projects()}
    missed = []
    for ref, title, team in CASES["true"]:
        found = trade[ref].match(title) if team == "trade" else O.match(official[ref], title)
        if not found:
            missed.append((team, ref, title))
    assert missed == []


def test_combiner_purges_a_carried_false_match_and_keeps_reviewed_items():
    rows = json.loads((SIGNALS / "top200_solar.json").read_text())
    aliases = json.loads((SIGNALS / "aliases.json").read_text())
    exclusions = {"projects": EXCLUSIONS}
    standings = json.loads((SIGNALS / "alias_standings.json").read_text())
    stamp = "2026-11-14T12:34:49Z"
    previous = {"schema": "project-signals.v1", "generated_at": "2026-11-14T12:46:07Z",
                "parts": {"trade": {"status": "ok", "items": 3, "generated_at": stamp}},
                "projects": {"11678": {"signals": [
                    {"title": "Falling masonry kills man in East Yorkshire", "link": "https://www.constructionenquirer.com/a",
                     "publisher": "Construction Enquirer", "date": "2026-11-05", "family": "trade", "basis": "alias", "confidence": "confirmed"},
                    {"title": "Boom Power secures planning permission for 49.99MW Drove Lane solar PV plant in East Yorkshire",
                     "link": "https://www.solarpowerportal.co.uk/b", "publisher": "Solar Power Portal", "date": "2026-10-23",
                     "family": "trade", "basis": "alias", "confidence": "confirmed"}]},
                    "12588": {"signals": [
                        {"title": "UK rejects 840MW Botley West solar farm", "link": "https://renews.biz/c", "publisher": "reNEWS",
                         "date": "2026-11-10", "family": "trade", "basis": "alias", "confidence": "confirmed"}]}}}
    result = C.combine(rows, aliases, {}, previous=previous, now_iso="2026-11-15T05:23:00Z", use_module=False,
                       exclusions=exclusions, standings=standings)
    assert [i for t in C.TIERS for i in result["projects"]["11678"][t]] == []
    kept = result["projects"]["12588"]["recent_news"]
    assert [i["title"] for i in kept] == ["UK rejects 840MW Botley West solar farm"] and kept[0]["collected_at"] == stamp
    assert result["dropped"]["title gate"] == 1 and result["dropped"]["exclusion rule"] == 1
    assert result["generated_at"] == stamp and result["parts"]["trade"]["status"] == "stale"


def test_shared_links_follow_the_reviewers_findings():
    rows = json.loads((SIGNALS / "top200_solar.json").read_text())
    aliases = json.loads((SIGNALS / "aliases.json").read_text())
    reviewed = json.loads((SIGNALS / "reviewed_signals.json").read_text())
    reviewed["items"].append({"repd_ref": "7840", "title": "£80m solar farm gets green light", "publisher": "Evesham Observer",
                              "link": "http://www.eveshamobserver.co.uk/?p=35578", "date": "2014-11-13", "family": "regional",
                              "basis": "reviewed 2026-11-14", "confidence": "confirmed"})
    result = C.combine(rows, aliases, {"reviewed": reviewed}, now_iso="2026-11-14T12:00:00Z", use_module=False,
                       exclusions={"projects": EXCLUSIONS}, standings=json.loads((SIGNALS / "alias_standings.json").read_text()))

    def on(ref, needle):
        return [i for t in C.TIERS for i in result["projects"][ref][t] if needle in i["link"]]

    assert on("1980", "eveshamobserver") and not on("7840", "eveshamobserver")          # the 2014 approval is 1980's
    assert on("11278", "inkl.com") and not on("7191", "inkl.com")                         # one refusal, one project
    # Historic reviewer discovery does not independently prove both REPD identities.
    # One copy of a generic "two projects" headline must not assert also_projects.
    for first, second, needle in (("9729", "9739", "morpethherald"),
                                  ("7823", "8254", "high-court")):
        matches = [(ref, item) for ref in (first, second) for item in on(ref, needle)]
        # An ambiguous historical link can appear only as separate possible review
        # candidates, not a proven multi-project binding or confirmed headline.
        assert matches
        assert all("also_projects" not in item for ref, item in matches)
        assert all(item["confidence"] == "possible" for ref, item in matches)
    edf = [(ref, item) for ref in ("6071", "7630") for item in on(ref, "edf-acquires-100mw")]
    # An unnamed EDF article cannot become two independent confirmed REPD
    # bindings. One discovery candidate is retained, never also_projects.
    assert len(edf) == 1
    assert edf[0][1]["confidence"] == "possible" and "also_projects" not in edf[0][1]
    assert "Defford Aerodrome solar farm" not in aliases["projects"]["7840"]["aliases"]


def test_link_key_recognises_copies_of_one_page():
    same = (("http://eveshamobserver.co.uk/?p=35578", "https://eveshamobserver.co.uk/?p=35578"),
            ("https://thecourier.co.uk/fp/news/x", "https://www.thecourier.co.uk/fp/news/x"),
            ("https://m.thecourier.co.uk/fp/news/x", "https://www.thecourier.co.uk/fp/news/x"),
            ("https://www.energyglobal.com/solar/13102025/a/amp/", "https://www.energyglobal.com/solar/13102025/a"),
            ("https://www.energyglobal.com/solar/12122025/b/", "https://www.energyglobal.com/solar/12122025/b"),
            ("https://moderngov.stockton.gov.uk/Data/Planning Committee/1/att.pdf", "https://moderngov.stockton.gov.uk/Data/Planning%20Committee/1/att.pdf"),
            ("https://x.example/a?a=1&b=2", "https://x.example/a?b=2&a=1"),
            ("https://x.example/projects/EN010118?lang=en", "https://x.example/projects/EN010118"))
    for a, b in same:
        assert C.link_key(C.D.canonical_link(a) or a) == C.link_key(C.D.canonical_link(b) or b), (a, b)
    assert C.link_key("https://eveshamobserver.co.uk/?p=35578") != C.link_key("https://eveshamobserver.co.uk/?p=35579")


def test_one_date_rule_for_collectors_and_combiner():
    for value, expected in (
            ("Fri, 14 Nov 2026 10:00:00 -0000", "2026-11-14"), ("Fri, 14 Nov 2026 10:00:00 BST", "2026-11-14"),
            ("Fri, 14 Nov 2026 10:00:00 CET", "2026-11-14"), ("Fri, 14 Nov 2026 10:00:00", "2026-11-14"),
            ("2026-11-14", "2026-11-14"), ("2026-11-14T10:00:00", "2026-11-14"), ("20261114", "2026-11-14"),
            ("Sat, 14 Nov 26 10:00:00 GMT", "2026-11-14"), ("Sun, 14 Nov 49 10:00:00 GMT", None),
            ("Fri, 14 Nov 69 10:00:00 GMT", None), ("2027-01-01T00:00:00Z", None), ("Thu, 01 Jan 1970 00:00:00 GMT", None),
            ("Sat, 15 Nov 2026 00:30:00 +0100", "2026-11-15"), ("2026-11-14T23:30:00-05:00", "2026-11-14"),
            ("Mon, 30 Feb 2026 10:00:00 GMT", None), ("2026-02-30", None), ("2026-99-99", None), ("2026-13-45", None),
            ("0000-00-00", None), ("03/04/2026", "2026-04-03"), ("3/4/26", "2026-04-03"), ("1/2/0026", None),
            ("2026-11-14 10:00", "2026-11-14"), ("14 Sept 2026", "2026-09-14"), ("14.11.2026", "2026-11-14"),
            ("04/14/2026", "2026-04-14"), ("", None), (None, None), ("last week", None)):
        assert DATES.day(value, TODAY) == expected, value
        assert C.parse_date(value, TODAY) == expected, value
    assert DATES.day("2026-11-15", TODAY) == "2026-11-15" and DATES.day("2026-11-16", TODAY) is None   # tomorrow, not later
    assert T.day_of("2026-11-14T23:30:00-05:00") == "2026-11-14" and T.day_of("Fri, 14 Nov 2026 10:00:00 BST") == "2026-11-14"
    assert O.parse_day("3/4/26") == "2026-04-03" and O.parse_day("1/2/0026") is None and O.parse_day("14 Sept 2026") == "2026-09-14"
    assert T.date_near("Nov 10, 2026 | Related: Solar farm refused 3 December 2025") == "2026-11-10"
    assert T.date_near("Hearing on 3 December 2099") is None
    assert DATES.url_day("https://www.energyglobal.com/solar/12052025/a-headline/") == "2025-05-12"
    assert DATES.url_day("https://now.solar/2026/10/29/a-headline/") == "2026-10-29"
    assert DATES.url_day("https://example.co.uk/news/2025/06/a-headline") is None
    assert DATES.url_year("https://example.co.uk/news/2025/06/a-headline") == 2025


def test_year_is_kept_for_an_undated_item_when_the_link_or_the_reviewer_gives_it():
    rows = [{"rank": 1, "repd_ref": "12588", "site_name": "Botley West Solar Project", "planning_ref": "EN010147"}]
    reviewed = {"schema": C.PART_SCHEMA, "team": "reviewed", "generated_at": "2026-11-14T12:00:00Z", "sources": [], "items": [
        {"repd_ref": "12588", "title": "Update", "link": "https://example.co.uk/wp-content/uploads/2023/12/update.pdf",
         "publisher": "Parish", "date": None, "year": 2024, "family": "regional", "basis": "reviewed 2026-11-14", "confidence": "confirmed"},
        {"repd_ref": "12588", "title": "Milestone", "link": "https://example.co.uk/newsroom/2026/milestone/",
         "publisher": "Paper", "date": None, "family": "regional", "basis": "reviewed 2026-11-14", "confidence": "confirmed"},
        {"repd_ref": "12588", "title": "No clue", "link": "https://example.co.uk/a", "publisher": "Paper", "date": None,
         "family": "regional", "basis": "reviewed 2026-11-14", "confidence": "confirmed"}]}
    result = C.combine(rows, None, {"reviewed": reviewed}, now_iso="2026-11-14T12:00:00Z", use_module=False)
    got = {i["title"]: (i["year"], i["freshness"], i["tier"]) for i in result["projects"]["12588"]["archive"]}
    assert got == {"Update": (2024, "undated", "archive"), "Milestone": (2026, "undated", "archive"), "No clue": (None, "undated", "archive")}
    assert result["projects"]["12588"]["recent_news"] == [] and C.schema_errors(result) == []


def test_a_part_file_older_than_two_days_is_stale_not_ok():
    rows = [{"rank": 1, "repd_ref": "12588", "site_name": "Botley West Solar Project", "planning_ref": "EN010147"}]
    old = {"schema": C.PART_SCHEMA, "team": "trade", "generated_at": "2026-10-01T00:00:00Z", "sources": [], "items": [
        {"repd_ref": "12588", "title": "Botley West Solar Farm refused", "link": "https://example.co.uk/a", "publisher": "Paper",
         "date": "2026-09-30", "family": "trade", "basis": "alias", "confidence": "confirmed"}]}
    result = C.combine(rows, None, {"trade": old}, now_iso="2026-11-14T12:00:00Z", use_module=False)
    assert result["parts"]["trade"]["status"] == "failed" and "older than 48 hours" in result["parts"]["trade"]["note"]
    assert result["generated_at"] is None and result["stale"] is True

Test Index

A test in the tests folder of GlobalGrid2050. It is built from the rss step (`rss`), the projects step (`projects`) and the fetch step (`fetch`).

testglobalgrid2050 / automation/news/signals/tests/test_index.py · lines 1–302 of 302 · Entry point · pattern projects (shared by 4 files)

What it does
It tests its inputs. Defines 23 functions or classes, including rss, projects, test_derived_alias_and_core_names, test_match_rule, test_bbc_feed_list_is_derived_from_the_counties. Uses libraries __future__, json, sys, pathlib, pytest. Side effects: reads or writes files; makes network requests.
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 top.json; JSON file aliases.json; JSON file missing.json; JSON file top200_solar.json; JSON file part.json; JSON file cache.json; JSON file none.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Offline tests for `automation/news/signals/index.py`. No network: feeds and GDELT answers are given in memory. Its code works with 400 MW.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/signals/tests · test
Uses
__future__, json, sys, pathlib, pytest, index
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
rss, projects, test_derived_alias_and_core_names, test_match_rule, test_bbc_feed_list_is_derived_from_the_counties, test_every_top200_county_has_a_bbc_feed, test_collect_rss_reads_summary_but_never_stores_it, test_excluded_sources_and_publishers, test_gdelt_query_and_url, test_parse_gdelt, gdelt_body, test_gdelt_cache_rate_limit_and_rotation
Defines here
rss, projects, test_derived_alias_and_core_names, test_match_rule, test_bbc_feed_list_is_derived_from_the_counties, test_every_top200_county_has_a_bbc_feed, test_collect_rss_reads_summary_but_never_stores_it, fetch, test_excluded_sources_and_publishers, test_gdelt_query_and_url, test_parse_gdelt, gdelt_body, test_gdelt_cache_rate_limit_and_rotation, fetch, test_gdelt_stops_politely_and_respects_the_cap, test_gdelt_carries_on_after_one_refused_query, fetch, test_gdelt_time_budget, test_gdelt_steps_down_when_a_window_is_not_allowed, fetch, test_tidy_dedupes_prefers_confirmed_and_caps, item, test_main_offline_writes_the_contract_part
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/signals/tests/test_index.py:1-302 · blob 61b132c8872cd90c47082d03af7c5f9aedd40575 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Offline tests for automation/news/signals/index.py. No network: feeds and GDELT answers are given in memory."""
from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

SIGNALS = Path(__file__).resolve().parents[1]
for path in (str(SIGNALS.parent), str(SIGNALS)):
    if path not in sys.path:
        sys.path.insert(0, path)

import index as I  # noqa: E402

NOW = "2026-11-14T12:00:00Z"
FOUR = {"rank": 4, "repd_ref": "20003", "site_name": "Cottam Solar Project", "operator": "Island Green Power", "mw": 600.0,
        "county": "Lincolnshire", "country": "England", "planning_authority": "PINS", "planning_ref": "EN010133"}
TOP = [
    {"rank": 1, "repd_ref": "12588", "site_name": "Botley West, Botley - Botley West Solar Project",
     "operator": "Photovolt Development Partners & SolarFive ", "mw": 840.0, "county": "Oxfordshire",
     "country": "England", "planning_authority": "The Planning Inspectorate - National Infrastructure",
     "planning_ref": "EN010147"},
    {"rank": 2, "repd_ref": "20001", "site_name": "Rigifa Solar Farm & Battery Storage", "operator": "Example Energy Ltd",
     "mw": 60.0, "county": "Aberdeenshire", "country": "Scotland", "planning_authority": "Aberdeenshire",
     "planning_ref": "APP/2025/0001"},
    {"rank": 3, "repd_ref": "20002", "site_name": "Mill Solar Farm", "operator": "Example Energy Ltd", "mw": 50.0,
     "county": "Kent", "country": "England", "planning_authority": "Ashford", "planning_ref": "24/00001"},
]
ALIASES = {"schema": "project-signal-aliases.v1", "projects": {
    "12588": {"aliases": ["Botley West Solar Farm"], "alias_status": "confirmed", "planning_ref": "EN010147"},
    "20001": {"aliases": ["Rigifa Solar Farm"], "alias_status": "confirmed", "exclude": ["Caithness"]},
}}


def rss(*entries):
    body = "".join("<item><title>%s</title><link>%s</link><pubDate>%s</pubDate><description>%s</description></item>" % e
                   for e in entries)
    return ("<?xml version='1.0'?><rss version='2.0'><channel><title>t</title>%s</channel></rss>" % body).encode()


@pytest.fixture
def projects(tmp_path):
    top, aliases = tmp_path / "top.json", tmp_path / "aliases.json"
    top.write_text(json.dumps(TOP))
    aliases.write_text(json.dumps(ALIASES))
    return I.load_projects(top, aliases)


def test_derived_alias_and_core_names(tmp_path, projects):
    assert I.clean_site_name("Botley West, Botley - Botley West Solar Project") == "Botley West Solar Project"
    assert I.clean_site_name("Green Hill Solar Farm & Battery Storage") == "Green Hill Solar Farm"
    assert I.clean_site_name("Tillbridge Solar Farm, Hemswell - Solar Panels") == "Tillbridge Solar Farm"
    assert I.core_name("The Tween Bridge Solar Farm") == "Tween Bridge"
    botley, rigifa, mill = projects
    assert botley["cores"] == ["botley west"] and botley["alias_status"] == "confirmed"
    assert mill["alias_status"] == "derived" and mill["aliases"] == ["Mill Solar Farm"]
    assert mill["cores"] == []                       # "Mill" alone is too common to match on
    top = tmp_path / "top.json"
    assert [p["alias_status"] for p in I.load_projects(top, tmp_path / "missing.json")] == ["derived"] * 3


def test_match_rule(projects):
    botley, rigifa, mill = projects
    assert I.match_item(botley, "Botley West solar farm refused by minister")[0] == "strong"
    assert I.match_item(botley, "Botley West solar project decision due")[0] == "strong"
    assert I.match_item(botley, "Decision on EN010147 published")[0] == "strong"
    # County RSS summaries may discover a candidate, but they do not prove the identity of a generic headline.
    assert I.match_item(botley, "Huge solar farm refused", "The Botley West Solar Farm would have covered farmland.", True)[0] == "weak"
    assert I.match_item(botley, "Huge solar farm refused", "The Botley West Solar Farm in Oxfordshire is refused.")[0] == "weak"
    unrelated = I.match_item(botley, "Longfield Solar Farm receives consent",
                             "Botley West Solar Farm was discussed in a separate item.", True)
    assert unrelated is None or unrelated[0] != "strong"  # wrong scheme in title never gains confirmed identity
    assert I.match_item(botley, "Huge solar farm refused", "The Botley West Solar Farm would have covered farmland.")[0] == "weak"
    assert I.match_item(botley, "Solar plan near Botley West divides villagers")[0] == "weak"
    assert I.match_item(botley, "Botley West residents meet over road closure") is None      # a bare name is not enough
    assert I.match_item(botley, "Solar farm refused in Oxfordshire") is None
    assert I.match_item(rigifa, "Rigifa solar farm in Caithness approved") is None           # exclude phrase
    assert I.match_item(mill, "Mill solar farm approved")[0] == "strong"                     # full alias still matches
    assert I.match_item(mill, "Solar plan for old mill site") is None


def test_bbc_feed_list_is_derived_from_the_counties(projects):
    feeds, unmapped = I.bbc_feeds(projects)
    urls = dict(feeds)
    assert "https://feeds.bbci.co.uk/news/england/oxford/rss.xml" in urls
    assert urls["https://feeds.bbci.co.uk/news/england/oxford/rss.xml"] == {"oxfordshire"}
    assert "https://feeds.bbci.co.uk/news/rss.xml" in urls and unmapped == []
    assert "https://feeds.bbci.co.uk/news/england/norfolk/rss.xml" not in urls


def test_every_top200_county_has_a_bbc_feed():
    projects = I.load_projects(SIGNALS / "top200_solar.json", None)
    assert len(projects) == 200
    feeds, unmapped = I.bbc_feeds(projects)
    assert unmapped == []
    assert all(url.startswith("https://feeds.bbci.co.uk/news/") and url.endswith("rss.xml") for url, _ in feeds)


def test_collect_rss_reads_summary_but_never_stores_it(projects):
    oxford = "https://feeds.bbci.co.uk/news/england/oxford/rss.xml"
    bodies = {
        oxford: rss(("Minister refuses giant solar farm", "https://www.bbc.co.uk/news/articles/abc?at_medium=RSS",
                     "Tue, 10 Nov 2026 12:00:00 GMT", "The Botley West Solar Farm was refused development consent."),
                    ("Bus timetable changes", "https://www.bbc.co.uk/news/articles/def", "Tue, 10 Nov 2026 12:00:00 GMT", "x"),
                    ("Solar eclipse photos", "https://news.google.com/rss/articles/xyz", "Tue, 10 Nov 2026 12:00:00 GMT", "x")),
    }

    def fetch(url):
        if url not in bodies:
            raise OSError("HTTP 404")
        return bodies[url]

    feeds = [(oxford, {"oxfordshire"}), ("https://feeds.bbci.co.uk/news/england/nowhere/rss.xml", set())]
    items, health = I.collect_rss(feeds, projects, fetch, "BBC News", "bbc", "BBC News RSS")
    assert [h["status"] for h in health] == ["ok", "failed"]            # one bad feed never stops the run
    assert [v[2] for v in I.collect_rss.unmatched.values()] == []       # the eclipse item is a Google link: dropped
    assert len(items) == 1
    item = items[0]
    assert item == {"repd_ref": "12588", "title": "Minister refuses giant solar farm",
                    "link": "https://www.bbc.co.uk/news/articles/abc", "publisher": "BBC News", "date": "2026-11-10",
                    "family": "bbc", "confidence": "uncertain",
                    "basis": "BBC News RSS: alias 'Botley West Solar Farm' in feed summary; the feed is the project's county feed; kept as weak: headline lacks a verified project name"}
    assert "refused development consent" not in json.dumps(items)
    record = I.source_record("bbc-rss", I.BBC_BASE, health)
    assert record["status"] == "partial" and record["failures"] == 1 and record["items"] == 1


def test_excluded_sources_and_publishers():
    assert I.is_excluded("https://news.google.com/rss/articles/x")
    assert I.is_excluded("https://www.google.co.uk/url?q=x")
    assert I.is_excluded("https://www.reuters.com/world/uk/x")
    assert not I.is_excluded("https://www.bbc.co.uk/news/articles/x")
    assert I.publisher_of("https://www.bbc.co.uk/news/articles/x") == ("BBC News", "bbc")
    assert I.publisher_of("https://www.solarpowerportal.co.uk/x") == ("Solar Power Portal", "trade")
    assert I.publisher_of("https://www.oxfordmail.co.uk/news/x") == ("oxfordmail.co.uk", "regional")


def test_gdelt_query_and_url(projects):
    botley = projects[0]
    assert I.gdelt_phrase(botley) == "Botley West"
    assert I.gdelt_phrase(projects[2]) == "Mill Solar Farm"            # weak name: the full alias is asked
    assert I.gdelt_query("Botley West") == '"Botley West" solar sourcecountry:UK'
    assert I.gdelt_query("Sunnica") == "Sunnica solar sourcecountry:UK"
    assert "domainis:bbc.co.uk OR domainis:theguardian.com" in I.gdelt_query("Botley West", "domains")
    url = I.gdelt_url(I.gdelt_query("Botley West"), I.GDELT_WINDOWS[0][1], NOW)
    assert url.startswith("https://api.gdeltproject.org/api/v2/doc/doc?query=%22Botley+West%22+solar+sourcecountry%3AUK")
    assert "mode=artlist" in url and "format=json" in url and "startdatetime=20170101000000" in url
    assert "enddatetime=20261114120000" in url


def test_parse_gdelt():
    assert I.parse_gdelt("") == [] and I.parse_gdelt("{}") == []
    body = json.dumps({"articles": [{"url": "https://www.bbc.co.uk/news/a", "title": "Botley West solar farm refused",
                                     "seendate": "20261110T121500Z", "domain": "bbc.co.uk", "language": "English"}]})
    assert I.parse_gdelt(body) == [("Botley West solar farm refused", "https://www.bbc.co.uk/news/a", "bbc.co.uk",
                                    None, "English")]                      # the crawl date is not a publication date
    dated = json.dumps({"articles": [{"url": "https://www.example-paper.co.uk/news/2019/05/07/solar-farm-approved",
                                      "title": "Solar farm approved", "seendate": "20261110T121500Z"},
                                     {"url": "https://a.co.uk/x", "title": "t", "seendate": "20261345T000000Z"}]})
    assert [a[3] for a in I.parse_gdelt(dated)] == ["2019-05-07", None]   # the article's own date, from its link
    with pytest.raises(ValueError, match="too short"):
        I.parse_gdelt("The specified phrase is too short.")


def gdelt_body(*arts):
    return json.dumps({"articles": [{"url": u, "title": t, "seendate": d, "domain": "x", "language": "English"}
                                    for t, u, d in arts]})


def test_gdelt_cache_rate_limit_and_rotation(projects):
    calls, sleeps = [], []
    answers = {
        "Botley West": [(429, "rate limit"), (200, gdelt_body(
            ("Botley West solar farm refused", "https://www.bbc.co.uk/news/a", "20261110T120000Z"),
            ("Oxfordshire solar farm row deepens | Oxford Mail", "https://www.oxfordmail.co.uk/news/b", "20261001T120000Z"),
            ("Oxfordshire solar farm row deepens", "https://www.heraldseries.co.uk/news/b", "20261001T120000Z"),
            ("Solar tiles , roofs and prices", "https://www.oxfordmail.co.uk/news/d", "20261001T120000Z"),
            ("Oxfordshire and Aberdeenshire react as Rigifa solar farm approved", "https://www.oxfordmail.co.uk/news/e", "20261001T120000Z"),
            ("Council budget agreed", "https://www.oxfordmail.co.uk/news/c", "20261002T120000Z"),
            ("Botley West solar farm refused", "https://news.google.com/x", "20261110T120000Z"),
            ("Botley West solar farm refused - Reuters", "https://www.reuters.com/x", "20261110T120000Z")))],
        "Rigifa": [(200, gdelt_body(("Rigifa solar farm in Caithness approved", "https://www.example.co.uk/r", "20260101T000000Z")))],
        "Mill Solar Farm": [(200, "{}")],
    }

    def fetch(url):
        calls.append(url)
        for phrase, queue in answers.items():
            if phrase.replace(" ", "+") in url:
                return queue.pop(0) if len(queue) > 1 else queue[0]
        return 200, "{}"

    cache = {}
    client = I.Gdelt(fetch, cache, NOW, cap=10, sleep=sleeps.append, interval=0)
    items, per_project, dropped = I.collect_gdelt(projects, client)
    assert client.stats["http_429"] == 1 and 10 in sleeps                 # waited ten seconds, retried once
    items = I.tidy(items)
    assert [(i["repd_ref"], i["family"], i["confidence"], i["title"]) for i in items] == [
        ("12588", "bbc", "confirmed", "Botley West solar farm refused"),
        ("12588", "regional", "uncertain", "Oxfordshire solar farm row deepens")]      # syndicated copy kept once
    assert "headline says solar and Oxfordshire but not the name" in items[1]["basis"]
    assert dropped["headline says solar but neither the name nor the county"] == 1
    assert dropped["headline names another of the 200"] == 1
    assert dropped["excluded source"] == 2 and dropped["headline has neither the name nor solar"] == 1
    assert dropped["exclude phrase"] == 1 and per_project["20001"]["kept"] == 0
    assert len(cache) == 3 and client.stats["empty"] == 1
    before = len(calls)
    again = I.Gdelt(fetch, cache, NOW, cap=10, sleep=sleeps.append, interval=0)
    items2, _, _ = I.collect_gdelt(projects, again)
    assert len(calls) == before and again.stats["cache_hits"] == 3 and len(I.tidy(items2)) == 2   # cached by query
    cache[I.gdelt_query("Botley West")]["fetched_at"] = "2026-11-01T00:00:00Z"
    del cache[I.gdelt_query("Rigifa")]
    assert [p["repd_ref"] for p in I.rotation(projects, cache)] == ["20001", "12588", "20002"]   # never asked first


def test_gdelt_stops_politely_and_respects_the_cap(projects, monkeypatch):
    monkeypatch.setattr(I, "GDELT_MAX_REFUSALS", 2)
    stopped = I.Gdelt(lambda url: (429, ""), {}, NOW, cap=10, sleep=lambda s: None, interval=0)
    items, per_project, _ = I.collect_gdelt(projects, stopped)
    assert items == [] and per_project == {} and "429" in stopped.stats["stopped"]
    assert stopped.stats["requests"] == 2 * I.GDELT_MAX_REFUSALS and stopped.stats["refused_queries"] == I.GDELT_MAX_REFUSALS
    capped = I.Gdelt(lambda url: (200, "{}"), {}, NOW, cap=1, sleep=lambda s: None, interval=0)
    I.collect_gdelt(projects, capped)
    assert capped.stats["requests"] == 1 and capped.stats["not_asked"] >= 2


def test_gdelt_carries_on_after_one_refused_query(tmp_path):
    top = tmp_path / "top.json"
    top.write_text(json.dumps(TOP + [FOUR]))
    projects = I.load_projects(top, None)
    seen = []

    def fetch(url):
        seen.append(url)
        return (429, "Please limit requests to one every 5 seconds or contact someone@example.org.") if "Botley" in url else (200, "{}")

    client = I.Gdelt(fetch, {}, NOW, cap=20, sleep=lambda s: None, interval=0)
    _, per_project, _ = I.collect_gdelt(projects, client)
    assert "12588" not in per_project and len(per_project) == 3 and not client.stats["stopped"]
    assert client.stats["refused_queries"] == 1 and "limit requests" in client.stats["error_samples"][0]
    assert "@" not in client.stats["error_samples"][0] and "(address removed)" in client.stats["error_samples"][0]
    assert I.gdelt_title("Government greenlights 400MW Beacon Fen solar , storage | Paper") == "Government greenlights 400MW Beacon Fen solar, storage"


def test_gdelt_time_budget(projects):
    ticks = iter(range(0, 10000, 50))
    client = I.Gdelt(lambda url: (200, "{}"), {}, NOW, cap=50, sleep=lambda s: None, interval=0, seconds=120,
                     clock=lambda: next(ticks))
    I.collect_gdelt(projects, client)
    assert "time budget" in client.stats["stopped"] and client.stats["not_asked"] >= 1 and client.stats["answered"] >= 1


def test_gdelt_steps_down_when_a_window_is_not_allowed(projects):
    def fetch(url):
        if "startdatetime" in url:
            return 200, "Invalid timespan or start date."
        return 200, gdelt_body(("Botley West solar farm refused", "https://www.bbc.co.uk/news/a", "20261110T120000Z"))

    client = I.Gdelt(fetch, {}, NOW, cap=10, sleep=lambda s: None, interval=0)
    assert len(client.ask(I.gdelt_query("Botley West"))) == 1
    assert client.stats["window"] == "last 12 months" and client.stats["errors"] == 0


def test_tidy_dedupes_prefers_confirmed_and_caps(projects):
    def item(n, confidence="uncertain", date="2026-01-0%d"):
        return {"repd_ref": "12588", "title": "t%d" % n, "link": "https://e.co.uk/%d" % n, "publisher": "e",
                "date": date % n if "%d" in date else date, "family": "regional", "basis": "b", "confidence": confidence}

    rows = [item(1), item(1, "confirmed"), item(2), item(3)] + [dict(item(4), repd_ref="99999")]
    out = I.tidy(rows, [item(5), {"repd_ref": "12588", "title": "g", "link": "https://news.google.com/x",
                                  "confidence": "uncertain", "date": None, "family": "regional"}], {"12588"})
    assert [i["link"][-1] for i in out] == ["1", "5", "3", "2"] and out[0]["confidence"] == "confirmed"
    assert len(I.tidy([item(n) for n in range(1, 10)], cap=3)) == 3
    cov = I.coverage(out, projects)
    assert cov["with_signal"] == 1 and cov["with_confirmed_signal"] == 1 and cov["with_signal_by_family"]["regional"] == 1


def test_main_offline_writes_the_contract_part(tmp_path, monkeypatch):
    top, aliases = tmp_path / "top.json", tmp_path / "aliases.json"
    top.write_text(json.dumps(TOP))
    aliases.write_text(json.dumps(ALIASES))
    monkeypatch.setattr(I, "fetch_feed", lambda url: rss(
        ("Botley West solar farm refused", "https://www.bbc.co.uk/news/articles/abc", "Tue, 10 Nov 2026 12:00:00 GMT", "s")))
    monkeypatch.setattr(I, "fetch_gdelt", lambda url: (200, "{}"))
    monkeypatch.setattr(I.time, "sleep", lambda s: None)
    monkeypatch.setattr(I, "GDELT_INTERVAL_S", 0)
    monkeypatch.setattr(I.Throttle, "wait", lambda self, host, interval=None: None)
    out, probe, cache = tmp_path / "part.json", tmp_path / "probe.md", tmp_path / "cache.json"
    code = I.main(["--top200", str(top), "--aliases", str(aliases), "--out", str(out), "--probe", str(probe),
                   "--cache", str(cache), "--now", NOW, "--truth", str(tmp_path / "none.json")])
    part = json.loads(out.read_text())
    assert code == 0 and part["schema"] == "project-signals-part.v1" and part["team"] == "index"
    assert [s["id"] for s in part["sources"]] == ["bbc-rss", "guardian-rss", "gdelt-doc"]
    assert all(set(s) == {"id", "url", "status", "requests", "failures", "items", "error"} for s in part["sources"])
    assert len(part["items"]) == 1                                         # the same link from many feeds, once
    assert set(part["items"][0]) == {"repd_ref", "title", "link", "publisher", "date", "family", "basis", "confidence"}
    assert part["coverage"]["with_signal"] == 1
    assert "1 of 3" in probe.read_text() and len(json.loads(cache.read_text())["queries"]) == 3
    text = out.read_text() + probe.read_text()
    assert "/home/" not in text and "@" not in text