GLOBALGRID2050 / EXPLORE CODE

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

Test Datacentre Feed and 2 more files

A test in the tests folder of GlobalGrid2050 that checks Datacentre Feed. It is built from the cell step (`cell`), the site step (`site`) and the rss step (`rss`).

578 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 803 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 Datacentre Feed test · globalgrid2050 / automation/news/tests/test_datacentre_feed.py lines 1–322
  2. Test Documents test · globalgrid2050 / automation/news/tests/test_documents.py lines 1–111
  3. Test Engine test · globalgrid2050 / automation/news/tests/test_engine.py lines 1–145

Test Datacentre Feed

A test in the tests folder of GlobalGrid2050 that checks Datacentre Feed. It is built from the cell step (`cell`), the site step (`site`) and the rss step (`rss`).

testglobalgrid2050 / automation/news/tests/test_datacentre_feed.py · lines 1–322 of 322 · Entry point

What it does
It tests its inputs. Defines 28 functions or classes, including cell, site, rss, atom, test_classify_in_scope. 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 (path word 'datacentre'): 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 prox.json; JSON file a.json; JSON file b.json; JSON file none.json; JSON file o.json; JSON file missing.json; JSON file datacentre-news.v1.schema.json; JSON file pinned.json.
Downstream impact
Used directly by 3 files: GlobalGrid2050 Datacentre News Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Tests for `automation/news/datacentre_feed.py`. Synthetic fixtures only; no network.
Why it matters
Run by GlobalGrid2050 Datacentre News Workflow, GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Datacentre Feed (sys.path import), __future__, json, sys, pathlib, pytest
Used by
run by GlobalGrid2050 Datacentre News Workflow (workflow run), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
cell, site, rss, atom, test_classify_in_scope, test_classify_out_of_scope, test_summary_is_used_for_matching_but_never_stored, test_parse_rss_and_atom_dates_and_links, test_parse_rejects_dtd_entities_oversize_and_non_feeds, test_canonical_link_strips_tracking_and_fragment, test_titles_are_plain_text, test_register_site_name_beats_operator_and_repd_context
Defines here
cell, site, rss, atom, test_classify_in_scope, test_classify_out_of_scope, test_summary_is_used_for_matching_but_never_stored, test_parse_rss_and_atom_dates_and_links, test_parse_rejects_dtd_entities_oversize_and_non_feeds, test_canonical_link_strips_tracking_and_fragment, test_titles_are_plain_text, test_register_site_name_beats_operator_and_repd_context, test_unreliable_point_has_no_repd_context_and_generic_names_never_match, test_short_uppercase_operator_is_case_exact_and_alias_works, test_general_operator_alone_does_not_make_a_datacentre_story, test_sponsored_headlines_are_dropped_and_build_is_told_from_financing, test_sites_capped_per_item, test_one_failing_feed_is_recorded_and_others_continue, fetch, test_merge_dedups_by_link_keeps_first_seen_orders_and_caps, test_fixture_run_end_to_end_is_deterministic, test_all_feeds_failing_without_previous_output_exits_nonzero, test_feed_list_is_https_and_explained, test_output_matches_json_schema, test_pinned_items_are_always_in_the_feed, test_shipped_pinned_file_is_valid, test_shipped_pinned_items_carry_a_date, test_items_from_earlier_runs_are_brought_to_the_current_shape
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_datacentre_feed.py:1-322 · blob 65dda07f6e943615c011c879c669c079ea5139bc · 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
"""Tests for automation/news/datacentre_feed.py. Synthetic fixtures only; no network."""
from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

PKG = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PKG))

import datacentre_feed as D  # noqa: E402

FIXTURES = Path(__file__).resolve().parent / "fixtures" / "datacentre"
NOW = "2026-11-14T01:30:00Z"


def cell(count=0, mw=0.0, unknown=0):
    return {"count": count, "mw_stated": mw, "count_mw_unknown": unknown}


def site(rid, name, operator, reliable=True, solar=(0, 0.0, 0), battery=(0, 0.0, 0)):
    statuses = ("operational", "under_construction", "consented", "in_planning")
    radii = {"10": {"solar": {s: cell() for s in statuses}, "battery": {s: cell() for s in statuses},
                    "wind_onshore": {s: cell() for s in statuses}, "wind_offshore": {s: cell() for s in statuses}}}
    radii["10"]["solar"]["consented"] = cell(*solar)
    radii["10"]["battery"]["in_planning"] = cell(*battery)
    return {"id": rid, "name": name, "operator": operator, "status": "pipeline", "proximity_reliable": reliable,
            "radii": radii}


REGISTER = [
    site("dc-1", "Equinix LD8", "Equinix", solar=(3, 40.5, 1)),
    site("dc-2", "Equinix MA1", "Equinix", battery=(2, 99.0, 0)),
    site("dc-3", "North Wales AI Growth Zone", None, reliable=False),
    site("dc-4", "Microsoft Newport data centre", "Microsoft"),
    site("dc-5", "Unnamed data centre", None),
    site("dc-6", "SCC", "SCC"),
    site("dc-7", "AWS Example", "Amazon Web Services"),
]


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


