GLOBALGRID2050 / EXPLORE CODE

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

Test Hardening Nl013 and 2 more files

A test in the tests folder of GlobalGrid2050 that checks Automation — Renewable Energy Planning Database (REPD) and Renewable Energy Planning Database (REPD) Build Root, using SHA-256.

569 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 834 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 Hardening Nl013 test · globalgrid2050 / automation/repd/tests/test_hardening_nl013.py lines 1–214
  2. Test Hashguard test · globalgrid2050 / automation/repd/tests/test_hashguard.py lines 1–169
  3. Test Monthly test · globalgrid2050 / automation/repd/tests/test_monthly.py lines 1–186

Test Hardening Nl013

A test in the tests folder of GlobalGrid2050 that checks Automation — Renewable Energy Planning Database (REPD) and Renewable Energy Planning Database (REPD) Build Root, using SHA-256.

testglobalgrid2050 / automation/repd/tests/test_hardening_nl013.py · lines 1–214 of 214 · Entry point · pattern fake_repo (shared by 2 files)

What it does
It tests its inputs. Defines 20 functions or classes, including fake_repo, _ctx, test_stage_raising_system_exit_is_reported_and_hash_guard_still_runs, exiting_clean, test_acceptance_waivers_come_only_from_the_known_anomalies_file. Uses libraries __future__, datetime, hashlib, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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: CSV file repd.csv; CSV file in.csv; Excel file in.xlsx; JSON file run_report.json; CSV file c.csv; JSON file 2026q3.json; JSON file k.json; CSV file REPD_Publication_Q3_2026.csv. Out: CSV file repd.csv; CSV file in.csv; Excel file in.xlsx; JSON file 2099q1_known_anomalies.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the fake repo helper (`fake_repo`), the exiting clean helper (`exiting_clean`) and the REPD updater class (`REPDUpdater`). Hardening tests from the independent QA of PR #57 (Team 1, NL-013, 14 Nov 2026).
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/repd/tests · test
Uses
Automation — Renewable Energy Planning Database (REPD) (import), Renewable Energy Planning Database (REPD) Build Root (import), Test Validate (import), __future__, datetime, hashlib, json, os, subprocess, sys, pathlib
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
fake_repo, test_stage_raising_system_exit_is_reported_and_hash_guard_still_runs, test_acceptance_waivers_come_only_from_the_known_anomalies_file, REPDUpdater, test_build_master_writes_nothing_into_the_repo_and_needs_no_config, test_build_root_reads_hashes_from_the_committed_v1_descriptor, test_valid_csv_date_that_is_a_different_date_from_the_typed_xlsx_fails, test_unparseable_csv_date_is_not_rescued_by_a_typed_xlsx_date, test_month_first_and_unpadded_forms_of_the_typed_date_still_resolve, test_a_ref_known_for_a_date_reason_does_not_waive_a_coordinate_failure, test_hashguard_sees_files_that_git_status_hides, test_hashguard_absent_sparse_path_is_not_a_violation
Defines here
fake_repo, _ctx, test_stage_raising_system_exit_is_reported_and_hash_guard_still_runs, exiting_clean, test_acceptance_waivers_come_only_from_the_known_anomalies_file, REPDUpdater, __init__, refine_dataset, test_build_master_writes_nothing_into_the_repo_and_needs_no_config, test_build_root_reads_hashes_from_the_committed_v1_descriptor, _gates, test_valid_csv_date_that_is_a_different_date_from_the_typed_xlsx_fails, test_unparseable_csv_date_is_not_rescued_by_a_typed_xlsx_date, test_month_first_and_unpadded_forms_of_the_typed_date_still_resolve, test_a_ref_known_for_a_date_reason_does_not_waive_a_coordinate_failure, _git, test_hashguard_sees_files_that_git_status_hides, test_hashguard_absent_sparse_path_is_not_a_violation, test_october_2026_cleaning_is_exactly_the_832_logged_changes, test_descriptor_expectations_gate_fails_on_wrong_count_or_hash
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/repd/tests/test_hardening_nl013.py:1-214 · blob 676a98ba1f37a9b62e54a94d84d5041b5e9de3a0 · 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
"""Hardening tests from the independent QA of PR #57 (Team 1, NL-013, 14 Nov 2026).

Each test pins one defect found by crafted input or by the end-to-end offline run; every one of
them failed on f9ccd703 and passes with the NL-013 patches. Synthetic fixtures only, except the
optional October regression at the end (set REPD_Q3_DIR to the folder holding the official
REPD_Publication_Q3_2026.csv/.xlsx).
"""
from __future__ import annotations

import datetime
import hashlib
import json
import os
import subprocess
import sys
from pathlib import Path

import pytest

HERE = Path(__file__).resolve().parent
PKG = HERE.parent
REPO = PKG.parents[1]
for p in (str(REPO), str(PKG), str(HERE)):
    if p not in sys.path:
        sys.path.insert(0, p)

