GLOBALGRID2050 / EXPLORE CODE

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

Test Evidence Store and 3 more files

A test in the tests folder of GlobalGrid2050 that checks Evidence Store and Match, using SHA-256.

639 lines of Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 804 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 Engine Independent test · globalgrid2050 / automation/news/tests/test_engine_independent.py lines 1–206
  2. Test Events test · globalgrid2050 / automation/news/tests/test_events.py lines 1–97
  3. Test Evidence Publish test · globalgrid2050 / automation/news/tests/test_evidence_publish.py lines 1–74
  4. Test Evidence Store test · globalgrid2050 / automation/news/tests/test_evidence_store.py lines 1–262

Test Engine Independent

A test in the tests folder of GlobalGrid2050 that checks Engine. It is built from the run step (`run`).

testglobalgrid2050 / automation/news/tests/test_engine_independent.py · lines 1–206 of 206 · Entry point

What it does
It tests solar and the REPD register. Defines 19 functions or classes, including run, test_independent_title_only_without_content_or_scores, test_independent_general_market_news_has_no_project_evidence, test_independent_duplicate_title_two_unrelated_urls_are_not_merged, test_independent_tracking_variants_preserve_original_urls_deterministically. Uses libraries __future__, 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, the REPD register.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Independent Agent 3 V9.28 News Engine acceptance: synthetic fixtures only.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Engine (import), __future__, copy, json, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
run, test_independent_title_only_without_content_or_scores, test_independent_general_market_news_has_no_project_evidence, test_independent_duplicate_title_two_unrelated_urls_are_not_merged, test_independent_tracking_variants_preserve_original_urls_deterministically, test_independent_same_url_with_different_publisher_fails_closed, test_independent_ambiguous_repd_name_never_proves_identity, test_independent_non_repd_id_cannot_be_repd_identity, test_independent_explicit_multiple_repd_ids_are_ambiguous_not_verified, test_independent_reject_unsafe_urls, test_independent_source_id_cannot_override_contradictory_source_publisher, test_independent_source_label_cannot_contradict_without_publisher_key
Defines here
run, test_independent_title_only_without_content_or_scores, test_independent_general_market_news_has_no_project_evidence, test_independent_duplicate_title_two_unrelated_urls_are_not_merged, test_independent_tracking_variants_preserve_original_urls_deterministically, test_independent_same_url_with_different_publisher_fails_closed, test_independent_ambiguous_repd_name_never_proves_identity, test_independent_non_repd_id_cannot_be_repd_identity, test_independent_explicit_multiple_repd_ids_are_ambiguous_not_verified, test_independent_reject_unsafe_urls, test_independent_source_id_cannot_override_contradictory_source_publisher, test_independent_source_label_cannot_contradict_without_publisher_key, test_independent_invalid_publisher_dates_fail_closed, test_independent_missing_dates_remain_null, test_independent_bad_hashes_fail_closed, test_independent_rights_assertion_does_not_authorise_publication, test_independent_publisher_body_cannot_create_repd_id, test_independent_invalid_observation_timestamps_fail_closed, test_independent_valid_iso_date_and_timezone_preserved_verbatim
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/tests/test_engine_independent.py:1-206 · blob 118d93b6d04103653f71779238074d428272e383 · 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
"""Independent Agent 3 V9.28 News Engine acceptance: synthetic fixtures only.

Run against the exact PR #130 source on an isolated branch. No network, real
publisher extraction, rights acceptance, source activation or public output.
"""
from __future__ import annotations

import copy
import json

import pytest

from automation.news.engine import build_intelligence, canonical_url


SOURCE = {
    "id": "fixture_press",
    "publisher": "Fixture Press",
    "kind": "reporting",
    "rights_status": "unknown",
    "enabled": False,
    "output_policy": "headline_link_only",
}
ARTICLE = {
    "url": "https://press.example.org/news/solar?utm_campaign=test",
    "title": "East Meadow Solar Farm moves to planning",
    "source_id": "fixture_press",
    "source": "Fixture Press",
    "publisher": "Fixture Press",
    "pub_date": "2026-11-16T08:00:00Z",
    "first_seen": "2026-11-16T09:00:00Z",
    "fetched_at": "2026-11-16T09:05:00Z",
    "source_receipt_sha256": "a" * 64,
    "content": "REPD 2002 invented body text must not become a match",
    "importance_score": 1.0,
    "ranking_score": 99999,
    "score": 12,
    "priority": 1,
    "rank": 1,
}
PROJECTS = [
    {"id": "1018", "name": "East Meadow Solar Farm", "technology": "solar"},
    {"id": "2002", "name": "A Different Solar Farm", "technology": "solar"},
]


