GLOBALGRID2050 / EXPLORE CODE

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

Test Signals Acid and 2 more files

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

700 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 810 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 Relevance test · globalgrid2050 / automation/news/tests/test_relevance.py lines 1–118
  2. Test Research Context test · globalgrid2050 / automation/news/tests/test_research_context.py lines 1–150
  3. Test Signals Acid test · globalgrid2050 / automation/news/tests/test_signals_acid.py lines 1–432

Test Relevance

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

testglobalgrid2050 / automation/news/tests/test_relevance.py · lines 1–118 of 118 · Entry point

What it does
It tests solar. Defines 14 functions or classes, including _ranked, _comp, test_components_visible_and_sum, test_capacity_component, test_recency_against_reference_not_clock. Uses libraries json, datetime, pytest.
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 prev_feed.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Defines `test_components_visible_and_sum`, `test_capacity_component`, `test_recency_against_reference_not_clock` and 9 more. Its code works with 150 MW and 530 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
Events (import), json, datetime, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
test_components_visible_and_sum, test_capacity_component, test_recency_against_reference_not_clock, test_national_route_and_colocation, test_consent_of_large_solar_outranks_small_withdrawal, test_datacentre_component_reliability, test_novelty_uses_previous_feed_and_siblings, test_top_events_folds_siblings, test_profile_hash_stable, test_article_evidence_tiers, test_article_event_classification, test_corroboration_and_contradiction
Defines here
_ranked, _comp, test_components_visible_and_sum, test_capacity_component, test_recency_against_reference_not_clock, test_national_route_and_colocation, test_consent_of_large_solar_outranks_small_withdrawal, test_datacentre_component_reliability, test_novelty_uses_previous_feed_and_siblings, test_top_events_folds_siblings, test_profile_hash_stable, test_article_evidence_tiers, test_article_event_classification, test_corroboration_and_contradiction
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_relevance.py:1-118 · blob 9e75ddde295ae4fa4d3b44a5d973259ee69d76f4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import json
from datetime import date

import pytest

from automation.news import events as E
from automation.news import relevance as R

REF = date(2026, 10, 23)


def _ranked(releases, dc=None, previous=None):
    old, new = E.load_pair(*releases)
    doc = E.build_events(old, new)
    return R.rank_events(doc["events"], REF, dc, previous)


def _comp(ev, name):
    return next(c for c in ev["relevance"]["components"] if c["name"] == name)


def test_components_visible_and_sum(releases):
    for ev in _ranked(releases):
        comps = ev["relevance"]["components"]
        assert [c["name"] for c in comps] == ["capacity", "stage", "technology", "recency", "national_route",
                                             "datacentre_proximity", "novelty", "evidence_tier", "colocated_storage"]
        assert ev["relevance"]["score"] == pytest.approx(sum(c["points"] for c in comps))
        assert all(c["basis"] for c in comps)
        assert ev["relevance"]["score"] <= ev["relevance"]["max_possible"]


def test_capacity_component():
    assert R.capacity_component(None)["points"] == 0
    assert "unknown" in R.capacity_component(None)["basis"]
    assert R.capacity_component(999)["points"] == pytest.approx(30.0)
    assert R.capacity_component(5000)["points"] == 30.0
    assert R.capacity_component(9)["points"] == pytest.approx(10.0)


def test_recency_against_reference_not_clock():
    assert R.recency_component("2026-10-01", REF)["points"] == 10
    assert R.recency_component("2026-06-01", REF)["points"] == 4
    assert R.recency_component("2020-01-01", REF)["points"] == 0
    assert R.recency_component(None, REF)["points"] == 1


def test_national_route_and_colocation(releases):
    ev = next(e for e in _ranked(releases) if e["ref"] == "1" and e["event_type"] == "CONSENTED")
    assert _comp(ev, "national_route")["points"] == 8
    assert _comp(ev, "colocated_storage")["points"] == 3
    assert _comp(ev, "evidence_tier")["tier"] == "official_record"


def test_consent_of_large_solar_outranks_small_withdrawal(releases):
    ranked = _ranked(releases)
    pos = {(e["ref"], e["event_type"]): e["rank"] for e in ranked}
    assert pos[("1", "CONSENTED")] < pos[("6", "WITHDRAWN")]
    assert [e["rank"] for e in ranked] == list(range(1, len(ranked) + 1))


def test_datacentre_component_reliability():
    ctx = {"nearest": {"id": "dcuk-x", "status": "operational", "km": 4.2, "proximity_reliable": True}}
    assert R.datacentre_component(ctx)["points"] == 10
    ctx["nearest"]["km"] = 30
    assert R.datacentre_component(ctx)["points"] == 2
    ctx["nearest"]["proximity_reliable"] = False
    assert R.datacentre_component(ctx)["points"] == 0
    assert R.datacentre_component(None)["points"] == 0
    assert "not a connection" in R.datacentre_component({"nearest": {"id": "d", "km": 1, "status": "x"}})["basis"]


def test_novelty_uses_previous_feed_and_siblings(releases, tmp_path):
    prev = tmp_path / "prev_feed.json"
    prev.write_text(json.dumps({"canonical_items": [
        {"repd_ref": "1", "role": "PRIMARY_MATCH", "event": "CONSENT", "gg_article_id": "A1"},
        {"repd_ref": "3", "role": "PRIMARY_MATCH", "event": "ACQUISITION", "gg_article_id": "A2"}]}))
    previous = R.load_previous_feed(prev)
    ranked = _ranked(releases, previous=previous)
    get = lambda ref, t: next(e for e in ranked if e["ref"] == ref and e["event_type"] == t)  # noqa: E731
    assert _comp(get("1", "CONSENTED"), "novelty")["points"] == 0
    assert _comp(get("2", "CONSENTED"), "novelty")["points"] == 0       # sibling of ref 1, same event
    assert _comp(get("3", "CONSTRUCTION_STARTED"), "novelty")["points"] == 3
    assert _comp(get("4", "OPERATIONAL"), "novelty")["points"] == 6