from automation.repd import run, build_root  # noqa: E402
import hashguard as HG  # noqa: E402
import test_validate as TV  # noqa: E402


# ---------------------------------------------------------------- run.py
@pytest.fixture
def fake_repo(tmp_path):
    repo = tmp_path / "repo"
    (repo / "dist").mkdir(parents=True)
    TV.write_csv  # noqa: B018 (import check)
    (repo / "repd.csv").write_text("Ref ID\n1\n", encoding="utf-8")
    return repo


def _ctx(repo, tmp_path):
    src = tmp_path / "src"
    src.mkdir()
    (src / "in.csv").write_text("Ref ID\n1\n", encoding="utf-8")
    (src / "in.xlsx").write_bytes(b"PK fake")
    d = {"label": "2026q3", "release_folder": "202611132345", "row_floor": 1, "previous_baseline_path": "repd.csv"}
    return run.RunContext(repo_root=repo, out_dir=tmp_path / "out", descriptor=d, offline=True,
                          local_csv=src / "in.csv", local_xlsx=src / "in.xlsx", check_pins=False,
                          protected_globs=["repd.csv"])


def test_stage_raising_system_exit_is_reported_and_hash_guard_still_runs(fake_repo, tmp_path, monkeypatch):
    """scripts/repd_updater.py raises SystemExit when config/registry.yaml is missing; on f9ccd703 that
    killed run.py with no run report and no post-run hash guard."""
    def exiting_clean(csv_path, out_dir):
        raise SystemExit("ERROR: config/registry.yaml not found.")
    monkeypatch.setattr(run, "load_module", lambda name: None)
    monkeypatch.setattr(run, "find_component",
                        lambda s: (exiting_clean, "fake.clean") if s == "clean" else (None, "absent"))
    report = run.run_pipeline(_ctx(fake_repo, tmp_path))
    stages = {s["stage"]: s for s in report["stages"]}
    assert stages["clean"]["status"] == "failed" and "registry.yaml" in stages["clean"]["error"]
    assert report["stages"][-1]["stage"] == "hash_guard" and report["overall"] == "failed"
    assert (tmp_path / "out" / "run_report.json").is_file()


def test_acceptance_waivers_come_only_from_the_known_anomalies_file(tmp_path):
    assert run.acceptance_waivers("2026q3") == ["15915:Address"]
    assert run.acceptance_waivers("2099q1", base=tmp_path) == []
    (tmp_path / "2099q1_known_anomalies.json").write_text(json.dumps({"acceptance_waive_cells": ["no-colon"]}))
    with pytest.raises(run.StageError):
        run.acceptance_waivers("2099q1", base=tmp_path)


# ---------------------------------------------------------------- build_root.py
STUB_UPDATER = '''
import os
class REPDUpdater:
    def __init__(self, registry_path="config/registry.yaml"):
        if not os.path.isfile(registry_path):
            raise SystemExit("ERROR: " + registry_path + " not found.")
        os.makedirs("dist", exist_ok=True)
        os.makedirs("data", exist_ok=True)
        self.cwd = os.getcwd()
    def refine_dataset(self, csv_path):
        assert os.path.isfile(csv_path), csv_path
        return {"type": "FeatureCollection", "features": [], "cwd": self.cwd}
'''


def test_build_master_writes_nothing_into_the_repo_and_needs_no_config(tmp_path, monkeypatch):
    repo = tmp_path / "repo"
    (repo / "scripts").mkdir(parents=True)
    (repo / "scripts" / "repd_updater.py").write_text(STUB_UPDATER, encoding="utf-8")
    canonical = tmp_path / "c.csv"
    canonical.write_text("Ref ID\n1\n", encoding="utf-8")
    monkeypatch.delitem(sys.modules, "repd_updater", raising=False)
    monkeypatch.syspath_prepend(str(repo / "scripts"))
    before = sorted(p.relative_to(repo).as_posix() for p in repo.rglob("*"))
    cwd = os.getcwd()
    result = build_root.build_master(canonical, repo)        # no config/ in this checkout
    assert result["type"] == "FeatureCollection"
    assert Path(result["cwd"]).resolve() != repo.resolve()
    assert sorted(p.relative_to(repo).as_posix() for p in repo.rglob("*")
                  if "__pycache__" not in p.parts) == [b for b in before if "__pycache__" not in b]
    assert os.getcwd() == cwd


def test_build_root_reads_hashes_from_the_committed_v1_descriptor():
    v1 = json.loads((PKG / "releases" / "2026q3.json").read_text(encoding="utf-8"))
    d = build_root.normalise_descriptor(v1)
    assert d["expected_csv_sha256"] == v1["expected"]["csv_sha256"]
    assert d["expected_xlsx_sha256"] == v1["expected"]["xlsx_sha256"]
    flat = build_root.normalise_descriptor({"published": "2026-11-13", "expected_csv_sha256": "a" * 64})
    assert flat["page_last_updated"] == "2026-11-13" and flat["expected_csv_sha256"] == "a" * 64