def run(items=None, sources=None, projects=None):
    return build_intelligence(
        [copy.deepcopy(ARTICLE)] if items is None else items,
        [copy.deepcopy(SOURCE)] if sources is None else sources,
        copy.deepcopy(PROJECTS) if projects is None else projects,
    )


def test_independent_title_only_without_content_or_scores():
    out = run()
    assert out["counts"] == {
        "articles": 1, "provisional_project_edges": 1,
        "verified_project_edges": 0, "rights_unresolved_articles": 1,
    }
    row = out["articles"][0]
    assert [e["id"] for e in row["project_candidates"]] == ["1018"]
    assert row["project_candidates"][0]["status"] == "PROVISIONAL"
    assert row["publisher_independence"] == "UNASSESSED"
    assert row["publication_eligibility"] == "WITHHELD_INDEPENDENT_REVIEW_REQUIRED"
    serialised = json.dumps(out)
    assert "invented body text" not in serialised
    for forbidden in ("importance_score", "ranking_score", '"score"', '"priority"', '"rank"'):
        assert forbidden not in serialised


def test_independent_general_market_news_has_no_project_evidence():
    market = {**ARTICLE, "title": "UK solar industry investment rises"}
    out = run(items=[market])
    assert out["articles"][0]["project_candidates"] == []
    assert out["counts"]["provisional_project_edges"] == 0
    assert out["counts"]["verified_project_edges"] == 0


def test_independent_duplicate_title_two_unrelated_urls_are_not_merged():
    first = copy.deepcopy(ARTICLE)
    second = {**ARTICLE, "url": "https://other.example.org/news/solar"}
    out = run(items=[first, second])
    assert out["counts"]["articles"] == 2
    assert out["counts"]["verified_project_edges"] == 0


def test_independent_tracking_variants_preserve_original_urls_deterministically():
    a = copy.deepcopy(ARTICLE)
    b = {**ARTICLE, "url": "https://press.example.org/news/solar?utm_medium=email"}
    forward = run(items=[a, b])
    reverse = run(items=[b, a])
    assert forward == reverse
    assert forward["counts"]["articles"] == 1
    assert forward["articles"][0]["observed_article_urls"] == sorted([a["url"], b["url"]])


def test_independent_same_url_with_different_publisher_fails_closed():
    other_source = {**SOURCE, "id": "other", "publisher": "Other Outlet"}
    mismatched = {**ARTICLE, "source_id": "other", "publisher": "Other Outlet", "source": "Other Outlet"}
    with pytest.raises(ValueError, match="collision"):
        run(items=[ARTICLE, mismatched], sources=[SOURCE, other_source])


def test_independent_ambiguous_repd_name_never_proves_identity():
    projects = PROJECTS + [{"id": "3000", "name": "East Meadow Solar Farm"}]
    out = run(projects=projects)
    assert out["counts"]["provisional_project_edges"] == 0
    assert out["counts"]["verified_project_edges"] == 0


def test_independent_non_repd_id_cannot_be_repd_identity():
    out = run(projects=[{"id": "dc-001", "name": "East Meadow Solar Farm", "namespace": "datacentre"}])
    assert out["counts"]["provisional_project_edges"] == 0


def test_independent_explicit_multiple_repd_ids_are_ambiguous_not_verified():
    item = {**ARTICLE, "title": "REPD 1018 and REPD 2002 planning update"}
    out = run(items=[item])
    assert out["counts"]["provisional_project_edges"] == 2
    assert out["counts"]["verified_project_edges"] == 0
    assert all(e.get("ambiguous_multi_project") for e in out["articles"][0]["project_candidates"])


@pytest.mark.parametrize("value", [
    "http://press.example.org/news", "https://localhost/local", "https://127.0.0.1/news",
    "https://user@press.example.org/news", "https://press.example.org:8080/news",
])
def test_independent_reject_unsafe_urls(value):
    with pytest.raises(ValueError):
        canonical_url(value)


def test_independent_source_id_cannot_override_contradictory_source_publisher():
    """REGRESSION: valid source_id must not conceal another publisher in source."""
    bad = {**ARTICLE, "source": "Other Outlet"}
    with pytest.raises(ValueError, match="attribution"):
        run(items=[bad])


def test_independent_source_label_cannot_contradict_without_publisher_key():
    bad = {**ARTICLE, "source": "Other Outlet"}
    del bad["publisher"]
    with pytest.raises(ValueError, match="attribution"):
        run(items=[bad])