def atom(*entries):
    body = "".join('<entry><title>%s</title><link href="%s"/><summary>%s</summary><updated>%s</updated></entry>'
                   % e for e in entries)
    return ('<?xml version="1.0"?><feed xmlns="http://www.w3.org/2005/Atom"><title>t</title>%s</feed>'
            % body).encode()


# ----------------------------------------------------------------- classification

@pytest.mark.parametrize("title,lanes", [
    ("Firm to invest £2bn in new data centre", ["capex"]),
    ("Datacentre expansion approved by council planning committee", ["capex", "politics"]),
    ("Minister names second AI growth zone", ["politics"]),
    ("Hyperscaler capex passes $190bn as staff cut", ["capex"]),
    ("Data centres face water limits in drought", ["politics"]),
    ("AI infrastructure build slows", ["capex"]),
    ("Supercomputer consultation opens", ["politics"]),
    ("Data center funding round closes", ["capex"]),
])
def test_classify_in_scope(title, lanes):
    assert D.classify(title, "")[1] == lanes


@pytest.mark.parametrize("title", [
    "Council planning row over housing estate",       # policy but no data-centre term
    "Data centre opens to visitors",                  # data centre but no money or policy term
    "Computer prices rise",                           # 'compute' must be a whole word
    "Datacentre-themed board game wins prize",        # no lane term
])
def test_classify_out_of_scope(title):
    assert D.classify(title, "") is None


def test_summary_is_used_for_matching_but_never_stored():
    feed = rss(("Big announcement in Slough", "https://example.org/a", "A £1bn data centre investment, secret body",
                "Thu, 12 Nov 2026 07:10:00 GMT"))
    items, health = D.collect([("u", "S", "w")], lambda u: feed, None, NOW)
    assert len(items) == 1 and items[0]["lanes"] == ["capex"]
    assert "secret body" not in json.dumps(items)
    assert set(items[0]) == {"title", "link", "source", "date", "first_seen", "lanes", "matched_terms", "sites",
                             "site_matches", "capex_basis", "pinned", "operator_sites"}


# ----------------------------------------------------------------- parsing

def test_parse_rss_and_atom_dates_and_links():
    r = D.parse_feed(rss(("A", "https://x.org/1", "", "Thu, 12 Nov 2026 07:10:00 GMT")))
    a = D.parse_feed(atom(("B", "https://x.org/2", "", "2026-11-12T10:00:00+01:00")))
    assert r[0][:2] == ("A", "https://x.org/1") and a[0][:2] == ("B", "https://x.org/2")
    assert D.parse_date(r[0][2]) == "2026-11-12T07:10:00Z"
    assert D.parse_date(a[0][2]) == "2026-11-12T09:00:00Z"
    assert D.parse_date("") is None and D.parse_date("not a date") is None
    assert D.parse_date("2026-11-12T10:00:00") is None   # no timezone: unknown, not guessed


def test_parse_rejects_dtd_entities_oversize_and_non_feeds():
    with pytest.raises(ValueError):
        D.parse_feed(b'<?xml version="1.0"?><!DOCTYPE x [<!ENTITY a "b">]><rss><channel/></rss>')
    with pytest.raises(ValueError):
        D.parse_feed(b"<html><body>hi</body></html>")
    with pytest.raises(ValueError):
        D.parse_feed(b"<rss><channel><title>broken")
    with pytest.raises(ValueError):
        D.parse_feed(b"<rss>" + b" " * (D.MAX_BYTES + 1) + b"</rss>")


def test_canonical_link_strips_tracking_and_fragment():
    a = D.canonical_link("https://www.BBC.co.uk/news/articles/x1?at_medium=RSS&at_campaign=rss#top")
    b = D.canonical_link("https://www.bbc.co.uk/news/articles/x1?utm_source=feed")
    assert a == b == "https://www.bbc.co.uk/news/articles/x1"
    assert D.canonical_link("https://example.org/p?id=7&utm_medium=x") == "https://example.org/p?id=7"
    assert D.canonical_link("javascript:alert(1)") is None
    assert D.canonical_link("") is None


def test_titles_are_plain_text():
    assert D.clean_text("<b>Data</b> &amp; centres  &lt;bn&gt;", 300) == "Data & centres <bn>"


# ----------------------------------------------------------------- register join

def test_register_site_name_beats_operator_and_repd_context():
    reg = D.Register(REGISTER)
    sites, operator_sites, n = reg.match("Equinix LD8 expansion: £500m investment")
    assert n == 2 and [s["id"] for s in sites] == ["dc-1"] and sites[0]["matched_on"] == "site_name"
    # The operator's other site is listed for review only: not a named site, and no REPD context.
    assert [s["id"] for s in operator_sites] == ["dc-2"] and operator_sites[0]["matched_on"] == "operator"
    assert "repd_nearby" not in operator_sites[0]
    ctx = sites[0]["repd_nearby"]
    assert ctx["radius_km"] == 10 and ctx["projects"] == 3 and ctx["projects_mw_unknown"] == 1
    assert ctx["mw_stated"] == 40.5 and ctx["mw_stated_by_technology"]["solar"] == 40.5