# ---------------------------------------------------------------- validate.py
def _gates(tmp_path, rows, **kw):
    tmp_path.mkdir(parents=True, exist_ok=True)
    code, rep, g = TV.run(tmp_path, rows, **kw)
    return code, g


def test_valid_csv_date_that_is_a_different_date_from_the_typed_xlsx_fails(tmp_path):
    rs = TV.rows_default(); rs[3]["Operational"] = "01/02/2022"          # not a swap of 5 Mar 2022
    code, g = _gates(tmp_path, rs, xlsx_dates={("4", "Operational"): datetime.datetime(2022, 3, 5)})
    assert code == 1 and g["C1_dates_valid"]["status"] == "fail"
    assert g["C1_dates_valid"]["detail"]["invalid"][0]["ref"] == "4"


def test_unparseable_csv_date_is_not_rescued_by_a_typed_xlsx_date(tmp_path):
    rs = TV.rows_default(); rs[3]["Operational"] = "early 2022"
    code, g = _gates(tmp_path, rs, xlsx_dates={("4", "Operational"): datetime.datetime(2022, 3, 5)})
    assert code == 1 and g["C1_dates_valid"]["status"] == "fail"


def test_month_first_and_unpadded_forms_of_the_typed_date_still_resolve(tmp_path):
    rs = TV.rows_default()
    rs[3]["Operational"] = "3/14/2022"     # impossible day-first, month-first = 14 Mar
    rs[4]["Operational"] = "5/3/2022"      # unpadded day-first = 5 Mar
    xd = {("4", "Operational"): datetime.datetime(2022, 3, 14), ("5", "Operational"): datetime.datetime(2022, 3, 5)}
    code, g = _gates(tmp_path, rs, xlsx_dates=xd)
    assert code == 0 and g["C1_dates_valid"]["status"] == "warn"


def test_a_ref_known_for_a_date_reason_does_not_waive_a_coordinate_failure(tmp_path):
    rs = TV.rows_default(); rs[1]["Y-coordinate"] = "9999999"
    tmp_path.mkdir(exist_ok=True)
    k = tmp_path / "k.json"
    k.write_text(json.dumps({"known": {"2": "Operational holds text NA"}, "known_coordinates": {}}))
    code, g = _gates(tmp_path / "a", rs, xlsx=False, extra=["--csv-only", "--known-anomalies", str(k)])
    assert code == 1 and g["C4_coordinates_numeric_and_in_bounds"]["status"] == "fail"
    k.write_text(json.dumps({"known": {"2": "x"}, "known_coordinates": {"2": "wrong in source"}}))
    code, g = _gates(tmp_path / "b", rs, xlsx=False, extra=["--csv-only", "--known-anomalies", str(k)])
    assert code == 0 and g["C4_coordinates_numeric_and_in_bounds"]["status"] == "warn"


# ---------------------------------------------------------------- hashguard.py
def _git(repo, *args):
    subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)


@pytest.mark.parametrize("flag", ["--skip-worktree", "--assume-unchanged"])
def test_hashguard_sees_files_that_git_status_hides(tmp_path, flag):
    repo = tmp_path / "r"
    repo.mkdir()
    _git(repo, "init", "-q"); _git(repo, "config", "user.email", "t@example.invalid"); _git(repo, "config", "user.name", "t")
    (repo / "a.txt").write_text("original\n")
    _git(repo, "add", "."); _git(repo, "commit", "-qm", "init")
    before = HG.snapshot_git(str(repo))
    _git(repo, "update-index", flag, "a.txt")
    (repo / "a.txt").write_text("tampered\n")
    rep = HG.compare(before, HG.snapshot_worktree(str(repo)))
    assert rep["result"] == "FAIL" and rep["violations"][0]["path"] == "a.txt"


def test_hashguard_absent_sparse_path_is_not_a_violation(tmp_path):
    repo = tmp_path / "r"
    repo.mkdir()
    _git(repo, "init", "-q"); _git(repo, "config", "user.email", "t@example.invalid"); _git(repo, "config", "user.name", "t")
    (repo / "a.txt").write_text("original\n")
    _git(repo, "add", "."); _git(repo, "commit", "-qm", "init")
    before = HG.snapshot_git(str(repo))
    _git(repo, "update-index", "--skip-worktree", "a.txt")
    (repo / "a.txt").unlink()                     # what a sparse checkout looks like
    assert HG.compare(before, HG.snapshot_worktree(str(repo)))["result"] == "PASS"


# ---------------------------------------------------------------- October regression (optional)
Q3 = Path(os.environ.get("REPD_Q3_DIR", "/nonexistent"))


