In this section
- Make Standin test · globalgrid2050 / automation/repd/tests/pages/make_standin.py lines 1–130
- Renewable Energy Planning Database (REPD) — Tests test · globalgrid2050 / automation/repd/tests/pages/run.sh lines 1–15
- Test Pages Harness test · globalgrid2050 / automation/repd/tests/pages/test_pages_harness.py lines 1–82
- Reconstruct V6 Canonical test · globalgrid2050 / automation/repd/tests/reconstruct_v6_canonical.py lines 1–45
- Test Acceptance test · globalgrid2050 / automation/repd/tests/test_acceptance.py lines 1–388
Make Standin
A Python command-line tool in the pages folder of GlobalGrid2050 that tests Renewable Energy Planning Database (REPD) grid batteries, REPD solar operational over 4MW, REPD master and standin counts.
testglobalgrid2050 / automation/repd/tests/pages/make_standin.py · lines 1–130 of 130 · Entry point · pattern read_rows (shared by 3 files)
- What it does
- It tests REPD grid batteries, REPD solar operational over 4MW, REPD master and standin counts. Defines 6 functions or classes, including norm, capacity, read_rows, write_csv, main. Uses libraries __future__, argparse, csv, io, json. 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 repd-grid-batteries.csv; CSV file repd-solar-operational-over-4mw.csv; CSV file repd-solar-operational.csv; JSON file repd_master.json; command-line arguments. Out: JSON file repd_master.json; JSON file STANDIN_COUNTS.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 2 files: Renewable Energy Planning Database (REPD) — Tests (globalgrid2050); Test Pages Harness (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It reads rows (`read_rows`) and writes CSV (`write_csv`). Build a STAND-IN set of October root datasets for the page harness. Its code works with 1 MW and 4 MW. It writes `repd.csv`. It accepts `--staged`, `--out` and `--repo`.
- Why it matters
- Checked by 2 tests, including Renewable Energy Planning Database (REPD) — Tests.
- Application
- globalgrid2050 · automation/repd/tests/pages · Python CLI
- Uses
- __future__, argparse, csv, io, json, re, sys, pathlib
- Used by
- run by Renewable Energy Planning Database (REPD) — Tests (script call), imported by Test Pages Harness (import)
- Produces
- norm, capacity, read_rows, write_csv, main
- Defines here
- norm, capacity, read_rows, write_csv, main, cap
- 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/pages/make_standin.py:1-130 · blob 0d6739088f4263ea72e69f69cb0a01b269fd4d38 · 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
#!/usr/bin/env python3
"""Build a STAND-IN set of October root datasets for the page harness.
Used only when the lead's build_root.py output (auto/root_out/) is not available yet.
Reads a canonical staged REPD CSV (53 columns, UTF-8 with or without BOM) and writes,
into --out (never into the repo):
repd.csv all rows, all columns
repd-grid-batteries.csv Technology Type == Battery and
Development Status (short) in BATTERY_STATUSES
repd-solar-operational.csv Solar Photovoltaics, Operational, capacity > 1 MW,
Mounting Type for Solar in {Ground, Roof}
(column subset copied from --columns-like if given)
repd-solar-operational-over-4mw.csv Solar Photovoltaics, Operational, capacity > 4 MW
dist/repd_master.json via scripts/repd_updater.py REPDUpdater.refine_dataset
(imported from --repo, never modified)
All CSVs are written UTF-8 without BOM, LF line endings. Blank capacity is unknown and
therefore never passes a "> N MW" filter. The filters are the documented ones; on the
January 2026 root repd.csv they reproduce the January subset counts for both solar files
exactly (1209 and 924); see NOTES.md for the battery file.
"""
from __future__ import annotations
import argparse
import csv
import io
import json
import re
import sys
from pathlib import Path
BATTERY_STATUSES = {
"Operational", "Under Construction", "Awaiting Construction",
"Application Submitted", "Appeal Lodged", "No Application Required",
}
SOLAR = "Solar Photovoltaics"
def norm(h: str) -> str:
return re.sub(r"\s+", " ", h.replace("", "")).strip()
def capacity(v: str):
v = (v or "").replace(",", "").strip()
if not v:
return None
try:
return float(v)
except ValueError:
return None
def read_rows(path: Path):
text = path.read_bytes().decode("utf-8-sig")
rdr = csv.reader(io.StringIO(text, newline=""))
header = next(rdr)
rows = [r for r in rdr if r]
return header, rows
def write_csv(path: Path, header, rows):
path.parent.mkdir(parents=True, exist_ok=True)
buf = io.StringIO(newline="")
w = csv.writer(buf, lineterminator="\n")
w.writerow(header)
w.writerows(rows)
path.write_bytes(buf.getvalue().encode("utf-8"))
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--staged", required=True, type=Path)
ap.add_argument("--out", required=True, type=Path)
ap.add_argument("--repo", type=Path, help="repo checkout holding scripts/repd_updater.py (for repd_master.json)")
ap.add_argument("--columns-like", type=Path,
help="January repd-solar-operational.csv; its header defines that file's column subset")
a = ap.parse_args(argv)
header, rows = read_rows(a.staged)
ix = {norm(h): i for i, h in enumerate(header)}
for need in ("Technology Type", "Development Status (short)", "Installed Capacity (MWelec)", "Mounting Type for Solar"):
if need not in ix:
sys.exit(f"staged CSV lacks column {need!r}")
T, S, C, M = (ix[k] for k in ("Technology Type", "Development Status (short)",
"Installed Capacity (MWelec)", "Mounting Type for Solar"))
a.out.mkdir(parents=True, exist_ok=True)
out_header = [h.replace("", "") for h in header]
def cap(r):
return capacity(r[C])
bat = [r for r in rows if r[T].strip() == "Battery" and r[S].strip() in BATTERY_STATUSES]
so = [r for r in rows if r[T].strip() == SOLAR and r[S].strip() == "Operational"
and (cap(r) or 0) > 1 and r[M].strip() in ("Ground", "Roof")]
so4 = [r for r in rows if r[T].strip() == SOLAR and r[S].strip() == "Operational" and (cap(r) or 0) > 4]
write_csv(a.out / "repd.csv", out_header, rows)
write_csv(a.out / "repd-grid-batteries.csv", out_header, bat)
write_csv(a.out / "repd-solar-operational-over-4mw.csv", out_header, so4)
if a.columns_like:
jan_head = a.columns_like.read_bytes().decode("utf-8-sig").splitlines()[0]
want = [norm(h) for h in next(csv.reader([jan_head]))]
missing = [w for w in want if w not in ix]
if missing:
sys.exit(f"columns-like header has columns absent from staged CSV: {missing}")
sel = [ix[w] for w in want]
write_csv(a.out / "repd-solar-operational.csv", [out_header[i] for i in sel], [[r[i] for i in sel] for r in so])
else:
write_csv(a.out / "repd-solar-operational.csv", out_header, so)
counts = {"repd.csv": len(rows), "repd-grid-batteries.csv": len(bat),
"repd-solar-operational.csv": len(so), "repd-solar-operational-over-4mw.csv": len(so4)}
if a.repo:
sys.path.insert(0, str(a.repo / "scripts"))
import repd_updater # noqa: E402 (read-only import of the live writer)
from pyproj import Transformer
up = repd_updater.REPDUpdater.__new__(repd_updater.REPDUpdater) # skip __init__ (it mkdirs dist/ in cwd)
up.transformer = Transformer.from_crs("epsg:27700", "epsg:4326", always_xy=True)
gj = up.refine_dataset(str(a.out / "repd.csv"))
(a.out / "dist").mkdir(exist_ok=True)
(a.out / "dist" / "repd_master.json").write_text(json.dumps(gj, separators=(",", ":")), encoding="utf-8")
counts["dist/repd_master.json"] = len(gj["features"])
(a.out / "STANDIN_COUNTS.json").write_text(json.dumps(counts, indent=2) + "\n", encoding="utf-8")
print(json.dumps(counts, indent=2))
if __name__ == "__main__":
main()Renewable Energy Planning Database (REPD) — Tests
A shell script in the pages folder of GlobalGrid2050 that tests REPD solar operational and the REPD register.
testglobalgrid2050 / automation/repd/tests/pages/run.sh · lines 1–15 of 15 · Entry point
- What it does
- It tests REPD solar operational and the REPD register. Side effects: 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-solar-operational.csv; JSON file results.json.
- Downstream impact
- It is itself an entry point (shell script); no other file was found loading it.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · automation/repd/tests/pages · shell script
- Uses
- Make Standin (script call), Harness (script call)
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- 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/pages/run.sh:1-15 · blob fa17d6cb51bbc6173bf665663c92303b12e21286 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env bash
# Usage: run.sh <pages repo checkout> <january dir> <october dir or staged CSV> <out dir>
# If arg 3 is a CSV file, a stand-in October set is built from it first (make_standin.py).
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
PAGES="$1"; JAN="$2"; OCT="$3"; OUT="$4"
mkdir -p "$OUT"
[ -d "$HERE/node_modules/papaparse" ] || (cd "$HERE" && npm ci --no-audit --no-fund)
if [ -f "$OCT" ]; then
python3 "$HERE/make_standin.py" --staged "$OCT" --out "$OUT/october_standin" --repo "$PAGES" \
--columns-like "$JAN/repd-solar-operational.csv"
OCT="$OUT/october_standin"
fi
node "$HERE/harness.js" --pages "$PAGES" --set "jan=$JAN" --set "oct=$OCT" \
--json "$OUT/results.json" --md "$OUT/results.md"Test Pages Harness
A test in the tests folder of GlobalGrid2050 that checks Make Standin and Harness Test.
testglobalgrid2050 / automation/repd/tests/pages/test_pages_harness.py · lines 1–82 of 82 · Entry point
- What it does
- It tests its inputs. Defines _staged, test_filters_and_encoding, test_columns_like_subset, test_missing_column_fails_closed, test_node_harness_unit_tests. Uses libraries csv, io, json, shutil, subprocess. 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 staged.csv; JSON file STANDIN_COUNTS.json; CSV file repd.csv; CSV file repd-grid-batteries.csv; CSV file repd-solar-operational.csv; CSV file repd-solar-operational-over-4mw.csv; CSV file like.csv; CSV file bad.csv.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Pytest entry points for the page harness (synthetic fixtures only, no network).
- Why it matters
- Run by GlobalGrid2050 Project Signals Acid Workflow.
- Application
- globalgrid2050 · automation/repd/tests/pages · test
- Uses
- Make Standin (import), Harness Test (script call), csv, io, json, shutil, subprocess, sys, pathlib, pytest
- Used by
- run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- test_filters_and_encoding, test_columns_like_subset, test_missing_column_fails_closed, test_node_harness_unit_tests
- Defines here
- _staged, test_filters_and_encoding, test_columns_like_subset, test_missing_column_fails_closed, test_node_harness_unit_tests
- 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/pages/test_pages_harness.py:1-82 · blob 9e66eb94f0bb83f987e2f48c1963ff7b2e299a67 · 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
"""pytest entry points for the page harness (synthetic fixtures only, no network)."""
import csv
import io
import json
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import make_standin # noqa: E402
HEADER = ["Old Ref ID", "Ref ID", "Site Name", "Technology Type", "Installed Capacity (MWelec)",
"Mounting Type for Solar", "Development Status", "Development Status (short)", "X-coordinate", "Y-coordinate",
"Planning Permission Granted"]
def _staged(tmp_path, rows, bom=True):
buf = io.StringIO(newline="")
w = csv.writer(buf, lineterminator="\n")
w.writerow(HEADER)
w.writerows(rows)
p = tmp_path / "staged.csv"
p.write_bytes(("" if bom else "").encode() + buf.getvalue().encode("utf-8"))
return p
ROWS = [
["", "1", "Bat Op", "Battery", "50", "", "Operational", "Operational", "1", "1", ""],
["", "2", "Bat Refused", "Battery", "50", "", "Application Refused", "Application Refused", "1", "1", ""],
["", "3", "Bat Appeal", "Battery", "", "", "Appeal Lodged", "Appeal Lodged", "1", "1", ""],
["", "4", "Sol Ground 2", "Solar Photovoltaics", "2", "Ground ", "Operational", "Operational", "1", "1", ""],
["", "5", "Sol Float 5", "Solar Photovoltaics", "5", "Floating", "Operational", "Operational", "1", "1", ""],
["", "6", "Sol blank cap", "Solar Photovoltaics", "", "Ground", "Operational", "Operational", "1", "1", ""],
["", "7", "Sol exactly 1", "Solar Photovoltaics", "1", "Roof", "Operational", "Operational", "1", "1", ""],
["", "8", "Sol Roof 4.5 café", "Solar Photovoltaics", "4.5", "Roof", "Operational", "Operational", "1", "1", ""],
]
def test_filters_and_encoding(tmp_path):
out = tmp_path / "out"
make_standin.main(["--staged", str(_staged(tmp_path, ROWS)), "--out", str(out)])
counts = json.loads((out / "STANDIN_COUNTS.json").read_text())
assert counts == {"repd.csv": 8, "repd-grid-batteries.csv": 2, "repd-solar-operational.csv": 2,
"repd-solar-operational-over-4mw.csv": 2}
for f in ("repd.csv", "repd-grid-batteries.csv", "repd-solar-operational.csv", "repd-solar-operational-over-4mw.csv"):
b = (out / f).read_bytes()
assert not b.startswith(b"\xef\xbb\xbf"), f
b.decode("utf-8")
assert b"\r\n" not in b
so = (out / "repd-solar-operational.csv").read_text(encoding="utf-8")
assert "Sol Ground 2" in so and "café" in so and "blank cap" not in so and "exactly 1" not in so
so4 = (out / "repd-solar-operational-over-4mw.csv").read_text(encoding="utf-8")
assert "Sol Float 5" in so4 and "Sol Roof 4.5" in so4
def test_columns_like_subset(tmp_path):
like = tmp_path / "like.csv"
like.write_text("Ref ID,Site Name,Are they re-applying (Old REPD Ref) \n", encoding="utf-8")
with pytest.raises(SystemExit):
make_standin.main(["--staged", str(_staged(tmp_path, ROWS)), "--out", str(tmp_path / "o"), "--columns-like", str(like)])
like.write_text("Ref ID,Site Name,Planning Permission Granted\n", encoding="utf-8") # double space matches
make_standin.main(["--staged", str(_staged(tmp_path, ROWS)), "--out", str(tmp_path / "o2"), "--columns-like", str(like)])
head = (tmp_path / "o2" / "repd-solar-operational.csv").read_text(encoding="utf-8").splitlines()[0]
assert head == "Ref ID,Site Name,Planning Permission Granted"
def test_missing_column_fails_closed(tmp_path):
p = tmp_path / "bad.csv"
p.write_text("Ref ID,Site Name\n1,a\n", encoding="utf-8")
with pytest.raises(SystemExit):
make_standin.main(["--staged", str(p), "--out", str(tmp_path / "o")])
@pytest.mark.skipif(shutil.which("node") is None or not (HERE / "node_modules" / "papaparse").exists(),
reason="node or node_modules (npm ci) not available")
def test_node_harness_unit_tests():
r = subprocess.run(["node", "--test", "harness.test.js"], cwd=HERE, capture_output=True, text=True, timeout=300)
assert r.returncode == 0, r.stdout + r.stderrReconstruct V6 Canonical
A Python module in the tests folder of GlobalGrid2050.
testglobalgrid2050 / automation/repd/tests/reconstruct_v6_canonical.py · lines 1–45 of 45
- What it does
- It tests its inputs. Uses libraries csv, json, sys. 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: command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Build V6 (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Rebuild the identity-relevant columns of the July V6 canonical CSV from the committed `dist/project_identity_v6.json` (the canonical CSV itself was never committed), so the identity stage can be re-run under the default (July) descriptor and compared byte-for-byte.
- Why it matters
- Checked by Test Build V6.
- Application
- globalgrid2050 · automation/repd/tests · Python module
- Uses
- csv, json, sys
- Used by
- run by Test Build V6 (script call)
- Produces
- none declared
- Defines here
- none
- 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/reconstruct_v6_canonical.py:1-45 · blob 75ea516e98d337025305a7151bf02ed076699b2a · 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
"""Rebuild the identity-relevant columns of the July V6 canonical CSV from the committed
dist/project_identity_v6.json (the canonical CSV itself was never committed), so the
identity stage can be re-run under the default (July) descriptor and compared byte-for-byte."""
import csv, json, sys
ident = json.load(open(sys.argv[1], encoding="utf-8"))
out = sys.argv[2]
rel_cols = [c["field"] for c in ident["detected_relationship_columns"]]
base = ["Ref ID", "Old Ref ID", "Record Last Updated (dd/mm/yyyy)", "Site Name", "Technology Type",
"Installed Capacity (MWelec)", "Development Status (short)", "Operator (or Applicant)", "County", "Region",
"Country", "Planning Authority", "Planning Application Reference", "Planning Application Submitted",
"Planning Application Withdrawn", "Planning Permission Refused", "Planning Permission Granted",
"Planning Permission Expired", "Under Construction", "Operational"]
headers = base + rel_cols
fillers = [f"Unused Column {i}" for i in range(ident["detected_header_count"] - len(headers))]
headers += fillers
raw_key = {"Record Last Updated (dd/mm/yyyy)": "repd_record_updated_raw", "Site Name": "site_name",
"Technology Type": "technology", "Installed Capacity (MWelec)": "capacity_mw_raw",
"Development Status (short)": "status", "Operator (or Applicant)": "operator", "County": "county",
"Region": "region", "Country": "country", "Planning Authority": "planning_authority",
"Planning Application Reference": "planning_application_reference",
"Planning Application Submitted": "planning_application_submitted_raw",
"Planning Application Withdrawn": "planning_application_withdrawn_raw",
"Planning Permission Refused": "planning_permission_refused_raw",
"Planning Permission Granted": "planning_permission_granted_raw",
"Planning Permission Expired": "planning_permission_expired_raw",
"Under Construction": "under_construction_raw", "Operational": "operational_raw"}
recs = ident["records"]
assert [r["source_row"] for r in recs] == list(range(2, len(recs) + 2))
with open(out, "w", encoding="utf-8-sig", newline="") as fh:
w = csv.writer(fh)
w.writerow(headers)
for r in recs:
row = {"Ref ID": r["repd_ref"] or "", "Old Ref ID": r["repd_old_ref"] or ""}
for col, key in raw_key.items():
# dated fields: the identity keeps *_raw only for the update date; the 7 official
# dates are stored normalised, so write them back as dd/mm/yyyy
if key.endswith("_raw") and key not in r:
iso = r[key[:-4]]
row[col] = f"{iso[8:10]}/{iso[5:7]}/{iso[0:4]}" if iso else ""
else:
row[col] = r.get(key) or ""
for col in rel_cols:
row[col] = ", ".join(x["repd_ref"] for x in r["relationships"] if x["source_field"] == col)
w.writerow([row.get(h, "") for h in headers])
print("rows", len(recs), "headers", len(headers))Test Acceptance
A test in the tests folder of GlobalGrid2050 that checks Acceptance. It makes official (`make_official`), makes cleaned (`make_cleaned`) and writes CSV (`write_csv`).
testglobalgrid2050 / automation/repd/tests/test_acceptance.py · lines 1–388 of 388 · Entry point · pattern write_xlsx (shared by 2 files)
- What it does
- It tests its inputs. Defines 44 functions or classes, including blank, setv, make_official, make_cleaned, write_csv. Uses libraries __future__, csv, datetime, io, json. 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: CSV file official.csv; Excel file official.xlsx; CSV file cleaned.csv; JSON file baseline.json; CSV file repd-2026q3.csv; CSV file bat.csv; CSV file solar.csv; CSV file over4.csv. Out: JSON file m.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Synthetic-fixture tests for `acceptance.py` (no network, no real data needed). It writes `repd-2026q3.csv`.
- Why it matters
- Run by GlobalGrid2050 Project Signals Acid Workflow.
- Application
- globalgrid2050 · automation/repd/tests · test
- Uses
- Acceptance (import), __future__, csv, datetime, io, json, os, sys, pathlib
- Used by
- run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- blank, setv, make_official, make_cleaned, write_csv, write_xlsx, solar_op_rows, build, cfg, failed, test_correct_candidate_passes_everything, test_without_xlsx_xlsx_classes_fail_closed
- Defines here
- blank, setv, make_official, make_cleaned, write_csv, write_xlsx, solar_op_rows, build, cfg, failed, test_correct_candidate_passes_everything, test_without_xlsx_xlsx_classes_fail_closed, test_disallowed_class_fails, test_missing_and_duplicated_refs, dmg, test_unclassified_value_change, dmg, test_month_first_left_or_blanked, dmg, test_mojibake_in_subset, dmg, test_non_utf8_full_file, dmg, test_bare_cr_and_broken_records, dmg, test_embedded_line_break_left_in_output, dmg, test_subset_missing_row_and_reformatted_numbers, dmg, test_blank_capacity_never_passes_threshold
- 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_acceptance.py:1-388 · blob b8e44266715e34842b83475b667599ad000d60b3 · 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
"""Synthetic-fixture tests for acceptance.py (no network, no real data needed).
A tiny official CSV + XLSX pair is built with one instance of every documented change
class; a correct candidate must pass every check, and each kind of real damage seen in
the January 2026 files (mojibake, bare CR, broken records, missing rows, re-formatted
numbers, month-first dates left in place, GeoJSON drift) must make the matching check fail.
Optional real-data check: set REPD_JAN_DIR to a globalgrid2050 checkout to assert that the
January root files fail the expected checks.
"""
from __future__ import annotations
import csv
import datetime as dt
import io
import json
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import acceptance as A # noqa: E402
openpyxl = pytest.importorskip("openpyxl")
pytest.importorskip("pyproj")
H = A.OFFICIAL_HEADER
IX = {A.norm_header(h): i for i, h in enumerate(H)}
def blank():
return [""] * len(H)
def setv(row, col, v):
row[IX[A.norm_header(col)]] = v
# ref, tech, short status, capacity CSV, capacity XLSX, mounting, X, Y, site name
BASE = [
("1", "Battery", "Operational", "50", 50, "", "530000", "180000", "Ørsted Battery"),
("2", "Battery", "Refused", "20", 20, "", "400000", "300000", "Refused Battery"),
("3", "Solar Photovoltaics", "Operational", "5.20", 5.2, "Ground", "450000", "250000", "Big Solar"),
("4", "Solar Photovoltaics", "Operational", "2.00", 2, "Roof", "", "", "Roof Solar No Coords"),
("5", "Solar Photovoltaics", "Operational", "0.37", 0.365, "Ground", "460000", "260000", "Small Solar"),
("6", "Wind Offshore", "Application Submitted", "", None, "", "600000", "400000", "Sea Wind"),
("7", "Battery", "Application Submitted", "100", 100, "", "350000", "350000", "Bat\xa0Seven "),
]
def make_official():
rows = []
for ref, tech, st, cap, _x, mnt, x, y, name in BASE:
r = blank()
for c, v in (("Ref ID", ref), ("Technology Type", tech), ("Development Status (short)", st),
("Development Status", st), ("Installed Capacity (MWelec)", cap), ("Mounting Type for Solar", mnt),
("X-coordinate", x), ("Y-coordinate", y), ("Site Name", name),
("Operator (or Applicant)", "Op " + ref), ("Record Last Updated (dd/mm/yyyy)", "01/10/2026"),
("Address", "Road " + ref)):
setv(r, c, v)
rows.append(r)
# change-class material
setv(rows[0], "Planning Application Submitted", "9/14/2026") # month-first, Excel m/d/yyyy
setv(rows[1], "Operational", "NA") # NA in date column
setv(rows[2], "Address", "Line one\nLine two") # embedded line break
setv(rows[5], "Offshore Wind Round", "03/01/1900") # number stored as date
setv(rows[2], "Planning Application Reference", "NA") # NA in text column
return rows
def make_cleaned(off_rows):
rows = [list(r) for r in off_rows]
setv(rows[0], "Planning Application Submitted", "14/09/2026")
setv(rows[1], "Operational", "")
setv(rows[2], "Address", "Line one Line two")
setv(rows[5], "Offshore Wind Round", "3")
setv(rows[2], "Planning Application Reference", "")
setv(rows[4], "Installed Capacity (MWelec)", "0.365") # XLSX precision
setv(rows[6], "Site Name", "Bat Seven") # NBSP + trailing space
return rows
def write_csv(path, header, rows, enc="utf-8", term="\n"):
buf = io.StringIO(newline="")
w = csv.writer(buf, lineterminator=term)
w.writerow(header)
w.writerows(rows)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(buf.getvalue().encode(enc))
def write_xlsx(path, off_rows):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "REPD"
ws.append(H)
for i, r in enumerate(off_rows):
vals = list(r)
vals[IX["Ref ID"]] = int(r[IX["Ref ID"]])
cap = BASE[i][4]
vals[IX["Installed Capacity (MWelec)"]] = cap
vals[IX["Record Last Updated (dd/mm/yyyy)"]] = dt.datetime(2026, 10, 1)
vals[IX["Planning Application Submitted"]] = None
vals[IX["Offshore Wind Round"]] = None
vals = [None if v == "" else v for v in vals]
ws.append(vals)
rown = ws.max_row
c = ws.cell(row=rown, column=IX["Record Last Updated (dd/mm/yyyy)"] + 1)
c.number_format = "mm-dd-yy"
if i == 0:
c = ws.cell(row=rown, column=IX["Planning Application Submitted"] + 1, value=dt.datetime(2026, 9, 14))
c.number_format = "m/d/yyyy"
if i == 5:
c = ws.cell(row=rown, column=IX["Offshore Wind Round"] + 1, value=dt.datetime(1900, 1, 3))
c.number_format = "mm-dd-yy"
wb.save(path)
def solar_op_rows(rows):
sel = [IX[A.norm_header(h)] for h in A.SOLAR_OP_HEADER]
return [[r[i] for i in sel] for r in rows]
def build(tmp_path, damage=None):
"""Write a complete, correct candidate; damage(dict of paths/rows) may alter it before writing."""
off = make_official()
cl = make_cleaned(off)
d = {"off": off, "cleaned": cl, "full": [list(r) for r in cl]}
g = lambda r, c: r[IX[c]] # noqa: E731
d["batteries"] = [list(r) for r in cl if g(r, "Technology Type") == "Battery"
and g(r, "Development Status (short)") in A.BATTERY_STATUSES]
sol = [r for r in cl if g(r, "Technology Type") == A.SOLAR and g(r, "Development Status (short)") == "Operational"]
d["solar_op"] = solar_op_rows([r for r in sol if (A.to_float(g(r, "Installed Capacity (MWelec)")) or 0) > 1
and g(r, "Mounting Type for Solar") in ("Ground", "Roof")])
d["over4"] = [list(r) for r in sol if (A.to_float(g(r, "Installed Capacity (MWelec)")) or 0) > 4]
d["solar_op_header"] = list(A.SOLAR_OP_HEADER)
d["full_enc"] = "utf-8"
d["raw_patch"] = {}
if damage:
damage(d)
p = {
"official_csv": tmp_path / "official.csv", "official_xlsx": tmp_path / "official.xlsx",
"cleaned": tmp_path / "cleaned.csv", "root": tmp_path / "root", "baseline": tmp_path / "baseline.json",
}
write_csv(p["official_csv"], H, d["off"], enc="cp1252", term="\r\n")
write_xlsx(p["official_xlsx"], d["off"])
write_csv(p["cleaned"], H, d["cleaned"])
root = p["root"]
write_csv(root / "repd-2026q3.csv", H, d["full"], enc=d["full_enc"])
write_csv(root / "bat.csv", H, d["batteries"])
write_csv(root / "solar.csv", d["solar_op_header"], d["solar_op"])
write_csv(root / "over4.csv", H, d["over4"])
for name, (old, new) in d["raw_patch"].items():
f = root / name
f.write_bytes(f.read_bytes().replace(old, new, 1))
cleaned_file = A.read_csv(p["cleaned"])
exp, _ = A.expected_master(cleaned_file)
feats = [{"type": "Feature", "properties": {"repd_ref": k, "name": "x", "capacity": 0.0},
"geometry": {"type": "Point", "coordinates": list(v)}} for k, v in exp.items()]
if "master_patch" in d:
feats = d["master_patch"](feats)
(root / "dist").mkdir(parents=True, exist_ok=True)
(root / "dist" / "m.json").write_text(json.dumps({"type": "FeatureCollection", "features": feats}))
p["baseline"].write_text(json.dumps({"type": "FeatureCollection", "features": [
{"type": "Feature", "properties": {"name": "a", "capacity": 1.0}, "geometry": {"type": "Point",
"coordinates": [0, 51]}}]}))
return p
def cfg(p, **kw):
base = dict(official_csv=p["official_csv"], official_xlsx=p["official_xlsx"], cleaned=p["cleaned"],
root_dir=p["root"], full="repd-2026q3.csv", batteries="bat.csv", solar_op="solar.csv",
over4="over4.csv", master="dist/m.json", baseline_master=p["baseline"], expect_month_first=1)
base.update(kw)
return A.Config(**base)
def failed(rep):
return sorted(c.id for c in rep.failed)
# ------------------------------------------------------------------ good candidate
def test_correct_candidate_passes_everything(tmp_path):
rep = A.run(cfg(build(tmp_path)))
assert failed(rep) == [], rep.text()
c = rep.checks["cleaned.cells_classified"].details["counts"]
assert c == {"month_first_date": 1, "na_date": 1, "embedded_line_break": 1, "number_as_date": 1,
"na_text": 1, "xlsx_precision": 1, "whitespace_control": 1}
assert rep.checks["master.features"].details["expected"] == 5 # refs 1,3,5,6,7 (2 refused, 4 no coords)
assert not any(c.status == "SKIP" for c in rep.checks.values())
assert set(rep.checks) == set(A.CHECK_IDS)
def test_without_xlsx_xlsx_classes_fail_closed(tmp_path):
rep = A.run(cfg(build(tmp_path), official_xlsx=None))
assert "cleaned.cells_classified" in failed(rep)
un = rep.checks["cleaned.cells_classified"].details["unclassified"]
assert {u[1] for u in un} == {"Planning Application Submitted", "Installed Capacity (MWelec)"}
assert rep.checks["cleaned.month_first_corrected"].status == "SKIP"
def test_disallowed_class_fails(tmp_path):
rep = A.run(cfg(build(tmp_path), allowed=A.DEFAULT_ALLOWED - {"na_text"}))
assert failed(rep) == ["cleaned.cells_classified"]
# ------------------------------------------------------------------ damage that must be detected
def test_missing_and_duplicated_refs(tmp_path):
def dmg(d):
d["cleaned"] = d["cleaned"][1:] + [d["cleaned"][2]]
rep = A.run(cfg(build(tmp_path, dmg)))
det = rep.checks["cleaned.refs_exactly_once"].details
assert det["missing"] == ["1"] and det["repeated"] == {"3": 2}
def test_unclassified_value_change(tmp_path):
def dmg(d):
setv(d["cleaned"][2], "Installed Capacity (MWelec)", "6.20")
d["full"] = [list(r) for r in d["cleaned"]]
rep = A.run(cfg(build(tmp_path, dmg)))
assert "cleaned.cells_classified" in failed(rep)
assert rep.checks["cleaned.cells_classified"].details["unclassified"][0][:2] == ("3", "Installed Capacity (MWelec)")
def test_month_first_left_or_blanked(tmp_path):
def dmg(d):
setv(d["cleaned"][0], "Planning Application Submitted", "") # quarantined instead of corrected
d["full"] = [list(r) for r in d["cleaned"]]
rep = A.run(cfg(build(tmp_path, dmg)))
assert {"cleaned.month_first_corrected", "cleaned.cells_classified"} <= set(failed(rep))
def test_mojibake_in_subset(tmp_path):
def dmg(d):
setv(d["batteries"][0], "Site Name", "Ørsted Battery".encode("utf-8").decode("latin-1"))
rep = A.run(cfg(build(tmp_path, dmg)))
assert set(failed(rep)) == {"batteries.no_mojibake", "batteries.filter"}
named = rep.checks["batteries.no_mojibake"].details["named"]
assert named and named[0][2] == "Ørsted Battery"
def test_non_utf8_full_file(tmp_path):
def dmg(d):
d["full_enc"] = "cp1252"
rep = A.run(cfg(build(tmp_path, dmg)))
assert failed(rep) == ["full.utf8"]
def test_bare_cr_and_broken_records(tmp_path):
# a line-based tool split a multi-line address: the record is cut in two
def dmg(d):
d["batteries"][0][IX["Address"]] = "Road 1"
d["raw_patch"]["bat.csv"] = (b"Road 1", b"Road\r1")
rep = A.run(cfg(build(tmp_path, dmg)))
f = set(failed(rep))
assert {"batteries.no_bare_cr", "batteries.field_count", "batteries.filter"} <= f
def test_embedded_line_break_left_in_output(tmp_path):
def dmg(d):
setv(d["over4"][0], "Address", "Line one\nLine two")
rep = A.run(cfg(build(tmp_path, dmg)))
assert {"over4.no_embedded_breaks", "over4.filter"} <= set(failed(rep))
def test_subset_missing_row_and_reformatted_numbers(tmp_path):
def dmg(d):
d["batteries"] = d["batteries"][:-1]
d["over4"][0][IX["Installed Capacity (MWelec)"]] = "5.2" # pandas float re-serialisation of 5.20
rep = A.run(cfg(build(tmp_path, dmg)))
assert rep.checks["batteries.filter"].details["missing"] == ["7"]
assert rep.checks["over4.filter"].details["numeric_reformatted"] == 1
def test_blank_capacity_never_passes_threshold(tmp_path):
def dmg(d):
r = list(d["cleaned"][3])
setv(r, "Installed Capacity (MWelec)", "")
d["cleaned"][3] = r
p = build(tmp_path, dmg)
exp = A.expected_subsets(A.read_csv(p["cleaned"]))
assert "4" not in [r[IX["Ref ID"]] for r in exp["solar_op"]]
def test_solar_op_header_must_match_january(tmp_path):
def dmg(d):
d["solar_op_header"] = [A.norm_header(h) for h in A.SOLAR_OP_HEADER]
rep = A.run(cfg(build(tmp_path, dmg)))
assert failed(rep) == ["solar_op.header"]
def test_master_drift(tmp_path):
def dmg(d):
def patch(feats):
feats = feats[1:]
feats[0]["geometry"]["coordinates"][0] += 0.01
del feats[1]["properties"]["capacity"]
return feats
d["master_patch"] = patch
rep = A.run(cfg(build(tmp_path, dmg)))
det = rep.checks["master.features"].details
assert det["missing"] == ["1"] and len(det["moved"]) == 1
assert rep.checks["master.keys_superset"].details["lacking"] == {"capacity": 1}
def test_master_unparseable(tmp_path):
p = build(tmp_path)
(p["root"] / "dist" / "m.json").write_text("{not json")
rep = A.run(cfg(p))
assert "master.parses" in failed(rep)
def test_pin_mismatch(tmp_path):
p = build(tmp_path)
rep = A.run(cfg(p, pins={str(p["official_csv"]): "0" * 64}))
assert failed(rep) == ["inputs.unchanged"]
# ------------------------------------------------------------------ units and CLI
def test_units():
assert A.month_first_format("m/d/yyyy") and not A.month_first_format("mm-dd-yy")
assert not A.month_first_format("[$-10452]dd/mm/yyyy;@") and not A.month_first_format("General")
assert A.demojibake("Ã\x98rsted") == "Ørsted" and A.demojibake("Ørsted") is None
assert A.is_mojibake("CromerÂ\xa0") and not A.is_mojibake("Brân")
assert A.classify_cell("Site Name", " A\xa0 B ", "A B", None) == "whitespace_control"
assert A.classify_cell("Address", "a\r\nb", "a b", None) == "embedded_line_break"
assert A.classify_cell("Operational", "NA", "", None) == "na_date"
assert A.classify_cell("Installed Capacity (MWelec)", "0.37", "0.365", (0.365, "0.00")) == "xlsx_precision"
assert A.classify_cell("Installed Capacity (MWelec)", "0.37", "0.38", (0.365, "0.00")) is None
assert A.classify_cell("Offshore Wind Round", "02/01/1900", "2.5", (dt.datetime(1900, 1, 2, 12), "mm-dd-yy")) \
== "number_as_date"
assert A.classify_cell("Planning Application Submitted", "9/14/2026", "14/09/2026",
(dt.datetime(2026, 9, 14), "m/d/yyyy")) == "month_first_date"
assert A.classify_cell("Planning Application Submitted", "9/14/2026", "14/09/2026",
(dt.datetime(2026, 9, 14), "mm-dd-yy")) is None
def test_cli_exit_codes_and_json(tmp_path):
p = build(tmp_path)
args = ["--official-csv", str(p["official_csv"]), "--official-xlsx", str(p["official_xlsx"]),
"--cleaned", str(p["cleaned"]), "--root-dir", str(p["root"]), "--full", "repd-2026q3.csv",
"--batteries", "bat.csv", "--solar-op", "solar.csv", "--over4", "over4.csv",
"--master", "dist/m.json", "--baseline-master", str(p["baseline"]), "--json", str(tmp_path / "r.json")]
assert A.main(args) == 0
assert json.loads((tmp_path / "r.json").read_text())["failed"] == []
assert A.main(args + ["--disallow-class", "xlsx_precision"]) == 1
assert A.main(["--official-csv", str(tmp_path / "nope.csv"), "--cleaned", str(p["cleaned"])]) == 2
# ------------------------------------------------------------------ optional real data
JAN = os.environ.get("REPD_JAN_DIR")
@pytest.mark.skipif(not JAN, reason="set REPD_JAN_DIR to a globalgrid2050 checkout")
def test_january_root_files_are_detected_as_damaged():
j = Path(JAN)
rep = A.run(A.Config(official_csv=j / "repd.csv", cleaned=j / "repd.csv", root_dir=j,
baseline_master=j / "dist" / "repd_master.json"))
f = set(failed(rep))
assert {"batteries.no_mojibake", "solar_op.no_mojibake", "over4.no_mojibake",
"batteries.field_count", "batteries.no_bare_cr", "batteries.filter",
"full.utf8"} <= f
assert rep.checks["batteries.field_count"].details["count"] == 33
assert rep.checks["batteries.filter"].details["extra"] and not rep.checks["batteries.filter"].details["missing"]
def test_partial_whitespace_normalisation_is_whitespace_but_joined_words_are_not():
assert A.classify_cell("Site Name", "Road\n - Solar ", "Road - Solar", None) == "embedded_line_break"
assert A.classify_cell("Site Name", "Line\ntwo", "Linetwo", None) is None
def test_waived_cell_is_reported_not_failed(tmp_path):
def dmg(d):
setv(d["cleaned"][0], "Address", "Road ?")
d["full"] = [list(r) for r in d["cleaned"]]
d["batteries"][0][IX["Address"]] = "Road ?"
p = build(tmp_path, dmg)
rep = A.run(cfg(p))
assert {"cleaned.cells_classified", "cleaned.text_matches_excel"} <= set(failed(rep))
rep = A.run(cfg(p, waived=frozenset({("1", "Address")})))
assert failed(rep) == []
assert rep.checks["cleaned.cells_classified"].details["waived"]