In this section
- Test Policy Commitments test · globalgrid2050 / automation/news/tests/test_policy_commitments.py lines 1–268
- Test Policy Context test · globalgrid2050 / automation/news/tests/test_policy_context.py lines 1–60
- Test Prospecting test · globalgrid2050 / automation/news/tests/test_prospecting.py lines 1–335
Test Policy Commitments
A test in the tests folder of GlobalGrid2050 that checks Ledger and News — Policy Commitments, using SHA-256.
testglobalgrid2050 / automation/news/tests/test_policy_commitments.py · lines 1–268 of 268 · Entry point · pattern document (shared by 3 files)
- What it does
- It tests its inputs. Defines 25 functions or classes, including sample, numeric, document, claim, only_result. Uses libraries copy, csv, io, json, 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 sample_ledger.json; JSON file historical_sources.json.
- Downstream impact
- Used directly by 3 files: Test Transition Context (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It is built from the sample step (`sample`), the numeric step (`numeric`) and the document step (`document`). COVENANT states, attribution and compatible measurements; no source network.
- Why it matters
- Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow. Checked by Test Transition Context.
- Application
- globalgrid2050 · automation/news/tests · test
- Uses
- Ledger (import), News — Policy Commitments (import), copy, csv, io, json, pathlib, sys, pytest, socket
- Used by
- imported by Test Transition Context (import), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- sample, numeric, only_result, test_real_seed_is_bounded_and_cannot_invent_compliance, test_supported_result_is_a_numerical_relation_not_a_compliance_label, test_unknown_applicability_wins_over_measurement, test_conditional_offer_does_not_apply_without_identity_and_conditions, test_incomplete_instrument_cannot_become_an_adopted_result, test_future_deadline_is_not_yet_due_but_missing_overdue_evidence_is_unknown, test_incompatible_measurement_returns_unknown_instead_of_converting, test_finance_announcement_cannot_substitute_for_disbursement, test_reported_or_press_release_claim_is_only_reported_progress
- Defines here
- sample, numeric, document, claim, only_result, test_real_seed_is_bounded_and_cannot_invent_compliance, test_supported_result_is_a_numerical_relation_not_a_compliance_label, test_unknown_applicability_wins_over_measurement, test_conditional_offer_does_not_apply_without_identity_and_conditions, test_incomplete_instrument_cannot_become_an_adopted_result, test_future_deadline_is_not_yet_due_but_missing_overdue_evidence_is_unknown, test_incompatible_measurement_returns_unknown_instead_of_converting, test_finance_announcement_cannot_substitute_for_disbursement, test_reported_or_press_release_claim_is_only_reported_progress, test_changed_baseline_and_old_revision_do_not_transfer_measurement, test_unresolved_source_corrections_remain_visible, test_conflicting_measurements_are_not_silently_selected, test_bad_contracts_fail_closed, test_future_review_clock_fails_closed, test_json_csv_are_stable_traceable_and_spreadsheet_safe, test_cli_emits_json_and_csv_without_writing_or_network, test_target_cannot_borrow_an_unrelated_read_source, test_update_claim_and_statement_must_use_same_read_locator, test_restatement_requires_reconciliation_without_replacing_old_values, test_history_inventory_covers_bounded_primary_chain_without_claiming_missing_bytes
- 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_policy_commitments.py:1-268 · blob 538a597cc9789fe29740cd2f4a4eaff861dab371 · 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
"""COVENANT states, attribution and compatible measurements; no source network."""
import copy
import csv
import io
import json
from pathlib import Path
import sys
import pytest
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
from automation.news.policy_commitments import ledger as policy
AS_OF = "2026-11-16T18:00:00Z"
HERE = ROOT / "automation/news/policy_commitments"
@pytest.fixture
def sample():
return json.loads((HERE / "sample_ledger.json").read_text(encoding="utf-8"))
@pytest.fixture
def numeric():
# Synthetic source/measurement receipts exercise the shared FIGURES contract.
def document(identity, kind, published, retrieved, sha, state, locator):
return {"id": identity, "title": "Synthetic " + identity, "issuer": "Synthetic institution",
"url": "https://institution.example/" + identity, "version": "fixture-original",
"published_on": published, "reviewed_at": retrieved, "retrieved_at": retrieved,
"content_sha256": sha * 64, "hash_limitation": None,
"document_state": state, "source_kind": kind,
"read_coverage": {"state": "READ", "locators": [locator], "note": "Synthetic fixture only"}}
target_doc = document("policy", "PRIMARY_POLICY", "2026-01-01", "2026-01-02T00:00:00Z", "a", "ADOPTED", "target")
actual_doc = document("measurement", "OFFICIAL_MEASUREMENT", "2026-11-15", "2026-11-16T00:00:00Z", "b", "PUBLISHED", "table")
def claim(identity, doc, value, basis):
return {"schema": "globalgrid2050.filing-figure.v1", "claim_id": identity, "status": "machine-provisional",
"quantity_kind": "energised_load", "metric": "Energised site load", "value": value, "scale": "1",
"unit": "MW", "original_unit": "MW", "currency": None, "finance_stage": None,
"entity": {"scope": "site", "id": "site:synthetic", "consolidation_group_id": None,
"identity_evidence_url": "https://institution.example/site-identity"},
"reporting_period": {"start": "2026-01-01", "end": "2026-10-31"},
"as_of": "2026-10-31", "basis": basis, "assurance": "unknown",
"provenance": {"document_id": doc["id"], "document_url": doc["url"], "sha256": doc["content_sha256"],
"page": None, "section": doc["read_coverage"]["locators"][0],
"published_date": doc["published_on"], "retrieved_at": doc["retrieved_at"]},
"revision": {"id": "original", "supersedes_claim_id": None, "restated": False}}
source = {"document_id": "policy", "locator": "target"}
return {"schema": policy.SCHEMA, "coverage_note": "Synthetic comparison fixtures; no real delivery claims.",
"documents": [target_doc, actual_doc],
"scopes": [{"id": "scope:site", "jurisdiction": "Fixture", "description": "One identified site",
"entity_id": "site:synthetic", "figure_entity_scope": "site"}],
"commitments": [{"id": "commitment:site", "issuer": "Synthetic institution", "source": source,
"scope_id": "scope:site", "statement_type": "UNDERTAKING", "statement": "Synthetic capacity undertaking",
"conditions": [], "metric": {"label": "Energised site load", "numeric_support": "SUPPORTED", "limitation": None},
"target": claim("figure:target", target_doc, "100.00", "forecast"), "baseline": None,
"baseline_state": "NOT_REQUIRED", "deadline": {"value": "2026-10-31", "wording": "by 31 October 2026"},
"reporting_obligation": None, "applicability": {"state": "ESTABLISHED", "reason": "Fixture identity receipt",
"evidence": [source]},
"revision": {"id": "original", "supersedes_commitment_id": None, "baseline_changed": False}}],
"updates": [{"id": "update:site", "commitment_id": "commitment:site", "commitment_revision_id": "original",
"baseline_revision_id": "original", "source": {"document_id": "measurement", "locator": "table"},
"reported_on": "2026-11-15", "statement": "Synthetic measurement report", "kind": "NUMERIC_REPORT",
"claim": claim("figure:actual", actual_doc, "120.00", "reported"), "measurement_state": "DOCUMENTED_MEASUREMENT"}]}
def only_result(payload):
return policy.evaluate(payload, as_of=AS_OF)["results"][0]
def test_real_seed_is_bounded_and_cannot_invent_compliance(sample):
report = policy.evaluate(sample, as_of=AS_OF)
assert len(report["results"]) == 8 and len(report["documents"]) == 3
states = {r["commitment_id"]: r["state"] for r in report["results"]}
assert states["uk:dc:control-centre"] == "REPORTED_PROGRESS"
assert list(states.values()).count("UNKNOWN") == 7
assert all(r["legal_compliance"] == "NOT_ASSESSED" and r["status"] == "machine-provisional" for r in report["results"])
assert all(r["comparison"] is None and r["target"] is None for r in report["results"])
assert all(r["measurement_state"] == "UNKNOWN" for r in report["results"])
national = next(r for r in report["results"] if r["commitment_id"] == "uk:dc:national-capacity-context")
assert national["deadline"]["value"] == "2030" # source precision retained, no invented date
assert national["scope"]["entity_id"] is None
assert all(d["content_sha256"] is None for d in report["documents"] if d["source_kind"] != "PRIMARY_POLICY")
@pytest.mark.parametrize("value,relation", [("120.00", "GREATER_THAN"), ("100.00", "EQUAL"), ("80.00", "LESS_THAN")])
def test_supported_result_is_a_numerical_relation_not_a_compliance_label(numeric, value, relation):
numeric["updates"][0]["claim"]["value"] = value
before = copy.deepcopy(numeric)
result = only_result(numeric)
assert result["state"] == "EVIDENCE_SUPPORTED_RESULT"
assert result["comparison"]["relation"] == relation
assert result["legal_compliance"] == "NOT_ASSESSED"
assert result["target"]["value"] == "100.00" # exact FIGURES lexeme
assert numeric == before
def test_unknown_applicability_wins_over_measurement(numeric):
numeric["commitments"][0]["applicability"]["state"] = "UNKNOWN"
assert only_result(numeric)["state"] == "UNKNOWN"
def test_conditional_offer_does_not_apply_without_identity_and_conditions(sample):
result = next(r for r in policy.evaluate(sample, as_of=AS_OF)["results"] if r["commitment_id"] == "uk:dc:support-offer")
assert result["statement_type"] == "CONDITIONAL_OFFER" and result["conditions"]
assert result["state"] == "UNKNOWN" and result["comparison"] is None
@pytest.mark.parametrize("state", ["DRAFT", "IN_PROGRESS", "UNKNOWN"])
def test_incomplete_instrument_cannot_become_an_adopted_result(numeric, state):
numeric["documents"][0]["document_state"] = state
assert only_result(numeric)["state"] == "UNKNOWN"
def test_future_deadline_is_not_yet_due_but_missing_overdue_evidence_is_unknown(numeric):
numeric["updates"] = []
numeric["commitments"][0]["deadline"] = {"value": "2027", "wording": "by 2027"}
assert only_result(numeric)["state"] == "NOT_YET_DUE"
assert policy.evaluate(numeric, as_of="2027-06-01T00:00:00Z")["results"][0]["state"] == "UNKNOWN"
numeric["commitments"][0]["deadline"] = {"value": "2026-10-31", "wording": "by 31 October 2026"}
assert only_result(numeric)["state"] == "UNKNOWN"
@pytest.mark.parametrize("change", [
lambda c: c.update(unit="GW", original_unit="GW"),
lambda c: c.update(metric="Contracted site load"),
lambda c: c.update(quantity_kind="secured_connection"),
lambda c: c.update(reporting_period={"start": "2026-01", "end": "2026-10"}),
lambda c: c["entity"].update(consolidation_group_id="group:different"),
])
def test_incompatible_measurement_returns_unknown_instead_of_converting(numeric, change):
change(numeric["updates"][0]["claim"])
result = only_result(numeric)
assert result["state"] == "UNKNOWN" and result["comparison"] is None
assert "incompatible" in result["reasons"][0]
def test_finance_announcement_cannot_substitute_for_disbursement(numeric):
for claim in (numeric["commitments"][0]["target"], numeric["updates"][0]["claim"]):
claim.update(quantity_kind="finance", metric="Disbursed project funding", unit="currency",
original_unit="pounds sterling", currency="GBP", finance_stage="disbursed")
numeric["commitments"][0]["metric"]["label"] = "Disbursed project funding"
numeric["updates"][0]["claim"]["finance_stage"] = "announced"
result = only_result(numeric)
assert result["state"] == "UNKNOWN" and "finance_stage" in result["reasons"][0]
def test_reported_or_press_release_claim_is_only_reported_progress(numeric):
numeric["updates"][0]["measurement_state"] = "REPORTED"
numeric["documents"][1]["source_kind"] = "PRESS_RELEASE"
assert only_result(numeric)["state"] == "REPORTED_PROGRESS"
numeric["updates"][0]["measurement_state"] = "DOCUMENTED_MEASUREMENT"
with pytest.raises(ValueError, match="cannot certify"):
policy.validate_ledger(numeric)
def test_changed_baseline_and_old_revision_do_not_transfer_measurement(numeric):
prior = copy.deepcopy(numeric["commitments"][0])
prior["id"] = "prior:site"
prior["target"]["claim_id"] = "figure:prior"
numeric["commitments"].append(prior)
numeric["commitments"][0]["revision"] = {"id": "revised", "supersedes_commitment_id": "prior:site", "baseline_changed": True}
result = next(r for r in policy.evaluate(numeric, as_of=AS_OF)["results"] if r["commitment_id"] == "commitment:site")
assert result["state"] == "UNKNOWN" and "revision" in result["reasons"][0]
assert len(policy.evaluate(numeric, as_of=AS_OF)["results"]) == 2
old = next(r for r in policy.evaluate(numeric, as_of=AS_OF)["results"] if r["commitment_id"] == "prior:site")
assert old["state"] == "UNKNOWN" and old["superseded_by"] == ["commitment:site"]
@pytest.mark.parametrize("kind", ["CORRECTION", "CONTRADICTION"])
def test_unresolved_source_corrections_remain_visible(numeric, kind):
update = copy.deepcopy(numeric["updates"][0])
update.update(id="update:correction", kind=kind, claim=None, measurement_state="UNKNOWN")
numeric["updates"].append(update)
result = only_result(numeric)
assert result["state"] == "UNKNOWN" and len(result["updates"]) == 2
def test_conflicting_measurements_are_not_silently_selected(numeric):
second = copy.deepcopy(numeric["updates"][0])
second["id"] = "update:second"
second["claim"].update(claim_id="figure:second", value="90")
numeric["updates"].append(second)
assert only_result(numeric)["state"] == "UNKNOWN"
@pytest.mark.parametrize("change", [
lambda x: x.update(contacts=["unrequested personal field"]),
lambda x: x.update(commitments=[]),
lambda x: x["commitments"][0]["target"].update(unit="ratio"),
lambda x: x["commitments"][0]["target"].update(value=100.0),
lambda x: x["updates"][0]["claim"]["entity"].update(id="site:unrelated"),
lambda x: x["updates"][0]["claim"]["provenance"].update(sha256="c" * 64),
lambda x: x["updates"][0]["source"].update(locator="unread section"),
lambda x: x["documents"][1].update(document_state="DRAFT"),
lambda x: x["updates"][0].update(reported_on="2030-01-01"),
lambda x: x["updates"][0].update(reported_on="2026-10-01"),
lambda x: x["documents"][0].update(url="https://127.1/private"),
lambda x: x["commitments"][0]["applicability"].update(evidence=[]),
lambda x: x["commitments"][0]["revision"].update(supersedes_commitment_id="commitment:site"),
lambda x: x["commitments"][0]["metric"].update(numeric_support="UNSUPPORTED", limitation="Unsupported metric"),
])
def test_bad_contracts_fail_closed(numeric, change):
change(numeric)
with pytest.raises(ValueError):
policy.evaluate(numeric, as_of=AS_OF)
def test_future_review_clock_fails_closed(numeric):
with pytest.raises(ValueError, match="follows evaluation"):
policy.evaluate(numeric, as_of="2026-11-15T00:00:00Z")
def test_json_csv_are_stable_traceable_and_spreadsheet_safe(numeric):
numeric["documents"][0]["issuer"] = numeric["commitments"][0]["issuer"] = "=unsafe()"
report = policy.evaluate(numeric, as_of=AS_OF)
assert policy.dumps_report(report) == policy.dumps_report(policy.evaluate(numeric, as_of=AS_OF))
csv_rows = list(csv.DictReader(io.StringIO(policy.csv_report(report))))
assert len(csv_rows) == 1 and csv_rows[0]["issuer"] == "'=unsafe()"
assert json.loads(csv_rows[0]["target"])["value"] == "100.00"
assert json.loads(csv_rows[0]["source"])["content_sha256"] == "a" * 64
assert json.loads(csv_rows[0]["updates"])[0]["reported_on"] == "2026-11-15"
def test_cli_emits_json_and_csv_without_writing_or_network(sample, monkeypatch, capsys):
import socket
monkeypatch.setattr(socket, "getaddrinfo", lambda *a, **k: pytest.fail("Unexpected network"))
for format in ("json", "csv"):
assert policy.main(["--as-of", AS_OF, "--format", format]) == 0
output = capsys.readouterr().out
assert str(ROOT) not in output
if format == "json":
assert len(json.loads(output)["results"]) == 8
else:
assert len(list(csv.DictReader(io.StringIO(output)))) == 8
def test_target_cannot_borrow_an_unrelated_read_source(numeric):
measured = numeric["updates"][0]["claim"]
numeric["commitments"][0]["target"]["provenance"] = copy.deepcopy(measured["provenance"])
with pytest.raises(ValueError, match="Target claim differs"):
policy.validate_ledger(numeric)
def test_update_claim_and_statement_must_use_same_read_locator(numeric):
numeric["documents"][1]["read_coverage"]["locators"].append("another table")
numeric["updates"][0]["source"]["locator"] = "another table"
with pytest.raises(ValueError, match="Update claim source differs"):
policy.validate_ledger(numeric)
def test_restatement_requires_reconciliation_without_replacing_old_values(numeric):
numeric["updates"][0]["claim"]["revision"] = {
"id": "restatement", "supersedes_claim_id": "figure:earlier", "restated": True}
result = only_result(numeric)
assert result["state"] == "UNKNOWN" and "reconciliation" in result["reasons"][0]
assert result["updates"][0]["claim"]["value"] == "120.00"
def test_history_inventory_covers_bounded_primary_chain_without_claiming_missing_bytes():
history = json.loads((HERE / "historical_sources.json").read_text(encoding="utf-8"))
assert history["schema"] == "globalgrid2050.policy-history.sources.v1"
assert len(history["sources"]) == 10
assert len({s["id"] for s in history["sources"]}) == 10
assert all(s["content_sha256"] is None and s["retrieved_at"] is None for s in history["sources"])
assert all(s["read_coverage"]["locators"] for s in history["sources"])
assert all(s["document_state"] != "ADOPTED" or "agenda" in s["title"].lower()
for s in history["sources"] if "cop31" in s["id"].lower())Test Policy Context
A test in the tests folder of GlobalGrid2050 that checks Policy Context.
testglobalgrid2050 / automation/news/tests/test_policy_context.py · lines 1–60 of 60 · Entry point · pattern document (shared by 3 files)
- What it does
- It tests its inputs. Defines 8 functions or classes, including document, extract, test_typed_policy_quantities_never_become_project_capacity_or_compliance, test_unapproved_source_refused, test_missing_or_changed_evidence_fails_closed. Uses libraries 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.
- Downstream impact
- Used directly by 3 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- Defines `document`, `extract`, `test_typed_policy_quantities_never_become_project_capacity_or_compliance` and 5 more. Its code works with 6 GW.
- Why it matters
- Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow, GlobalGrid2050 Project Signals Acid Workflow and GlobalGrid2050 V934 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/news/tests · test
- Uses
- Policy Context (import), pytest
- Used by
- run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
- Produces
- document, extract, test_typed_policy_quantities_never_become_project_capacity_or_compliance, test_unapproved_source_refused, test_missing_or_changed_evidence_fails_closed, test_duplicate_quantities_and_headings_are_not_silently_selected, test_hidden_script_text_cannot_supply_policy_quantity, test_timestamp_and_publication_order
- Defines here
- document, extract, test_typed_policy_quantities_never_become_project_capacity_or_compliance, test_unapproved_source_refused, test_missing_or_changed_evidence_fails_closed, test_duplicate_quantities_and_headings_are_not_silently_selected, test_hidden_script_text_cannot_supply_policy_quantity, test_timestamp_and_publication_order
- 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_policy_context.py:1-60 · blob ba46ac8b7a0e8e3bb463f347b75414126eea3629 · 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.filings.policy_context import HEADINGS, OGL, SOURCE, extract_covenant
import pytest
def document(extra=''):
headings = ''.join(f'<h2 id="{key}">{text}</h2>' for key, text, _ in HEADINGS)
return ('<meta name="govuk:primary-publishing-organisation" content="HM Treasury">'
'<main id="content"><h1>The Data Centre Covenant</h1>'
'<p>Published 28 October 2026</p>'
f'<a href="{OGL}">Licence</a>{headings}'
'<p>The Government estimates 6 GW of AI data centre capacity by 2030.</p>'
'<p>New facilities should achieve a Power Usage Effectiveness of 1.3 or better.</p>'
f'{extra}</main>').encode()
def extract(data=None, **changes):
return extract_covenant(document() if data is None else data,
**{'source_url': SOURCE, 'retrieved_at': '2026-11-18T00:00:00Z', **changes})
def test_typed_policy_quantities_never_become_project_capacity_or_compliance():
result = extract()
assert len(result['themes']) == 5
assert [(q['value'], q['unit']) for q in result['quantities']] == [('6', 'GW'), ('1.3', 'ratio')]
assert result['quantities'][1]['comparison'] == 'AT_MOST'
assert '1.3 or better' in result['quantities'][1]['meaning']
assert result['published_date'] == {'value': '2026-10-28', 'precision': 'DAY'}
assert result['project_compliance'] is result['available_capacity'] is None
assert result['connections'] == result['asset_associations'] == []
assert result['rights']['review_state'] == 'REVIEW_REQUIRED'
@pytest.mark.parametrize('url', [SOURCE + '?spoof=1', SOURCE.replace('gov.uk', 'evil.test'), 'file:///policy'])
def test_unapproved_source_refused(url):
with pytest.raises(ValueError, match='source_not_approved'):
extract(source_url=url)
@pytest.mark.parametrize('data', [b'', b'x' * 250001, document().replace(b'The Data Centre Covenant', b'Other policy'), document().replace(b'1.3 or better', b'1.2 or better'), document().replace(b'28 October 2026', b'28 October 2027'), document().replace(OGL.encode(), b'https://evil.test'), document().replace(b'HM Treasury', b'Other authority')])
def test_missing_or_changed_evidence_fails_closed(data):
with pytest.raises(ValueError):
extract(data)
def test_duplicate_quantities_and_headings_are_not_silently_selected():
for extra in ['<p>Power Usage Effectiveness of 1.3 or better</p>', '<h2>1. Lower electricity bills</h2>']:
with pytest.raises(ValueError, match='ambiguous'):
extract(document(extra))
def test_hidden_script_text_cannot_supply_policy_quantity():
data = document().replace(b'<p>The Government estimates 6 GW of AI data centre capacity by 2030.</p>', b'<script>6 GW by 2030</script>')
with pytest.raises(ValueError, match='quantity_missing'):
extract(data)
def test_timestamp_and_publication_order():
for timestamp in ['2026-10-27T10:00:00Z', '2026-11-18T00:00:00']:
with pytest.raises(ValueError):
extract(retrieved_at=timestamp)Test Prospecting
A test in the tests folder of GlobalGrid2050 that checks Prospecting and Evidence Store, using SHA-256.
testglobalgrid2050 / automation/news/tests/test_prospecting.py · lines 1–335 of 335 · Entry point · pattern forbidden (shared by 2 files)
- What it does
- It tests its inputs. Defines 26 functions or classes, including write_pin, baseline, evidence, dc, test_real_official_scope_stable_and_no_invented_events_or_freshness. Uses libraries copy, hashlib, json, pathlib, sys. 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 input.json; JSON file projects.json; JSON file triage.json; JSON file first.json; JSON file second.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 writes pin (`write_pin`) and is built from the baseline step (`baseline`) and the evidence step (`evidence`). Offline research priorities: real pinned baseline plus synthetic receipt fixtures.
- Why it matters
- Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
- Application
- globalgrid2050 · automation/news/tests · test
- Uses
- Prospecting (import), Evidence Store (import), copy, hashlib, json, pathlib, sys, pytest, socket
- Used by
- run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- write_pin, baseline, evidence, dc, test_real_official_scope_stable_and_no_invented_events_or_freshness, test_missing_name_capacity_country_remain_unknown, test_invalid_capacity_cannot_become_positive_priority, test_future_record_date_rejected_even_outside_returned_top_n, test_evidence_is_provisional_and_news_age_never_becomes_event, test_bad_news_input_fails_closed, test_dc_distinct_unknown_capacity_and_original_revision, test_invalid_dc_fails_even_when_filtered_out
- Defines here
- write_pin, baseline, evidence, dc, test_real_official_scope_stable_and_no_invented_events_or_freshness, test_missing_name_capacity_country_remain_unknown, test_invalid_capacity_cannot_become_positive_priority, test_future_record_date_rejected_even_outside_returned_top_n, test_evidence_is_provisional_and_news_age_never_becomes_event, test_bad_news_input_fails_closed, test_dc_distinct_unknown_capacity_and_original_revision, test_invalid_dc_fails_even_when_filtered_out, test_cli_hash_failure_preserves_previous_artifact, test_cli_repeatable_bytes_and_no_local_path, test_cli_refuses_release_tree_output_without_touching_baseline, test_changed_official_pin_fails_closed, test_company_names_do_not_infer_listed_parent_or_enable_personal_enrichment, test_multiple_headlines_do_not_manufacture_independent_momentum, test_generator_requires_no_network, forbidden, test_dc_country_revision_must_identify_declared_country, test_public_links_reject_browser_numeric_aliases_and_nonpublic_addresses, test_public_links_allow_normal_dns_and_canonical_public_ips_offline, forbidden, test_later_source_run_only_refreshes_articles_actually_observed, test_article_observation_clock_missing_fails_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_prospecting.py:1-335 · blob c008233b47b4cd6768c6ac3f33436e4381f10837 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Offline research priorities: real pinned baseline plus synthetic receipt fixtures."""
import copy
import hashlib
import json
from pathlib import Path
import sys
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from automation.news import prospecting as p
from automation.news.acquisition.evidence_store import EvidenceStore
AS_OF = "2026-11-16T23:00:00Z"
FETCHED = "2026-11-16T18:00:00Z"
ROOT = Path(__file__).resolve().parents[3]
def write_pin(tmp_path, payload, name="input.json"):
raw = json.dumps(payload, allow_nan=True).encode()
path = tmp_path / name
path.write_bytes(raw)
return path, hashlib.sha256(raw).hexdigest()
@pytest.fixture(scope="module")
def baseline():
return p.official(ROOT)
@pytest.fixture
def evidence(baseline):
rows, ids, _ = baseline
projects = [dict(r, id=r["repd_ref"]) for r, _ in rows if r["repd_ref"] in ids]
# Synthetic accepted receipt, never a claim that a real publisher authorised reuse.
receipt = {"id": "synthetic", "status": "ok", "url": "https://publisher.example/feed",
"fetched_at": FETCHED, "response_sha256": "a" * 64, "http_status": 200,
"eligible_for_publication": True, "probe_only": False, "rights_status": "accepted",
"rights_review_url": "https://publisher.example/fixture-rights",
"channel_access": {"state": "OPEN", "checked_at": FETCHED,
"review_url": "https://publisher.example/fixture-access"},
"article_access": {"https://publisher.example/story": {
"state": "OPEN", "checked_at": FETCHED,
"review_url": "https://publisher.example/fixture-story-access"}}}
article = {"id": "test-article", "url": "https://publisher.example/story",
"title": "Synthetic project headline", "pub_date": "2026-11-15T12:00:00Z",
"source_id": "synthetic", "publisher": "Synthetic publisher"}
match = {"project_id": ids[0], "article_url": article["url"],
"status": "PROVISIONAL", "match_method": "repd_id"}
with EvidenceStore() as store:
store.record_run(projects, [article], [match], FETCHED, [receipt])
snapshot = store.snapshot(timestamp=FETCHED)
return snapshot
@pytest.fixture
def dc():
path = ROOT / "uk_renewables_pipeline/202611161630/global-datacentres/projects.json"
data = json.loads(path.read_bytes())
data["records"] = data["records"][:1]
data["record_count"] = data["country_count"] = 1
return data
def test_real_official_scope_stable_and_no_invented_events_or_freshness(baseline):
before = json.dumps(baseline, sort_keys=True)
result = p.build(as_of=AS_OF, limit=1000)
assert result == p.build(as_of=AS_OF, limit=1000)
assert result["input_count"] == 7775
assert result["input_receipts"][0]["solar1000_count"] == 1000
assert result["input_receipts"][0]["observed_at"] is None
assert result["input_receipts"][0]["freshness"] == "UNKNOWN"
assert result["profile_sha256"] == p.relevance.profile_sha256(result["profile"])
records = result["records"]
assert records == sorted(records, key=lambda r: (-r["score"], r["id"]))
assert all(r["score"] == round(sum(c["points"] for c in r["reasons"]), 2) for r in records)
assert all(r["record_state"] == "OFFICIAL" and r["research_state"] == "UNKNOWN" for r in records)
assert all("coverage unknown" in r["reasons"][-1]["basis"] for r in records)
assert all("event" not in r and "event_date" not in r and "available_grid_mw" not in r for r in records)
assert all(c["name"] not in {"stage", "novelty", "datacentre_proximity", "recency"}
for r in records for c in r["reasons"])
assert all(r["event_at"] is None and r["heat"]["score"] == 0
and not r["corporate_eligibility"]["eligible"] for r in records)
assert json.dumps(baseline, sort_keys=True) == before
assert all(not row["enabled"] and row["rights_state"] == "UNKNOWN" for row in result["unsupported_interfaces"])
def test_missing_name_capacity_country_remain_unknown(baseline):
row, source = copy.deepcopy(baseline[0][0])
row.update(name="", country="", capacity_mw=None, capacity_known=False, repd_record_updated=None)
candidate = p.official_candidate(row, source, {}, p._moment(AS_OF))
assert candidate["name"] is candidate["country"] is candidate["capacities"]["repd_installed_mw"] is None
assert candidate["record_freshness"]["state"] == "UNKNOWN"
assert candidate["reasons"][0]["points"] == 0
@pytest.mark.parametrize("value", [-1, float("nan"), float("inf"), True, "100"])
def test_invalid_capacity_cannot_become_positive_priority(value, baseline):
row, source = copy.deepcopy(baseline[0][0])
row["capacity_mw"] = value
with pytest.raises(ValueError):
p.official_candidate(row, source, {}, p._moment(AS_OF))
def test_future_record_date_rejected_even_outside_returned_top_n():
with pytest.raises(ValueError, match="Future official record date"):
p.build(as_of="2026-01-01T00:00:00Z", limit=1)
def test_evidence_is_provisional_and_news_age_never_becomes_event(evidence, baseline, tmp_path):
spec = write_pin(tmp_path, evidence)
records, receipt = p.evidence_input(spec, baseline[1], p._moment(AS_OF))
ref = baseline[1][0]
row, source = next(x for x in baseline[0] if x[0]["repd_ref"] == ref)
candidate = p.official_candidate(row, source, records[ref], p._moment(AS_OF))
assert candidate["record_state"] == "OFFICIAL" and candidate["research_state"] == "PROVISIONAL"
assert candidate["evidence"][0]["state"] == "PROVISIONAL"
assert candidate["reasons"][-1]["points"] == 5
assert receipt["sha256"] == spec[1]
assert candidate["last_researched_at"] == FETCHED
assert candidate["evidence"][0]["title"] == "Synthetic project headline" and "event_date" not in candidate
old_records, _ = p.evidence_input(spec, baseline[1], p._moment("2027-01-01T00:00:00Z"))
stale = p.official_candidate(row, source, old_records[ref], p._moment("2027-01-01T00:00:00Z"))
assert stale["reasons"][-1]["points"] == 0
assert stale["evidence"][0]["freshness"]["state"] == "STALE"
assert stale["evidence"][0]["pub_date"] == candidate["evidence"][0]["pub_date"]
@pytest.mark.parametrize("change", [
lambda x: x["sources"][0].update(rights_status="unknown"),
lambda x: x["sources"][0].update(status="failed"),
lambda x: x["sources"][0].update(probe_only=True),
lambda x: x["sources"][0].update(fetched_at="2026-11-17T00:00:00Z"),
lambda x: x["sources"][0].update(rights_review_url="https://127.0.0.1/private"),
lambda x: x["sources"][0].pop("channel_access"),
lambda x: x["sources"][0]["channel_access"].update(state="PAYWALLED"),
lambda x: x["sources"][0]["channel_access"].update(state="UNKNOWN"),
lambda x: x["sources"][0].update(article_access={}),
lambda x: x["sources"][0]["article_access"]["https://publisher.example/story"].update(state="PAYWALLED"),
lambda x: x.update(generated_at="2026-11-17T00:00:00Z"),
lambda x: x.update(schema="globalgrid2050.news.pipeline-headlines.v1"),
lambda x: next(r for r in x["projects"] if r["evidence"])["evidence"][0].update(source_id="unreceipted"),
lambda x: next(r for r in x["projects"] if r["evidence"])["evidence"][0].update(pub_date="2027-01-01T00:00:00Z"),
lambda x: next(r for r in x["projects"] if r["evidence"])["evidence"][0].update(pub_date="2026-11-15"),
lambda x: next(r for r in x["projects"] if r["evidence"])["evidence"][0].update(last_seen="2026-11-14T00:00:00Z"),
])
def test_bad_news_input_fails_closed(change, evidence, tmp_path):
change(evidence)
with pytest.raises(ValueError):
p.build(as_of=AS_OF, evidence=write_pin(tmp_path, evidence), limit=1)
def test_dc_distinct_unknown_capacity_and_original_revision(dc, tmp_path):
dc["records"][0]["source"]["private_path"] = "never-export-local-receipts"
spec = write_pin(tmp_path, dc)
result = p.build(as_of=AS_OF, datacentres=spec, record_type="data_centre")
assert result["input_count"] == 7776 and result["eligible_count"] == 1
row = result["records"][0]
assert row["id"].startswith("DC-WD-") and row["record_state"] == "PROVISIONAL"
assert row["official_status"] is None
assert row["capacities"] == {"it_load_mw": None, "site_demand_mw": None, "grid_connection_mw": None}
assert row["source"]["revision_url"] == dc["records"][0]["source"]["revision_url"]
assert row["source"]["sha256"] == spec[1]
assert "never-export-local-receipts" not in json.dumps(result)
assert str(tmp_path) not in json.dumps(result)
@pytest.mark.parametrize("change", [
lambda x: x.update(schema="other"),
lambda x: x.update(record_count=2),
lambda x: x.update(country_count=2),
lambda x: x.update(generated_from_retrieval="2027-01-01T00:00:00Z"),
lambda x: x["records"][0].update(verification_status="VERIFIED"),
lambda x: x["records"][0]["capacity"].update(it_load_mw=123),
lambda x: x["records"][0]["source"].update(licence="unknown"),
lambda x: x["records"][0]["source"].update(revision_url="https://www.wikidata.org/wiki/Q142068695"),
lambda x: x["records"][0]["field_sources"].update(country="https://localhost/private"),
])
def test_invalid_dc_fails_even_when_filtered_out(change, dc, tmp_path):
change(dc)
with pytest.raises(ValueError):
p.build(as_of=AS_OF, datacentres=write_pin(tmp_path, dc), record_type="renewable_project", limit=1)
def test_cli_hash_failure_preserves_previous_artifact(tmp_path):
source, _ = write_pin(tmp_path, {"untrusted": True})
output = tmp_path / "triage.json"
output.write_bytes(b"previous reviewed artifact")
with pytest.raises(SystemExit) as error:
p.main(["--as-of", AS_OF, "--out", str(output), "--datacentres", str(source),
"--datacentres-sha256", "0" * 64])
assert error.value.code == 2
assert output.read_bytes() == b"previous reviewed artifact"
assert set(tmp_path.iterdir()) == {source, output}
def test_cli_repeatable_bytes_and_no_local_path(tmp_path):
first, second = tmp_path / "first.json", tmp_path / "second.json"
for target in (first, second):
assert p.main(["--as-of", AS_OF, "--out", str(target), "--limit", "10"]) == 0
assert first.read_bytes() == second.read_bytes()
assert str(ROOT).encode() not in first.read_bytes()
def test_cli_refuses_release_tree_output_without_touching_baseline():
manifest = ROOT / "uk_renewables_pipeline" / p.queue.RELEASE_ID / "solar1000/manifest.json"
before = manifest.read_bytes()
with pytest.raises(SystemExit):
p.main(["--as-of", AS_OF, "--out", str(manifest)])
assert manifest.read_bytes() == before
def test_changed_official_pin_fails_closed(monkeypatch):
monkeypatch.setattr(p.queue, "BUILD_MANIFEST_SHA256", "0" * 64)
with pytest.raises(ValueError, match="Immutable V9.24 input changed"):
p.build(as_of=AS_OF)
def test_company_names_do_not_infer_listed_parent_or_enable_personal_enrichment(dc, tmp_path):
dc["records"][0].update(name="NASDAQ famous listed group FTSE250",
operator="Ambiguous company name", directors=["Must not export"],
residential_address="Must not export")
result = p.build(as_of=AS_OF, datacentres=write_pin(tmp_path, dc), record_type="data_centre")
eligibility = result["records"][0]["corporate_eligibility"]
assert eligibility["state"] == "UNKNOWN" and eligibility["listed_parent"] is None
assert not eligibility["eligible"] and not eligibility["membership_evidence"]
assert "Must not export" not in json.dumps(result)
assert not result["source_policy"]["sme_targeting"]
assert not result["source_policy"]["government_hosting_implies_reuse_permission"]
def test_multiple_headlines_do_not_manufacture_independent_momentum(evidence, baseline, tmp_path):
row = next(r for r in evidence["projects"] if r["evidence"])
duplicate = dict(row["evidence"][0], id="syndicated", url="https://publisher.example/repost")
row["evidence"].append(duplicate)
row["evidence_count"] = row["provisional_count"] = evidence["evidence_count"] = 2
source = evidence["sources"][0]
source["article_access"][duplicate["url"]] = source["article_access"]["https://publisher.example/story"]
records, _ = p.evidence_input(write_pin(tmp_path, evidence), baseline[1], p._moment(AS_OF))
official, provenance = next(x for x in baseline[0] if x[0]["repd_ref"] == row["project_id"])
candidate = p.official_candidate(official, provenance, records[row["project_id"]], p._moment(AS_OF))
assert candidate["reasons"][-1]["points"] == 5
assert candidate["heat"]["state"] == "UNKNOWN" and candidate["heat"]["independent_signal_count"] is None
def test_generator_requires_no_network(monkeypatch):
import socket
def forbidden(*args, **kwargs):
raise AssertionError("Network is not part of offline triage")
monkeypatch.setattr(socket, "socket", forbidden)
monkeypatch.setattr(socket, "getaddrinfo", forbidden)
assert p.build(as_of=AS_OF, limit=1)["returned_count"] == 1
def test_dc_country_revision_must_identify_declared_country(dc, tmp_path):
record = dc["records"][0]
assert record["country"]["wikidata_id"] == "Q408"
record["field_sources"]["country"] = record["source"]["revision_url"]
with pytest.raises(ValueError, match="Country revision identity differs"):
p.build(as_of=AS_OF, datacentres=write_pin(tmp_path, dc), record_type="data_centre")
@pytest.mark.parametrize("host", [
"127.1", "127.0.0.1", "127.0.0.1.", "127.0.0.01", "0177.0.0.1",
"0x7f.1", "0x7f000001", "0x7f000001.", "2130706433", "2130706433.",
"%31%32%37.0.0.%31", "127.0.0.1", "224.0.0.1", "239.255.255.250",
"240.0.0.1", "10.0.0.1", "169.254.169.254", "192.0.2.1", "0.0.0.0",
"[::1]", "[ff02::1]", "[fe80::1]", "[::ffff:127.0.0.1]", "[2606:4700:4700::1111%eth0]",
"localhost.", "host.local.",
])
def test_public_links_reject_browser_numeric_aliases_and_nonpublic_addresses(host):
with pytest.raises(ValueError):
p.public_url("https://" + host + "/private")
@pytest.mark.parametrize("host", ["www.gov.uk", "www.wikidata.org", "www.gov.uk.",
"8.8.8.8", "1.1.1.1", "[2606:4700:4700::1111]"])
def test_public_links_allow_normal_dns_and_canonical_public_ips_offline(host, monkeypatch):
import socket
def forbidden(*args, **kwargs):
raise AssertionError("Public link validation must remain offline")
monkeypatch.setattr(socket, "getaddrinfo", forbidden)
url = "https://" + host + "/source"
assert p.public_url(url) == url
@pytest.mark.parametrize("observed_again", [False, True])
def test_later_source_run_only_refreshes_articles_actually_observed(observed_again, evidence, baseline, tmp_path):
rows, ids, _ = baseline
projects = [dict(r, id=r["repd_ref"]) for r, _ in rows if r["repd_ref"] in ids]
first_seen = "2026-10-27T18:00:00Z"
original = next(r for r in evidence["projects"] if r["evidence"])["evidence"][0]
article = {key: original[key] for key in ("id", "url", "title", "pub_date", "source_id", "publisher")}
article["pub_date"] = "2026-10-26T12:00:00Z"
first_source = copy.deepcopy(evidence["sources"][0])
first_source["fetched_at"] = first_seen
first_source["channel_access"]["checked_at"] = first_seen
first_source["article_access"][article["url"]]["checked_at"] = first_seen
latest_source = copy.deepcopy(first_source)
latest_source["fetched_at"] = FETCHED
latest_source["channel_access"]["checked_at"] = FETCHED
match = {"project_id": ids[0], "article_url": article["url"],
"status": "PROVISIONAL", "match_method": "repd_id"}
with EvidenceStore() as store:
store.record_run(projects, [article], [match], first_seen, [first_source])
store.record_run(projects, [article] if observed_again else [],
[match] if observed_again else [], FETCHED, [latest_source])
snapshot = store.snapshot(timestamp=FETCHED)
records, receipt = p.evidence_input(write_pin(tmp_path, snapshot), ids, p._moment(AS_OF))
official, source = next(x for x in rows if x[0]["repd_ref"] == ids[0])
candidate = p.official_candidate(official, source, records[ids[0]], p._moment(AS_OF))
assert candidate["reasons"][-1]["points"] == (5 if observed_again else 0)
exported = candidate["evidence"][0]
assert exported["retrieval_freshness"]["state"] == ("WITHIN_WINDOW" if observed_again else "STALE")
assert exported["retrieval_freshness"]["timestamp"] == (FETCHED if observed_again else first_seen)
assert exported["retrieval_freshness"]["basis"] == "article last observed time"
assert exported["freshness"]["state"] == "WITHIN_WINDOW"
assert exported["pub_date"] == article["pub_date"] and exported["first_seen"] == first_seen
assert exported["source"]["fetched_at"] == FETCHED
assert receipt["freshness"]["state"] == "WITHIN_WINDOW" # source health is separate
@pytest.mark.parametrize("remove", [False, True])
def test_article_observation_clock_missing_fails_closed(remove, evidence, tmp_path):
article = next(r for r in evidence["projects"] if r["evidence"])["evidence"][0]
if remove:
article.pop("last_seen")
else:
article["last_seen"] = None
with pytest.raises(ValueError):
p.build(as_of=AS_OF, evidence=write_pin(tmp_path, evidence), limit=1)