@pytest.mark.skipif(not (Q3 / "REPD_Publication_Q3_2026.csv").is_file(), reason="set REPD_Q3_DIR to the official October files")
def test_october_2026_cleaning_is_exactly_the_832_logged_changes():
    import clean as C
    csv_raw = (Q3 / "REPD_Publication_Q3_2026.csv").read_bytes()
    xlsx_raw = (Q3 / "REPD_Publication_Q3_2026.xlsx").read_bytes()
    res = C.clean(csv_raw, xlsx_raw, C.CleanOptions(as_of=datetime.date(2026, 11, 13)))
    assert hashlib.sha256(res.csv_bytes).hexdigest() == "d937ae16ad07f43caaaa25b4cee56399e1e9b9bb2ae5ecb7bc88cf9bc092e4b9"
    assert res.log["cells_changed_distinct"] == 832 and res.log["verification"]["unexplained_differences"] == 0
    assert (REPO / "repd-2026q3.csv").read_bytes() == res.csv_bytes if (REPO / "repd-2026q3.csv").is_file() else True


def test_descriptor_expectations_gate_fails_on_wrong_count_or_hash(tmp_path):
    """S6 had no failing-input test: an identical truncation of CSV and XLSX passes S1-S5 and is caught only here."""
    rs = TV.rows_default()
    code, g = _gates(tmp_path / "rows", rs, extra=["--expect-rows", "14", "--expect-unique-refs", "14"])
    assert code == 1 and g["S6_descriptor_expectations"]["status"] == "fail"
    code, g = _gates(tmp_path / "sha", rs, extra=["--expect-csv-sha256", "0" * 64])
    assert code == 1 and g["S6_descriptor_expectations"]["status"] == "fail"
    code, g = _gates(tmp_path / "ok", rs, extra=["--expect-rows", "12", "--expect-unique-refs", "12"])
    assert code == 0 and g["S6_descriptor_expectations"]["status"] == "pass"

Test Hashguard

A test in the tests folder of GlobalGrid2050 that checks Renewable Energy Planning Database (REPD) Hashguard, using SHA-256. It makes repo (`make_repo`) and snaps file (`snap_file`).

testglobalgrid2050 / automation/repd/tests/test_hashguard.py · lines 1–169 of 169 · Entry point · pattern make_repo (shared by 3 files)

What it does
It tests the REPD register. Defines 13 functions or classes, including git, make_repo, snap_file, compare, test_snapshot_matches_ls_tree_format. Uses libraries json, os, shutil, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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.
Inputs & outputs
In: CSV file repd.csv; JSON file repd_master.json; JSON file rep.json; JSON file project_identity_2026q3.json; JSON file gpu-reuse.json. Out: JSON file project_identity_2026q3.json; CSV file repd.csv; JSON file repd_master.json; JSON file a.json; CSV file b.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Tests for `automation/repd/hashguard.py` using throw-away git repositories under `tmp_path`.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/repd/tests · test
Uses
Renewable Energy Planning Database (REPD) Hashguard (sys.path import), json, os, shutil, subprocess, sys, pytest
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
git, make_repo, snap_file, compare, test_snapshot_matches_ls_tree_format, test_untouched_worktree_and_additions_pass, test_changed_shrank_disappeared_fail, test_allow_list_excuses_only_matching_paths, test_commit_vs_commit, test_sha256_mode, test_non_git_directory_uses_raw_blob_ids, test_crlf_blob_committed_before_eol_attribute_is_not_a_false_change
Defines here
git, make_repo, snap_file, compare, test_snapshot_matches_ls_tree_format, test_untouched_worktree_and_additions_pass, test_changed_shrank_disappeared_fail, test_allow_list_excuses_only_matching_paths, test_commit_vs_commit, test_sha256_mode, test_non_git_directory_uses_raw_blob_ids, test_crlf_blob_committed_before_eol_attribute_is_not_a_false_change, test_baseline_manifest_reader_and_errors
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/repd/tests/test_hashguard.py:1-169 · blob 154223aca9ec21f564bae7121d39ad04c7aac08e · 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
"""Tests for automation/repd/hashguard.py using throw-away git repositories under tmp_path."""
import json
import os
import shutil
import subprocess
import sys

import pytest

HERE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.dirname(HERE)
if PKG not in sys.path:
    sys.path.insert(0, PKG)

import hashguard as H  # noqa: E402

pytestmark = pytest.mark.skipif(shutil.which('git') is None, reason='git not installed')

ENV = dict(os.environ, GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='t@example.invalid', GIT_COMMITTER_NAME='t',
           GIT_COMMITTER_EMAIL='t@example.invalid', GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM='1')


def git(repo, *args):
    return subprocess.run(['git', '-C', str(repo), *args], check=True, capture_output=True, env=ENV).stdout


def make_repo(tmp_path, files):
    repo = tmp_path / 'repo'
    repo.mkdir()
    git(repo, 'init', '-q', '-b', 'main')
    for p, data in files.items():
        fp = repo / p
        fp.parent.mkdir(parents=True, exist_ok=True)
        fp.write_bytes(data)
    git(repo, 'add', '-A')
    git(repo, 'commit', '-q', '-m', 'init')
    return repo


FILES = {'repd.csv': b'a,b\n1,2\n3,4\n', 'dist/repd_master.json': b'{"features": [1, 2, 3]}\n',
         'uk_renewables_pipeline/v9/index.html': b'<html>v9</html>\n', 'docs/notes.md': b'notes\n'}