def test_top_events_folds_siblings(releases):
    top = R.top_events(_ranked(releases), 5)
    assert len(top) == 5
    lead = top[0]
    assert set(lead["grouped_refs"]) <= {"1", "2"}


def test_profile_hash_stable():
    assert R.profile_sha256() == R.profile_sha256(json.loads(json.dumps(R.DEFAULT_PROFILE)))


def test_article_evidence_tiers():
    assert R.evidence_tier_of("GOV.UK", "https://www.gov.uk")[0] == "official_record"
    assert R.evidence_tier_of("Some Council", "https://planning.example.gov.uk")[0] == "official_record"
    assert R.evidence_tier_of("reNEWS", "https://renews.biz")[0] == "attributed_reporting"
    assert R.evidence_tier_of("", "https://news.google.com/rss/x")[0] == "unverified_lead"


def test_article_event_classification():
    assert R.classify_article_event("Hatton solar farm approved on appeal") == "CONSENTED"
    assert R.classify_article_event("Blocked BESS: appeal fails for 150 MW site") == "REFUSED"
    assert R.classify_article_event("Coalburn 1 battery enters operations") == "OPERATIONAL"
    assert R.classify_article_event("Ampyr acquires 530MW East Yorkshire Solar Farm") == "ACQUISITION"


def test_corroboration_and_contradiction():
    project = {"ref": "5", "status": "Application Refused"}
    c, contra = R.corroboration("CONSENTED", project, {})
    assert c["points"] == 0 and contra and "Application Refused" in contra
    c, contra = R.corroboration("REFUSED", project, {"5": {"REFUSED"}})
    assert c["points"] == 6 and contra is None
    c, _ = R.corroboration("CONSENTED", {"ref": "1", "status": "Awaiting Construction"}, {})
    assert c["points"] == 3

Test Research Context

A test in the tests folder of GlobalGrid2050 that checks Pipeline Headlines and Research Indexes. It is built from the must not fetch helper (`must_not_fetch`) and the item step (`item`).

testglobalgrid2050 / automation/news/tests/test_research_context.py · lines 1–150 of 150 · Entry point

What it does
It tests the REPD register. Defines 15 functions or classes, including test_global_context_keep, test_global_context_reject, test_institutional_research_rejects_general_financial_marketing, test_no_eligible_html_index_is_reported_unavailable_not_healthy, test_uk_standard_lane_still_rejects_swiss_non_uk_context. Uses libraries pathlib, sys, pytest. 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: the REPD register.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
International research lane regression checks: no weakening of UK/Renewable Energy Planning Database (REPD) controls.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Pipeline Headlines (sys.path import), Research Indexes (sys.path import), pathlib, 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_global_context_keep, test_global_context_reject, test_institutional_research_rejects_general_financial_marketing, test_no_eligible_html_index_is_reported_unavailable_not_healthy, test_uk_standard_lane_still_rejects_swiss_non_uk_context, test_curated_deloitte_is_attributed_without_fabricated_date_or_repd, test_bounded_html_index_keeps_english_same_host_only, test_html_discovery_passes_through_context_classification, test_research_is_lane_capped_without_crowding_original_world_lanes, test_new_context_never_displaces_existing_headlines_at_capacity, test_swiss_national_bank_rdf_rss1_is_parsed_without_legacy_feed_changes, test_rss1_rejects_unsafe_entities
Defines here
test_global_context_keep, test_global_context_reject, test_institutional_research_rejects_general_financial_marketing, test_no_eligible_html_index_is_reported_unavailable_not_healthy, test_uk_standard_lane_still_rejects_swiss_non_uk_context, test_curated_deloitte_is_attributed_without_fabricated_date_or_repd, must_not_fetch, test_bounded_html_index_keeps_english_same_host_only, test_html_discovery_passes_through_context_classification, test_research_is_lane_capped_without_crowding_original_world_lanes, test_new_context_never_displaces_existing_headlines_at_capacity, item, test_swiss_national_bank_rdf_rss1_is_parsed_without_legacy_feed_changes, test_rss1_rejects_unsafe_entities, test_publisher_rss1_label_may_serve_valid_rss2_without_legacy_parser_change
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_research_context.py:1-150 · blob 529d470048bbbdbefe25115d794168a5cdd20ae8 · 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
"""International research lane regression checks: no weakening of UK/REPD controls."""
from pathlib import Path
import sys
import pytest

PKG = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PKG))
import pipeline_headlines as P
import research_indexes as R

NOW = "2026-11-21T16:00:00Z"

@pytest.mark.parametrize("title,category", [
    ("A study on data centres shows that the real bottleneck lies in the grid", "datacentre"),
    ("DNV Energy Transition Outlook 2026: grid and storage investment", "grid"),
    ("Swissgrid announces electricity transmission grid capacity improvements", "grid"),
    ("Federal Reserve says interest rates will stay unchanged", "finance"),
    ("Bank of England monetary policy statement and Bank Rate", "finance"),
    ("HM Treasury announces infrastructure financing review", "finance"),
    ("Powering the AI revolution: data centre grid connections", "datacentre"),
    ("The Swiss electricity grid faces new power demand constraints", "grid"),
])
def test_global_context_keep(title, category):
    assert P.lane_label(title, "global_context") == (category, None, None)