def test_unreliable_point_has_no_repd_context_and_generic_names_never_match():
    reg = D.Register(REGISTER)
    sites, _, _ = reg.match("North Wales AI Growth Zone gets minister visit")
    assert sites[0]["id"] == "dc-3" and sites[0]["repd_nearby"] is None
    assert reg.match("Unnamed data centre planning row")[0] == []


def test_short_uppercase_operator_is_case_exact_and_alias_works():
    reg = D.Register(REGISTER)
    assert reg.match("SCC wins data centre contract")[1][0]["id"] == "dc-6"
    assert reg.match("Accessibility of data centre jobs")[:2] == ([], [])
    assert reg.match("AWS to invest £8bn in UK data centres")[1][0]["id"] == "dc-7"


def test_general_operator_alone_does_not_make_a_datacentre_story():
    reg = D.Register(REGISTER)
    feed = rss(("Microsoft to invest £1bn in new office software", "https://e.org/1", "", ""),
               ("Equinix secures £300m funding", "https://e.org/2", "", ""),
               ("Microsoft data centre investment confirmed", "https://e.org/3", "", ""))
    items, _ = D.collect([("u", "S", "w")], lambda u: feed, reg, NOW)
    assert [i["link"] for i in items] == ["https://e.org/2", "https://e.org/3"]
    assert "register site" in items[0]["matched_terms"]["datacentre"]
    assert items[1]["sites"] == [] and items[1]["operator_sites"][0]["id"] == "dc-4"
    assert items[0]["capex_basis"] == "financing"


def test_sponsored_headlines_are_dropped_and_build_is_told_from_financing():
    feed = rss(("Sponsored: Why data centre investment must rethink water", "https://e.org/1", "", ""),
               ("Fund of £600m established to support data centre projects", "https://e.org/2", "", ""),
               ("Construction starts on £1bn data centre", "https://e.org/3", "", ""))
    items, _ = D.collect([("u", "S", "w")], lambda u: feed, None, NOW)
    assert [(i["link"], i["capex_basis"]) for i in items] == [("https://e.org/2", "financing"),
                                                              ("https://e.org/3", "build")]
    assert all(i["pinned"] is False for i in items)


def test_sites_capped_per_item():
    many = [site("dc-%02d" % i, "Op Site %d" % i, "Bigco") for i in range(9)]
    sites, operator_sites, n = D.Register(many).match("Bigco data centre investment")
    assert n == 9 and sites == [] and len(operator_sites) == D.SITES_PER_ITEM


# ----------------------------------------------------------------- collection, failure, merge, ordering

def test_one_failing_feed_is_recorded_and_others_continue():
    good = rss(("Data centre £1bn investment", "https://e.org/1", "", "Thu, 12 Nov 2026 07:10:00 GMT"))

    def fetch(url):
        if url == "bad":
            raise OSError("network unreachable")
        return good
    items, health = D.collect([("bad", "X", "w"), ("good", "Y", "w")], fetch, None, NOW)
    assert [h["status"] for h in health] == ["failed", "ok"] and "network unreachable" in health[0]["error"]
    assert len(items) == 1
    out = D.build({}, items, health, NOW)
    assert out["status"] == "partial" and out["counts"]["feeds_failed"] == 1


def test_merge_dedups_by_link_keeps_first_seen_orders_and_caps():
    old = [{"link": "https://e.org/1", "date": "2026-11-01T00:00:00Z", "first_seen": "2026-11-01T01:00:00Z",
            "lanes": ["capex"], "sites": [], "title": "old"}]
    new = [{"link": "https://e.org/1", "date": "2026-11-01T00:00:00Z", "first_seen": NOW, "lanes": ["capex"],
            "sites": [], "title": "new"},
           {"link": "https://e.org/2", "date": None, "first_seen": NOW, "lanes": ["politics"], "sites": [],
            "title": "undated"},
           {"link": "https://e.org/3", "date": "2026-11-05T00:00:00Z", "first_seen": NOW, "lanes": ["politics"],
            "sites": [], "title": "newer"}]
    merged = D.merge(old, new)
    assert [m["link"] for m in merged] == ["https://e.org/3", "https://e.org/1", "https://e.org/2"]
    assert merged[1]["title"] == "new" and merged[1]["first_seen"] == "2026-11-01T01:00:00Z"
    assert len(D.merge(old, new, cap=2)) == 2 and D.merge(old, new, cap=2)[-1]["link"] == "https://e.org/1"