@pytest.mark.parametrize("bad", ["not-a-date", "2026-02-30", "2026-13-17", "2026-11-16T35:00:00Z"])
def test_independent_invalid_publisher_dates_fail_closed(bad):
    """Bad dates must not masquerade as accepted publication times."""
    with pytest.raises(ValueError, match="timestamp"):
        run(items=[{**ARTICLE, "pub_date": bad}])


def test_independent_missing_dates_remain_null():
    item = copy.deepcopy(ARTICLE)
    for key in ("pub_date", "first_seen", "fetched_at"):
        item.pop(key)
    row = run(items=[item])["articles"][0]
    assert row["published_at"] is None
    assert row["first_seen"] is None
    assert row["fetched_at"] is None


@pytest.mark.parametrize("bad", ["abc", "A" * 64, 12, None])
def test_independent_bad_hashes_fail_closed(bad):
    item = {**ARTICLE, "source_receipt_sha256": bad}
    if bad is None:
        # An absent receipt is allowed as unknown, so test explicit null separately.
        assert run(items=[item])["articles"][0]["source_receipt_sha256"] is None
    else:
        with pytest.raises(ValueError, match="receipt"):
            run(items=[item])


def test_independent_rights_assertion_does_not_authorise_publication():
    source = {**SOURCE, "rights_status": "accepted", "enabled": True,
              "rights_review_url": "https://publisher.example.org/rights"}
    row = run(sources=[source])["articles"][0]
    assert row["publication_eligibility"].startswith("WITHHELD")
    assert row["usage_rights"]["status"] == "accepted"
    assert row["verification_status"] == "NOT_VERIFIED"


def test_independent_publisher_body_cannot_create_repd_id():
    item = {**ARTICLE, "title": "Industry capacity outlook in Britain",
            "content": "REPD reference 1018 and named East Meadow Solar Farm"}
    assert run(items=[item])["counts"]["provisional_project_edges"] == 0


@pytest.mark.parametrize("field,bad", [
    ("first_seen", "yesterday"), ("first_seen", "2026-11-31T14:00:00Z"),
    ("fetched_at", "2026-14-01"), ("fetched_at", "2026-11-16T27:00:00Z"),
])
def test_independent_invalid_observation_timestamps_fail_closed(field, bad):
    with pytest.raises(ValueError, match="timestamp"):
        run(items=[{**ARTICLE, field: bad}])


def test_independent_valid_iso_date_and_timezone_preserved_verbatim():
    out = run(items=[{**ARTICLE, "pub_date": "2026-11-16",
                      "first_seen": "2026-11-16T12:00:00+00:00"}])
    row = out["articles"][0]
    assert row["published_at"] == "2026-11-16"
    assert row["first_seen"] == "2026-11-16T12:00:00+00:00"
    assert row["verification_status"] == "NOT_VERIFIED"

Test Events

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

testglobalgrid2050 / automation/news/tests/test_events.py · lines 1–97 of 97 · Entry point

What it does
It tests solar. Defines 12 functions or classes, including _build, _by, test_every_status_event_type, test_capacity_operator_technology_changes, test_cosmetic_operator_change_not_emitted. Uses libraries json.
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 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Defines `test_every_status_event_type`, `test_capacity_operator_technology_changes`, `test_cosmetic_operator_change_not_emitted` and 7 more. Its code works with 400 MW.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Events (import), json
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
test_every_status_event_type, test_capacity_operator_technology_changes, test_cosmetic_operator_change_not_emitted, test_unknown_capacity_is_null_never_zero, test_headline_is_from_data_only, test_event_dates_from_milestone_columns, test_colocated_siblings_share_group, test_large_application_threshold, test_deterministic_ids_and_bytes, test_classify_status_ladder
Defines here
_build, _by, test_every_status_event_type, test_capacity_operator_technology_changes, test_cosmetic_operator_change_not_emitted, test_unknown_capacity_is_null_never_zero, test_headline_is_from_data_only, test_event_dates_from_milestone_columns, test_colocated_siblings_share_group, test_large_application_threshold, test_deterministic_ids_and_bytes, test_classify_status_ladder
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_events.py:1-97 · blob 59b332e98dbe56824e0c2652c7f8ffd9cc7d9172 · 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
import json

from automation.news import events as E


def _build(releases, **kw):
    old, new = E.load_pair(*releases)
    return E.build_events(old, new, "prev", "new", **kw)


def _by(doc):
    out = {}
    for ev in doc["events"]:
        out.setdefault((ev["ref"], ev["event_type"]), ev)
    return out