@pytest.mark.parametrize("title", [
    "Markets rally as chipmakers announce a share buyback",
    "Deloitte appoints new chief executive in Zurich",
    "KPMG wins national audit firm of the year",
    "Swiss tourism industry reports summer growth",
    "Federal Reserve publishes staff survey response",
    "Sponsored feature: data centre grid investments",
])
def test_global_context_reject(title):
    assert P.lane_label(title, "global_context", "energy_research") is None

def test_institutional_research_rejects_general_financial_marketing():
    assert P.lane_label("Banking & Capital Markets", "global_context", "energy_research") is None
    assert P.lane_label("Deloitte confirms interest rates rise", "global_context", "energy_research") is None
    assert P.lane_label("Data centres face electricity-grid bottleneck", "global_context", "energy_research") == ("datacentre", None, None)
    assert P.lane_label("Federal Reserve says interest rates rise", "global_context", "macro_policy") == ("finance", None, None)

def test_no_eligible_html_index_is_reported_unavailable_not_healthy():
    feed = {"url": "https://www.dnv.com/news/", "source": "DNV", "kind": "html_index",
            "lane": "global_context", "focus": "energy_research", "article_prefixes": ["/news/"]}
    items, health = P.collect([feed], lambda url: b"<html><body>No relevant links</body></html>",
                              P.Repd([]), NOW)
    assert items == []
    assert health[0]["status"] == "failed"
    assert "No eligible index links" in health[0]["error"]

def test_uk_standard_lane_still_rejects_swiss_non_uk_context():
    repd = P.Repd([])
    title = "Swiss electricity grid constraints hit data centre developers"
    assert not P.is_uk(title, repd)
    body = ('<rss><channel><item><title>' + title + '</title>'
            '<link>https://example.org/swiss</link></item></channel></rss>').encode()
    items, _ = P.collect([{"url":"https://x.example/feed", "source":"X", "uk_only":False}],
                         lambda url: body, repd, NOW)
    assert not items

def test_curated_deloitte_is_attributed_without_fabricated_date_or_repd():
    url = "https://www.deloitte.com/ch/en/about/press-room/studie-zu-rechenzentren-zeigt-der-eigentliche-engpass-liegt-im-netz.html"
    feed = {"url": url, "source": "Deloitte Switzerland", "kind": "curated", "lane": "global_context",
            "title": "A study on data centres shows that the real bottleneck lies in the grid"}
    def must_not_fetch(url):
        raise AssertionError("curated link must not be falsely described as fetched")
    items, health = P.collect([feed], must_not_fetch, P.Repd([]), NOW)
    assert len(items) == 1
    assert items[0]["link"] == url
    assert items[0]["source"] == "Deloitte Switzerland"
    assert items[0]["date"] is None and items[0]["possible_match"] is None
    assert health[0]["kept"] == 1

def test_bounded_html_index_keeps_english_same_host_only():
    feed = {"url":"https://www.deloitte.com/ch/en/about/press-room.html",
            "article_prefixes":["/ch/en/about/press-room/"],"english_only":True}
    body = b"""<html><body>
    <a href="/ch/en/about/press-room/data-centres-grid.html">Data centres: electricity grid bottleneck research</a>
    <a href="/ch/de/about/press-room/studie.html">Data centres on Swiss grid study</a>
    <a href="https://evil.example/ch/en/about/press-room/fraud.html">Data centres fake offsite study</a>
    <a href="/ch/en/about/press-room.html">Press room landing page</a>
    <a href="/ch/en/about/press-room/data-centres-grid.html">Data centres: electricity grid bottleneck research</a>
    </body></html>"""
    got = R.index_entries(body, feed)
    assert len(got) == 1
    assert got[0][1] == "https://www.deloitte.com/ch/en/about/press-room/data-centres-grid.html"
    assert got[0][2] is None

def test_html_discovery_passes_through_context_classification():
    feed = {"url":"https://www.dnv.com/news/", "source":"DNV", "lane":"global_context",
            "kind":"html_index","article_prefixes":["/news/"]}
    body = b"""<html><a href="/news/2026/critical-grid-update/">
      DNV grid capacity and energy infrastructure study
    </a><a href="/news/2026/irrelevant/">DNV announces new colleague in Oslo</a></html>"""
    items, _ = P.collect([feed], lambda u: body, P.Repd([]), NOW)
    assert len(items) == 1
    assert items[0]["date"] is None and items[0]["possible_match"] is None

def test_research_is_lane_capped_without_crowding_original_world_lanes():
    assert P.WORLD_LANE_CAPS["global_context"] >= 25
    assert P.WORLD_LANE_CAPS["china_solar"] == 10
    assert P.WORLD_LANE_CAPS["datacentre_money"] == 10

def test_new_context_never_displaces_existing_headlines_at_capacity():
    def item(title, url, source, date):
        return {"title": title, "link": url, "source": source, "date": date,
                "first_seen": NOW, "category": "grid", "technology": None, "possible_match": None}
    legacy = [item(f"UK National Grid connection reform {n}",
                   f"https://example.org/uk-{n}", "Original", "2026-11-19T10:00:00Z") for n in range(3)]
    extra = [item("Swiss data centres need more electricity grid capacity",
                  "https://example.org/ch", "Swissgrid", "2026-11-21T10:00:00Z")]
    got = P.merge([], legacy + extra, P.Repd([]), NOW, cap=3,
                  lanes={"Swissgrid": "global_context"}, focuses={"Swissgrid": "energy_research"})
    assert len(got) == 3
    assert {x["link"] for x in got} == {x["link"] for x in legacy}
    assert all(x["possible_match"] is None for x in got)

