GLOBALGRID2050 / EXPLORE CODE

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

Test News Algorithm and 3 more files

A test in the tests folder of GlobalGrid2050 that checks News Algorithm. It is built from the article step (`article`) and the rank step (`rank`).

406 lines of Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 806 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 Grid Watch test · globalgrid2050 / automation/news/tests/test_grid_watch.py lines 1–93
  2. Test Names test · globalgrid2050 / automation/news/tests/test_names.py lines 1–41
  3. Test News Algorithm test · globalgrid2050 / automation/news/tests/test_news_algorithm.py lines 1–154
  4. Test News Priority Export test · globalgrid2050 / automation/news/tests/test_news_priority_export.py lines 1–118

Test Grid Watch

A test in the tests folder of GlobalGrid2050 that checks News — Grid Watch. It is built from the grid watch test class (`GridWatchTest`).

testglobalgrid2050 / automation/news/tests/test_grid_watch.py · lines 1–93 of 93 · Entry point

What it does
It tests its inputs. Defines 14 functions or classes, including GridWatchTest, test_three_official_operator_fixture_rows, test_dedup_exact_observations_but_not_conflicts, test_status_never_promoted, test_missing_identity_does_not_fuzzy_match. Uses libraries json, copy, pathlib, unittest. 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 sources.json; JSON file fixtures.json.
Downstream impact
Used directly by 4 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Run from repository root: python -m unittest discover -s `automation/news/tests` -p `test_grid_watch.py`.
Why it matters
Run by 4 workflows and scripts, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow, GlobalGrid2050 Project Signals Acid Workflow and GlobalGrid2050 V928 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
News — Grid Watch (import), json, copy, pathlib, unittest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 V928 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
Produces
GridWatchTest
Defines here
GridWatchTest, test_three_official_operator_fixture_rows, test_dedup_exact_observations_but_not_conflicts, test_status_never_promoted, test_missing_identity_does_not_fuzzy_match, test_exact_supplier_scheme_identifier_not_connection_proof, test_reject_spoofed_url, test_reject_unverified_source_id_or_operator_disagreement, test_reject_unrecognised_evidence_claims, test_exact_etys_code_remains_unverified_crosswalk, test_metric_kinds_units_are_not_interchangeable, test_preserves_explicit_source_rights_without_granting_publication, test_publication_cannot_follow_retrieval, test_refuses_ambiguous_clock
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_grid_watch.py:1-93 · blob 88a9db4e78ce98c1a321427116cd134dabf05bc9 · 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
"""Run from repository root: python -m unittest discover -s automation/news/tests -p test_grid_watch.py"""
import json
from copy import deepcopy
from pathlib import Path
import unittest

from automation.news.grid_watch import build_grid_rows, normalise

HERE = Path(__file__).resolve().parents[1] / "grid_watch"
SOURCES = {s["id"]: s for s in json.loads((HERE / "sources.json").read_text())["sources"]}
RECORDS = json.loads((HERE / "fixtures.json").read_text())["records"]