def test_every_status_event_type(releases):
    by = _by(_build(releases))
    assert ("1", "CONSENTED") in by and ("2", "CONSENTED") in by
    assert ("3", "CONSTRUCTION_STARTED") in by
    assert ("4", "OPERATIONAL") in by
    assert ("5", "REFUSED") in by
    assert ("6", "WITHDRAWN") in by
    assert ("7", "STATUS_REVERSAL") in by
    assert ("12", "LAPSED_OR_REVISED") in by
    assert ("9", "REMOVED_FROM_REGISTER") in by
    assert ("20", "NEW_LARGE_APPLICATION") in by
    assert ("21", "NEW_APPLICATION") in by
    assert ("22", "CONSENTED") in by and by[("22", "CONSENTED")]["basis"] == "new_record"
    assert ("23", "NEW_RECORD") in by


def test_capacity_operator_technology_changes(releases):
    by = _by(_build(releases))
    cap = by[("8", "CAPACITY_CHANGE")]["change"]
    assert cap == {"old_mw": 50.0, "new_mw": 57.0, "delta_mw": 7.0, "kind": "revised"}
    stated = by[("10", "CAPACITY_CHANGE")]["change"]
    assert stated["old_mw"] is None and stated["new_mw"] == 30.0 and stated["kind"] == "stated"
    assert by[("8", "OPERATOR_CHANGE")]["change"]["new_operator"] == "New Owner Plc"
    assert by[("11", "TECHNOLOGY_CHANGE")]["change"] == {"old_technology": "Solar Photovoltaics", "new_technology": "Battery"}


def test_cosmetic_operator_change_not_emitted(releases):
    doc = _build(releases)
    assert ("6", "OPERATOR_CHANGE") not in _by(doc)
    assert doc["operator_cosmetic_changes_not_emitted"] == 1


def test_unknown_capacity_is_null_never_zero(releases):
    doc = _build(releases)
    india = [e for e in doc["events"] if e["ref"] == "10"]
    assert all(e["previous_capacity_mw"] is None for e in india)
    assert "capacity not stated" not in india[0]["headline"] or india[0]["capacity_mw"] is None


def test_headline_is_from_data_only(releases):
    by = _by(_build(releases))
    h = by[("1", "CONSENTED")]["headline"]
    assert h == "Consented: Alpha Fen Solar Farm, 400 MW solar, Lincolnshire (REPD 1); previously Application Submitted"
    assert by[("7", "STATUS_REVERSAL")]["headline"].endswith("moved from Awaiting Construction back to Application Submitted")
    assert "first listed in this release" in by[("20", "NEW_LARGE_APPLICATION")]["headline"]


def test_event_dates_from_milestone_columns(releases):
    by = _by(_build(releases))
    assert by[("1", "CONSENTED")]["event_date"] == "2026-09-15"
    assert by[("1", "CONSENTED")]["event_date_source"] == "Planning Permission Granted"
    assert by[("3", "CONSTRUCTION_STARTED")]["event_date"] == "2026-09-20"
    assert by[("7", "STATUS_REVERSAL")]["event_date"] is None


def test_colocated_siblings_share_group(releases):
    by = _by(_build(releases))
    assert by[("1", "CONSENTED")]["group_key"] == by[("2", "CONSENTED")]["group_key"] == "DEV-1"
    assert by[("1", "CONSENTED")]["sibling_refs_same_event"] == ["2"]


def test_large_application_threshold(releases):
    by = _by(_build(releases, large_application_mw=1000))
    assert ("20", "NEW_APPLICATION") in by


def test_deterministic_ids_and_bytes(releases):
    a = json.dumps(_build(releases), sort_keys=True)
    b = json.dumps(_build(releases), sort_keys=True)
    assert a == b
    ids = [e["event_id"] for e in _build(releases)["events"]]
    assert len(ids) == len(set(ids))


def test_classify_status_ladder():
    assert E.classify_status("Under Construction", "Awaiting Construction") == ["STATUS_REVERSAL"]
    assert E.classify_status("Operational", "Decommissioned") == ["DECOMMISSIONED"]
    assert E.classify_status("Application Refused", "Awaiting Construction") == ["CONSENTED"]
    assert E.classify_status("Application Submitted", "Appeal Lodged") == ["APPEAL_LODGED"]
    assert E.classify_status("Awaiting Construction", None) == ["REMOVED_FROM_REGISTER"]

Test Evidence Publish

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