def test_swiss_national_bank_rdf_rss1_is_parsed_without_legacy_feed_changes():
    xml = b"""<?xml version="1.0"?>
    <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
             xmlns="http://purl.org/rss/1.0/"
             xmlns:dc="http://purl.org/dc/elements/1.1/">
       <item rdf:about="https://www.snb.ch/en/example/monetary">
         <title>Swiss National Bank monetary policy assessment</title>
         <link>https://www.snb.ch/en/example/monetary</link>
         <dc:date>2026-11-19T10:00:00Z</dc:date>
       </item>
    </rdf:RDF>"""
    feed = {"url":"https://www.snb.ch/public/rss/en/mopo","source":"Swiss National Bank",
            "kind":"rss1","lane":"global_context","focus":"macro_policy"}
    items, health = P.collect([feed], lambda url: xml, P.Repd([]), NOW)
    assert len(items) == 1 and items[0]["date"] == "2026-11-19T10:00:00Z"
    assert items[0]["category"] == "finance" and items[0]["possible_match"] is None
    assert health[0]["status"] == "ok"

def test_rss1_rejects_unsafe_entities():
    with pytest.raises(ValueError):
        R.rss1_entries(b'<!DOCTYPE rdf:RDF [<!ENTITY x "wrong">]><rdf:RDF/>')

def test_publisher_rss1_label_may_serve_valid_rss2_without_legacy_parser_change():
    feed = b"""<?xml version="1.0"?>
      <rss version="2.0"><channel><item>
        <title>Swiss National Bank monetary policy assessment</title>
        <link>https://www.snb.ch/en/release/monetary</link>
        <pubDate>Thu, 19 Nov 2026 10:00:00 GMT</pubDate>
      </item></channel></rss>"""
    entries = R.rss1_entries(feed)
    assert entries[0][0] == "Swiss National Bank monetary policy assessment"
    assert len(entries) == 1

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 1–432 of 960 · 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
known, open_item, item, part, reviewed, world, Run, __init__, project, combine, tiers, shown, reports, find, confirmed, total_items, projects_with_items, base_parts, case_parts, test_R01_repd_9050_takes_no_headline_without_solar_farm_or_the_place, test_R01_a_false_match_already_published_is_not_carried_into_the_next_file, test_R01_no_collector_attaches_a_reported_false_match_as_a_confident_match, test_R01_confidence_is_earned_not_inherited_from_the_part, test_R01_true_headlines_are_kept_as_confirmed, test_R01_real_alias_table_no_confirmed_item_under_an_alias_that_is_not_evidenced, test_R01_aliases_the_confidence_tester_would_downgrade_show_no_confirmed_item, collector_verdict, test_R01_tester_false_matches_no_collector_is_confident, test_R01_tester_false_matches_are_never_published_as_confirmed, test_R01_tester_false_matches_fixture_is_complete
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:1-432 · 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
"""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. No network.

Written against contract version 2 (schema project-signals.v2: tiers recent_news, official, archive; planning
file apart; honest generated_at). The combiner is run as a program, the way the workflow runs it, so the suite
does not depend on its internals.

Known failing: a test that the code on main (schema project-signals.v1) does not meet carries `known(...)`, an
xfail naming the review finding it covers (NL-019 = the independent code review on neural-link issue 19;
"definition N" = the definitions of done of the acid cycle). The marker is strict, and it is applied only
while combine.py still declares version 1: on version 1 a marked test that passes is a failure, and on code that
declares version 2 the marker is not applied, so every marked test must pass there.

Rule ids in the test names (R01 to R15) are the rows of the scorecard.
"""
from __future__ import annotations

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

import pytest

TESTS = Path(__file__).resolve().parent
NEWS = TESTS.parent
SIGNALS = NEWS / "signals"
REPO = NEWS.parents[1]
FIXTURES = TESTS / "fixtures" / "acid"
for _path in (str(TESTS), str(NEWS), str(SIGNALS)):
    if _path not in sys.path:
        sys.path.insert(0, _path)

import acid_live as L  # noqa: E402
import acid_report  # noqa: E402

COMBINE = SIGNALS / "combine.py"
VERSION_1 = "project-signals.v2" not in COMBINE.read_text(encoding="utf-8")
PART_SCHEMA = "project-signals-part.v1"
NOW = "2026-11-14T12:00:00Z"
COLLECTED = "2026-11-14T11:50:00Z"
NEXT_DAY = "2026-11-15T12:00:00Z"
NEXT_COLLECTED = "2026-11-15T11:50:00Z"

WORLD = json.loads((FIXTURES / "projects.json").read_text(encoding="utf-8"))
FALSE_MATCHES = json.loads((FIXTURES / "false_matches.json").read_text(encoding="utf-8"))["cases"]
DATES = json.loads((FIXTURES / "dates.json").read_text(encoding="utf-8"))["cases"]
TESTERS = json.loads((FIXTURES / "tester_cases.json").read_text(encoding="utf-8"))
TESTER_FALSE = json.loads((FIXTURES / "tester_false_matches.json").read_text(encoding="utf-8"))
REAL_TOP200 = json.loads((SIGNALS / "top200_solar.json").read_text(encoding="utf-8"))
REAL_ALIASES = json.loads((SIGNALS / "aliases.json").read_text(encoding="utf-8"))
REVIEWED = json.loads((SIGNALS / "reviewed_signals.json").read_text(encoding="utf-8"))
NEWS_FAMILIES = ("bbc", "trade", "national", "regional")