class GridWatchTest(unittest.TestCase):
    def test_three_official_operator_fixture_rows(self):
        rows = build_grid_rows(RECORDS, SOURCES)
        self.assertEqual(len(rows), 3)
        self.assertEqual({r["scheme"]["operator"] for r in rows}, {"NGET", "SSEN-T", "SPT"})
        self.assertTrue(all(r["evidence"]["licence_state"] == "UNASSESSED" and not r["publishable"] for r in rows))
        self.assertTrue(all(r["links"]["grid_connection"] is None and r["links"]["available_capacity_mw"] is None for r in rows))
        self.assertIsNone(next(r for r in rows if r["scheme"]["operator"] == "SSEN-T")["scheme"]["scheme_key"])

    def test_dedup_exact_observations_but_not_conflicts(self):
        b = deepcopy(RECORDS[0]); b["retrieved_at"] = "2026-11-17T00:00:00Z"
        self.assertEqual(len(build_grid_rows([RECORDS[0], b], SOURCES)), 1)
        b["stage"] = "consented"
        self.assertEqual(len(build_grid_rows([RECORDS[0], b], SOURCES)), 2)

    def test_status_never_promoted(self):
        row = normalise(RECORDS[1], SOURCES)
        self.assertEqual(row["evidence"]["reported_stage"], "under_construction")
        self.assertFalse(row["publishable"])
        self.assertIsNone(row["links"]["repd_ref"])

    def test_missing_identity_does_not_fuzzy_match(self):
        row = normalise(RECORDS[0], SOURCES)
        self.assertIsNone(row["scheme"]["scheme_key"])
        b = deepcopy(RECORDS[0]); b["scheme_name"] = "Bramford / Twinstead"
        self.assertIsNone(normalise(b, SOURCES)["scheme"]["scheme_key"])

    def test_exact_supplier_scheme_identifier_not_connection_proof(self):
        row = normalise(RECORDS[2], SOURCES)
        self.assertEqual(row["scheme"]["scheme_key"], "SPT:EGL1/E2DC")
        self.assertIsNone(row["links"]["grid_connection"])

    def test_reject_spoofed_url(self):
        for url in ("http://www.nationalgrid.com/foo", "https://www.nationalgrid.com.evil.test/foo",
                    "https://evil@www.nationalgrid.com/foo", "https://www.nationalgrid.com:444/foo"):
            b = dict(RECORDS[0], source_url=url)
            with self.subTest(url=url), self.assertRaises(ValueError): normalise(b, SOURCES)

    def test_reject_unverified_source_id_or_operator_disagreement(self):
        for patch in ({"source_id": "unknown"}, {"network_operator":"NESO"}):
            with self.assertRaises(ValueError): normalise(dict(RECORDS[0], **patch), SOURCES)

    def test_reject_unrecognised_evidence_claims(self):
        for patch in ({"connected_capacity_mw": 100}, {"stage": "approved"}, {"etys_node_code": "cot 41"}):
            with self.assertRaises(ValueError): normalise(dict(RECORDS[0], **patch), SOURCES)

    def test_exact_etys_code_remains_unverified_crosswalk(self):
        row = normalise(dict(RECORDS[0], etys_node_code="COTT41"), SOURCES)
        self.assertEqual(row["links"]["etys_node_code_as_reported"], "COTT41")
        self.assertFalse(row["links"]["etys_node_link_verified"])

    def test_metric_kinds_units_are_not_interchangeable(self):
        b = dict(RECORDS[0], reported_metric={"kind":"equipment_rating", "value":100, "unit":"MW"})
        with self.assertRaises(ValueError): normalise(b, SOURCES)
        b["reported_metric"] = {"kind":"equipment_rating", "value":100, "unit":"MVA"}
        self.assertEqual(normalise(b, SOURCES)["reported_metric"]["unit"], "MVA")
        for v in (True, "100", -1, float("nan")):
            b["reported_metric"]["value"] = v
            with self.assertRaises(ValueError): normalise(b, SOURCES)

    def test_preserves_explicit_source_rights_without_granting_publication(self):
        sources = deepcopy(SOURCES)
        sources["nget-projects"]["licence_state"] = "RESTRICTED"
        row = normalise(RECORDS[0], sources)
        self.assertEqual(row["evidence"]["licence_state"], "RESTRICTED")
        self.assertEqual(row["evidence"]["review_state"], "REVIEW_REQUIRED")
        self.assertFalse(row["publishable"])
        sources["nget-projects"].pop("licence_state")
        self.assertEqual(normalise(RECORDS[0], sources)["evidence"]["licence_state"], "UNASSESSED")

    def test_publication_cannot_follow_retrieval(self):
        b = dict(RECORDS[0], published_at="2027-01-01T00:00:00Z")
        with self.assertRaises(ValueError): normalise(b, SOURCES)

    def test_refuses_ambiguous_clock(self):
        with self.assertRaises(ValueError): normalise(dict(RECORDS[0], retrieved_at="2026-11-16"), SOURCES)


if __name__ == "__main__":
    unittest.main()

Test Names

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

testglobalgrid2050 / automation/news/tests/test_names.py · lines 1–41 of 41 · Entry point