testglobalgrid2050 / automation/news/tests/test_evidence_publish.py · lines 1–74 of 74 · Entry point · pattern repos (shared by 4 files)

What it does
It tests its inputs. Defines 7 functions or classes, including git, repos, commit, test_create_and_direct_successor, test_concurrent_rollback_is_not_undone. Uses libraries subprocess, pytest. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Defines `git`, `repos`, `commit` 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
Publish (import), subprocess, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
git, repos, commit, test_create_and_direct_successor, test_concurrent_rollback_is_not_undone, test_concurrent_creation_rejected, test_non_descendant_never_reaches_push
Defines here
git, repos, commit, test_create_and_direct_successor, test_concurrent_rollback_is_not_undone, test_concurrent_creation_rejected, test_non_descendant_never_reaches_push
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_evidence_publish.py:1-74 · blob 32c5a73d145f724c21edba46f15e0273e96412a7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Real local bare-repo races: no network and no production refs."""
import subprocess

import pytest

from automation.news.acquisition.publish import REF, publish


def git(folder, *args):
    return subprocess.run(["git", "-C", str(folder), *args], check=True,
                          capture_output=True, text=True).stdout.strip()


@pytest.fixture
def repos(tmp_path):
    remote, writer = tmp_path / "remote.git", tmp_path / "writer"
    git(tmp_path, "init", "--bare", str(remote))
    git(tmp_path, "init", str(writer))
    git(writer, "config", "user.name", "Synthetic test")
    git(writer, "config", "user.email", "test@example.invalid")
    git(writer, "remote", "add", "origin", str(remote))
    return remote, writer


def commit(writer, label):
    (writer / "evidence.txt").write_text(label)
    git(writer, "add", ".")
    git(writer, "commit", "-m", label)
    return git(writer, "rev-parse", "HEAD")


def test_create_and_direct_successor(repos):
    remote, writer = repos
    first = commit(writer, "initial")
    publish(writer, "")
    second = commit(writer, "weekly")
    publish(writer, first)
    assert git(remote, "rev-parse", REF) == second


def test_concurrent_rollback_is_not_undone(repos):
    remote, writer = repos
    first = commit(writer, "initial")
    publish(writer, "")
    restored = commit(writer, "restored-state")
    publish(writer, first)
    commit(writer, "new-snapshot")
    git(remote, "update-ref", REF, first, restored)  # concurrent owner's rollback
    with pytest.raises(subprocess.CalledProcessError):
        publish(writer, restored)
    assert git(remote, "rev-parse", REF) == first


def test_concurrent_creation_rejected(repos):
    remote, writer = repos
    first = commit(writer, "initial")
    publish(writer, "")
    with pytest.raises(subprocess.CalledProcessError):
        # A different newly-created root cannot replace an existing branch.
        git(writer, "checkout", "--orphan", "other-root")
        commit(writer, "other")
        publish(writer, "")
    assert git(remote, "rev-parse", REF) == first


def test_non_descendant_never_reaches_push(repos):
    remote, writer = repos
    first = commit(writer, "initial")
    publish(writer, "")
    commit(writer, "middle")
    commit(writer, "latest")
    with pytest.raises(ValueError, match="direct successor"):
        publish(writer, first)
    assert git(remote, "rev-parse", REF) == first

Test Evidence Store

A test in the tests folder of GlobalGrid2050 that checks Evidence Store and Match, using SHA-256.

testglobalgrid2050 / automation/news/tests/test_evidence_store.py · lines 1–262 of 262 · Entry point · pattern projects (shared by 4 files)

What it does
It tests solar. Defines 16 functions or classes, including projects, articles, sources, matches, test_database_is_durable_idempotent_and_has_no_bodies. Uses libraries copy, csv, hashlib, json, sqlite3. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
Inputs & outputs
In: JSON file latest.json; SQLite database.
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 projects step (`projects`), the articles step (`articles`) and the sources step (`sources`). Acquisition storage gates: immutable scope, provisional status and publication.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Evidence Store (import), Match (import), copy, csv, hashlib, json, sqlite3, pathlib, sys, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
projects, articles, sources, matches, test_database_is_durable_idempotent_and_has_no_bodies, test_no_evidence_row_replaced_when_match_found, test_invalid_run_fails_without_mutating_store, test_seed_metadata_cannot_drift, test_database_blocks_verified_and_unknown_schema, test_immutable_exports_roundtrip_and_pointer, test_schema_failure_keeps_previous_pointer, test_csv_neutralizes_untrusted_formulas
Defines here
projects, articles, sources, matches, test_database_is_durable_idempotent_and_has_no_bodies, test_no_evidence_row_replaced_when_match_found, test_invalid_run_fails_without_mutating_store, test_seed_metadata_cannot_drift, test_database_blocks_verified_and_unknown_schema, test_immutable_exports_roundtrip_and_pointer, test_schema_failure_keeps_previous_pointer, test_csv_neutralizes_untrusted_formulas, test_no_successful_run_cannot_export, test_changed_article_is_rejected_before_state_or_exports_change, test_existing_snapshot_bytes_cannot_be_overwritten, test_snapshot_rejects_evidence_without_accepted_source_receipt
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_evidence_store.py:1-262 · blob 4ee5563e1cbe792a576333dfba7e621bf429fd28 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Acquisition storage gates: immutable scope, provisional status and publication."""
import copy
import csv
import hashlib
import json
import sqlite3
from pathlib import Path
import sys

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from automation.news.acquisition.evidence_store import (
    EvidenceStore, EvidenceValidationError, NO_EVIDENCE, PROVISIONAL,
    export_snapshot, validate_snapshot,
)

