GLOBALGRID2050 / EXPLORE CODE

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

Test Filing Figures and 3 more files

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

632 lines of Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 805 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 Filing Figures test · globalgrid2050 / automation/news/tests/test_filing_figures.py lines 1–233
  2. Test Global Datacentres test · globalgrid2050 / automation/news/tests/test_global_datacentres.py lines 1–109
  3. Test Grid DC Context test · globalgrid2050 / automation/news/tests/test_grid_dc_context.py lines 1–225
  4. Test Grid Government V938 test · globalgrid2050 / automation/news/tests/test_grid_government_v938.py lines 1–65

Test Filing Figures

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

testglobalgrid2050 / automation/news/tests/test_filing_figures.py · lines 1–233 of 233 · Entry point · pattern claim (shared by 7 files)

What it does
It tests its inputs. Defines 22 functions or classes, including claim, test_exact_decimal_scale_and_source_precision_survive_json, test_no_mutation_or_shared_nested_containers, test_lossy_nonfinite_or_ambiguous_numbers_rejected, test_finance_stages_and_signed_reported_value_remain_distinct. Uses libraries copy, decimal, 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.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Synthetic contract fixtures only; no claims about real issuers or projects.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Contracts (import), copy, decimal, json, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
claim, test_exact_decimal_scale_and_source_precision_survive_json, test_no_mutation_or_shared_nested_containers, test_lossy_nonfinite_or_ambiguous_numbers_rejected, test_finance_stages_and_signed_reported_value_remain_distinct, test_electrical_claims_keep_kind_scope_and_unit, test_no_automatic_power_energy_money_conversion, test_unknown_finance_semantics_or_verified_status_rejected, test_negative_power_and_attached_currency_rejected, test_consolidation_scope_is_preserved_not_allocated_to_project, test_forecast_not_audited_actual_and_future_period_explicit, test_invalid_source_dates_rejected
Defines here
claim, test_exact_decimal_scale_and_source_precision_survive_json, test_no_mutation_or_shared_nested_containers, test_lossy_nonfinite_or_ambiguous_numbers_rejected, test_finance_stages_and_signed_reported_value_remain_distinct, test_electrical_claims_keep_kind_scope_and_unit, test_no_automatic_power_energy_money_conversion, test_unknown_finance_semantics_or_verified_status_rejected, test_negative_power_and_attached_currency_rejected, test_consolidation_scope_is_preserved_not_allocated_to_project, test_forecast_not_audited_actual_and_future_period_explicit, test_invalid_source_dates_rejected, test_period_order_precision_and_missing_temporal_basis, test_retrieval_requires_valid_offset_timestamp, test_chronology_and_nullable_publication_preserved, test_source_calendar_offset_explicit_at_retrieval_day_boundary, test_revision_and_restatement_preserve_history, test_no_personal_or_untrusted_extra_fields_pass_through, test_provenance_url_syntax_rejects_private_literals_and_confusion, test_hash_and_locator_required_without_fabricating_source_evidence, test_unsupported_scope_and_arbitrary_nested_payload_fail, test_metric_missing_or_unencodable_text_rejected
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_filing_figures.py:1-233 · blob b9e44fd389d9c35bd5a771e2c945c36b034ddd97 · 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
"""Synthetic contract fixtures only; no claims about real issuers or projects."""

from copy import deepcopy
from decimal import Decimal
import json

import pytest

from automation.news.filings.contracts import (
    ClaimValidationError, ENERGY_KINDS, POWER_KINDS, SCHEMA, dumps_claim, validate_claim,
)


@pytest.fixture
def claim():
    return {
        "schema": SCHEMA, "claim_id": "filing:synthetic:capex:1",
        "status": "machine-provisional", "quantity_kind": "finance", "metric": "Capital expenditure", "value": "1.20",
        "scale": "1e9", "unit": "currency", "original_unit": "billion US dollars",
        "currency": "USD", "finance_stage": "announced",
        "entity": {"scope": "consolidated_group", "id": "group:synthetic",
                   "consolidation_group_id": "group:synthetic",
                   "identity_evidence_url": "https://www.sec.gov/synthetic-identity"},
        "reporting_period": {"start": "2026-01", "end": "2026-09"},
        "as_of": "2026-09-30", "basis": "reported", "assurance": "unknown",
        "provenance": {"document_id": "filing:synthetic",
                       "document_url": "https://www.sec.gov/synthetic-document",
                       "sha256": "a" * 64, "page": "12", "section": "Capital expenditure",
                       "published_date": "2026-10-01", "retrieved_at": "2026-11-16T12:00:00Z"},
        "revision": {"id": "original", "supersedes_claim_id": None, "restated": False},
    }


def test_exact_decimal_scale_and_source_precision_survive_json(claim):
    wire = dumps_claim(claim)
    assert json.loads(wire) == claim
    assert json.loads(wire)["value"] == "1.20"
    assert json.loads(wire)["scale"] == "1e9"
    assert json.loads(wire)["reporting_period"]["end"] == "2026-09"
    assert wire == dumps_claim(dict(reversed(list(claim.items()))))


def test_no_mutation_or_shared_nested_containers(claim):
    before = deepcopy(claim)
    result = validate_claim(claim)
    result["entity"]["id"] = "group:changed"
    result["reporting_period"]["end"] = "2026-10"
    assert claim == before