def snap_file(tmp_path, repo, name='before.tsv'):
    out = tmp_path / name
    assert H.main(['snapshot', '--git', str(repo), '--out', str(out)]) == 0
    return out


def compare(tmp_path, *args):
    rep = tmp_path / 'rep.json'
    code = H.main(['compare', *args, '--json', str(rep), '--quiet'])
    return code, (json.loads(rep.read_text()) if rep.exists() else None)


def test_snapshot_matches_ls_tree_format(tmp_path):
    repo = make_repo(tmp_path, FILES)
    out = snap_file(tmp_path, repo)
    lines = out.read_text().splitlines()
    assert len(lines) == len(FILES)
    oid, size, path = lines[0].split('\t')
    assert path == 'dist/repd_master.json' and int(size) == len(FILES[path])
    assert oid == git(repo, 'rev-parse', 'HEAD:' + path).decode().strip()


def test_untouched_worktree_and_additions_pass(tmp_path):
    repo = make_repo(tmp_path, FILES)
    before = snap_file(tmp_path, repo)
    (repo / 'dist').joinpath('project_identity_2026q3.json').write_bytes(b'{}\n')
    (repo / 'uk_renewables_pipeline/202611132345').mkdir(parents=True)
    (repo / 'uk_renewables_pipeline/202611132345/index.html').write_bytes(b'new\n')
    for extra in ([], ['--full-hash']):
        code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(repo), *extra)
        assert code == 0 and rep['result'] == 'PASS'
        assert [a['path'] for a in rep['additions']] == ['dist/project_identity_2026q3.json',
                                                         'uk_renewables_pipeline/202611132345/index.html']


def test_changed_shrank_disappeared_fail(tmp_path):
    repo = make_repo(tmp_path, FILES)
    before = snap_file(tmp_path, repo)
    (repo / 'repd.csv').write_bytes(b'a,b\n')                                 # truncated
    (repo / 'dist/repd_master.json').write_bytes(b'{"features": [9, 9, 9]}\n')  # same size, new bytes
    os.remove(repo / 'uk_renewables_pipeline/v9/index.html')
    for extra in ([], ['--full-hash']):
        code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(repo), *extra)
        assert code == 1 and rep['result'] == 'FAIL'
        got = {v['path']: v['change'] for v in rep['violations']}
        assert got == {'repd.csv': 'shrank', 'dist/repd_master.json': 'changed',
                       'uk_renewables_pipeline/v9/index.html': 'disappeared'}


def test_allow_list_excuses_only_matching_paths(tmp_path):
    repo = make_repo(tmp_path, FILES)
    before = snap_file(tmp_path, repo)
    (repo / 'docs/notes.md').write_bytes(b'notes updated\n')
    (repo / 'repd.csv').write_bytes(b'x\n')
    allow = tmp_path / 'allow.txt'
    allow.write_text('# owned by this component\ndocs/\n')
    code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(repo), '--allow-file', str(allow))
    assert code == 1 and [v['path'] for v in rep['violations']] == ['repd.csv']
    assert rep['allowed_changes'][0]['path'] == 'docs/notes.md' and rep['allowed_changes'][0]['allowed_by'] == 'docs/'
    code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(repo), '--allow-file', str(allow),
                        '--allow', 'repd.*')
    assert code == 0 and rep['allowed_changes_total'] == 2


def test_commit_vs_commit(tmp_path):
    repo = make_repo(tmp_path, FILES)
    before = snap_file(tmp_path, repo)
    (repo / 'new.txt').write_bytes(b'n\n')
    git(repo, 'add', '-A'); git(repo, 'commit', '-q', '-m', 'add')
    code, rep = compare(tmp_path, '--before', str(before), '--after-git', f'{repo}@HEAD')
    assert code == 0 and rep['additions_total'] == 1
    git(repo, 'rm', '-q', 'docs/notes.md'); git(repo, 'commit', '-q', '-m', 'rm')
    after = snap_file(tmp_path, repo, 'after.tsv')
    code, rep = compare(tmp_path, '--before', str(before), '--after', str(after))
    assert code == 1 and rep['violations'][0] == {'path': 'docs/notes.md', 'change': 'disappeared',
                                                  'before_id': rep['violations'][0]['before_id'], 'before_size': 6}


def test_sha256_mode(tmp_path):
    root = tmp_path / 'plain'
    root.mkdir()
    (root / 'a.json').write_bytes(b'{"x": 1}\n')
    (root / 'b.csv').write_bytes(b'1,2\n')
    lst = tmp_path / 'list.txt'
    lst.write_text('a.json\n./b.csv\n')
    before = tmp_path / 's.tsv'
    assert H.main(['snapshot', '--root', str(root), '--paths-file', str(lst), '--out', str(before)]) == 0
    assert all(l.startswith('sha256:') for l in before.read_text().splitlines())
    (root / 'c.txt').write_bytes(b'new\n')
    code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(root))
    assert code == 0 and [a['path'] for a in rep['additions']] == ['c.txt']
    (root / 'b.csv').write_bytes(b'1\n')
    code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(root))
    assert code == 1 and rep['violations'][0]['change'] == 'shrank'