def test_fixture_run_end_to_end_is_deterministic(tmp_path):
    reg = tmp_path / "prox.json"
    reg.write_text(json.dumps({"records": REGISTER}), encoding="utf-8")
    out1, out2 = tmp_path / "a.json", tmp_path / "b.json"
    args = ["--pinned", "none.json", "--fixtures", str(FIXTURES), "--proximity", str(reg), "--now", NOW]
    assert D.main(args + ["--out", str(out1)]) == 0
    assert D.main(args + ["--out", str(out2)]) == 0
    a, b = out1.read_bytes(), out2.read_bytes()
    assert a == b
    data = json.loads(a)
    assert data["schema"] == D.SCHEMA and data["status"] == "partial"
    # 9 feeds: politics fixture is broken XML, science and DCD have no fixture (network failure stand-ins)
    assert data["counts"]["feeds_ok"] == 6 and data["counts"]["feeds_failed"] == 3
    links = [i["link"] for i in data["items"]]
    assert len(links) == len(set(links)) == 9          # Kao Data is not in this synthetic register
    assert links.count("https://www.bbc.co.uk/news/articles/fx0001") == 1     # same story via two feeds
    assert data["items"][-1]["date"] is None                                  # undated last
    dates = [i["date"] for i in data["items"] if i["date"]]
    assert dates == sorted(dates, reverse=True)
    eq = next(i for i in data["items"] if i["link"].endswith("fx0001"))
    assert eq["lanes"] == ["capex"] and {s["id"] for s in eq["sites"] + eq["operator_sites"]} == {"dc-1", "dc-2"}
    # re-running over its own output keeps the file stable (merge is idempotent)
    assert D.main(args + ["--out", str(out1)]) == 0
    assert out1.read_bytes() == a


def test_all_feeds_failing_without_previous_output_exits_nonzero(tmp_path):
    empty = tmp_path / "none"
    empty.mkdir()
    out = tmp_path / "o.json"
    assert D.main(["--pinned", "none.json", "--fixtures", str(empty), "--proximity", str(tmp_path / "missing.json"), "--now", NOW,
                   "--out", str(out)]) == 1
    data = json.loads(out.read_text(encoding="utf-8"))
    assert data["status"] == "failed" and data["items"] == []
    # with an earlier good file the run keeps it and exits 0
    out.write_text(json.dumps({"schema": D.SCHEMA, "items": [
        {"link": "https://e.org/k", "date": None, "first_seen": NOW, "lanes": ["capex"], "sites": [],
         "title": "kept"}]}), encoding="utf-8")
    assert D.main(["--pinned", "none.json", "--fixtures", str(empty), "--now", NOW, "--out", str(out)]) == 0
    assert json.loads(out.read_text(encoding="utf-8"))["items"][0]["title"] == "kept"


def test_feed_list_is_https_and_explained():
    assert len(D.FEEDS) == len({u for u, _, _ in D.FEEDS}) <= 12
    for url, source, why in D.FEEDS:
        assert url.startswith("https://") and source and len(why) > 20


def test_output_matches_json_schema(tmp_path):
    jsonschema = pytest.importorskip("jsonschema")
    reg = tmp_path / "prox.json"
    reg.write_text(json.dumps({"records": REGISTER}), encoding="utf-8")
    out = tmp_path / "o.json"
    D.main(["--pinned", "none.json", "--fixtures", str(FIXTURES), "--proximity", str(reg), "--now", NOW, "--out", str(out)])
    schema = json.loads((PKG / "schema" / "datacentre-news.v1.schema.json").read_text(encoding="utf-8"))
    jsonschema.validate(json.loads(out.read_text(encoding="utf-8")), schema)


def test_pinned_items_are_always_in_the_feed(tmp_path):
    """An owner-pinned headline is carried even when every feed is empty or failing."""
    import json
    from automation.news import datacentre_feed as feed

    pinned = tmp_path / "pinned.json"
    pinned.write_text(json.dumps({"items": [
        {"title": "A pinned headline", "link": "https://example.org/a?utm_source=x", "source": "Example",
         "date": "2026-11-08", "lanes": ["politics"], "reason": "owner"},
        {"title": "No lane, dropped", "link": "https://example.org/b", "lanes": []},
    ]}), encoding="utf-8")
    items = feed.load_pinned(pinned, "2026-11-14T00:00:00Z")
    assert [i["title"] for i in items] == ["A pinned headline"]
    assert items[0]["lanes"] == ["politics"] and items[0]["sites"] == []
    assert feed.load_pinned(tmp_path / "absent.json", "2026-11-14T00:00:00Z") == []


def test_shipped_pinned_file_is_valid():
    import json
    from pathlib import Path
    from automation.news import datacentre_feed as feed

    path = Path(feed.__file__).with_name("datacentre_pinned.json")
    items = feed.load_pinned(path, "2026-11-14T00:00:00Z")
    assert len(items) == len(json.loads(path.read_text(encoding="utf-8"))["items"]) >= 1
    assert all(i["link"].startswith("https://") for i in items)


def test_shipped_pinned_items_carry_a_date():
    from pathlib import Path
    from automation.news import datacentre_feed as feed

    items = feed.load_pinned(Path(feed.__file__).with_name("datacentre_pinned.json"), "2026-11-14T00:00:00Z")
    assert all(i["date"] for i in items), "a pinned item without a parseable date shows undated in the panel"