@pytest.mark.parametrize("value", [1.2, 1, True, None, Decimal("1.20"), "NaN", "Infinity",
                                      "-Infinity", "1e9", "1,200", "01.2", ".2", "1.", " 1.20", "1.20\n", "9" * 101])
def test_lossy_nonfinite_or_ambiguous_numbers_rejected(claim, value):
    claim["value"] = value
    with pytest.raises(ClaimValidationError, match="value"):
        validate_claim(claim)


@pytest.mark.parametrize("stage", ["announced", "committed", "disbursed", "reported"])
def test_finance_stages_and_signed_reported_value_remain_distinct(claim, stage):
    claim.update(finance_stage=stage, value="-123456789012345678901234567890.00100")
    assert validate_claim(claim)["finance_stage"] == stage
    assert json.loads(dumps_claim(claim))["value"].endswith(".00100")


@pytest.mark.parametrize("kind", sorted(POWER_KINDS | ENERGY_KINDS))
def test_electrical_claims_keep_kind_scope_and_unit(claim, kind):
    claim.update(quantity_kind=kind, unit="MWh" if kind in ENERGY_KINDS else "MW",
                 original_unit="source units", scale="1", currency=None, finance_stage=None)
    claim["entity"].update(scope="phase", id="phase:synthetic", consolidation_group_id=None)
    result = validate_claim(claim)
    assert result["quantity_kind"] == kind
    assert result["entity"]["scope"] == "phase"
    assert result["value"] == "1.20"


@pytest.mark.parametrize("kind,unit", [("storage_energy", "MW"), ("storage_power", "MWh"),
                                       ("it_load", "GWh"), ("finance", "MW")])
def test_no_automatic_power_energy_money_conversion(claim, kind, unit):
    claim.update(quantity_kind=kind, unit=unit)
    if kind != "finance":
        claim.update(currency=None, finance_stage=None)
    with pytest.raises(ClaimValidationError, match="unit"):
        validate_claim(claim)


@pytest.mark.parametrize("key,value", [("currency", None), ("currency", "US$"), ("currency", "usd"),
                                       ("finance_stage", "paid-or-announced"), ("scale", 1000),
                                       ("scale", "2"), ("status", "VERIFIED"), ("basis", "estimated"),
                                       ("original_unit", "")])
def test_unknown_finance_semantics_or_verified_status_rejected(claim, key, value):
    claim[key] = value
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)


def test_negative_power_and_attached_currency_rejected(claim):
    claim.update(quantity_kind="project_demand", unit="MW", value="-1", currency=None, finance_stage=None)
    with pytest.raises(ClaimValidationError, match="negative"):
        validate_claim(claim)
    claim.update(value="1", currency="USD")
    with pytest.raises(ClaimValidationError, match="currency"):
        validate_claim(claim)


def test_consolidation_scope_is_preserved_not_allocated_to_project(claim):
    group = validate_claim(claim)
    subsidiary = deepcopy(claim)
    subsidiary["claim_id"] = "filing:synthetic:subsidiary:1"
    subsidiary["entity"].update(scope="issuer", id="issuer:subsidiary")
    validated = validate_claim(subsidiary)
    assert validated["entity"]["id"] != group["entity"]["id"]
    assert validated["entity"]["consolidation_group_id"] == group["entity"]["id"]
    claim["entity"]["consolidation_group_id"] = None
    with pytest.raises(ClaimValidationError, match="group identity"):
        validate_claim(claim)


def test_forecast_not_audited_actual_and_future_period_explicit(claim):
    claim["reporting_period"] = {"start": "2027", "end": "2029"}
    with pytest.raises(ClaimValidationError, match="forecast"):
        validate_claim(claim)
    claim["basis"] = "forecast"
    claim["as_of"] = "2029-12"
    assert validate_claim(claim)["reporting_period"]["end"] == "2029"
    assert validate_claim(claim)["as_of"] == "2029-12"
    claim["assurance"] = "audited"
    with pytest.raises(ClaimValidationError, match="audited actual"):
        validate_claim(claim)


@pytest.mark.parametrize("value", ["2026-13", "2026-02-30", "0000", "2026-1", "20261101", True])
def test_invalid_source_dates_rejected(claim, value):
    claim["as_of"] = value
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)


def test_period_order_precision_and_missing_temporal_basis(claim):
    for period in ({"start": "2026-10", "end": "2026-09"},
                   {"start": "2026", "end": "2026-09"}, None):
        claim.update(reporting_period=period, as_of=None)
        with pytest.raises(ClaimValidationError):
            validate_claim(claim)


@pytest.mark.parametrize("value", ["2026-11-16T12:00:00", "2026-11-16", "2026-13-16T12:00:00Z"])
def test_retrieval_requires_valid_offset_timestamp(claim, value):
    claim["provenance"]["retrieved_at"] = value
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)


def test_chronology_and_nullable_publication_preserved(claim):
    claim["provenance"]["published_date"] = None
    assert validate_claim(claim)["provenance"]["published_date"] is None
    claim["provenance"]["published_date"] = "2026-12"
    with pytest.raises(ClaimValidationError, match="publication"):
        validate_claim(claim)
    claim["provenance"]["published_date"] = None
    claim["as_of"] = "2027"
    with pytest.raises(ClaimValidationError, match="observation"):
        validate_claim(claim)