NOW = "2026-11-16T16:00:00Z"
LATER = "2026-11-23T16:00:00Z"


@pytest.fixture
def projects():
    return [{"id": str(i), "name": f"Project {i}", "latitude": 52.1 if i == 1000 else None,
             "longitude": -1.2 if i == 1000 else None} for i in range(1000, 2000)]


@pytest.fixture
def articles():
    return [{"id": "article1", "url": "https://www.pv-magazine.com/example/",
             "title": "Project 1000 solar plans", "pub_date": "2026-11-15T10:00:00Z",
             "source_id": "pv_magazine_global", "publisher": "PV Magazine",
             "content": "This transient snippet must never reach SQLite or published exports."}]


@pytest.fixture
def sources():
    return [{"id": "pv_magazine_global", "status": "ok", "url": "https://www.pv-magazine.com/feed/",
             "fetched_at": NOW, "response_sha256": "a" * 64, "http_status": 200,
             "eligible_for_publication": True, "probe_only": False, "rights_status": "accepted",
             "rights_review_url": "https://fixtures.example/synthetic-rights-review"}]


def matches(articles):
    return [{"project_id": "1000", "article_url": articles[0]["url"],
             "status": PROVISIONAL, "match_method": "exact_name"}]


def test_database_is_durable_idempotent_and_has_no_bodies(tmp_path, projects, articles, sources):
    db = tmp_path / "state.sqlite"
    with EvidenceStore(db) as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        store.record_run(projects, articles, matches(articles), NOW, sources)
        assert store.connection.execute("SELECT count(*) FROM projects").fetchone()[0] == 1000
        assert store.connection.execute("SELECT count(*) FROM articles").fetchone()[0] == 1
        assert store.connection.execute("SELECT count(*) FROM evidence").fetchone()[0] == 1000
        assert store.connection.execute("SELECT count(*) FROM evidence WHERE status=?", (NO_EVIDENCE,)).fetchone()[0] == 999
    assert b"This transient snippet" not in db.read_bytes()
    with EvidenceStore(db) as store:
        # Feed rotation must not erase a match discovered last week.
        store.record_run(projects, [], [], LATER, [{**sources[0], "fetched_at": LATER}])
        snapshot = validate_snapshot(store.snapshot(), [p["id"] for p in projects])
        assert snapshot["evidence_count"] == 1
        assert snapshot["projects"][0]["evidence"][0]["first_seen"] == NOW
        assert {key: snapshot["projects"][0]["evidence"][0][key]
                for key in ("id", "title", "pub_date", "source_id", "publisher")} == {
                    key: articles[0][key] for key in ("id", "title", "pub_date", "source_id", "publisher")}
        assert snapshot["projects"][0]["last_researched_at"] == LATER


def test_no_evidence_row_replaced_when_match_found(projects, articles, sources):
    with EvidenceStore() as store:
        store.record_run(projects, articles, [], NOW, sources)
        store.record_run(projects, articles, matches(articles), LATER, sources)
        rows = store.connection.execute("SELECT * FROM evidence WHERE project_id='1000'").fetchall()
        assert len(rows) == 1 and rows[0]["status"] == PROVISIONAL