def test_items_from_earlier_runs_are_brought_to_the_current_shape():
    old = [{"title": "Sponsored: data centre water", "link": "https://e.org/s", "date": None, "first_seen": NOW,
            "lanes": ["politics"], "matched_terms": {"datacentre": [], "capex": [], "politics": ["water"]},
            "sites": [], "site_matches": 0},
           {"title": "Equinix LD8 expansion", "link": "https://e.org/1", "date": None, "first_seen": NOW,
            "lanes": ["capex"], "matched_terms": {"datacentre": [], "capex": ["expansion"], "politics": []},
            "sites": [{"id": "dc-1", "matched_on": "site_name", "repd_nearby": None},
                      {"id": "dc-2", "matched_on": "operator", "repd_nearby": {"projects": 2}}], "site_matches": 2}]
    merged = D.merge(old, [])
    assert [m["link"] for m in merged] == ["https://e.org/1"]
    assert [s["id"] for s in merged[0]["sites"]] == ["dc-1"]
    assert merged[0]["operator_sites"] == [{"id": "dc-2", "matched_on": "operator"}]
    assert merged[0]["capex_basis"] == "build" and merged[0]["pinned"] is False

Test Documents

A test in the tests folder of GlobalGrid2050 that checks Documents, using SHA-256. It is built from the synthetic step (`synthetic`) and the parse step (`parse`).

testglobalgrid2050 / automation/news/tests/test_documents.py · lines 1–111 of 111 · Entry point · pattern synthetic (shared by 7 files)

What it does
It tests its inputs. Defines 11 functions or classes, including synthetic, parse, test_synthetic_typed_power_has_exact_units_meaning_and_locator, test_unit_or_meaning_or_context_ambiguity_abstains, test_wrong_crossproject_identity_abstains. Uses libraries copy, hashlib, json, os, 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.
Inputs & outputs
In: JSON file government-facts.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Synthetic parser negatives plus optional pinned actual local-byte verification.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Documents (import), copy, hashlib, json, os, pathlib, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
synthetic, parse, test_synthetic_typed_power_has_exact_units_meaning_and_locator, test_unit_or_meaning_or_context_ambiguity_abstains, test_wrong_crossproject_identity_abstains, test_script_facts_and_title_markup_never_become_authority, test_duplicate_capacity_and_mixed_tables_abstain, test_no_partial_date_expansion_or_fabricated_instants, test_unknown_unsafe_sources_changed_hash_and_pdf_unavailable, test_source_receipts_fail_closed_even_when_policy_hash_is_pinned, test_actual_pinned_documents_when_local_receipts_available
Defines here
synthetic, parse, test_synthetic_typed_power_has_exact_units_meaning_and_locator, test_unit_or_meaning_or_context_ambiguity_abstains, test_wrong_crossproject_identity_abstains, test_script_facts_and_title_markup_never_become_authority, test_duplicate_capacity_and_mixed_tables_abstain, test_no_partial_date_expansion_or_fabricated_instants, test_unknown_unsafe_sources_changed_hash_and_pdf_unavailable, test_source_receipts_fail_closed_even_when_policy_hash_is_pinned, test_actual_pinned_documents_when_local_receipts_available
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_documents.py:1-111 · blob b9d732e24aa7fde8968bdd682ec16c90e6695c1a · 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
"""Synthetic parser negatives plus optional pinned actual local-byte verification."""
from copy import deepcopy
from hashlib import sha256
import json
import os
from pathlib import Path

import pytest

from automation.news.filings.documents import POLICIES, OGL, BoundedHTML, _distil_html, day, distil_document

URL = list(POLICIES)[1]
POLICY = POLICIES[URL]
STAMP = "2026-11-17T15:48:11Z"


def synthetic(body=None, project="EN020026", extra=""):
    body = body if body is not None else "It is a high voltage direct current link between Kent and Suffolk. It will have a transmission capacity of up to 2 gigawatts."
    return (f'<main id="content"><h1>{POLICY["title"]}</h1><dl><dt>From:</dt><dd>{POLICY["publisher"]}</dd><dt>Published:</dt><dd>30 October 2026</dd></dl>'
            f'<a href="https://example.test/projects/{project}">Project</a><div class="gem-c-govspeak"><p>{body}</p><p>Date of decision</p><p>30 October 2026</p>{extra}</div></main>').encode()


def parse(data):
    return _distil_html(data, POLICY, URL, STAMP)


def test_synthetic_typed_power_has_exact_units_meaning_and_locator():
    data = synthetic()
    result = parse(data)
    assert result["publishable"] is False
    claim = result["claims"][0]
    assert (claim["value"], claim["unit"], claim["basis"], claim["as_of"]) == ("2", "GW", "forecast", "2026-10-30")
    assert claim["quantity_kind"] == "grid_upgrade"
    assert result["unknowns"]["current_capacity"] is None
    locator = result["facts"][1]["locator"]
    assert locator["paragraph"] == 1 and locator["document_sha256"] == sha256(data).hexdigest()
    assert locator["selector"] == "main#content > div:nth-of-type(1) > p:nth-of-type(1)"