def known(finding, text, strict=True):
    """Known failing on main until the fixer's pull request; see the module docstring."""
    return pytest.mark.xfail(condition=VERSION_1, strict=strict, reason="%s: %s" % (finding, text))


def open_item(text):
    """A recommendation outside contract version 2: reported, never a failure."""
    return pytest.mark.xfail(strict=False, reason="OPEN, outside contract v2: %s" % text)


# ---------------------------------------------------------------- fixtures and the runner

def item(ref, slug, title=None, date="2026-11-01", family="trade", confidence="confirmed", publisher="Example News", **more):
    base = {"repd_ref": str(ref), "title": title or "Headline %s" % slug, "link": "https://news.example.co.uk/%s" % slug,
            "publisher": publisher, "date": date, "family": family, "basis": "alias in title", "confidence": confidence}
    base.update(more)
    return base


def part(team, items, stamp=COLLECTED, sources=None):
    if sources is None:
        sources = [{"id": team + "-source", "url": "https://news.example.co.uk/", "status": "ok", "requests": 3,
                    "failures": 0, "items": len(items), "error": ""}]
    return {"schema": PART_SCHEMA, "team": team, "generated_at": stamp, "items": items, "sources": sources}


def reviewed(items, stamp="2026-11-14T10:00:00Z"):
    for one in items:
        one.setdefault("basis", "reviewed 2026-11-14")
        if not one["basis"].startswith("reviewed"):
            one["basis"] = "reviewed 2026-11-14"
    return part("reviewed", items, stamp, sources=[])


def world(tmp, extra_refs=(), aliases_patch=None):
    """Write the fixture top-200 list and alias table (plus real rows for `extra_refs`); return their paths."""
    rows = [dict(r) for r in WORLD["top200"]]
    aliases = json.loads(json.dumps(WORLD["aliases"]))
    for ref in extra_refs:
        if ref in aliases["projects"]:
            continue
        rows.append(dict(next(r for r in REAL_TOP200 if str(r["repd_ref"]) == ref), rank=len(rows) + 1))
        aliases["projects"][ref] = REAL_ALIASES["projects"][ref]
    for ref, patch in (aliases_patch or {}).items():
        aliases["projects"][ref].update(patch)
    top, table = tmp / "top200.json", tmp / "aliases.json"
    top.write_text(json.dumps(rows), encoding="utf-8")
    table.write_text(json.dumps(aliases), encoding="utf-8")
    return top, table


class Run:
    def __init__(self, code, doc, text, out):
        self.code, self.doc, self.text, self.out = code, doc, text, out

    def project(self, ref):
        assert self.doc is not None, "the combiner wrote no file (exit %s): %s" % (self.code, self.text[-400:])
        return self.doc["projects"][str(ref)]


def combine(tmp, parts=None, now=NOW, previous=None, name="out", top200=None, aliases=None, extra_refs=(), aliases_patch=None):
    """Run combine.py as the workflow does. parts: {team: part dict | raw text | None (file absent)}.
    A reviewed part is always passed (empty unless given) so the committed reviewed file does not leak in."""
    work = tmp / name
    work.mkdir(parents=True, exist_ok=True)
    if top200 is None:
        top200, aliases = world(work, extra_refs, aliases_patch)
    given = {"official": None, "trade": None, "index": None, "reviewed": reviewed([])}
    given.update(parts or {})
    args = [sys.executable, str(COMBINE), "--top200", str(top200), "--aliases", str(aliases), "--now", now]
    for team, value in given.items():
        path = work / ("part-%s.json" % team)
        if isinstance(value, dict):
            path.write_text(json.dumps(value), encoding="utf-8")
        elif isinstance(value, str):
            path.write_text(value, encoding="utf-8")
        args += ["--" + team, str(path)]
    out = work / "project_signals.json"
    if previous is not None:
        out.write_bytes(Path(previous).read_bytes())          # as in the workflow: the previous file is at --out
        args += ["--previous", str(out)]
    args += ["--out", str(out), "--summary", str(work / "summary.md")]
    done = subprocess.run(args, capture_output=True, text=True, timeout=120, cwd=str(REPO))
    doc = None
    if out.exists():
        try:
            doc = json.loads(out.read_text(encoding="utf-8"))
        except ValueError:
            doc = None
    return Run(done.returncode, doc, done.stdout + done.stderr, out)


def tiers(project):
    """The three lists of contract version 2; a version 1 project fails here, saying why."""
    assert all(isinstance(project.get(name), list) for name in L.LISTS), \
        "version 1 output: one mixed 'signals' list per project, no recent_news / official / archive"
    return {name: project[name] for name in L.LISTS}


def shown(project):
    return L.shown(project)


def reports(project, title):
    """The items that carry this headline: shown under it, or folded into another item's cluster as a source."""
    return [i for i in shown(project) if i["title"] == title or any(s.get("title") == title for s in i.get("sources") or [])]


def find(project, slug):
    return [i for i in shown(project) if i["link"].endswith("/" + slug)]


def confirmed(one):
    return one.get("confidence") == "confirmed"


