GLOBALGRID2050 / EXPLORE CODE

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

Test Acquisition and 3 more files

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

549 lines of Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 801 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. Conftest test · globalgrid2050 / automation/news/tests/conftest.py lines 1–92
  2. News Engine Acceptance Demo test · globalgrid2050 / automation/news/tests/news_engine_acceptance_demo.py lines 1–73
  3. Test Acquisition test · globalgrid2050 / automation/news/tests/test_acquisition.py lines 1–204
  4. Test Acquisition Analytics test · globalgrid2050 / automation/news/tests/test_acquisition_analytics.py lines 1–180

Conftest

A Python module in the tests folder of GlobalGrid2050 that tests prev, solar, wind and the Renewable Energy Planning Database (REPD) register.

testglobalgrid2050 / automation/news/tests/conftest.py · lines 1–92 of 92 · Entry point · pattern releases (shared by 4 files)

What it does
It tests prev, solar, wind and the REPD register. Defines row, write_csv, releases. Uses libraries __future__, csv, sys, pathlib, pytest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, wind, the REPD register.
Inputs & outputs
In: CSV file prev.csv; CSV file new.csv.
Downstream impact
Used directly by 3 files: Test Binder (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It writes CSV (`write_csv`) and is built from the row step (`row`) and the releases step (`releases`). Shared fixtures for automation/news tests. Synthetic REPD releases; no network. It writes `prev.csv`.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow. Checked by Test Binder.
Application
globalgrid2050 · automation/news/tests · Python module
Uses
__future__, csv, sys, pathlib, pytest
Used by
imported by Test Binder (import), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
row, write_csv, releases
Defines here
row, write_csv, releases
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/conftest.py:1-92 · blob 2159c30a04455a364a13be8f0208be1880413ca0 · 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
"""Shared fixtures for automation/news tests. Synthetic REPD releases; no network."""
from __future__ import annotations

import csv
import sys
from pathlib import Path

import pytest

REPO = Path(__file__).resolve().parents[3]
if str(REPO) not in sys.path:
    sys.path.insert(0, str(REPO))

COLUMNS = [
    "Old Ref ID", "Ref ID", "Record Last Updated (dd/mm/yyyy)", "Operator (or Applicant)", "Site Name",
    "Technology Type", "Storage Co-location REPD Ref ID", "Installed Capacity (MWelec)",
    "Development Status", "Development Status (short)", "County", "Region", "Country", "Planning Authority",
    "Planning Application Reference", "Planning Application Submitted", "Planning Application Withdrawn",
    "Planning Permission Refused", "Appeal Lodged", "Appeal Withdrawn", "Appeal Refused", "Appeal Granted",
    "Planning Permission  Granted", "Secretary of State - Refusal", "Secretary of State - Granted",
    "Planning Permission Expired", "Under Construction", "Operational",
]


def row(ref, site, tech, mw, status, *, operator="Example Energy Ltd", county="Lincolnshire",
        region="East Midlands", country="England", authority="North Kesteven", pref="", coloc="",
        updated="01/10/2026", **dates):
    r = {c: "" for c in COLUMNS}
    r.update({"Ref ID": str(ref), "Site Name": site, "Technology Type": tech,
              "Installed Capacity (MWelec)": "" if mw is None else str(mw), "Development Status (short)": status,
              "Development Status": status, "Operator (or Applicant)": operator, "County": county,
              "Region": region, "Country": country, "Planning Authority": authority,
              "Planning Application Reference": pref, "Storage Co-location REPD Ref ID": coloc,
              "Record Last Updated (dd/mm/yyyy)": updated})
    key = {"granted": "Planning Permission  Granted", "submitted": "Planning Application Submitted",
           "refused": "Planning Permission Refused", "uc": "Under Construction", "op": "Operational",
           "withdrawn": "Planning Application Withdrawn", "appeal": "Appeal Lodged"}
    for k, v in dates.items():
        r[key[k]] = v
    return r


def write_csv(path: Path, rows) -> Path:
    with path.open("w", newline="", encoding="utf-8-sig") as f:
        w = csv.DictWriter(f, fieldnames=COLUMNS)
        w.writeheader()
        for r in rows:
            w.writerow(r)
    return path


PREVIOUS = [
    row(1, "Alpha Fen Solar Farm", "Solar Photovoltaics", 400, "Application Submitted", submitted="01/02/2025",
        authority="The Planning Inspectorate - National Infrastructure", pref="EN010999", coloc="2"),
    row(2, "Alpha Fen Solar Farm", "Battery", 600, "Application Submitted", coloc="1"),
    row(3, "Bravo Lane - Battery Storage", "Battery", 100, "Awaiting Construction", granted="01/01/2026"),
    row(4, "Charlie Moor Solar", "Solar Photovoltaics", 49.9, "Under Construction", uc="01/03/2026"),
    row(5, "Delta Hill Wind", "Wind Onshore", 30, "Application Submitted"),
    row(6, "Echo Park Solar", "Solar Photovoltaics", 20, "Application Submitted", operator="Foo Power / Bar Ltd"),
    row(7, "Foxtrot Offshore Wind Farm", "Wind Offshore", 3600, "Awaiting Construction", region="Offshore", county=""),
    row(8, "Golf Battery", "Battery", 50, "Application Submitted", operator="Old Owner Ltd"),
    row(9, "Hotel Road Solar", "Solar Photovoltaics", 10, "Application Submitted"),
    row(10, "India Solar", "Solar Photovoltaics", None, "Awaiting Construction"),
    row(11, "Juliet Solar", "Solar Photovoltaics", 5, "Operational"),
    row(12, "Kilo Biomass", "Biomass (dedicated)", 12, "Awaiting Construction"),
]
NEW = [
    row(1, "Alpha Fen Solar Farm", "Solar Photovoltaics", 400, "Awaiting Construction", submitted="01/02/2025",
        granted="15/09/2026", authority="The Planning Inspectorate - National Infrastructure", pref="EN010999", coloc="2"),
    row(2, "Alpha Fen Solar Farm", "Battery", 600, "Awaiting Construction", granted="15/09/2026", coloc="1"),
    row(3, "Bravo Lane - Battery Storage", "Battery", 100, "Under Construction", granted="01/01/2026", uc="20/09/2026"),
    row(4, "Charlie Moor Solar", "Solar Photovoltaics", 49.9, "Operational", uc="01/03/2026", op="01/10/2026"),
    row(5, "Delta Hill Wind", "Wind Onshore", 30, "Application Refused", refused="01/08/2026"),
    row(6, "Echo Park Solar", "Solar Photovoltaics", 20, "Application Withdrawn", operator="Foo Power & Bar Limited",
        withdrawn="01/09/2026"),
    row(7, "Foxtrot Offshore Wind Farm", "Wind Offshore", 3600, "Application Submitted", region="Offshore", county=""),
    row(8, "Golf Battery", "Battery", 57, "Application Submitted", operator="New Owner Plc"),
    row(10, "India Solar", "Solar Photovoltaics", 30, "Awaiting Construction"),
    row(11, "Juliet Solar", "Battery", 5, "Operational"),
    row(12, "Kilo Biomass", "Biomass (dedicated)", 12, "Abandoned"),
    row(20, "Lima Solar Farm", "Solar Photovoltaics", 750, "Application Submitted", submitted="01/10/2026"),
    row(21, "Mike Battery", "Battery", 5, "Application Submitted"),
    row(22, "November Solar", "Solar Photovoltaics", 60, "Awaiting Construction", granted="01/07/2026"),
    row(23, "Oscar Solar", "Solar Photovoltaics", 1, "No Application Required"),
]


@pytest.fixture
def releases(tmp_path):
    prev = write_csv(tmp_path / "prev.csv", PREVIOUS)
    new = write_csv(tmp_path / "new.csv", NEW)
    return prev, new

News Engine Acceptance Demo

A Python command-line tool in the tests folder of GlobalGrid2050 that tests articles, sources, projects and solar.

testglobalgrid2050 / automation/news/tests/news_engine_acceptance_demo.py · lines 1–73 of 73 · Entry point

What it does
It tests articles, sources, projects and solar. Defines main. Uses libraries __future__, json, pathlib, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
Inputs & outputs
In: JSON file articles.json; JSON file sources.json; JSON file projects.json; JSON file out.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Synthetic OFFLINE CLI replay for Agent 3 independent acceptance.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · automation/news/tests · Python CLI
Uses
__future__, json, pathlib, subprocess, sys, tempfile
Used by
none found
Produces
main
Defines here
main
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/news_engine_acceptance_demo.py:1-73 · blob ed6c4097500776eb1b04cc9f400c961b8e290a6b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Synthetic OFFLINE CLI replay for Agent 3 independent acceptance.

All people, projects, publishers and URLs in this fixture are invented.
No network requests or publisher content retrieval occur.
"""
from __future__ import annotations

import json
from pathlib import Path
import subprocess
import sys
import tempfile


def main():
    articles = [
        {"url": "https://fixture.example.org/solar/east-meadow?utm_source=test",
         "title": "East Meadow Solar Farm consultation submitted",
         "source_id": "fixture_press", "source": "Fixture Press",
         "pub_date": "2026-11-16", "first_seen": "2026-11-16T12:00:00Z",
         "source_receipt_sha256": "a" * 64,
         "content": "DO NOT STORE OR MATCH: REPD 9999"},
        {"url": "https://fixture.example.org/solar/east-meadow?utm_medium=mail",
         "title": "East Meadow Solar Farm consultation submitted",
         "source_id": "fixture_press", "source": "Fixture Press",
         "pub_date": "2026-11-16", "first_seen": "2026-11-16T12:00:00Z",
         "source_receipt_sha256": "a" * 64},
        {"url": "https://fixture.example.org/markets/uk-renewables",
         "title": "UK energy markets see further investment",
         "source_id": "fixture_press", "source": "Fixture Press",
         "date": None, "first_seen": "2026-11-16T12:10:00Z"},
    ]
    sources = [
        {"id": "fixture_press", "publisher": "Fixture Press", "kind": "reporting",
         "rights_status": "unknown", "enabled": False,
         "output_policy": "headline_link_only"}
    ]
    projects = [{"id": "1018", "name": "East Meadow Solar Farm",
                 "namespace": "repd", "technology": "solar"}]
    with tempfile.TemporaryDirectory(prefix="news-engine-synthetic-") as tmp:
        root = Path(tmp)
        for name, payload in (("articles", articles), ("sources", sources), ("projects", projects)):
            (root / (name + ".json")).write_text(json.dumps(payload), encoding="utf-8")
        cmd = [sys.executable, "-m", "automation.news.engine",
               "--articles", str(root / "articles.json"),
               "--sources", str(root / "sources.json"),
               "--projects", str(root / "projects.json"),
               "--output", str(root / "out.json")]
        subprocess.run(cmd, check=True, capture_output=True, text=True)
        result = json.loads((root / "out.json").read_text(encoding="utf-8"))
    assert result["counts"] == {
        "articles": 2, "provisional_project_edges": 1,
        "verified_project_edges": 0, "rights_unresolved_articles": 2,
    }
    project_row = next(row for row in result["articles"] if row["project_candidates"])
    market_row = next(row for row in result["articles"] if not row["project_candidates"])
    assert len(project_row["observed_article_urls"]) == 2
    assert project_row["project_candidates"][0]["status"] == "PROVISIONAL"
    assert market_row["published_at"] is None
    assert all(row["publication_eligibility"].startswith("WITHHELD") for row in result["articles"])
    assert "DO NOT STORE" not in json.dumps(result)
    print(json.dumps({
        "label": "SYNTHETIC OFFLINE FIXTURE — NOT REAL SOURCES OR VERIFIED EVIDENCE",
        "schema": result["schema"], "counts": result["counts"],
        "project_candidate": project_row["project_candidates"][0],
        "market_news_has_no_project_binding": market_row["project_candidates"] == [],
        "observed_original_url_variants": len(project_row["observed_article_urls"]),
        "publication": project_row["publication_eligibility"],
    }, sort_keys=True, indent=2))


if __name__ == "__main__":
    main()

Test Acquisition

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

testglobalgrid2050 / automation/news/tests/test_acquisition.py · lines 1–204 of 204 · Entry point · pattern Session (shared by 2 files)

What it does
It tests the REPD register. Defines 30 functions or classes, including Response, __init__, __enter__, __exit__, iter_content. Uses libraries hashlib, json, socket, pathlib, pytest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the response class (`Response`), the iter content helper (`iter_content`) and the session class (`Session`). Network-free failure gates and identity regression tests for V9.25.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Fetch (import), Match (import), Normalise (import), Research Queue (import), hashlib, json, socket, pathlib, pytest, requests, yaml
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
Response, Session, test_exact_unchanged_selection_and_all_repd_rows, test_seed_tamper_is_fatal, test_source_configuration_fail_closed, test_duplicate_sources_rejected, test_normalise_strips_html_separates_date_and_body, test_missing_date_is_not_replaced_with_fetch_date, test_fetch_receipt_and_conditional_request, test_critical_source_failures_never_produce_success, test_rights_unknown_disabled_by_default_and_probe_never_authorizes, test_enabled_source_requires_attributable_rights_acceptance
Defines here
Response, __init__, __enter__, __exit__, iter_content, Session, __init__, get, test_exact_unchanged_selection_and_all_repd_rows, test_seed_tamper_is_fatal, test_source_configuration_fail_closed, test_duplicate_sources_rejected, test_normalise_strips_html_separates_date_and_body, test_missing_date_is_not_replaced_with_fetch_date, test_fetch_receipt_and_conditional_request, test_critical_source_failures_never_produce_success, test_rights_unknown_disabled_by_default_and_probe_never_authorizes, test_enabled_source_requires_attributable_rights_acceptance, test_xml_entity_rejected, test_strict_matching_rejects_bare_ids_partial_names_and_ambiguity, test_content_match_and_idempotent_results, test_ambiguity_outside_pilot_blocks_name_match_but_not_explicit_id, test_private_dns_answer_rejected_before_connect, test_public_dns_address_is_connected_without_second_resolution, FakeSocket, settimeout, setsockopt, connect, resolve, test_transport_error_does_not_expose_local_paths
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_acquisition.py:1-204 · blob 2ad839dadddf3db3fcb270c7490e266f4be22bbb · 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
"""Network-free failure gates and identity regression tests for V9.25."""
import hashlib
import json
import socket
from pathlib import Path

import pytest
import requests
import yaml

from automation.news.acquisition.fetch import FetchError, MAX_BYTES, _PublicHTTPSConnection, fetch_source, load_sources, parse_feed
from automation.news.acquisition.match import match_articles
from automation.news.acquisition.normalise import normalise_article
from automation.news.acquisition.research_queue import ROOT, load_seed_projects


SOURCE = load_sources(include_disabled=True)[0]
RSS = b'''<?xml version="1.0"?><rss version="2.0"><channel><item>
<title>Solar Farm A plans approved</title><link>https://www.pv-magazine.com/example/</link>
<pubDate>Mon, 16 Nov 2026 10:00:00 GMT</pubDate><description><![CDATA[<p>A proposal.</p>]]></description>
</item></channel></rss>'''


class Response:
    def __init__(self, status=200, body=RSS, headers=None):
        self.status_code, self.body, self.headers = status, body, headers or {}
    def __enter__(self):
        return self
    def __exit__(self, *args):
        pass
    def iter_content(self, size):
        for i in range(0, len(self.body), size):
            yield self.body[i:i + size]


class Session:
    def __init__(self, *responses):
        self.responses, self.calls = iter(responses), []
    def get(self, url, **kwargs):
        self.calls.append((url, kwargs))
        value = next(self.responses)
        if isinstance(value, Exception):
            raise value
        return value


def test_exact_unchanged_selection_and_all_repd_rows():
    projects = load_seed_projects()
    seed = json.loads((ROOT / 'uk_renewables_pipeline/202611161244/solar1000/manifest.json').read_text())
    assert len(projects) == 1000
    assert [p['id'] for p in projects] == seed['ids']
    assert all(p['technology'] == 'solar' for p in projects)


def test_seed_tamper_is_fatal(tmp_path):
    release = tmp_path / 'uk_renewables_pipeline/202611161244/solar1000'
    release.mkdir(parents=True)
    (release / 'manifest.json').write_text('{"ids": []}')
    with pytest.raises(ValueError, match='Immutable'):
        load_seed_projects(tmp_path)


@pytest.mark.parametrize('change', [
    {'url': 'http://www.pv-magazine.com/feed/'}, {'url': 'https://127.0.0.1/feed/'},
    {'url': 'https://www.pv-magazine.com:444/feed/'}, {'url': 'https://user@www.pv-magazine.com/feed/'},
    {'technology': ['solar', 'bess']}, {'enabled': 'true'}, {'output_policy': 'full_text'},
])
def test_source_configuration_fail_closed(tmp_path, change):
    p = tmp_path / 'sources.yaml'
    p.write_text(yaml.safe_dump([dict(SOURCE, **change)]))
    with pytest.raises(ValueError):
        load_sources(p)


def test_duplicate_sources_rejected(tmp_path):
    p = tmp_path / 'sources.yaml'
    p.write_text(yaml.safe_dump([SOURCE, SOURCE]))
    with pytest.raises(ValueError, match='Duplicate'):
        load_sources(p)


def test_normalise_strips_html_separates_date_and_body():
    article = normalise_article({'title': '<b>Solar</b> &amp; power<script>bad()</script>',
        'link': 'https://www.pv-magazine.com/article/#tracking',
        'pub_date': 'Mon, 16 Nov 2026 11:00:00 +0100', 'content': '<p>Body</p>'}, SOURCE)
    assert article['title'] == 'Solar & power'
    assert article['pub_date'] == '2026-11-16T10:00:00Z'
    assert article['url'] == 'https://www.pv-magazine.com/article/'
    assert article['content'] == 'Body'


def test_missing_date_is_not_replaced_with_fetch_date():
    with pytest.raises(ValueError):
        normalise_article({'title': 'title', 'url': 'https://www.pv-magazine.com/article/'}, SOURCE)


def test_fetch_receipt_and_conditional_request():
    session = Session(Response(headers={'ETag': 'v1'}), Response(304))
    first = fetch_source(SOURCE, session=session, probe=True)
    second = fetch_source(SOURCE, cache=first['cache'], session=session, probe=True)
    assert first['articles'] == second['articles']
    assert first['source']['response_sha256'] == hashlib.sha256(RSS).hexdigest()
    assert second['source']['http_status'] == 304
    assert session.calls[1][1]['headers']['If-None-Match'] == 'v1'
    assert session.calls[0][1]['timeout'] == (10, 25)


@pytest.mark.parametrize('response', [Response(403), Response(429), Response(500), Response(304),
    Response(body=b'<html>unavailable</html>'), Response(body=b'<rss><channel/></rss>'),
    Response(body=b'x' * (MAX_BYTES + 1)), requests.Timeout('timeout'),
    Response(302, headers={'Location': 'http://127.0.0.1/private'})])
def test_critical_source_failures_never_produce_success(response):
    with pytest.raises(FetchError):
        fetch_source(SOURCE, session=Session(response), probe=True)


def test_rights_unknown_disabled_by_default_and_probe_never_authorizes():
    assert load_sources() == []
    session = Session(Response())
    with pytest.raises(FetchError, match='disabled'):
        fetch_source(SOURCE, session=session)
    assert session.calls == []
    probe = fetch_source(SOURCE, session=session, probe=True)
    assert probe['source']['eligible_for_publication'] is False
    assert probe['source']['probe_only'] is True
    assert probe['source']['rights_status'] == 'unknown'


def test_enabled_source_requires_attributable_rights_acceptance(tmp_path):
    p = tmp_path / 'sources.yaml'
    p.write_text(yaml.safe_dump([dict(SOURCE, enabled=True)]))
    with pytest.raises(ValueError, match='rights acceptance'):
        load_sources(p)
    # A structural review URL is necessary, not independent proof of rights.
    accepted = dict(SOURCE, enabled=True, rights_status='accepted',
                    rights_review_url='https://example.org/review/accepted')
    p.write_text(yaml.safe_dump([accepted]))
    assert load_sources(p) == [accepted]
    receipt = fetch_source(accepted, session=Session(Response()))['source']
    assert receipt['eligible_for_publication'] is True
    assert receipt['rights_review_url'] == accepted['rights_review_url']


def test_xml_entity_rejected():
    with pytest.raises(FetchError):
        parse_feed(b'<!DOCTYPE rss [<!ENTITY x "unsafe">]><rss/>', SOURCE)


def test_strict_matching_rejects_bare_ids_partial_names_and_ambiguity():
    projects = [{'id': '1019', 'name': 'Solar Farm A'}, {'id': '1020', 'name': 'Solar Farm AB'},
                {'id': '2026', 'name': 'Manor Farm'}, {'id': '2027', 'name': 'Manor Farm'}]
    base = {'url': 'https://www.pv-magazine.com/article/'}
    matches = match_articles([dict(base, title='Solar Farm A plans approved in 2026')], projects)
    assert matches == [{'project_id': '1019', 'article_url': base['url'], 'status': 'PROVISIONAL', 'match_method': 'exact_name'}]
    assert not match_articles([dict(base, title='Manor Farm output increases in 2026')], projects)
    assert not match_articles([dict(base, title='Solar Farm ABC planning')], projects)
    assert match_articles([dict(base, title='REPD Ref ID: 2026 solar update')], projects)[0]['project_id'] == '2026'


def test_content_match_and_idempotent_results():
    article = {'title': 'Update', 'content': 'Solar Farm A is mentioned.', 'url': 'https://www.pv-magazine.com/a/'}
    result = match_articles([article, article], [{'id': '1019', 'name': 'Solar Farm A'}])
    assert len(result) == 1
    assert result[0]['status'] == 'PROVISIONAL'


def test_ambiguity_outside_pilot_blocks_name_match_but_not_explicit_id():
    projects = [{'id': '1019', 'name': 'Solar Farm A', 'name_ambiguous': True}]
    article = {'title': 'Solar Farm A plans approved', 'url': 'https://www.pv-magazine.com/a/'}
    assert match_articles([article], projects) == []
    article['title'] += ' REPD 1019'
    assert match_articles([article], projects)[0]['match_method'] == 'repd_id'


@pytest.mark.parametrize('address', ['127.0.0.1', '10.0.0.1', '169.254.169.254', '192.168.1.1', '::1', 'fc00::1', '224.0.0.1', 'ff02::1'])
def test_private_dns_answer_rejected_before_connect(monkeypatch, address):
    monkeypatch.setattr(socket, 'getaddrinfo', lambda *a, **kw: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (address, 443))])
    monkeypatch.setattr(socket, 'socket', lambda *a: pytest.fail('Private address must never connect'))
    with pytest.raises(FetchError, match='non-public'):
        _PublicHTTPSConnection('www.pv-magazine.com', timeout=10)._new_conn()


def test_public_dns_address_is_connected_without_second_resolution(monkeypatch):
    calls = []
    class FakeSocket:
        def settimeout(self, value):
            assert value == 10
        def setsockopt(self, *args):
            pass
        def connect(self, address):
            calls.append(address)
    def resolve(*args, **kwargs):
        calls.append('resolve')
        return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('8.8.8.8', 443))]
    monkeypatch.setattr(socket, 'getaddrinfo', resolve)
    monkeypatch.setattr(socket, 'socket', lambda *args: FakeSocket())
    _PublicHTTPSConnection('www.pv-magazine.com', timeout=10)._new_conn()
    assert calls == ['resolve', ('8.8.8.8', 443)]


def test_transport_error_does_not_expose_local_paths():
    with pytest.raises(FetchError) as error:
        fetch_source(SOURCE, session=Session(requests.ConnectionError('C:/private/session/file.pem')), probe=True)
    assert 'C:/' not in str(error.value)

Test Acquisition Analytics

A test in the tests folder of GlobalGrid2050 that checks Analytics and News — Acquisition, using SHA-256.

testglobalgrid2050 / automation/news/tests/test_acquisition_analytics.py · lines 1–180 of 180 · Entry point · pattern export (shared by 3 files)

What it does
It tests solar. Defines 14 functions or classes, including snapshot, export, bytes_in, test_full_seed_parquet_join_and_replay_preserve_operational_state, test_empty_evidence_keeps_typed_table_and_unknown_coordinates. Uses libraries copy, hashlib, json, pathlib, sys. 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: Parquet file projects.parquet; Parquet file evidence.parquet; JSON file latest.json; Parquet file changed.parquet; Parquet file wrong-schema.parquet; DuckDB queries. Out: JSON file latest.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the snapshot step (`snapshot`), the export step (`export`) and the bytes in helper (`bytes_in`). Full-row analytical closure and fail-closed immutable output checks. It reads `projects.parquet`.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Analytics (import), News — Acquisition (import), Evidence Store (import), Research Queue (import), copy, hashlib, json, pathlib, sys, duckdb, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
snapshot, export, bytes_in, test_full_seed_parquet_join_and_replay_preserve_operational_state, test_empty_evidence_keeps_typed_table_and_unknown_coordinates, test_invalid_source_fails_before_output, test_changed_source_same_generation_cannot_overwrite, test_artifact_tampering_rejected, test_recomputed_hash_cannot_hide_changed_parquet_values, test_failed_readback_leaves_no_partial_generation_or_pointer, test_output_path_with_quote_is_not_sql, test_fixed_payload_builds_identical_bytes_in_independent_directories
Defines here
snapshot, export, bytes_in, test_full_seed_parquet_join_and_replay_preserve_operational_state, test_empty_evidence_keeps_typed_table_and_unknown_coordinates, test_invalid_source_fails_before_output, test_changed_source_same_generation_cannot_overwrite, test_artifact_tampering_rejected, test_recomputed_hash_cannot_hide_changed_parquet_values, test_failed_readback_leaves_no_partial_generation_or_pointer, fail, test_output_path_with_quote_is_not_sql, test_fixed_payload_builds_identical_bytes_in_independent_directories, test_hash_repair_does_not_hide_wrong_column_type
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_acquisition_analytics.py:1-180 · blob 843d96ceb0d44e891e70f30ec1fe52ce75112609 · 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
"""Full-row analytical closure and fail-closed immutable output checks."""
import copy
import hashlib
import json
from pathlib import Path
import sys

import duckdb
import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from automation.news.acquisition import analytics
from automation.news.acquisition.evidence_store import EvidenceStore, EvidenceValidationError
from automation.news.acquisition.research_queue import load_seed_projects

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


@pytest.fixture
def snapshot():
    projects = load_seed_projects()
    article = {"id": "synthetic", "url": "https://fixtures.example/solar",
               "title": "Synthetic solar association", "pub_date": NOW,
               "source_id": "fixture", "publisher": "Synthetic test publisher"}
    source = {"id": "fixture", "status": "ok", "url": "https://fixtures.example/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"}
    # Same article associated with two projects: preserve association identity.
    matches = [{"project_id": p["id"], "article_url": article["url"],
                "status": "PROVISIONAL", "match_method": "repd_id"} for p in projects[:2]]
    with EvidenceStore() as store:
        store.record_run(projects, [article], matches, NOW, [source])
        return store.snapshot(), [p["id"] for p in projects]


def export(tmp_path, snapshot):
    payload, ids = snapshot
    receipt = analytics.export_analytics(payload, tmp_path, expected_project_ids=ids)
    return tmp_path / receipt["directory"], receipt


def bytes_in(directory):
    return {p.relative_to(directory).as_posix(): p.read_bytes()
            for p in directory.rglob("*") if p.is_file()}


def test_full_seed_parquet_join_and_replay_preserve_operational_state(tmp_path, snapshot):
    (tmp_path / "latest.json").write_bytes(b"existing pointer")
    (tmp_path / "evidence.sqlite").write_bytes(b"existing operational store")
    directory, receipt = export(tmp_path, snapshot)
    assert receipt["project_count"] == 1000
    assert receipt["evidence_count"] == 2
    assert not str(tmp_path) in json.dumps(receipt)
    with duckdb.connect() as db:
        projects = db.read_parquet(str(directory / "projects.parquet"))
        assert projects.count("*").fetchone()[0] == 1000
        assert projects.filter("verified_count <> 0 OR last_event IS NOT NULL").count("*").fetchone()[0] == 0
        evidence = db.read_parquet(str(directory / "evidence.parquet"))
        assert evidence.aggregate("count(DISTINCT project_id)").fetchone()[0] == 2
        assert evidence.aggregate("count(DISTINCT url)").fetchone()[0] == 1
        assert "body" not in evidence.columns
    before = bytes_in(tmp_path)
    assert export(tmp_path, snapshot)[1] == receipt
    assert bytes_in(tmp_path) == before
    assert before["latest.json"] == b"existing pointer"
    assert before["evidence.sqlite"] == b"existing operational store"


def test_empty_evidence_keeps_typed_table_and_unknown_coordinates(tmp_path, snapshot):
    payload, ids = copy.deepcopy(snapshot)
    for row in payload["projects"]:
        row.update(evidence=[], evidence_count=0, provisional_count=0,
                   status="RESEARCH_ATTEMPTED_NO_EVIDENCE", latitude=None, longitude=None)
    payload["evidence_count"] = 0
    directory, _ = export(tmp_path, (payload, ids))
    with duckdb.connect() as db:
        relation = db.read_parquet(str(directory / "evidence.parquet"))
        assert relation.columns == [c for c, _ in analytics.TABLES["evidence"]]
        assert relation.count("*").fetchone()[0] == 0
        projects = db.read_parquet(str(directory / "projects.parquet"))
        assert projects.filter("latitude IS NULL AND longitude IS NULL").count("*").fetchone()[0] == 1000


@pytest.mark.parametrize("mutation", [
    lambda p: p.update(verified_count=1),
    lambda p: p["sources"][0].update(rights_status="unknown"),
    lambda p: p["projects"][0].update(project_id="99999999"),
    lambda p: p["projects"][0]["evidence"][0].update(body="do not persist"),
    lambda p: p["projects"][0].update(evidence_count=999),
])
def test_invalid_source_fails_before_output(tmp_path, snapshot, mutation):
    payload, ids = copy.deepcopy(snapshot)
    mutation(payload)
    with pytest.raises(EvidenceValidationError):
        analytics.export_analytics(payload, tmp_path, expected_project_ids=ids)
    assert list(tmp_path.iterdir()) == []


def test_changed_source_same_generation_cannot_overwrite(tmp_path, snapshot):
    directory, _ = export(tmp_path, snapshot)
    before = bytes_in(directory)
    payload, ids = copy.deepcopy(snapshot)
    payload["projects"][0]["name"] = "Changed identity"
    with pytest.raises(EvidenceValidationError, match="source identity"):
        analytics.export_analytics(payload, tmp_path, expected_project_ids=ids)
    assert bytes_in(directory) == before


@pytest.mark.parametrize("change", ["corrupt", "missing", "extra"])
def test_artifact_tampering_rejected(tmp_path, snapshot, change):
    directory, _ = export(tmp_path, snapshot)
    parquet = directory / "projects.parquet"
    if change == "corrupt":
        parquet.write_bytes(parquet.read_bytes() + b"corruption")
    elif change == "missing":
        parquet.unlink()
    else:
        (directory / "unowned.txt").write_text("unexpected")
    with pytest.raises(EvidenceValidationError):
        analytics.validate_analytics(directory, snapshot[0], expected_project_ids=snapshot[1])


def test_recomputed_hash_cannot_hide_changed_parquet_values(tmp_path, snapshot):
    directory, _ = export(tmp_path, snapshot)
    path = directory / "evidence.parquet"
    replacement = tmp_path / "changed.parquet"
    with duckdb.connect() as db:
        db.read_parquet(str(path)).create_view("original")
        db.execute("COPY (SELECT * REPLACE ('VERIFIED' AS status) FROM original) TO "
                   + analytics._literal(replacement) + " (FORMAT PARQUET, COMPRESSION ZSTD)")
    path.write_bytes(replacement.read_bytes())
    manifest_path = directory / "manifest.json"
    manifest = json.loads(manifest_path.read_text())
    manifest["artifacts"]["evidence"].update(
        sha256=hashlib.sha256(path.read_bytes()).hexdigest(), bytes=path.stat().st_size)
    manifest_path.write_text(json.dumps(manifest))
    with pytest.raises(EvidenceValidationError, match="full-row comparison"):
        analytics.validate_analytics(directory, snapshot[0], expected_project_ids=snapshot[1])


def test_failed_readback_leaves_no_partial_generation_or_pointer(tmp_path, snapshot, monkeypatch):
    (tmp_path / "latest.json").write_bytes(b"accepted")
    def fail(*args, **kwargs):
        raise EvidenceValidationError("simulated readback failure")
    monkeypatch.setattr(analytics, "validate_analytics", fail)
    with pytest.raises(EvidenceValidationError, match="simulated"):
        export(tmp_path, snapshot)
    assert bytes_in(tmp_path) == {"latest.json": b"accepted"}
    assert [p.name for p in tmp_path.iterdir()] == ["latest.json"]


def test_output_path_with_quote_is_not_sql(tmp_path, snapshot):
    directory, _ = export(tmp_path / "producer's output", snapshot)
    assert directory.is_dir()


def test_fixed_payload_builds_identical_bytes_in_independent_directories(tmp_path, snapshot):
    first, receipt_a = export(tmp_path / "first", snapshot)
    second, receipt_b = export(tmp_path / "second", snapshot)
    assert bytes_in(first) == bytes_in(second)
    assert receipt_a == receipt_b


def test_hash_repair_does_not_hide_wrong_column_type(tmp_path, snapshot):
    directory, _ = export(tmp_path, snapshot)
    path = directory / "projects.parquet"
    replacement = tmp_path / "wrong-schema.parquet"
    with duckdb.connect() as db:
        db.read_parquet(str(path)).create_view("original")
        db.execute("COPY (SELECT * REPLACE (CAST(project_id AS BIGINT) AS project_id) FROM original) TO "
                   + analytics._literal(replacement) + " (FORMAT PARQUET, COMPRESSION ZSTD)")
    path.write_bytes(replacement.read_bytes())
    manifest_path = directory / "manifest.json"
    manifest = json.loads(manifest_path.read_text())
    manifest["artifacts"]["projects"].update(
        sha256=hashlib.sha256(path.read_bytes()).hexdigest(), bytes=path.stat().st_size)
    manifest_path.write_text(json.dumps(manifest))
    with pytest.raises(EvidenceValidationError, match="Parquet schema"):
        analytics.validate_analytics(directory, snapshot[0], expected_project_ids=snapshot[1])