def test_non_git_directory_uses_raw_blob_ids(tmp_path):
    repo = make_repo(tmp_path, FILES)
    before = snap_file(tmp_path, repo)
    plain = tmp_path / 'copy'
    shutil.copytree(repo, plain, ignore=shutil.ignore_patterns('.git'))
    code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(plain))
    assert code == 0 and rep['unchanged'] == len(FILES)


def test_crlf_blob_committed_before_eol_attribute_is_not_a_false_change(tmp_path):
    repo = make_repo(tmp_path, {'old.html': b'<p>\r\nold\r\n</p>\r\n'})
    (repo / '.gitattributes').write_bytes(b'* text=auto eol=lf\n')
    git(repo, 'add', '.gitattributes'); git(repo, 'commit', '-q', '-m', 'attrs')
    before = snap_file(tmp_path, repo)
    code, rep = compare(tmp_path, '--before', str(before), '--worktree', str(repo), '--full-hash')
    assert code == 0, rep['violations']


def test_baseline_manifest_reader_and_errors(tmp_path):
    m = tmp_path / 'm.tsv'
    m.write_text('d8b86239a676fc83fff27f6e1f645db4a3bfb06f\t952\t.cvaa/gpu-reuse.json\n'
                 '0123456789012345678901234567890123456789\t-\tsub\n')
    snap = H.read_manifest(str(m))
    assert snap['.cvaa/gpu-reuse.json'] == ('d8b86239a676fc83fff27f6e1f645db4a3bfb06f', 952) and snap['sub'][1] is None
    bad = tmp_path / 'bad.tsv'
    bad.write_text('only two\tcolumns\n')
    assert H.main(['compare', '--before', str(bad), '--worktree', str(tmp_path), '--quiet']) == 2
    mixed = tmp_path / 'mixed.tsv'
    mixed.write_text('sha256:00\t1\ta\n' + 'ab' * 20 + '\t1\tb\n')
    assert H.main(['compare', '--before', str(mixed), '--worktree', str(tmp_path), '--quiet']) == 2

Test Monthly

A test in the tests folder of GlobalGrid2050 that checks Automation — Renewable Energy Planning Database (REPD) and Renewable Energy Planning Database (REPD) Monthly, using SHA-256.

testglobalgrid2050 / automation/repd/tests/test_monthly.py · lines 1–186 of 186 · Entry point · pattern world (shared by 6 files)