def total_items(doc):
    return sum(len(shown(p)) for p in doc["projects"].values())


def projects_with_items(doc):
    return sum(1 for p in doc["projects"].values() if shown(p))


def base_parts(stamp=COLLECTED):
    """One healthy run: six projects with items, of every kind."""
    return {
        "official": part("official", [
            item("90001", "o-consent", "Alderwick Solar Farm: development consent decision", "2026-11-10", "official",
                 publisher="Planning Inspectorate"),
            item("90002", "o-exam", "Brantley Moor Solar Farm: examination closed", "2026-03-02", "official",
                 publisher="Planning Inspectorate")], stamp),
        "trade": part("trade", [
            item("90001", "t-consent", "Alderwick Solar Farm granted development consent", "2026-11-11"),
            item("90003", "t-mill", "Mill Solar Farm near Ashford approved", "2026-10-20"),
            item("90007", "t-tarn", "Tarnside Solar Farm plan submitted in Cumbria", "2026-09-30"),
            item("90008", "t-oxley-old", "Oxley Green Solar Farm proposed for Essex", "2021-05-04")], stamp),
        "index": part("index", [
            item("90008", "i-oxley-undated", "Oxley Green Solar Farm: what we know", None, "regional"),
            item("9050", "i-foston", "Solar farm at Foston wins approval", "2021-02-17", "regional")], stamp),
    }


# ---------------------------------------------------------------- R01 false matches

REJECT = [c for c in FALSE_MATCHES if c["expect"] == "reject"]
NOT_CONFIRMED = [c for c in FALSE_MATCHES if c["expect"] == "not_confirmed"]
ACCEPT = [c for c in FALSE_MATCHES if c["expect"] == "accept"]
REAL_REFS = {str(r["repd_ref"]) for r in REAL_TOP200}


def case_parts(cases, family="trade", team="trade"):
    return {team: part(team, [item(c["repd_ref"], "case-%d" % n, c["title"], "2026-11-05", family)
                              for n, c in enumerate(cases)])}


@known("NL-019 finding 5", "REPD 9050 'Bypass Solar Farm' takes headlines about bypass diodes; no exclusion rule")
@pytest.mark.parametrize("team, family", [("trade", "trade"), ("index", "regional"), ("official", "official"), ("reviewed", "trade")])
def test_R01_repd_9050_takes_no_headline_without_solar_farm_or_the_place(tmp_path, team, family):
    cases = [c for c in REJECT + ACCEPT if c["repd_ref"] == "9050"]
    parts = case_parts(cases, family, team)
    if team == "reviewed":
        parts = {"reviewed": reviewed(parts["reviewed"]["items"])}
    run = combine(tmp_path, parts)
    project = run.project("9050")
    titles = [i["title"] for i in shown(project)] + [s["title"] for i in shown(project) for s in i.get("sources") or []]
    wrong = [t for t in titles if not re.search(r"solar farm|foston|grantham", t, re.I)]
    assert not wrong, "REPD 9050 shows %r although the %s part only said so" % (wrong, team)
    for case in (c for c in cases if c["expect"] == "accept"):
        assert reports(project, case["title"]), "the true headline %r was lost" % case["title"]


@known("NL-019 finding 5", "a headline carried over from the previous file is not checked against the exclusion rule again")
def test_R01_a_false_match_already_published_is_not_carried_into_the_next_file(tmp_path):
    """Acid tester 5: a corrected false match must not be republished from the previous file for ever. The previous
    file here is a version 1 file as main publishes it today, holding a bypass-diode headline on REPD 9050."""
    first = {"schema": "project-signals.v1", "generated_at": "2026-11-13T05:23:00Z", "projects": {"9050": {"signals": [
        {"repd_ref": "9050", "title": "New bypass diode design cuts shading losses in PV modules",
         "link": "https://news.example.co.uk/old-diode", "publisher": "Example News", "date": "2026-11-12", "family": "trade",
         "basis": "alias phrase 'Bypass' in title", "confidence": "confirmed"}]}}}
    previous = tmp_path / "previous.json"
    previous.write_text(json.dumps(first), encoding="utf-8")
    run = combine(tmp_path, base_parts(), previous=previous)
    assert run.code == 0, run.text[-400:]
    assert not find(run.project("9050"), "old-diode"), "the bypass-diode headline came back from the previous file"


COLLECTOR_KNOWN = {
    ("trade", "9050"): ("Town bypass", "NL-019 finding 5", "trade.py: 'Bypass' followed by a solar word is a confirmed match (a road with solar-powered signs)"),
    ("trade", "11678"): ("Drove Lane", "acid tester 6 (recent news)", "trade.py ties 'East Yorkshire' plus developer 'Boom' to another Boom Power project, as confirmed"),
    ("official", "11678"): ("Drove Lane", "acid tester 6 (recent news)", "official.py ties 'East Yorkshire' with a solar word to another Boom Power project, as confirmed"),
}


@pytest.mark.parametrize("case", [c for c in REJECT + NOT_CONFIRMED if c["repd_ref"] in REAL_REFS],
                         ids=lambda c: "%s-%s" % (c["repd_ref"], re.sub(r"\W+", "-", c["title"][:32])))