def test_source_calendar_offset_explicit_at_retrieval_day_boundary(claim):
    claim["provenance"].update(published_date="2026-11-17", retrieved_at="2026-11-17T00:30:00+09:00")
    assert validate_claim(claim)["provenance"]["retrieved_at"].endswith("+09:00")
    # Same instant, unknown source timezone: conservative rejection is documented.
    claim["provenance"]["retrieved_at"] = "2026-11-16T15:30:00Z"
    with pytest.raises(ClaimValidationError, match="publication"):
        validate_claim(claim)


def test_revision_and_restatement_preserve_history(claim):
    claim["revision"] = {"id": "restatement:2", "supersedes_claim_id": "filing:older:capex:1", "restated": True}
    assert validate_claim(claim)["revision"]["supersedes_claim_id"] == "filing:older:capex:1"
    claim["revision"]["supersedes_claim_id"] = claim["claim_id"]
    with pytest.raises(ClaimValidationError, match="itself"):
        validate_claim(claim)
    claim["revision"]["supersedes_claim_id"] = None
    with pytest.raises(ClaimValidationError, match="earlier claim"):
        validate_claim(claim)
    claim["revision"]["restated"] = 1
    with pytest.raises(ClaimValidationError, match="boolean"):
        validate_claim(claim)


@pytest.mark.parametrize("level", [None, "entity", "provenance", "revision", "reporting_period"])
def test_no_personal_or_untrusted_extra_fields_pass_through(claim, level):
    target = claim if level is None else claim[level]
    target["director_residential_address"] = "synthetic forbidden field"
    with pytest.raises(ClaimValidationError, match="documented fields"):
        validate_claim(claim)


@pytest.mark.parametrize("url", ["http://www.sec.gov/x", "https://localhost/x", "https://127.1/x",
                                    "https://2130706433/x", "https://0x7f000001/x", "https://127.0.0.1/x",
                                    "https://224.0.0.1/x", "https://[::1]/x", "https://user:password@www.sec.gov/x",
                                    "https://www.sec.gov\\@127.0.0.1/x", "https://www.sec.gov:444/x",
                                    "https://host.internal/x", "https://www.sec.gov/%s\n"])
def test_provenance_url_syntax_rejects_private_literals_and_confusion(claim, url):
    claim["provenance"]["document_url"] = url
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)


def test_hash_and_locator_required_without_fabricating_source_evidence(claim):
    claim["provenance"].update(page=None, section=None)
    with pytest.raises(ClaimValidationError, match="locator"):
        validate_claim(claim)
    claim["provenance"].update(section="Table 1", sha256="unknown")
    with pytest.raises(ClaimValidationError, match="SHA256"):
        validate_claim(claim)


def test_unsupported_scope_and_arbitrary_nested_payload_fail(claim):
    claim["entity"]["scope"] = "person"
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)
    claim["entity"]["scope"] = "consolidated_group"
    claim["provenance"]["section"] = {"body": "untrusted data"}
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)


def test_metric_missing_or_unencodable_text_rejected(claim):
    claim["metric"] = "\ud800"
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)
    del claim["metric"]
    with pytest.raises(ClaimValidationError):
        validate_claim(claim)

Test Global Datacentres

A test in the tests folder of GlobalGrid2050 that uses SHA-256.

testglobalgrid2050 / automation/news/tests/test_global_datacentres.py · lines 1–109 of 109 · Entry point