@pytest.mark.parametrize("body", ["It currently has 2 gigawatts.", "It will have a transmission capacity of up to 2 gigawatt-hours.", "It will have a transmission capacity of up to 400 kilovolts.", "It will have a transmission capacity of up to 2 gigawatts.", "Unknown capacity"])
def test_unit_or_meaning_or_context_ambiguity_abstains(body):
    with pytest.raises(ValueError):
        parse(synthetic(body))


@pytest.mark.parametrize("project", ["EN999999", "EN020026 EN999999", ""])
def test_wrong_crossproject_identity_abstains(project):
    with pytest.raises(ValueError):
        parse(synthetic(project=project))


def test_script_facts_and_title_markup_never_become_authority():
    data = synthetic() + b'<script><p>It will have a transmission capacity of up to 99 gigawatts.</p></script>'
    assert parse(data)["claims"][0]["value"] == "2"
    with pytest.raises(ValueError):
        parse(synthetic().replace(b"Sea Link:", b"<img src=x onerror=alert(1)>Spoof:"))


def test_duplicate_capacity_and_mixed_tables_abstain():
    with pytest.raises(ValueError):
        parse(synthetic(extra='<p>It will have a transmission capacity of up to 3 gigawatts.</p>'))
    with pytest.raises(ValueError):
        parse(synthetic(body='<table><tr><td>2 gigawatts</td><td>3 gigawatts</td></tr></table>'))


@pytest.mark.parametrize("value", ["2026", "October 2026", "30 October 2026T00:00Z", "31 February 2026"])
def test_no_partial_date_expansion_or_fabricated_instants(value):
    with pytest.raises(ValueError):
        day(value)


def test_unknown_unsafe_sources_changed_hash_and_pdf_unavailable():
    for source in ("javascript:alert(1)", URL + "?spoof=1", "https://evil.test/"):
        assert distil_document(b"", source_url=source, receipt={})["reason"] == "source_not_approved"
    revised = distil_document(synthetic(), source_url=URL, receipt={})
    assert revised["reason"] == "source_revision_requires_review" and revised["facts"] == []
    for payload in (b"%PDF scanned image", b"%PDF mixed table unlocated", b"%PDF unknown rights"):
        result = distil_document(payload, source_url=URL, receipt={}, content_type="application/pdf")
        assert result["facts"] == [] and result["status"] == "unavailable"


def test_source_receipts_fail_closed_even_when_policy_hash_is_pinned(monkeypatch):
    data = synthetic()
    monkeypatch.setitem(POLICIES, URL, {**POLICY, "sha256": sha256(data).hexdigest(), "bytes": len(data)})
    receipt = {"source_url": URL, "sha256": sha256(data).hexdigest(), "bytes": len(data), "http_status": 200,
               "content_type": "text/html", "licence_url": OGL, "retrieved_at": STAMP}
    assert distil_document(data, source_url=URL, receipt=receipt)["status"] == "machine-provisional"
    for key, value in (("licence_url", "unknown"), ("http_status", 403), ("sha256", "0" * 64), ("retrieved_at", "2026-01-01")):
        bad = {**receipt, key: value}
        assert distil_document(data, source_url=URL, receipt=bad)["status"] == "unavailable"


def test_actual_pinned_documents_when_local_receipts_available():
    directory = os.environ.get("DOCUMENT_SOURCE_DIR")
    if not directory:
        pytest.skip("actual HTML bytes are private retrieval artifacts; set DOCUMENT_SOURCE_DIR")
    records = json.loads(Path("automation/news/grid_watch/government-facts.json").read_text())["records"]
    results = [distil_document((Path(directory) / f"source-{i}.html").read_bytes(), source_url=row["source_url"], receipt=row["source_receipt"]) for i, row in enumerate(records, 1)]
    assert [r["status"] for r in results] == ["machine-provisional"] * 2
    assert [len(r["facts"]) for r in results] == [4, 2]
    assert results[0]["facts"][0]["value"] == {"value": "2025-03-27", "precision": "DAY"}
    assert results[1]["claims"][0]["value"] == "2"
    assert all(r["publishable"] is False for r in results)
    for i, result in enumerate(results, 1):
        parser = BoundedHTML()
        parser.feed((Path(directory) / f"source-{i}.html").read_text(encoding="utf-8"))
        main = next(n for n in parser.root.walk() if n.tag == "main" and n.attrs.get("id") == "content")
        for fact in result["facts"]:
            found = [n for n in main.walk() if n.selector() == fact["locator"]["selector"]]
            assert len(found) == 1
            assert sha256(found[0].text().encode()).hexdigest() == fact["locator"]["text_sha256"]

Test Engine

A test in the tests folder of GlobalGrid2050 that checks Engine.

testglobalgrid2050 / automation/news/tests/test_engine.py · lines 1–145 of 145 · Entry point