@pytest.mark.parametrize("collector", ["trade", "index", "official"])
def test_R01_no_collector_attaches_a_reported_false_match_as_a_confident_match(case, collector, request):
    ref, title, summary = case["repd_ref"], case["title"], case.get("summary") or ""
    if collector == "trade":
        import trade as T
        project = next(p for p in T.load_projects(str(SIGNALS / "aliases.json")) if p.ref == ref)
        found = project.match(title, summary)
        confident = found is not None and found[1] == "confirmed"
    elif collector == "index":
        import index as I
        loaded = I.load_projects(str(SIGNALS / "top200_solar.json"), str(SIGNALS / "aliases.json"))
        project = next(p for p in (loaded.values() if isinstance(loaded, dict) else loaded) if str(p["repd_ref"]) == ref)
        found = I.match_item(project, title, summary)
        confident = found is not None and found[0] == "strong"
    else:
        import official as O
        project = next(p for p in O.load_projects() if str(p["repd_ref"]) == ref)
        found = O.match(project, title, summary)
        confident = found is not None and found[1] == "confirmed"
    if (collector, ref) in COLLECTOR_KNOWN and COLLECTOR_KNOWN[(collector, ref)][0] in title:
        request.applymarker(known(*COLLECTOR_KNOWN[(collector, ref)][1:]))
    assert not confident, "%s.py ties %r to REPD %s as a confident match: %r" % (collector, title, ref, found)


@known("NL-019 findings 1 and 5", "a part's 'confirmed' is taken on trust: no evidence check, no second term for a one-word alias")
@pytest.mark.parametrize("case", NOT_CONFIRMED, ids=lambda c: c["repd_ref"])
def test_R01_confidence_is_earned_not_inherited_from_the_part(tmp_path, case):
    extra = [case["repd_ref"]] if case["repd_ref"] in REAL_REFS else []
    run = combine(tmp_path, case_parts([case]), extra_refs=extra)
    kept = [i for i in shown(run.project(case["repd_ref"])) if i["title"] == case["title"]]
    assert not any(confirmed(i) for i in kept), "shown as confirmed although: %s" % case["why"]
    if not VERSION_1:
        assert all(i["confidence"] == "possible" for i in kept)


def test_R01_true_headlines_are_kept_as_confirmed(tmp_path):
    run = combine(tmp_path, case_parts(ACCEPT))
    for case in ACCEPT:
        kept = reports(run.project(case["repd_ref"]), case["title"])
        assert kept and confirmed(kept[0]), "lost or downgraded: %r (%s)" % (case["title"], case["why"])


@known("NL-019 finding 5", "143 confirmed, 47 uncertain and 10 derived aliases; items of an unconfirmed alias are still shown as confirmed")
def test_R01_real_alias_table_no_confirmed_item_under_an_alias_that_is_not_evidenced(tmp_path):
    table = REAL_ALIASES["projects"]
    weak = {ref for ref, entry in table.items()
            if entry.get("alias_status") != "confirmed" or not (entry.get("alias_evidence") or entry.get("alias_evidence_url"))}
    run = combine(tmp_path, {"reviewed": REVIEWED}, top200=SIGNALS / "top200_solar.json", aliases=SIGNALS / "aliases.json")
    wrong = sorted(ref for ref in weak if any(confirmed(i) for i in shown(run.project(ref))))
    assert not wrong, "%d of the %d projects without a confirmed, evidenced alias show a confirmed item: REPD %s" % (
        len(wrong), len(weak), ", ".join(wrong[:25]))


@open_item("acid tester 3 recommends 'possible' for eight aliases marked confirmed (one agreeing fact or an unexplained capacity conflict)")
def test_R01_aliases_the_confidence_tester_would_downgrade_show_no_confirmed_item(tmp_path):
    run = combine(tmp_path, {"reviewed": REVIEWED}, top200=SIGNALS / "top200_solar.json", aliases=SIGNALS / "aliases.json")
    wrong = [c["repd_ref"] for c in TESTERS["downgrade"] if any(confirmed(i) for i in shown(run.project(c["repd_ref"])))]
    assert not wrong, "confirmed items under aliases with one agreeing fact or a capacity conflict: REPD %s" % ", ".join(wrong)


_LOADED = {}


def collector_verdict(collector, ref, title, summary=""):
    """(attached, confident) as the collector's own matcher decides for the real alias table."""
    if collector == "trade":
        import trade as T
        if "trade" not in _LOADED:
            _LOADED["trade"] = {p.ref: p for p in T.load_projects(str(SIGNALS / "aliases.json"))}
        found = _LOADED["trade"][ref].match(title, summary)
        return found is not None, found is not None and found[1] == "confirmed"
    if collector == "index":
        import index as I
        if "index" not in _LOADED:
            loaded = I.load_projects(str(SIGNALS / "top200_solar.json"), str(SIGNALS / "aliases.json"))
            _LOADED["index"] = {str(p["repd_ref"]): p for p in (loaded.values() if isinstance(loaded, dict) else loaded)}
        found = I.match_item(_LOADED["index"][ref], title, summary)
        return found is not None, found is not None and found[0] == "strong"
    import official as O
    if "official" not in _LOADED:
        _LOADED["official"] = {str(p["repd_ref"]): p for p in O.load_projects()}
    found = O.match(_LOADED["official"][ref], title, summary)
    return found is not None, found is not None and found[1] == "confirmed"


TESTER_CLASSES = sorted(TESTER_FALSE["rule_classes"])