What it does
It tests its inputs. Defines 7 functions or classes, including load, test_curated_sample_is_genuinely_global_and_source_namespaced, test_export_reproduces_from_fixed_cc0_facts_and_original_coordinates, test_unknown_capacity_and_coordinates_never_fabricated, test_browser_model_filters_links_capacity_and_rejects_bad_records. Uses libraries hashlib, importlib.util, json, pathlib, subprocess. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'datacentres'): 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 source-facts.json; JSON file pipeline-audit.json; JSON file invalid-source.json; DuckDB queries.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Defines `load`, `test_curated_sample_is_genuinely_global_and_source_namespaced`, `test_export_reproduces_from_fixed_cc0_facts_and_original_coordinates` and 4 more.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
hashlib, importlib.util, json, pathlib, subprocess, copy, pytest, duckdb
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
load, test_curated_sample_is_genuinely_global_and_source_namespaced, test_export_reproduces_from_fixed_cc0_facts_and_original_coordinates, test_unknown_capacity_and_coordinates_never_fabricated, test_browser_model_filters_links_capacity_and_rejects_bad_records, test_parquet_exact_readback_schema_nulls_and_deterministic_bytes, test_invalid_inputs_are_quarantined_before_output_changes
Defines here
load, test_curated_sample_is_genuinely_global_and_source_namespaced, test_export_reproduces_from_fixed_cc0_facts_and_original_coordinates, test_unknown_capacity_and_coordinates_never_fabricated, test_browser_model_filters_links_capacity_and_rejects_bad_records, test_parquet_exact_readback_schema_nulls_and_deterministic_bytes, test_invalid_inputs_are_quarantined_before_output_changes
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_global_datacentres.py:1-109 · blob eed243ad30a1833f157f56f0fd3e75321b48de3c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Global DC facts remain separate, attributable, reproducible and conservative."""
import hashlib
import importlib.util
import json
from pathlib import Path
import subprocess
import copy

import pytest

ROOT = Path(__file__).resolve().parents[3]
DATA = ROOT / 'uk_renewables_pipeline/202611161630/global-datacentres'


def load(name):
    return json.loads((DATA / name).read_text(encoding='utf-8'))


def test_curated_sample_is_genuinely_global_and_source_namespaced():
    data = load('projects.json')
    assert data['record_count'] == len(data['records']) == 12
    assert data['country_count'] == len({p['country']['wikidata_id'] for p in data['records']}) == 10
    assert {'Japan', 'India', 'Australia', 'Brazil', 'United States', 'United Kingdom'} <= {p['country']['name'] for p in data['records']}
    assert len({p['id'] for p in data['records']}) == 12
    assert all(p['id'].startswith('DC-WD-Q') for p in data['records'])
    assert 'not a comprehensive' in data['coverage']
    assert all(p['operating_status'] == 'not_assessed' and p['verification_status'] == 'SOURCE_INDEXED' for p in data['records'])


def test_export_reproduces_from_fixed_cc0_facts_and_original_coordinates():
    spec = importlib.util.spec_from_file_location('global_dc_build', DATA / 'build.py')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    data = load('projects.json')
    assert module.build(DATA / 'source-facts.json') == data
    assert hashlib.sha256((DATA / 'source-facts.json').read_bytes()).hexdigest() == data['source_facts_sha256']
    facts = load('source-facts.json')
    assert facts['licence'] == 'CC0-1.0'
    assert all(r['http_status'] == 200 and len(r['response_sha256']) == 64 for r in facts['requests'])
    for record in data['records']:
        original = facts['entities'][record['id'].removeprefix('DC-WD-')]
        assert record['name'] == original['label']
        assert record['source']['revision'] == original['revision']
        assert f"oldid={original['revision']}" in record['source']['revision_url']
        if record['location'] is not None:
            coordinates = module.values(original, 'P625')[0]
            assert record['location']['latitude'] == coordinates['latitude']
            assert record['location']['longitude'] == coordinates['longitude']
            assert record['location']['precision_degrees'] == coordinates['precision']


def test_unknown_capacity_and_coordinates_never_fabricated():
    records = load('projects.json')['records']
    for record in records:
        assert record['capacity'] == {'it_load_mw': None, 'site_demand_mw': None, 'grid_connection_mw': None}
        assert all(source is None for source in record['capacity_sources'].values())
    for entity in ['Q142068471', 'Q142068695', 'Q142068699']:
        record = next(p for p in records if p['id'] == 'DC-WD-' + entity)
        assert record['location'] is None
    # A deprecated ISO claim is not promoted into a current code.
    assert next(p for p in records if p['country']['wikidata_id'] == 'Q55')['country']['code'] is None


def test_browser_model_filters_links_capacity_and_rejects_bad_records():
    result = subprocess.run(['node', str(DATA / 'test-model.cjs')], capture_output=True, text=True, check=True)
    assert 'PASS' in result.stdout


def test_parquet_exact_readback_schema_nulls_and_deterministic_bytes(tmp_path):
    import duckdb
    spec = importlib.util.spec_from_file_location('global_dc_furnace', DATA / 'build.py')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    module.build(DATA / 'source-facts.json', output_dir=tmp_path)
    audit = json.loads((tmp_path / 'pipeline-audit.json').read_text())
    parquet = tmp_path / module.PARQUET
    assert parquet.read_bytes() == (DATA / module.PARQUET).read_bytes()
    assert audit['double_compile'] == 'BYTE_IDENTICAL'
    assert audit['browser_export_source'] == 'DUCKDB_PARQUET_READBACK'
    assert audit['row_count'] == audit['distinct_source_ids'] == 12
    assert audit['quarantined_rows'] == audit['verified_rows'] == 0
    with duckdb.connect(':memory:') as db:
        assert db.execute('SELECT count(*) FROM read_parquet(?,hive_partitioning=false) WHERE it_load_mw IS NULL AND site_demand_mw IS NULL AND grid_connection_mw IS NULL', [str(parquet)]).fetchone()[0] == 12
        assert db.execute('SELECT count(*) FROM read_parquet(?,hive_partitioning=false) WHERE latitude IS NULL AND longitude IS NULL', [str(parquet)]).fetchone()[0] == 3
        assert db.execute('SELECT DISTINCT compression FROM parquet_metadata(?)', [str(parquet)]).fetchall() == [('ZSTD',)]


@pytest.mark.parametrize('mutation', [
    lambda f: f.update(licence='unknown'),
    lambda f: f['selected_ids'].append(f['selected_ids'][0]),
    lambda f: f['entities']['Q12857142']['claims']['P625'][0]['value'].update(latitude=200),
    lambda f: f['entities']['Q12857142']['claims'].update(P17=[]),
])
def test_invalid_inputs_are_quarantined_before_output_changes(tmp_path, mutation):
    spec = importlib.util.spec_from_file_location('global_dc_invalid', DATA / 'build.py')
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    facts = copy.deepcopy(load('source-facts.json'))
    mutation(facts)
    path = tmp_path / 'invalid-source.json'
    path.write_text(json.dumps(facts), encoding='utf-8')
    target = tmp_path / 'output'
    target.mkdir()
    previous = target / 'projects.json'
    previous.write_text('previous accepted output', encoding='utf-8')
    with pytest.raises(ValueError, match='quarantine'):
        module.build(path, output_dir=target)
    assert previous.read_text() == 'previous accepted output'
    assert not (target / module.PARQUET).exists()

Test Grid DC Context

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

testglobalgrid2050 / automation/news/tests/test_grid_dc_context.py · lines 1–225 of 225 · Entry point · pattern test_cli_writes_new_artifact_and_refuses_overwrite (shared by 2 files)

What it does
It tests its inputs. Defines 19 functions or classes, including bundle, test_actual_sources_keep_historical_rejection_and_unknown_current_state, test_committed_replay_matches_every_output_byte, test_replay_sorting_and_input_independence, test_bad_source_aborts_whole_generation. Uses libraries copy, json, pathlib, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'dc'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file grid-source-fixture.json; JSON file grid-context-fixture.json; JSON file grid-context.json; JSON file broken.json; JSON file output.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Scope, state and provenance regressions for the offline GRID-DC adapter.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Grid (import), copy, 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
bundle, test_actual_sources_keep_historical_rejection_and_unknown_current_state, test_committed_replay_matches_every_output_byte, test_replay_sorting_and_input_independence, test_bad_source_aborts_whole_generation, test_unapproved_or_unsafe_source_urls, test_bad_context_or_unsupported_inference, test_rejected_load_request_cannot_become_connection_or_operating_power, test_shared_figures_semantics_preserved, test_cannot_move_figures_between_entities_documents_or_clocks, test_duplicate_identifiers_rejected, test_no_private_fields_or_implicit_binding_are_passed_through
Defines here
bundle, test_actual_sources_keep_historical_rejection_and_unknown_current_state, test_committed_replay_matches_every_output_byte, test_replay_sorting_and_input_independence, test_bad_source_aborts_whole_generation, test_unapproved_or_unsafe_source_urls, test_bad_context_or_unsupported_inference, test_rejected_load_request_cannot_become_connection_or_operating_power, test_shared_figures_semantics_preserved, test_cannot_move_figures_between_entities_documents_or_clocks, test_duplicate_identifiers_rejected, test_no_private_fields_or_implicit_binding_are_passed_through, test_unknown_clock_and_missing_locator_fail_closed, test_retrieval_does_not_refresh_the_source_claim, test_exact_value_lexical_precision_is_not_rounded, test_synthetic_source_states_do_not_claim_current_connection, test_synthetic_funding_keeps_stage_without_allocating_capex, test_cli_writes_new_artifact_and_refuses_overwrite, test_failed_input_does_not_create_output
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_dc_context.py:1-225 · blob 551e23b1128c0af40ed14608b6ef0538202517ce · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
"""Scope, state and provenance regressions for the offline GRID-DC adapter."""
from copy import deepcopy
import json
from pathlib import Path
import subprocess
import sys

import pytest

from automation.news.dc_context.grid import build, dumps

FIXTURE = Path(__file__).parents[1] / "dc_context/grid-source-fixture.json"
AS_OF = "2026-11-16T18:00:00Z"


@pytest.fixture
def bundle():
    return json.loads(FIXTURE.read_text(encoding="utf-8"))


def test_actual_sources_keep_historical_rejection_and_unknown_current_state(bundle):
    result = build(bundle, as_of=AS_OF)
    assert result["context_count"] == 2
    assert result["numeric_claim_count"] == 1
    assert result["linked_project_count"] == 0
    ferc, culham = result["records"]
    assert ferc["source_state"] == "REJECTED"
    assert ferc["numeric_claims"][0]["value"] == "480"
    assert ferc["numeric_claims"][0]["quantity_kind"] == "project_demand"
    assert "every existing arrangement" in ferc["research_action"]
    assert culham["numeric_claims"] == []
    assert "basis" in culham["figures_omitted_reason"]
    for record in result["records"]:
        assert record["status"] == "PROVISIONAL"
        assert record["current_project_state"] == "UNKNOWN"
        assert record["source_document_age_days"] > 600
        assert record["retrieval_age_days"] == 0
        for key in ("canonical_project_id", "current_secured_connection",
                    "current_energised_load", "available_grid_capacity", "site_capex"):
            assert record[key] is None


def test_committed_replay_matches_every_output_byte(bundle):
    expected = FIXTURE.with_name("grid-context-fixture.json").read_bytes()
    assert dumps(build(bundle, as_of=AS_OF)).encode("utf-8") == expected


def test_replay_sorting_and_input_independence(bundle):
    before = deepcopy(bundle)
    first = build(bundle, as_of=AS_OF)
    assert bundle == before
    bundle["sources"].reverse()
    bundle["contexts"].reverse()
    assert dumps(build(bundle, as_of=AS_OF)) == dumps(first)
    first["records"][0]["source"]["publisher"] = "changed"
    assert build(bundle, as_of=AS_OF)["records"][0]["source"]["publisher"] != "changed"


@pytest.mark.parametrize("field,value", [
    ("http_status", 403), ("http_status", True), ("sha256", "0" * 63),
    ("bytes", 0), ("bytes", 4 * 1024 * 1024 + 1), ("bytes", True),
    ("access_state", "UNKNOWN"), ("access_state", "PAYWALLED"),
    ("output_policy", "FULL_TEXT"), ("authority", "COMPANY"),
    ("retrieved_at", "2026-11-17T00:00:00Z"),
    ("retrieved_at", "2026-11-16T12:00:00"),
    ("published_date", "2026-11-17"), ("published_date", "2025-02-30"),
    ("title", "<img src=x onerror=alert(1)>"),
])
def test_bad_source_aborts_whole_generation(bundle, field, value):
    bundle["sources"][0][field] = value
    with pytest.raises(ValueError):
        build(bundle, as_of=AS_OF)


@pytest.mark.parametrize("url", [
    "http://www.gov.uk/x", "https://www.gov.uk.evil.example/x",
    "https://www.gov.uk@127.0.0.1/x", "https://127.1/x",
    "https://www.gov.uk:8443/x", "https://www.gov.uk\\@example.com/x",
    "https://www.gov.uk/x?redirect=https://example.com", "https://www.gov.uk/x#redirect",
    "https://www.bloomberg.com/story", "https://www.gov.uk/\nfoo",
])
def test_unapproved_or_unsafe_source_urls(bundle, url):
    bundle["sources"][0]["url"] = url
    with pytest.raises(ValueError):
        build(bundle, as_of=AS_OF)


@pytest.mark.parametrize("field,value", [
    ("kind", "proximity_match"), ("source_state", "VERIFIED"),
    ("source_state", "OFFER_REPORTED"), ("entity_scope", "consolidated_group"),
    ("source_id", "missing-source"), ("name", "<script>alert(1)</script>"),
    ("country", "XX"), ("id", "../../private"),
    ("country", []), ("source_id", []), ("entity_scope", []),
])
def test_bad_context_or_unsupported_inference(bundle, field, value):
    bundle["contexts"][0][field] = value
    with pytest.raises(ValueError):
        build(bundle, as_of=AS_OF)


@pytest.mark.parametrize("kind", ["secured_connection", "energised_load", "grid_upgrade", "generation_power", "it_load"])
def test_rejected_load_request_cannot_become_connection_or_operating_power(bundle, kind):
    bundle["contexts"][1]["numeric_claims"][0]["quantity_kind"] = kind
    with pytest.raises(ValueError, match="numeric kind/basis"):
        build(bundle, as_of=AS_OF)


@pytest.mark.parametrize("key,value", [("basis", "reported"), ("value", 480), ("unit", "MWh"),
                                     ("status", "VERIFIED"), ("assurance", "audited")])
def test_shared_figures_semantics_preserved(bundle, key, value):
    bundle["contexts"][1]["numeric_claims"][0][key] = value
    with pytest.raises(ValueError):
        build(bundle, as_of=AS_OF)


@pytest.mark.parametrize("part,key,value", [
    ("entity", "id", "repd:1018"), ("entity", "scope", "site"),
    ("entity", "consolidation_group_id", "group:parent"),
    ("entity", "identity_evidence_url", "https://www.gov.uk/another-project"),
    ("provenance", "document_id", "ferc:different-docket"),
    ("provenance", "sha256", "a" * 64), ("provenance", "page", "2"),
    ("provenance", "section", "Another section"),
    ("provenance", "published_date", "2024-10-31"),
    ("provenance", "retrieved_at", "2026-11-16T17:13:22Z"),
])
def test_cannot_move_figures_between_entities_documents_or_clocks(bundle, part, key, value):
    bundle["contexts"][1]["numeric_claims"][0][part][key] = value
    with pytest.raises(ValueError, match="mismatch"):
        build(bundle, as_of=AS_OF)


@pytest.mark.parametrize("part", ["sources", "contexts"])
def test_duplicate_identifiers_rejected(bundle, part):
    bundle[part].append(deepcopy(bundle[part][0]))
    with pytest.raises(ValueError, match="duplicate"):
        build(bundle, as_of=AS_OF)


def test_no_private_fields_or_implicit_binding_are_passed_through(bundle):
    bundle["contexts"][0]["canonical_project_id"] = "DC-WD-Q123"
    with pytest.raises(ValueError, match="unexpected fields"):
        build(bundle, as_of=AS_OF)


def test_unknown_clock_and_missing_locator_fail_closed(bundle):
    with pytest.raises(ValueError, match="UTC timestamp"):
        build(bundle, as_of="2026-11-16")
    bundle["contexts"][0]["section"] = None
    with pytest.raises(ValueError, match="locator required"):
        build(bundle, as_of=AS_OF)


def test_retrieval_does_not_refresh_the_source_claim(bundle):
    original = build(bundle, as_of=AS_OF)
    newer = "2026-11-16T17:59:00Z"
    bundle["sources"][0]["retrieved_at"] = newer
    replay = build(bundle, as_of=AS_OF)
    assert replay["records"][1]["source_document_age_days"] == original["records"][1]["source_document_age_days"]
    assert replay["records"][1]["current_project_state"] == "UNKNOWN"


def test_exact_value_lexical_precision_is_not_rounded(bundle):
    bundle["contexts"][1]["numeric_claims"][0]["value"] = "480.00"
    result = build(bundle, as_of=AS_OF)
    assert result["records"][0]["numeric_claims"][0]["value"] == "480.00"


@pytest.mark.parametrize("kind,state,quantity,basis", [
    ("connection_offer", "OFFER_REPORTED", "secured_connection", "reported"),
    ("energisation_report", "ENERGISED_REPORTED", "energised_load", "reported"),
    ("grid_upgrade", "PLANNED", "grid_upgrade", "forecast"),
    ("grid_upgrade", "COMMISSIONED_REPORTED", "grid_upgrade", "reported"),
])
def test_synthetic_source_states_do_not_claim_current_connection(bundle, kind, state, quantity, basis):
    # Synthetic schema cases only: these do not reinterpret the real FERC order.
    context = bundle["contexts"][1]
    context["kind"], context["source_state"] = kind, state
    claim = context["numeric_claims"][0]
    claim["quantity_kind"], claim["basis"] = quantity, basis
    record = build(bundle, as_of=AS_OF)["records"][0]
    assert record["source_state"] == state
    assert record["numeric_claims"][0]["quantity_kind"] == quantity
    assert record["current_secured_connection"] is None
    assert record["current_project_state"] == "UNKNOWN"


@pytest.mark.parametrize("state", ["ANNOUNCED", "COMMITTED", "DISBURSED"])
def test_synthetic_funding_keeps_stage_without_allocating_capex(bundle, state):
    context = bundle["contexts"][1]
    context["kind"], context["source_state"] = "funding", state
    claim = context["numeric_claims"][0]
    claim.update(quantity_kind="finance", basis="reported", unit="currency", original_unit="US dollars",
                 currency="USD", finance_stage=state.lower(), value="1.20", scale="1e9")
    record = build(bundle, as_of=AS_OF)["records"][0]
    assert record["numeric_claims"][0]["finance_stage"] == state.lower()
    assert record["site_capex"] is None
    claim["finance_stage"] = "reported"
    with pytest.raises(ValueError, match="finance stage mismatch"):
        build(bundle, as_of=AS_OF)


def test_cli_writes_new_artifact_and_refuses_overwrite(tmp_path):
    output = tmp_path / "grid-context.json"
    command = [sys.executable, "-m", "automation.news.dc_context.grid", "--input", str(FIXTURE),
               "--as-of", AS_OF, "--output", str(output)]
    first = subprocess.run(command, capture_output=True, text=True)
    assert first.returncode == 0, first.stderr
    original = output.read_bytes()
    second = subprocess.run(command, capture_output=True, text=True)
    assert second.returncode != 0
    assert output.read_bytes() == original
    payload = json.loads(original)
    assert payload["context_count"] == 2
    assert payload["numeric_claim_count"] == 1


def test_failed_input_does_not_create_output(tmp_path, bundle):
    bundle["sources"][1]["http_status"] = 403
    source = tmp_path / "broken.json"
    source.write_text(json.dumps(bundle), encoding="utf-8")
    output = tmp_path / "output.json"
    result = subprocess.run([sys.executable, "-m", "automation.news.dc_context.grid", "--input", str(source),
                             "--as-of", AS_OF, "--output", str(output)], capture_output=True, text=True)
    assert result.returncode != 0
    assert not output.exists()

Test Grid Government V938

A test in the tests folder of GlobalGrid2050 that checks Government V938, using SHA-256. It is built from the grid government v938 test class (`GridGovernmentV938Test`).

testglobalgrid2050 / automation/news/tests/test_grid_government_v938.py · lines 1–65 of 65 · Entry point

What it does
It tests its inputs. Defines 6 functions or classes, including GridGovernmentV938Test, test_government_publisher_is_not_reported_operator, test_actual_government_receipts_and_day_clocks_remain_distinct, test_government_clock_rejects_fabricated_midnight_and_impossible_day, test_government_exact_url_hash_receipt_and_attribution_refuse_spoofs. 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 government-sources.v938.json; JSON file fixtures.json; JSON file government-facts.json.
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
V9.38 additive government-fact tests; original donor tests remain byte-exact.
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
Government V938 (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 V934 Preview Acceptance Workflow (workflow run)
Produces
GridGovernmentV938Test
Defines here
GridGovernmentV938Test, test_government_publisher_is_not_reported_operator, test_actual_government_receipts_and_day_clocks_remain_distinct, test_government_clock_rejects_fabricated_midnight_and_impossible_day, test_government_exact_url_hash_receipt_and_attribution_refuse_spoofs, test_one_notice_two_documents_unknown_counts_and_review_gate
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_government_v938.py:1-65 · blob e7efccbc83c5e32b41755b025fa9080527a9a162 · 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
"""V9.38 additive government-fact tests; original donor tests remain byte-exact."""
import json
from copy import deepcopy
from pathlib import Path
import unittest
from automation.news.grid_watch.government_v938 import build_grid_rows, normalise, reviewed_government_notice, FACTS_RIGHTS_SCOPE
HERE = Path(__file__).resolve().parents[1] / "grid_watch"
SOURCES = {s["id"]: s for name in ("sources.json", "government-sources.v938.json") for s in json.loads((HERE / name).read_text())["sources"]}
RECORDS = json.loads((HERE / "fixtures.json").read_text())["records"]
GOV_RECORDS = json.loads((HERE / "government-facts.json").read_text())["records"]

class GridGovernmentV938Test(unittest.TestCase):
    def test_government_publisher_is_not_reported_operator(self):
        rows = build_grid_rows(GOV_RECORDS, SOURCES)
        self.assertEqual(len(rows), 2)
        self.assertEqual({r["evidence"]["publisher"] for r in rows}, {"Planning Inspectorate", "Department for Energy Security and Net Zero"})
        self.assertTrue(all(r["scheme"]["operator"] == "NGET" and r["evidence"]["role"] == "government_authority" for r in rows))
        self.assertTrue(all(r["scheme"]["scheme_key"] is None and not r["publishable"] for r in rows))
        self.assertTrue(all(r["links"]["repd_ref"] is None and r["links"]["grid_connection"] is None and r["links"]["available_capacity_mw"] is None for r in rows))

    def test_actual_government_receipts_and_day_clocks_remain_distinct(self):
        rows = build_grid_rows(GOV_RECORDS, SOURCES)
        for row in rows:
            e = row["evidence"]
            self.assertIsNone(e["published_at"])
            self.assertEqual(e["published_date"], {"value": "2026-10-30", "precision": "DAY"})
            self.assertEqual(e["event_date"], {"value": "2026-10-30", "precision": "DAY"})
            self.assertEqual(e["source_sha256"], e["source_receipt"]["sha256"])
            self.assertEqual(e["source_receipt"]["http_status"], 200)
            self.assertGreater(e["source_receipt"]["bytes"], 60000)
        pins = next(r for r in rows if r["evidence"]["publisher"] == "Planning Inspectorate")
        self.assertEqual(pins["evidence"]["milestones"]["application_submitted"]["value"], "2025-03-27")
        self.assertEqual(pins["evidence"]["milestones"]["accepted_for_examination"]["value"], "2025-04-23")
        self.assertEqual(pins["evidence"]["milestones"]["recommendation"]["value"], "2026-07-30")

    def test_government_clock_rejects_fabricated_midnight_and_impossible_day(self):
        for patch in ({"published_at": "2026-10-30T00:00:00Z"}, {"published_date": {"value": "2026-10-30T00:00:00Z", "precision": "DAY"}}, {"event_date": {"value": "2026-02-30", "precision": "DAY"}}, {"published_date": None}, {"event_date": {"value": "2027-01-01", "precision": "DAY"}}):
            with self.subTest(patch=patch), self.assertRaises(ValueError): normalise(dict(GOV_RECORDS[0], **patch), SOURCES)

    def test_government_exact_url_hash_receipt_and_attribution_refuse_spoofs(self):
        for patch in ({"source_url": "https://www.gov.uk/government/news/unreviewed"}, {"source_url": GOV_RECORDS[0]["source_url"]+"?copy=1"}, {"source_url": "https://www.gov.uk.evil.example/source"}, {"source_sha256": "0"*64}, {"network_operator": "NESO"}, {"source_receipt": {}}):
            with self.subTest(patch=patch), self.assertRaises(ValueError): normalise(dict(GOV_RECORDS[0], **patch), SOURCES)
        for patch in ({"publisher": "NGET"}, {"operator": "NGET"}, {"reported_operators": ["NGET", "NESO"]}):
            sources = deepcopy(SOURCES);sources[GOV_RECORDS[0]["source_id"]].update(patch)
            with self.subTest(source_patch=patch), self.assertRaises(ValueError): normalise(GOV_RECORDS[0], sources)

    def test_one_notice_two_documents_unknown_counts_and_review_gate(self):
        rows = build_grid_rows(GOV_RECORDS, SOURCES);pending = reviewed_government_notice(rows)
        self.assertFalse(pending["publishable"]);self.assertIsNone(pending["notice_count"]);self.assertEqual(pending["document_count"], 2)
        self.assertEqual(pending["facts"]["planned_metric"], {"kind": "planned_transmission_upper_bound", "value": 2000, "unit": "MW"})
        self.assertIsNone(pending["facts"]["current_capacity_mw"]);self.assertIsNone(pending["facts"]["coordinates"])
        # Synthetic review references test the gate; they do not represent actual approval.
        approval = {"state": "APPROVED_FACTS_ONLY", "rights_scope": FACTS_RIGHTS_SCOPE, "facts_sha256": pending["facts_sha256"], "reviews": [{"role": "AGENT_A", "decision": "PASS", "reference": "https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-100"}, {"role": "AGENT_B", "decision": "PASS", "reference": "https://github.com/Ventusltd/neural-link-between-agents/issues/42  … [line shortened here: 421 characters; full line on GitHub]
        self.assertTrue(reviewed_government_notice(rows, approval)["publishable"])
        for patch in ({"rights_scope": "all_gov_content"}, {"facts_sha256": "0"*64}, {"reviews": approval["reviews"][:1]}, {"state": "REVIEW_REQUIRED"}):
            with self.subTest(patch=patch), self.assertRaises(ValueError): reviewed_government_notice(rows, dict(approval, **patch))
        changed = deepcopy(rows);changed[0]["links"]["available_capacity_mw"] = 2000
        with self.assertRaises(ValueError): reviewed_government_notice(changed, approval)
        changed = deepcopy(rows);changed[0]["evidence"]["licence_state"] = "RESTRICTED"
        with self.assertRaises(ValueError): reviewed_government_notice(changed, approval)
        with self.assertRaises(ValueError): reviewed_government_notice(build_grid_rows(RECORDS, SOURCES), approval)


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