What it does
It tests solar and the REPD register. Defines 15 functions or classes, including test_name_only_provisional_and_publisher_rights_and_timestamps_preserved, test_explicit_repd_id_is_not_verification_and_bare_digits_not_ids, test_duplicate_full_name_veto_and_distinct_non_repd_namespaces, test_identity_not_inferred_from_geo_similarity_and_zero_is_honest, test_duplicates_normalise_tracking_without_dropping_original_article_url. Uses libraries json, subprocess, sys, pytest. Side effects: 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. Domain terms in the code: solar, the REPD register.
Inputs & outputs
In: JSON file articles.json; JSON file sources.json; JSON file projects.json; JSON file out.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Offline positive/negative regression tests for the additive News Engine. Its code works with 1019 MW.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Engine (import), json, subprocess, sys, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
test_name_only_provisional_and_publisher_rights_and_timestamps_preserved, test_explicit_repd_id_is_not_verification_and_bare_digits_not_ids, test_duplicate_full_name_veto_and_distinct_non_repd_namespaces, test_identity_not_inferred_from_geo_similarity_and_zero_is_honest, test_duplicates_normalise_tracking_without_dropping_original_article_url, test_tracking_variants_dedupe_preserve_both_original_urls, test_deterministic_across_input_order, test_existing_pipeline_headlines_shape_is_accepted_with_unique_source, test_reject_non_public_or_unsafe_article_urls, test_unapproved_or_unlicensed_sources_fail_closed, test_rights_approved_does_not_grant_project_verification, test_canonical_collision_different_publisher_metadata_fails_closed
Defines here
test_name_only_provisional_and_publisher_rights_and_timestamps_preserved, test_explicit_repd_id_is_not_verification_and_bare_digits_not_ids, test_duplicate_full_name_veto_and_distinct_non_repd_namespaces, test_identity_not_inferred_from_geo_similarity_and_zero_is_honest, test_duplicates_normalise_tracking_without_dropping_original_article_url, test_tracking_variants_dedupe_preserve_both_original_urls, test_deterministic_across_input_order, test_existing_pipeline_headlines_shape_is_accepted_with_unique_source, test_reject_non_public_or_unsafe_article_urls, test_unapproved_or_unlicensed_sources_fail_closed, test_rights_approved_does_not_grant_project_verification, test_canonical_collision_different_publisher_metadata_fails_closed, test_ambiguous_multiple_explicit_refs_not_verified, test_article_source_provenance_mismatch_rejected, test_cli_no_overwrite_and_roundtrip
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_engine.py:1-145 · blob 61c4d788b81229a61581b8328ba878309aab5f53 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Offline positive/negative regression tests for the additive News Engine."""
import json
import subprocess
import sys

import pytest
from automation.news.engine import build_intelligence, canonical_url

S = {"id": "publisher_1", "publisher": "Independent Example", "kind": "reporting",
     "rights_status": "unknown", "enabled": False, "output_policy": "headline_link_only"}
P = [{"id": "1018", "name": "East Meadow Solar Farm", "technology": "solar"},
     {"id": "1019", "name": "Other Solar Farm", "technology": "solar"}]
A = {"url": "https://news.example.org/solar/1?utm_source=feed#fragment",
     "title": "East Meadow Solar Farm planning news", "publisher": "Independent Example",
     "source_id": "publisher_1", "pub_date": "2026-11-16T12:34:00Z",
     "first_seen": "2026-11-16T12:45:00Z", "source_receipt_sha256": "a" * 64,
     "content": "REPD 1019 (publisher body that must never be used or stored)"}


def test_name_only_provisional_and_publisher_rights_and_timestamps_preserved():
    out = build_intelligence([A], [S], P)
    assert out["schema"] == "globalgrid2050.ventus-news-intelligence.v1"
    assert out["counts"] == {"articles": 1, "provisional_project_edges": 1,
                             "verified_project_edges": 0, "rights_unresolved_articles": 1}
    row = out["articles"][0]
    assert row["publisher"] == A["publisher"]
    assert row["published_at"] == A["pub_date"]
    assert row["first_seen"] == A["first_seen"]
    assert row["source_receipt_sha256"] == "a" * 64
    assert row["usage_rights"]["status"] == "unknown"
    assert row["publication_eligibility"].startswith("WITHHELD")
    assert row["verification_status"] == "NOT_VERIFIED"
    assert row["project_candidates"] == [{"namespace": "repd", "id": "1018",
                                          "method": "exact_name", "status": "PROVISIONAL",
                                          "evidence_scope": "TITLE_ONLY", "independent_review": "REQUIRED"}]
    assert "publisher body" not in json.dumps(out)
    assert "1019" not in json.dumps(row)


def test_explicit_repd_id_is_not_verification_and_bare_digits_not_ids():
    out = build_intelligence([{**A, "title": "REPD reference 1019 changes"}], [S], P)
    assert out["articles"][0]["project_candidates"][0]["method"] == "repd_id"
    out2 = build_intelligence([{**A, "title": "Capacity 1019 MW changes"}], [S], P)
    assert out2["counts"]["provisional_project_edges"] == 0


def test_duplicate_full_name_veto_and_distinct_non_repd_namespaces():
    projects = P + [{"id": "2000", "name": P[0]["name"]},
                    {"namespace": "dcuk", "id": "dcuk-1", "name": P[0]["name"]}]
    out = build_intelligence([A], [S], projects)
    assert out["counts"]["provisional_project_edges"] == 0


def test_identity_not_inferred_from_geo_similarity_and_zero_is_honest():
    out = build_intelligence([{**A, "title": "A nearby developer starts construction"}], [S], P)
    assert out["counts"]["provisional_project_edges"] == 0
    assert out["counts"]["verified_project_edges"] == 0


def test_duplicates_normalise_tracking_without_dropping_original_article_url():
    rows = [A, {**A, "url": A["url"]}]
    out = build_intelligence(rows, [S], P)
    assert out["counts"]["articles"] == 1
    assert out["articles"][0]["original_article_url"] == A["url"]
    assert out["articles"][0]["canonical_article_url"] == "https://news.example.org/solar/1"


def test_tracking_variants_dedupe_preserve_both_original_urls():
    alternate = {**A, "url": "https://news.example.org/solar/1?utm_medium=email"}
    first = build_intelligence([A, alternate], [S], P)
    second = build_intelligence([alternate, A], [S], P)
    assert first == second
    assert first["counts"]["articles"] == 1
    assert first["articles"][0]["observed_article_urls"] == sorted([A["url"], alternate["url"]])


def test_deterministic_across_input_order():
    other = {**A, "url": "https://news.example.org/2", "title": "UK wind market news"}
    x = build_intelligence([A, other], [S], P)
    y = build_intelligence([other, A], [S], P)
    assert x == y
    assert x["counts"]["articles"] == 2


def test_existing_pipeline_headlines_shape_is_accepted_with_unique_source():
    out = build_intelligence({"items": [{"title": "Grid update", "link": A["url"],
                                          "source": S["publisher"], "date": "2026-11-16"}]}, [S])
    assert out["articles"][0]["published_at"] == "2026-11-16"
    assert out["articles"][0]["project_candidates"] == []


@pytest.mark.parametrize("bad", ["http://news.example.org/1", "https://127.0.0.1/a",
                                 "https://localhost/a", "https://person@news.example.org/a",
                                 "https://news.example.org:444/a", "https://news.example.org\\@evil.com/a",
                                 "https://news.example.org/a\nfoo"])
def test_reject_non_public_or_unsafe_article_urls(bad):
    with pytest.raises(ValueError):
        canonical_url(bad)


@pytest.mark.parametrize("source", [
    {**S, "enabled": True},
    {**S, "rights_status": "accepted"},
    {**S, "output_policy": "full_text"},
    {**S, "rights_status": "legal_unknown"},
])
def test_unapproved_or_unlicensed_sources_fail_closed(source):
    with pytest.raises(ValueError):
        build_intelligence([A], [source])


def test_rights_approved_does_not_grant_project_verification():
    approved = {**S, "rights_status": "accepted", "enabled": True,
                "rights_review_url": "https://publisher.example.org/licences/1"}
    out = build_intelligence([A], [approved], P)
    assert out["counts"]["verified_project_edges"] == 0
    assert out["articles"][0]["publication_eligibility"].startswith("WITHHELD")


def test_canonical_collision_different_publisher_metadata_fails_closed():
    with pytest.raises(ValueError, match="collision"):
        build_intelligence([A, {**A, "title": "Retitled story"}], [S], P)


def test_ambiguous_multiple_explicit_refs_not_verified():
    out = build_intelligence([{**A, "title": "REPD 1018 and REPD 1019"}], [S], P)
    edges = out["articles"][0]["project_candidates"]
    assert len(edges) == 2 and all(e["ambiguous_multi_project"] for e in edges)


def test_article_source_provenance_mismatch_rejected():
    with pytest.raises(ValueError, match="attribution"):
        build_intelligence([{**A, "publisher": "Other"}], [S], P)


def test_cli_no_overwrite_and_roundtrip(tmp_path):
    for name, data in [("articles", [A]), ("sources", [S]), ("projects", P)]:
        (tmp_path / (name + ".json")).write_text(json.dumps(data), encoding="utf-8")
    cmd = [sys.executable, "-m", "automation.news.engine", "--articles", str(tmp_path / "articles.json"),
           "--sources", str(tmp_path / "sources.json"), "--projects", str(tmp_path / "projects.json"),
           "--output", str(tmp_path / "out.json")]
    subprocess.run(cmd, check=True, capture_output=True, text=True)
    assert json.loads((tmp_path / "out.json").read_text())["counts"]["verified_project_edges"] == 0
    result = subprocess.run(cmd, capture_output=True, text=True)
    assert result.returncode != 0 and "FileExistsError" in result.stderr