@known("acid tester 1 (false matches)", "239 wrong headlines pass the collectors' matchers on main, 167 of them labelled confirmed")
@pytest.mark.parametrize("rule_class", TESTER_CLASSES)
def test_R01_tester_false_matches_no_collector_is_confident(rule_class):
    cases = [c for c in TESTER_FALSE["cases"] if rule_class in c["rule_classes"]]
    wrong = []
    for case in cases:
        for collector in ("trade", "index", "official"):
            if collector_verdict(collector, case["repd_ref"], case["title"])[1]:
                wrong.append("%s REPD %s %r" % (collector, case["repd_ref"], case["title"][:70]))
    assert not wrong, "class %s (%s): %d confident wrong matches in %d cases, e.g. %s" % (
        rule_class, TESTER_FALSE["rule_classes"][rule_class][:90], len(wrong), len(cases), "; ".join(wrong[:3]))


@known("acid tester 1 (false matches)", "the combiner publishes a wrong headline as confirmed whenever a part says confirmed")
@pytest.mark.parametrize("rule_class", TESTER_CLASSES)
def test_R01_tester_false_matches_are_never_published_as_confirmed(tmp_path, rule_class):
    cases = [c for c in TESTER_FALSE["cases"] if rule_class in c["rule_classes"]]
    items = [item(c["repd_ref"], "w%d" % n, c["title"], "2026-11-05") for n, c in enumerate(cases)]
    run = combine(tmp_path, {"trade": part("trade", items)}, top200=SIGNALS / "top200_solar.json", aliases=SIGNALS / "aliases.json")
    assert run.code == 0, run.text[-400:]
    wrong = ["REPD %s %r" % (c["repd_ref"], c["title"][:70]) for n, c in enumerate(cases)
             if any(confirmed(i) for i in find(run.project(c["repd_ref"]), "w%d" % n))]
    assert not wrong, "class %s: %d of %d wrong headlines are published as confirmed, e.g. %s" % (
        rule_class, len(wrong), len(cases), "; ".join(wrong[:3]))


def test_R01_tester_false_matches_fixture_is_complete():
    cases = TESTER_FALSE["cases"]
    assert len(cases) == 239 and sum(1 for c in cases if c["real"]) == 7
    assert all(c["repd_ref"] in REAL_REFS and c["title"] for c in cases)
    assert any(c["repd_ref"] == "9050" for c in cases)


# ---------------------------------------------------------------- R02 calendar and dates

MAIN_ACCEPTS_BAD_DATE = {"impossible-day", "impossible-month", "31-november", "zero-date", "future-months", "future-two-days",
                         "impossible-gdelt-slice"}


@pytest.mark.parametrize("case", DATES, ids=lambda c: c["id"])
def test_R02_combiner_never_shows_a_wrong_impossible_or_future_date(tmp_path, case, request):
    if case["id"] in MAIN_ACCEPTS_BAD_DATE:
        request.applymarker(known("NL-019 finding 3", "dates are accepted by their YYYY-MM-DD prefix: no calendar or future check"))
    run = combine(tmp_path, {"trade": part("trade", [item("90001", "dated", "Alderwick Solar Farm update", case["raw"])])})
    assert run.code == 0, run.text[-400:]
    kept = find(run.project("90001"), "dated")
    assert kept, "the item was dropped; an unreadable date makes it undated, it does not remove it"
    assert kept[0]["date"] in case["allowed"], "%r became %r (%s)" % (case["raw"], kept[0]["date"], case["why"])


@pytest.mark.parametrize("case", [c for c in DATES if c.get("collectors", True)], ids=lambda c: c["id"])
@pytest.mark.parametrize("reader", ["trade.day_of", "official.parse_day", "feed.parse_date"])
def test_R02_collector_date_readers_never_swap_day_and_month_or_invent_a_date(case, reader, request):
    if (reader, case["id"]) == ("official.parse_day", "year-0026"):
        request.applymarker(known("acid tester 2 (dates)", "official.parse_day reads 1/2/0026 as the year 26"))
    if reader == "trade.day_of":
        import trade as T
        got = T.day_of(case["raw"])
    elif reader == "official.parse_day":
        import official as O
        got = O.parse_day(case["raw"])
    else:
        import datacentre_feed as D
        got = D.parse_date(case["raw"])
    got = got[:10] if isinstance(got, str) else got
    if reader == "feed.parse_date" and got is None:
        return                      # the feed reader refuses any value without a time zone: undated, never wrong
    assert got in case["allowed"], "%s(%r) gave %r (%s)" % (reader, case["raw"], got, case["why"])


@known("NL-019 finding 3", "a date after the run is kept, so the item is ranked first as the newest")
def test_R02_a_future_dated_item_is_not_ranked_as_the_newest(tmp_path):
    run = combine(tmp_path, {"trade": part("trade", [
        item("90001", "future", "Alderwick Solar Farm to open", "2027-06-01"),
        item("90001", "real", "Alderwick Solar Farm granted development consent", "2026-11-11")])})
    first = shown(run.project("90001"))[0]
    assert first["link"].endswith("/real"), "first shown: %r dated %r" % (first["title"], first["date"])


@open_item("acid tester 2 (dates): a collector's date reader loses or misreads this value")
@pytest.mark.parametrize("case", TESTERS["date_readers"], ids=lambda c: c["name"])
def test_R02_tester_date_reader_recommendations(case):
    module, name = case["function"].split(".")
    if case["function"] == "datacentre_feed.parse_date":
        # The tester's recommendation concerns the written CALENDAR DAY,
        # not an inferred UTC timestamp. Keep datacentre_feed.parse_date()
        # strict for feed freshness and introduce a separately named reader.
        import datacentre_feed as D
        got = D.parse_calendar_day(case["value"])
    else:
        got = getattr(__import__(module), name)(case["value"])