@pytest.mark.parametrize("mutation", [
    lambda p, a, m, s: m[0].update(status="VERIFIED"),
    lambda p, a, m, s: m[0].update(project_id="999999"),
    lambda p, a, m, s: m[0].update(article_url="https://elsewhere.example/unfetched"),
    lambda p, a, m, s: m[0].update(match_method="fuzzy"),
    lambda p, a, m, s: s[0].update(status="failed"),
    lambda p, a, m, s: s[0].update(response_sha256=""),
    lambda p, a, m, s: s[0].update(eligible_for_publication=False),
    lambda p, a, m, s: s[0].update(probe_only=True),
    lambda p, a, m, s: s[0].update(rights_status="unknown"),
    lambda p, a, m, s: s[0].update(rights_review_url=None),
    lambda p, a, m, s: a[0].update(url="javascript:alert(1)"),
    lambda p, a, m, s: a[0].update(pub_date="not a date"),
    lambda p, a, m, s: p.pop(),
    lambda p, a, m, s: p[0].update(latitude=float("nan")),
])
def test_invalid_run_fails_without_mutating_store(projects, articles, sources, mutation):
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        before = store.snapshot()
        match = matches(articles)
        mutation(projects, articles, match, sources)
        with pytest.raises(EvidenceValidationError):
            store.record_run(projects, articles, match, LATER, sources)
        assert store.snapshot() == before


def test_seed_metadata_cannot_drift(projects, articles, sources):
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        projects[0]["name"] = "Changed identity"
        with pytest.raises(EvidenceValidationError, match="metadata changed"):
            store.record_run(projects, articles, matches(articles), LATER, sources)


def test_database_blocks_verified_and_unknown_schema(tmp_path, projects, articles, sources):
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        with pytest.raises(sqlite3.IntegrityError):
            store.connection.execute("UPDATE evidence SET status='VERIFIED' WHERE project_id='1000'")
    path = tmp_path / "bad.sqlite"
    with sqlite3.connect(path) as db:
        db.execute("PRAGMA user_version=9")
    with pytest.raises(EvidenceValidationError, match="Unsupported"):
        EvidenceStore(path)


def test_immutable_exports_roundtrip_and_pointer(tmp_path, projects, articles, sources):
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        ids = [p["id"] for p in projects]
        pointer = export_snapshot(store, tmp_path, expected_project_ids=ids)
        assert json.loads((tmp_path / "latest.json").read_text()) == pointer
        snapshot = json.loads((tmp_path / pointer["json"]).read_text())
        validate_snapshot(snapshot, ids)
        for filename, digest in pointer["sha256"].items():
            assert hashlib.sha256((tmp_path / pointer["snapshot"] / filename).read_bytes()).hexdigest() == digest
        with (tmp_path / pointer["csv"]).open(newline="") as handle:
            rows = list(csv.DictReader(handle))
        assert len(rows) == 1000 and rows[0]["provisional_count"] == "1"
        geojson = json.loads((tmp_path / pointer["geojson"]).read_text())
        assert len(geojson["features"]) == 1000
        assert geojson["features"][0]["geometry"]["coordinates"] == [-1.2, 52.1]
        assert geojson["features"][1]["geometry"] is None
        assert "content" not in snapshot["projects"][0]["evidence"][0]
        assert snapshot["projects"][0]["last_event"] is None
        # An identical invocation safely reproduces the same immutable artifact.
        assert export_snapshot(store, tmp_path, expected_project_ids=ids) == pointer
        previous = (tmp_path / "latest.json").read_bytes()
        articles[0]["title"] = "Changed article title"
        with pytest.raises(EvidenceValidationError, match="Stored article metadata changed"):
            store.record_run(projects, articles, matches(articles), NOW, sources)
        assert (tmp_path / "latest.json").read_bytes() == previous


@pytest.mark.parametrize("mutation", [
    lambda x: x.update(schema="wrong"),
    lambda x: x.update(verified_count=1),
    lambda x: x.update(project_count=True),
    lambda x: x.update(evidence_count=2),
    lambda x: x["projects"][0].update(status="VERIFIED"),
    lambda x: x["projects"][0].update(project_id="9999"),
    lambda x: x["projects"][0].update(last_event="planning approved"),
    lambda x: x["projects"][0]["evidence"][0].update(content="body"),
    lambda x: x["sources"][0].update(status="failed"),
    lambda x: x["sources"][0].update(rights_status="unknown"),
    lambda x: x["sources"][0].update(probe_only=True),
])
def test_schema_failure_keeps_previous_pointer(tmp_path, projects, articles, sources, mutation, monkeypatch):
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        ids = [p["id"] for p in projects]
        export_snapshot(store, tmp_path, expected_project_ids=ids)
        previous = (tmp_path / "latest.json").read_bytes()
        payload = copy.deepcopy(store.snapshot(LATER))
        mutation(payload)
        monkeypatch.setattr(store, "snapshot", lambda timestamp=None: payload)
        with pytest.raises(EvidenceValidationError):
            export_snapshot(store, tmp_path, LATER, expected_project_ids=ids)
        assert (tmp_path / "latest.json").read_bytes() == previous
        assert len(list(tmp_path.glob("snapshot_*"))) == 1