What it does
It tests solar, battery storage (BESS) and wind. Defines 6 functions or classes, including test_distinctive_stem_strips_addresses_and_boilerplate, test_generic_and_address_only_names_give_no_stem, test_aliases_trailing_and_places, test_operator_key_ignores_connectors_case_and_suffixes, test_descriptor_adjacency_for_one_word_names.
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, battery storage (BESS), wind.
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_distinctive_stem_strips_addresses_and_boilerplate`, `test_generic_and_address_only_names_give_no_stem`, `test_aliases_trailing_and_places` and 3 more. Its code works with 1 GWh and 500 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
Names (import)
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
test_distinctive_stem_strips_addresses_and_boilerplate, test_generic_and_address_only_names_give_no_stem, test_aliases_trailing_and_places, test_operator_key_ignores_connectors_case_and_suffixes, test_descriptor_adjacency_for_one_word_names, test_tech_context_and_family
Defines here
test_distinctive_stem_strips_addresses_and_boilerplate, test_generic_and_address_only_names_give_no_stem, test_aliases_trailing_and_places, test_operator_key_ignores_connectors_case_and_suffixes, test_descriptor_adjacency_for_one_word_names, test_tech_context_and_family
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_names.py:1-41 · blob b603556fb2a7f72ac59c6b451f7b522247c437d7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
from automation.news import names


def test_distinctive_stem_strips_addresses_and_boilerplate():
    assert names.distinctive_stem("Springwell, Lincoln - Springwell Solar Farm & Battery Storage") == "springwell"
    assert names.distinctive_stem("West Burton Power Station, North Road - Battery Storage") == "west burton"
    assert names.distinctive_stem("The Tween Bridge Solar Farm ") == "tween bridge"
    assert names.distinctive_stem("Green Hill Solar Farm & Battery Storage") == "green hill"


def test_generic_and_address_only_names_give_no_stem():
    assert names.distinctive_stem("The Grange") == ""
    assert names.distinctive_stem("Country Lane - Solar Farm") == ""
    assert names.distinctive_stem("New Road Solar Farm") == ""


def test_aliases_trailing_and_places():
    a = names.name_aliases("Moray Firth - Caledonia North Offshore Wind Farm")
    assert a == {"primary": "moray firth", "trailing": "caledonia north", "places": []}
    a = names.name_aliases("Engine Lane, Grimethorpe - Solar Farm")
    assert a["primary"] == "engine lane" and a["places"] == ["grimethorpe"]


def test_operator_key_ignores_connectors_case_and_suffixes():
    assert names.operator_key("Photovolt Development Partners / SolarFive") == \
        names.operator_key("PHOTOVOLT DEVELOPMENT PARTNERS & SolarFive Ltd")
    assert names.operator_key("Old Owner Ltd") != names.operator_key("New Owner Plc")


def test_descriptor_adjacency_for_one_word_names():
    assert names.descriptor_adjacent(names.padded("Qair buys Hessay Solar project"), "hessay")
    assert not names.descriptor_adjacent(names.padded("Hessay village fete"), "hessay")
    assert not names.descriptor_adjacent(names.padded("plans at the hessay solar"), "hessay")


def test_tech_context_and_family():
    assert names.tech_context(names.padded("500MW/1GWh BESS and solar PV")) == {"battery", "solar"}
    assert names.tech_family("Solar Photovoltaics") == "solar"
    assert names.tech_family("Liquid Air Energy Storage") == "battery"
    assert names.tech_family("Wind Offshore") == "wind"
    assert names.tech_family("Biomass (dedicated)") == "other"

Test News Algorithm

A test in the tests folder of GlobalGrid2050 that checks News Algorithm. It is built from the article step (`article`) and the rank step (`rank`).

testglobalgrid2050 / automation/news/tests/test_news_algorithm.py · lines 1–154 of 154 · Entry point · pattern article (shared by 4 files)

What it does
It tests solar. Defines 16 functions or classes, including article, rank, test_official_relevant_news_precedes_paid_discovery_without_deleting_credit, test_display_diversity_is_soft_and_does_not_drop_valuable_articles, test_generic_ai_finance_is_context_even_if_legacy_category_says_datacentre. Uses libraries copy, json, 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.
Downstream impact
Used directly by 3 files: Test News Priority Export (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Contract/negative tests for headline ordering, independent of live sources.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow. Checked by Test News Priority Export.
Application
globalgrid2050 · automation/news/tests · test
Uses
News Algorithm (import), copy, json, pytest
Used by
imported by Test News Priority Export (import), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
article, rank, test_official_relevant_news_precedes_paid_discovery_without_deleting_credit, test_display_diversity_is_soft_and_does_not_drop_valuable_articles, test_generic_ai_finance_is_context_even_if_legacy_category_says_datacentre, test_uk_context_does_not_claim_project_location_or_use_multinational_name, test_source_policy_is_not_inferred_from_publisher_label, test_listed_parent_needs_explicit_identity_and_listing_evidence, test_reviewed_original_reporting_credit_is_not_inferred_from_brand, test_publication_precision_and_freshness_never_use_first_seen, test_future_or_stale_government_article_does_not_lead_current_project_story, test_exclusion_and_document_genre_do_not_become_project_priority
Defines here
article, rank, test_official_relevant_news_precedes_paid_discovery_without_deleting_credit, test_display_diversity_is_soft_and_does_not_drop_valuable_articles, test_generic_ai_finance_is_context_even_if_legacy_category_says_datacentre, test_uk_context_does_not_claim_project_location_or_use_multinational_name, test_source_policy_is_not_inferred_from_publisher_label, test_listed_parent_needs_explicit_identity_and_listing_evidence, test_reviewed_original_reporting_credit_is_not_inferred_from_brand, test_publication_precision_and_freshness_never_use_first_seen, test_future_or_stale_government_article_does_not_lead_current_project_story, test_exclusion_and_document_genre_do_not_become_project_priority, test_exact_output_is_permutation_stable_and_does_not_mutate_or_republish_body, test_malformed_or_nonpublic_url_is_rejected, test_tracking_canonicalization_detects_duplicate_article_input, test_explicit_clock_required_and_policy_conflicts_fail_closed
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_news_algorithm.py:1-154 · blob 0a5a9b295803749e6f873f722ff35047159bfbe4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Contract/negative tests for headline ordering, independent of live sources."""
import copy
import json

import pytest

from automation.news import news_algorithm as N

NOW = "2026-11-16T13:06:13Z"


def article(link="https://news.example/1", title="UK solar farm granted planning consent", **extra):
    return {"title": title, "link": link, "source": "A credited publisher", "date": "2026-11-15T12:00:00Z",
            "first_seen": "2026-11-16T12:00:00Z", "category": "consent", "technology": "solar",
            "possible_match": None, **extra}


def rank(items, **kwargs):
    return N.rank_headlines(items, as_of=NOW, **kwargs)["items"]


def test_official_relevant_news_precedes_paid_discovery_without_deleting_credit():
    discovery = article("https://www.bloomberg.com/news/1", source="Bloomberg", date="2026-11-16T12:50:00Z")
    official = article("https://www.gov.uk/government/news/1", source="GOV.UK", date="2026-11-14T12:00:00Z")
    items = rank([discovery, official])
    assert [item["source"] for item in items] == ["GOV.UK", "Bloomberg"]
    assert items[1]["link"] == discovery["link"]
    assert items[1]["editorial"]["role"] == "discovery_lead"
    assert "subscription" in items[1]["editorial"]["source"]["access_notice"]
    assert all(item["editorial"]["verification_status"] == "NOT_VERIFIED" for item in items)


def test_display_diversity_is_soft_and_does_not_drop_valuable_articles():
    repeated = [article(f"https://news.example/{i}") for i in range(15)]
    alternative = article("https://other.example/1", date="2026-11-10T12:00:00Z")
    items = rank(repeated + [alternative])
    assert len(items) == 16 and items[1]["link"] == alternative["link"]
    assert items[2]["editorial"]["publisher_repetition_penalty"] == 8
    uncapped = rank(repeated + [alternative], diversity_penalty=0)
    assert uncapped[-1]["link"] == alternative["link"]


def test_generic_ai_finance_is_context_even_if_legacy_category_says_datacentre():
    stock = article("https://wire.example/1", "AI stocks rally before a busy earnings week", category="datacentre", date=NOW)
    dc = article("https://agency.example/1", "Data centre construction begins in Indiana", technology=None)
    items = rank([stock, dc])
    assert items[0]["link"] == dc["link"]
    assert items[1]["editorial"]["topics"] == []
    assert items[1]["editorial"]["context_bucket"] == 1


def test_uk_context_does_not_claim_project_location_or_use_multinational_name():
    uk = rank([article(title="UK solar project approved")])[0]
    overseas = rank([article(title="National Grid solar project approved in New South Wales")])[0]
    assert uk["editorial"]["components"]["uk_headline_context"] == 5
    assert overseas["editorial"]["components"]["uk_headline_context"] == 0
    assert "country" not in overseas and overseas["editorial"]["project_fact_status"] == "NOT_ASSESSED"


def test_source_policy_is_not_inferred_from_publisher_label():
    fake = article("https://other.example/1", source="GOV.UK")
    assert rank([fake])[0]["editorial"]["source"]["kind"] == "reporting"
    policy = {"source_id": "funding-agency", "hosts": ["other.example"], "kind": "institution",
              "review_url": "https://review.example/source/1", "publisher_group": "funding-agency"}
    row = rank([fake], source_policies=[policy])[0]
    assert row["editorial"]["source"]["kind"] == "institution"
    assert row["editorial"]["source"]["rights_approval"] == "not_assessed_by_ranking"


def test_listed_parent_needs_explicit_identity_and_listing_evidence():
    policy = {"source_id": "issuer", "hosts": ["news.example"], "kind": "listed_parent",
              "review_url": "https://review.example/source/1"}
    with pytest.raises(ValueError, match="listed-parent"):
        rank([article()], source_policies=[policy])
    policy.update(listed_parent_id="issuer:EXAMPLE", listing_evidence_url="https://exchange.example/issuer/EXAMPLE")
    assert rank([article()], source_policies=[policy])[0]["editorial"]["source"]["kind"] == "listed_parent"


def test_reviewed_original_reporting_credit_is_not_inferred_from_brand():
    row = article("https://www.reuters.com/energy/original", source="Reuters")
    assert rank([row])[0]["editorial"]["components"]["reviewed_original_reporting"] == 0
    receipt = {"article_url": row["link"], "kind": "original_reporting", "reviewed": True,
               "basis": "Reviewer inspected attributable original reporting; test fixture.",
               "review_url": "https://review.example/originality/1"}
    ranked = rank([row], originality=[receipt])[0]
    assert ranked["editorial"]["components"]["reviewed_original_reporting"] == 6
    assert ranked["source"] == "Reuters" and ranked["editorial"]["verification_status"] == "NOT_VERIFIED"
    with pytest.raises(ValueError, match="reviewed receipt"):
        rank([row], originality=[dict(receipt, reviewed=False)])


@pytest.mark.parametrize("date,state,precision", [
    (None, "unknown", "unknown"), ("2026-11-15", "current", "day"),
    ("2026-11-15T12:00:00", "unknown", "unknown"),
    ("2026-11-17T12:00:00Z", "future", "second"), ("2025-11-15", "stale", "day"),
])
def test_publication_precision_and_freshness_never_use_first_seen(date, state, precision):
    item = rank([article(date=date, first_seen=NOW)])[0]
    f = item["editorial"]["freshness"]
    assert f["state"] == state and f["precision"] == precision
    if state in ("unknown", "future"):
        assert f["points"] == 0
    assert item["date"] == date


def test_future_or_stale_government_article_does_not_lead_current_project_story():
    fresh = article("https://news.example/current")
    for date in ("2027-01-01", "2024-01-01"):
        gov = article("https://www.gov.uk/news/old", date=date)
        assert rank([gov, fresh])[0]["link"] == fresh["link"]


def test_exclusion_and_document_genre_do_not_become_project_priority():
    rows = [article("https://news.example/e", "Solar eclipse viewing plans announced"),
            article("https://news.example/whitepapers/report", "Global data centre market investment report"),
            article("https://news.example/real", "UK grid reinforcement approved")]
    ranked = rank(rows)
    assert ranked[0]["link"] == rows[-1]["link"]
    assert all(row["editorial"]["context_bucket"] == 1 for row in ranked[1:])


def test_exact_output_is_permutation_stable_and_does_not_mutate_or_republish_body():
    rows = [article("https://news.example/2"), article("https://other.example/1", body="must not survive")]
    before = copy.deepcopy(rows)
    left = N.rank_headlines(rows, as_of=NOW)
    right = N.rank_headlines(list(reversed(rows)), as_of=NOW)
    assert json.dumps(left, sort_keys=True) == json.dumps(right, sort_keys=True)
    assert rows == before and all("body" not in row for row in left["items"])


@pytest.mark.parametrize("url", [
    "javascript:alert(1)", "https://user:pass@news.example/x", "https://news.example:444/x",
    "https://127.1/x", "https://2130706433/x", "https://0x7f000001/x", "https://224.0.0.1/x",
    "https://[::1]/x", "https://example.local/x", "https://example.internal/x", "https://localhost/x",
    "https://news.example\\@evil.example/x", "https://news.example/\nfoo",
])
def test_malformed_or_nonpublic_url_is_rejected(url):
    with pytest.raises(ValueError, match="URL"):
        rank([article(url)])


def test_tracking_canonicalization_detects_duplicate_article_input():
    with pytest.raises(ValueError, match="duplicate canonical URL"):
        rank([article("https://news.example/1?utm_source=a"), article("https://news.example/1?utm_source=b")])


def test_explicit_clock_required_and_policy_conflicts_fail_closed():
    with pytest.raises(ValueError, match="timezone"):
        N.rank_headlines([article()], as_of="2026-11-16")
    policy = {"source_id": "one", "hosts": ["news.example"], "kind": "reporting", "review_url": "https://review.example/1"}
    with pytest.raises(ValueError, match="duplicate source policy"):
        rank([article()], source_policies=[policy, policy])
    with pytest.raises(ValueError, match="diversity"):
        rank([article()], diversity_penalty=True)

Test News Priority Export

A test in the tests folder of GlobalGrid2050 that checks Build News Priority and Test News Algorithm, using SHA-256.

testglobalgrid2050 / automation/news/tests/test_news_priority_export.py · lines 1–118 of 118 · Entry point · pattern document (shared by 3 files)

What it does
It tests its inputs. Defines 11 functions or classes, including document, raw, test_exact_bytes_determinism_and_legacy_input_preserved, test_health_not_reclassified_and_empty_is_valid, test_malformed_inputs_fail_before_output. Uses libraries copy, hashlib, json, pathlib, 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 headlines.json; JSON file priority.json; JSON file pipeline_headlines.snapshot.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the document step (`document`) and the raw step (`raw`). Rank publication must keep the legacy file intact and bind its exact bytes.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Build News Priority (import), Test News Algorithm (import), Test Pipeline Headlines (import), copy, hashlib, json, pathlib, 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
document, raw, test_exact_bytes_determinism_and_legacy_input_preserved, test_health_not_reclassified_and_empty_is_valid, test_malformed_inputs_fail_before_output, test_duplicates_and_oversize_fail, test_schema_growth_requires_explicit_validator_support, test_no_freshness_from_collection_time_or_fake_verification, test_cli_keeps_previous_output_on_schema_failure_and_never_changes_input, test_empty_saved_placeholder_cannot_be_presented_as_fresh_ranking, test_actual_collector_fixture_output_keeps_every_item
Defines here
document, raw, test_exact_bytes_determinism_and_legacy_input_preserved, test_health_not_reclassified_and_empty_is_valid, test_malformed_inputs_fail_before_output, test_duplicates_and_oversize_fail, test_schema_growth_requires_explicit_validator_support, test_no_freshness_from_collection_time_or_fake_verification, test_cli_keeps_previous_output_on_schema_failure_and_never_changes_input, test_empty_saved_placeholder_cannot_be_presented_as_fresh_ranking, test_actual_collector_fixture_output_keeps_every_item
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/tests/test_news_priority_export.py:1-118 · blob b58c494c8770b5cdd3064e9847fc909d997f3ab5 · 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
"""Rank publication must keep the legacy file intact and bind its exact bytes."""
import copy
import hashlib
import json
from pathlib import Path
import subprocess
import sys

import pytest

from automation.news import build_news_priority as B
from automation.news.tests.test_news_algorithm import article


def document(items=None):
    items = items if items is not None else [article()]
    return {"schema": B.P.SCHEMA, "generated_at": "2026-11-16T13:06:13Z", "status": "ok",
            "counts": {"items": len(items), "with_possible_match": 0, "feeds_ok": 1, "feeds_failed": 0,
                       "by_category": {}}, "limits": {"max_items": 200, "max_age_days": 120},
            "scope": "Headlines only", "feeds": [{"url": "https://news.example/feed", "source": "Example", "status": "ok"}],
            "items": items}


def raw(doc):
    return json.dumps(doc, ensure_ascii=False).encode()


def test_exact_bytes_determinism_and_legacy_input_preserved():
    doc = document([article("https://www.bloomberg.com/news/1", source="Bloomberg"),
                    article("https://www.gov.uk/news/1", "UK solar planning policy announced", source="GOV.UK", category="policy")])
    original = copy.deepcopy(doc)
    first = B.build(raw(doc))
    assert first == B.build(raw(doc)) and doc == original
    assert first["input_sha256"] == hashlib.sha256(raw(doc)).hexdigest()
    assert first["as_of"] == doc["generated_at"]
    assert [e["source"] for e in first["entries"]] == ["GOV.UK", "Bloomberg"]
    assert first["entries"][0]["title"] == doc["items"][1]["title"]
    assert B.build(raw(doc) + b"\n")["input_sha256"] != first["input_sha256"]


@pytest.mark.parametrize("status", ["ok", "partial", "failed"])
def test_health_not_reclassified_and_empty_is_valid(status):
    doc = document([])
    doc["status"] = status
    assert B.build(raw(doc))["entries"] == []
    assert doc["status"] == status


@pytest.mark.parametrize("change", [
    lambda d: d.update(schema="wrong"),
    lambda d: d.update(editorial={}),
    lambda d: d["items"][0].update(editorial={}),
    lambda d: d["counts"].update(items=99),
    lambda d: d["counts"].update(items=True),
    lambda d: d.update(generated_at="2026-02-30T12:00:00Z"),
    lambda d: d["items"][0].update(first_seen="2026-02-30T12:00:00Z"),
    lambda d: d["items"][0].update(first_seen="2026-11-17T12:00:00Z"),
    lambda d: d["items"][0].update(date="2026-02-30T12:00:00Z"),
    lambda d: d["items"][0].update(link="https://127.0.0.1/private"),
    lambda d: d["items"].append(copy.deepcopy(d["items"][0])),
])
def test_malformed_inputs_fail_before_output(change):
    doc = document()
    change(doc)
    with pytest.raises(ValueError):
        B.build(raw(doc))


def test_duplicates_and_oversize_fail():
    for data in (b'{"schema":1,"schema":2}', b'NaN', b"x" * (B.MAX_BYTES + 1)):
        with pytest.raises(ValueError):
            B.build(data)
    doc = document([article("https://news.example/1?utm_source=a"), article("https://news.example/1")])
    with pytest.raises(ValueError, match="canonical"):
        B.build(raw(doc))


def test_schema_growth_requires_explicit_validator_support():
    with pytest.raises(ValueError, match="unsupported"):
        B._validate("x", {"type": "string", "newValidationKeyword": True})


def test_no_freshness_from_collection_time_or_fake_verification():
    doc = document([article(date=None)])
    entry = B.build(raw(doc))["entries"][0]
    assert entry["freshness_state"] == "unknown"
    assert "VERIFIED" not in B.dumps(B.build(raw(doc)))


def test_cli_keeps_previous_output_on_schema_failure_and_never_changes_input(tmp_path):
    source, output = tmp_path / "headlines.json", tmp_path / "priority.json"
    source.write_bytes(raw(document()))
    before = source.read_bytes()
    command = [sys.executable, "-m", "automation.news.build_news_priority", "--input", str(source), "--output", str(output)]
    assert subprocess.run(command, capture_output=True).returncode == 0
    saved = output.read_bytes()
    assert source.read_bytes() == before
    source.write_bytes(b"{}")
    assert subprocess.run(command, capture_output=True).returncode != 0
    assert output.read_bytes() == saved
    assert subprocess.run(command[:-1] + [str(source)], capture_output=True).returncode != 0


def test_empty_saved_placeholder_cannot_be_presented_as_fresh_ranking():
    source = Path("uk_renewables_pipeline/202611161734/news/pipeline_headlines.snapshot.json")
    before = source.read_bytes()
    with pytest.raises(ValueError):
        B.build(before)
    assert source.read_bytes() == before


def test_actual_collector_fixture_output_keeps_every_item(tmp_path):
    from automation.news.tests.test_pipeline_headlines import run
    code, doc = run(tmp_path)
    assert code == 0
    result = B.build(raw(doc))
    assert result["input_count"] == len(doc["items"]) > 0
    assert {entry["link"] for entry in result["entries"]} == {item["link"] for item in doc["items"]}