What it does
It tests its inputs. Defines 15 functions or classes, including world, put, synthetic, run, test_quarter_from_date. Uses libraries json, shutil, sys, pathlib, pytest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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 2026q2.json; JSON file result.json; JSON file content_api_2027q1.json; JSON file 2027q1.json; JSON file v6_2027q1.json; CSV file REPD_Publication_Q1_2027.csv; JSON file content_api_2026q2_old_urls.json; Excel file REPD_Publication_Q1_2027.xlsx. Out: JSON file 2026q2_known_anomalies.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the world step (`world`), the put step (`put`) and the synthetic step (`synthetic`). Tests for `automation/repd/monthly.py` (the monthly workflow's helper).
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/repd/tests · test
Uses
Automation — Renewable Energy Planning Database (REPD) (import), Renewable Energy Planning Database (REPD) Monthly (import), Conftest (import), json, shutil, sys, pathlib, pytest
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
world, put, synthetic, run, test_quarter_from_date, test_new_release_writes_descriptors_allowlist_and_counts, test_unchanged_when_hashes_are_pinned, test_redirected_old_url_is_judged_by_hash_not_url, test_same_quarter_with_new_bytes_needs_a_person, test_unnamed_files_get_a_date_derived_id, test_acceptance_waivers_carry_forward, test_allowlist_is_idempotent_and_optional
Defines here
world, put, synthetic, run, test_quarter_from_date, test_new_release_writes_descriptors_allowlist_and_counts, test_unchanged_when_hashes_are_pinned, test_redirected_old_url_is_judged_by_hash_not_url, test_same_quarter_with_new_bytes_needs_a_person, test_unnamed_files_get_a_date_derived_id, test_acceptance_waivers_carry_forward, test_allowlist_is_idempotent_and_optional, test_unreadable_publication_is_an_error_not_green, test_github_output, test_real_october_files_are_unchanged_against_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/repd/tests/test_monthly.py:1-186 · blob c5b5724c37fbbb8131c1d711268a51480b2e8e5c · 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
"""Tests for automation/repd/monthly.py (the monthly workflow's helper). No network: content API
fixtures in fixtures/monthly/, synthetic official-style CSV/XLSX from conftest, a temporary
releases directory and a temporary repo root. The real October files are used if present."""
import json
import shutil
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
sys.path.insert(0, str(Path(__file__).resolve().parent))

from automation.repd import config, monthly  # noqa: E402
from conftest import base_rows, make_csv, make_xlsx  # noqa: E402

FIX = Path(__file__).resolve().parent / "fixtures" / "monthly"
PKG = Path(__file__).resolve().parents[1]
REPO = PKG.parents[1]
REAL = Path("/home/claude/repd-report/q3")
Q3_CSV = "48e76c49f33a1090e78108d1ea9bfe689b35963ea3be1bb4f6516d038a5ff862"


@pytest.fixture()
def world(tmp_path):
    """A repo root with scripts/ (for the V6 counters), an allow-list, and automation dirs."""
    root = tmp_path / "repo"
    (root / ".github").mkdir(parents=True)
    (root / ".github" / "large-files-allowlist.txt").write_text("# allow-list\nglobal_ports.geojson\n")
    (root / "scripts").symlink_to(REPO / "scripts")
    auto = root / "automation" / "repd"
    for sub in ("releases", "releases_v6", "baselines"):
        (auto / sub).mkdir(parents=True)
    shutil.copy(PKG / "releases" / "2026q2.json", auto / "releases")
    files = tmp_path / "files"
    files.mkdir()
    return {"root": root, "auto": auto, "files": files, "out": tmp_path / "out"}


def put(world, name, data):
    (world["files"] / name).write_bytes(data)


def synthetic(world, stem):
    rows = base_rows(6)
    put(world, f"{stem}.csv", make_csv(rows))
    put(world, f"{stem}.xlsx", make_xlsx(rows))


def run(world, api, *extra):
    argv = ["--out", str(world["out"]), "--repo-root", str(world["root"]), "--api-file", str(FIX / api),
            "--files-dir", str(world["files"]), "--release-folder", "202705060517", *extra]
    code = monthly.main(argv)
    return code, json.loads((world["out"] / "result.json").read_text())


def test_quarter_from_date():
    assert monthly.quarter_from_date("2026-11-13") == (2026, 3)
    assert monthly.quarter_from_date("2027-02-04") == (2026, 4)
    assert monthly.quarter_from_date("2027-05-06T09:30:00+01:00") == (2027, 1)
    assert monthly.quarter_from_date("2026-07-31") == (2026, 2)
    assert monthly.release_name((2026, 4)) == "January 2027"
    assert monthly.release_name((2027, 1)) == "April 2027"


def test_new_release_writes_descriptors_allowlist_and_counts(world):
    synthetic(world, "REPD_Publication_Q1_2027")
    code, res = run(world, "content_api_2027q1.json")
    assert code == 0 and res["status"] == "new" and res["release_id"] == "2027q1"
    assert res["published"]["label"] == "April 2027"
    assert res["counts"] == {"csv_rows": 6, "unique_refs": 6, "duplicate_refs": [],
                             "solar_gt_1mw": 3, "bess_gt_100mw": 3}
    d = config.load(world["auto"] / "releases" / "2027q1.json")      # validates the schema
    assert d.previous_release_id == "2026q2" and d.quarter == "Q1 2027"
    assert d.dataset_title == "Renewable Energy Planning Database (REPD): April 2027 (Q1 2027)"
    assert d.expected.csv_sha256 == res["files"]["csv"]["sha256"]
    v6 = json.loads((world["auto"] / "releases_v6" / "v6_2027q1.json").read_text())
    for key in ("release_id", "quarter_label", "output_suffix", "csv_url", "xlsx_url", "publication_date",
                "dataset_title", "expected_rows", "expected_unique_refs", "expected_solar_gt1",
                "expected_bess_gt100", "expected_csv_sha256", "expected_xlsx_sha256"):
        assert v6.get(key) not in (None, ""), key          # every key scripts/repd_sources_v6.py requires
    assert v6["output_suffix"] == "2027q1" and v6["expected_solar_gt1"] == 3
    allow = (world["root"] / ".github" / "large-files-allowlist.txt").read_text()
    for line in monthly.allowlist_lines("2027q1", "202705060517"):
        assert f"\n{line}\n" in allow
    assert (world["out"] / "raw" / "REPD_Publication_Q1_2027.csv").is_file()
    assert "New REPD release 2027q1" in (world["out"] / "summary.md").read_text()


def test_unchanged_when_hashes_are_pinned(world):
    synthetic(world, "REPD_Publication_Q1_2027")
    run(world, "content_api_2027q1.json")
    before = sorted(p.name for p in (world["auto"] / "releases").iterdir())
    allow = (world["root"] / ".github" / "large-files-allowlist.txt").read_text()
    shutil.rmtree(world["out"])
    code, res = run(world, "content_api_2027q1.json")
    assert code == 0 and res["status"] == "unchanged" and res["release_id"] == "2027q1"
    assert sorted(p.name for p in (world["auto"] / "releases").iterdir()) == before
    assert (world["root"] / ".github" / "large-files-allowlist.txt").read_text() == allow
    assert "No new REPD release" in (world["out"] / "summary.md").read_text()


def test_redirected_old_url_is_judged_by_hash_not_url(world, tmp_path):
    """GOV.UK serves the replaced July URL's file name with new bytes: hashes decide."""
    synthetic(world, "REPD_Publication_Q1_2027")
    run(world, "content_api_2027q1.json")              # pins the synthetic bytes as 2027q1
    shutil.rmtree(world["out"])
    for ext in ("csv", "xlsx"):                         # old July URL names now carry those bytes
        shutil.copy(world["files"] / f"REPD_Publication_Q1_2027.{ext}",
                    world["files"] / f"REPD_Publication_Q2_2026.{ext}")
    code, res = run(world, "content_api_2026q2_old_urls.json")
    assert code == 0 and res["status"] == "unchanged" and res["release_id"] == "2027q1"


def test_same_quarter_with_new_bytes_needs_a_person(world):
    synthetic(world, "REPD_Publication_Q1_2027")
    run(world, "content_api_2027q1.json")
    shutil.rmtree(world["out"])
    rows = base_rows(7)                                 # a correction: one more row, same quarter
    put(world, "REPD_Publication_Q1_2027.csv", make_csv(rows))
    put(world, "REPD_Publication_Q1_2027.xlsx", make_xlsx(rows))
    before = (world["auto"] / "releases" / "2027q1.json").read_text()
    code, res = run(world, "content_api_2027q1.json")
    assert code == 1 and res["status"] == "needs_person" and "2027q1" in res["reason"]
    assert (world["auto"] / "releases" / "2027q1.json").read_text() == before
    assert "needs a person" in (world["out"] / "summary.md").read_text()


def test_unnamed_files_get_a_date_derived_id(world):
    synthetic(world, "repd-extract")
    code, res = run(world, "content_api_unnamed.json")
    assert code == 0 and res["status"] == "new"
    assert res["release_id"] == "2026q4" and res["published"]["label"] == "January 2027"
    assert res["published"]["id_from"].startswith("publication date 2027-02-04")
    config.load(world["auto"] / "releases" / "2026q4.json")


def test_acceptance_waivers_carry_forward(world):
    (world["auto"] / "baselines" / "2026q2_known_anomalies.json").write_text(json.dumps(
        {"known": {"1": "x"}, "acceptance_waive_cells": ["15915:Address"]}))
    synthetic(world, "REPD_Publication_Q1_2027")
    code, res = run(world, "content_api_2027q1.json")
    known = json.loads((world["auto"] / "baselines" / "2027q1_known_anomalies.json").read_text())
    assert known["acceptance_waive_cells"] == ["15915:Address"] and known["known"] == {}


def test_allowlist_is_idempotent_and_optional(world):
    root = world["root"]
    assert len(monthly.add_allowlist(root, "2027q1", "202705060517")) == 3
    assert monthly.add_allowlist(root, "2027q1", "202705060517") == []
    synthetic(world, "REPD_Publication_Q1_2027")
    allow = (root / ".github" / "large-files-allowlist.txt").read_text()
    (root / ".github" / "large-files-allowlist.txt").write_text("x\n")
    run(world, "content_api_2027q1.json", "--no-allowlist")
    assert (root / ".github" / "large-files-allowlist.txt").read_text() == "x\n"
    assert allow.count("dist/repd_master_2027q1.json") == 1


def test_unreadable_publication_is_an_error_not_green(world, tmp_path):
    bad = tmp_path / "bad.json"
    bad.write_text('{"details": {"attachments": []}}')
    code = monthly.main(["--out", str(world["out"]), "--repo-root", str(world["root"]),
                         "--api-file", str(bad), "--files-dir", str(world["files"])])
    res = json.loads((world["out"] / "result.json").read_text())
    assert code == 2 and res["status"] == "error"


def test_github_output(world, monkeypatch, tmp_path):
    out = tmp_path / "gh_output"
    monkeypatch.setenv("GITHUB_OUTPUT", str(out))
    synthetic(world, "REPD_Publication_Q1_2027")
    run(world, "content_api_2027q1.json")
    lines = dict(line.split("=", 1) for line in out.read_text().splitlines())
    assert lines["status"] == "new" and lines["release_id"] == "2027q1"
    assert lines["release_folder"] == "202705060517" and lines["csv"].endswith("REPD_Publication_Q1_2027.csv")


@pytest.mark.skipif(not (REAL / "REPD_Publication_Q3_2026.csv").is_file(), reason="real October files absent")
def test_real_october_files_are_unchanged_against_main(tmp_path):
    out = tmp_path / "out"
    code = monthly.main(["--out", str(out), "--repo-root", str(REPO), "--api-file",
                         str(Path(__file__).resolve().parent / "fixtures" / "detect_fetch" / "content_api_2026q3.json"),
                         "--files-dir", str(REAL)])
    res = json.loads((out / "result.json").read_text())
    assert code == 0 and res["status"] == "unchanged" and res["release_id"] == "2026q3"
    assert res["files"]["csv"]["sha256"] == Q3_CSV