def test_csv_neutralizes_untrusted_formulas(tmp_path, projects, articles, sources):
    projects[0]["name"] = "=HYPERLINK(\"https://malicious.example\")"
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        pointer = export_snapshot(store, tmp_path, expected_project_ids=[p["id"] for p in projects])
        with (tmp_path / pointer["csv"]).open(newline="") as handle:
            rows = list(csv.DictReader(handle))
        assert rows[0]["name"].startswith("'=")


def test_no_successful_run_cannot_export(tmp_path, projects):
    with EvidenceStore() as store:
        with pytest.raises(EvidenceValidationError, match="No successful"):
            export_snapshot(store, tmp_path, expected_project_ids=[p["id"] for p in projects])
    assert not (tmp_path / "latest.json").exists()


@pytest.mark.parametrize("field,value", [
    ("id", "replacement-article-id"),
    ("title", "Project 1001 solar plans"),
    ("pub_date", "2026-11-22T10:00:00Z"),
    ("source_id", "replacement_source"),
    ("publisher", "Replacement publisher"),
])
def test_changed_article_is_rejected_before_state_or_exports_change(
        tmp_path, projects, articles, sources, field, value):
    from automation.news.acquisition.match import match_articles

    database = tmp_path / "state.sqlite"
    with EvidenceStore(database) as store:
        store.record_run(projects, articles, match_articles(articles, projects), NOW, sources)
        ids = [p["id"] for p in projects]
        export_snapshot(store, tmp_path, expected_project_ids=ids)
        before = {str(path.relative_to(tmp_path)): path.read_bytes()
                  for path in tmp_path.rglob("*") if path.is_file()}
        previous_snapshot = store.snapshot()
        changed = [{**articles[0], field: value}]
        receipts = copy.deepcopy(sources)
        if field == "source_id":
            # The replacement has a valid receipt, isolating metadata immutability
            # from the independent requirement to have an accepted source.
            receipts.append({**sources[0], "id": value})
        changed_matches = match_articles(changed, projects)
        if field == "title":
            assert [m["project_id"] for m in changed_matches] == ["1001"]
        with pytest.raises(EvidenceValidationError, match="Stored article metadata changed"):
            store.record_run(projects, changed, changed_matches, LATER, receipts)
        assert store.snapshot() == previous_snapshot
        assert {str(path.relative_to(tmp_path)): path.read_bytes()
                for path in tmp_path.rglob("*") if path.is_file()} == before


def test_existing_snapshot_bytes_cannot_be_overwritten(tmp_path, projects, articles, sources):
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        ids = [p["id"] for p in projects]
        pointer = export_snapshot(store, tmp_path, expected_project_ids=ids)
        previous = (tmp_path / "latest.json").read_bytes()
        target = tmp_path / pointer["json"]
        target.write_bytes(b"Synthetic conflicting snapshot bytes")
        with pytest.raises(EvidenceValidationError, match="Immutable snapshot"):
            export_snapshot(store, tmp_path, expected_project_ids=ids)
        assert target.read_bytes() == b"Synthetic conflicting snapshot bytes"
        assert (tmp_path / "latest.json").read_bytes() == previous


def test_snapshot_rejects_evidence_without_accepted_source_receipt(
        tmp_path, projects, articles, sources, monkeypatch):
    with EvidenceStore() as store:
        store.record_run(projects, articles, matches(articles), NOW, sources)
        ids = [p["id"] for p in projects]
        export_snapshot(store, tmp_path, expected_project_ids=ids)
        before = {str(path.relative_to(tmp_path)): path.read_bytes()
                  for path in tmp_path.rglob("*") if path.is_file()}
        payload = copy.deepcopy(store.snapshot(LATER))
        payload["projects"][0]["evidence"][0]["source_id"] = "no-accepted-source-receipt"
        monkeypatch.setattr(store, "snapshot", lambda timestamp=None: payload)
        with pytest.raises(EvidenceValidationError, match="Article has no successful source receipt"):
            export_snapshot(store, tmp_path, expected_project_ids=ids)
        assert {str(path.relative_to(tmp_path)): path.read_bytes()
                for path in tmp_path.rglob("*") if path.is_file()} == before