In this section
- Build Connection Points ingest · data-grid-gb / derived/build_connection_points.py lines 358–372
- Test Assets test · data-grid-gb / tests/test_assets.py lines 1–368
- Test DC Address Locations test · data-grid-gb / tests/test_dc_address_locations.py lines 1–242
Build Connection Points
A Python command-line tool in the derived folder of Data Grid GB that reads GB transmission network, grid substations, transformers and 400kV.
ingestdata-grid-gb / derived/build_connection_points.py · lines 358–372 of 372 (continued from section 1699) · Entry point · pattern tokens (shared by 8 files)
- What it does
- It loads GB transmission network, grid substations, transformers and 400kV. Defines 8 functions or classes, including normalise, tokens, shore_qualifier, qualifier_compatible, site_join_context. Uses libraries io, json, os, re, collections. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: transformers, 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; GeoJSON file grid_substations.geojson. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- Downstream impact
- Used directly by 3 files: Refresh Network Products Workflow (data-grid-gb); Verify Connection Points (data-grid-gb); Verify Phase0 Acceptance (data-grid-gb).
- What it achieves
- It serialises join context (`serialise_join_context`) and summarises fault rows (`summarise_fault_rows`). Derive the browser-sized connection-point product. Its code works with 132 kV and 400 kV.
- Why it matters
- Imported by Verify Connection Points and Verify Phase0 Acceptance. Run by Refresh Network Products Workflow.
- Application
- data-grid-gb · derived · Python CLI
- Uses
- io, json, os, re, collections
- Used by
- run by Refresh Network Products Workflow (workflow run), imported by Verify Connection Points (import), imported by Verify Phase0 Acceptance (import)
- Produces
- normalise, tokens, shore_qualifier, qualifier_compatible, site_join_context, serialise_join_context, summarise_fault_rows, main
- 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
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 derived/build_connection_points.py:358-372 · blob 68a413752f72678a6285c578794c937fc595de83 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
json.dumps(product, ensure_ascii=False, separators=(",", ":")) + "\n")
print(f"wrote derived/{OUTPUT} "
f"({os.path.getsize(out) / 1024:.0f} kB)")
for key, value in product["counts"].items():
print(f" {key:<26} {value:>6,}")
print(f" join: exact {joined_exact}, tokens {joined_token}, "
f"ambiguous exact {ambiguous_exact}, ambiguous tokens {ambiguous_token}, "
f"ambiguous identities {ambiguous_identity}, "
f"shore qualifier conflicts {qualifier_conflict}, "
f"unlocated {unjoined}")
return 0
if __name__ == "__main__":
raise SystemExit(main())Test Assets
A test in the tests folder of Data Grid GB that checks Reproduce and Pipeline, using SHA-256. It makes root (`make_root`) and sets up (`setUp`).
testdata-grid-gb / tests/test_assets.py · lines 1–368 of 368 · Entry point · pattern SchemaTests (shared by 2 files)
- What it does
- It tests its inputs. Defines 40 functions or classes, including good_datacentre, raw_requests, normalise, make_root, opener_for. Uses libraries __future__, contextlib, io, json, os. Side effects: reads or writes files; makes network requests.
- Inputs & outputs
- In: JSON file sites.json; GeoJSON file fake-src.geojson; JSON file s1.json; JSON file sources.json; JSON file escape.json. Out: JSON file sources.json; JSON file sites.json; GeoJSON file fake-src.geojson.
- Downstream impact
- Used directly by 1 file: Test Assets Workflow (data-grid-gb).
- What it achieves
- Tests for the data-centre and conventional-generation pipelines (assetpipe, `ci/verify.py`, `reproduce.py`). It writes `datacentres/normalised/fake-src.geojson`.
- Why it matters
- Checked by Test Assets Workflow.
- Application
- data-grid-gb · tests · test
- Uses
- Reproduce (import), Pipeline (import), Schema (import), Xlsx (import), Data Grid GB — Assetpipe (import), CI Verify (import), Data Grid GB — CI (import), __future__, contextlib, io, json, os, shutil, sys, tempfile
- Used by
- run by Test Assets Workflow (workflow run)
- Produces
- good_datacentre, raw_requests, normalise, make_root, opener_for, quiet, SchemaTests, PipelineTests, RepositoryTests, XlsxTests
- Defines here
- good_datacentre, raw_requests, normalise, make_root, opener_for, opener, quiet, SchemaTests, test_good_record_passes, test_ambiguous_mw_field_is_rejected, test_it_load_and_grid_connection_both_required_as_keys, test_unknown_is_null_not_zero, test_no_commitment_status, test_location_precision_rules, test_evidence_url_must_be_https, test_conventional_capacity_needs_a_basis, test_feature_has_null_geometry_when_location_unknown, PipelineTests, setUp, tearDown, fetch, test_fetch_pins_and_refetch_is_stable, test_changed_upstream_fails_until_update_pins, test_unverified_source_is_not_fetched_by_default_and_never_normalised, test_normalise_verify_reproduce_round_trip, test_verify_fails_on_tampered_raw_output_or_licence, test_nondeterministic_normaliser_is_caught_by_reproduce, test_schema_problem_blocks_normalised_output, test_network_failure_is_reported_and_keeps_previous_snapshot, blocked
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 tests/test_assets.py:1-368 · blob c4d56d0770d698ba4ad8a9a7754a5f9597697ea3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: supporting_data
"""Tests for the data-centre and conventional-generation pipelines (assetpipe, ci/verify.py, reproduce.py).
Run with ``python -m unittest discover -s tests -v``. Standard library only; the one
test that needs openpyxl skips without it, unless ASSETS_REQUIRE_DEPS=1 (the
requirements leg of CI), where a skip would hide a broken install and fails instead.
"""
from __future__ import annotations
import contextlib
import io
import json
import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import reproduce # noqa: E402
from assetpipe import pipeline, schema, xlsx # noqa: E402
from ci import verify # noqa: E402
REQUIRE_DEPS = os.environ.get("ASSETS_REQUIRE_DEPS") == "1"
def good_datacentre(**over) -> dict:
rec = {
"id": "fake-src:site-1",
"name": "Example Data Centre",
"operator": None,
"status": "in_planning",
"it_load_mw": None,
"grid_connection_mw": 90,
"dates": {"application": "2026-03"},
"source": {"id": "fake-src", "licence": "OGL-3.0",
"licence_url": "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
"evidence_url": "https://example.org/application/1"},
"location": {"lon": -1.5, "lat": 52.5, "precision": "site"},
}
rec.update(over)
return rec
FAKE_FETCHER = '''
import json
SOURCE_ID = "fake-src"
LANE = "TEST"
STATUS = "ready"
def raw_requests():
return [{"file": "sites.json", "url": "https://example.org/sites.json"}]
def normalise(raw):
rows = json.loads(raw["sites.json"])
out = []
for row in rows:
out.append({
"id": "fake-src:" + row["ref"], "name": row["name"], "operator": None,
"status": row["status"], "it_load_mw": row.get("it"), "grid_connection_mw": row.get("grid"),
"dates": {},
"source": {"id": "fake-src", "licence": "OGL-3.0",
"licence_url": "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
"evidence_url": "https://example.org/sites/" + row["ref"]},
"location": {"lon": row["lon"], "lat": row["lat"], "precision": "site"},
})
return out
'''
FAKE_ROWS = [
{"ref": "b", "name": "Site B", "status": "consented", "it": 40, "grid": 60, "lon": -0.4, "lat": 51.5},
{"ref": "a", "name": "Site A", "status": "announced", "it": None, "grid": None, "lon": -2.2, "lat": 53.4},
]
def make_root(tmp: Path, *, open_value="yes", fetcher=FAKE_FETCHER) -> Path:
for domain in ("datacentres", "conventional"):
(tmp / domain / "fetchers").mkdir(parents=True)
sources = []
if domain == "datacentres":
sources = [
{"id": "fake-src", "title": "Fake", "publisher": "Test", "url": "https://example.org/",
"licence": "OGL-3.0",
"licence_url": "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
"open": open_value, "module": "fake_src", "lane": "TEST"},
{"id": "closed-src", "title": "Closed", "publisher": "Test", "url": "https://example.org/c",
"licence": "proprietary", "licence_url": None, "open": "no", "module": None},
]
(tmp / domain / "fetchers" / "fake_src.py").write_text(fetcher, encoding="utf-8")
(tmp / domain / "NOTICE").write_text(
"".join(f"{e['id']} (open: {e['open']})\n" for e in sources), encoding="utf-8")
(tmp / domain / "sources.json").write_text(json.dumps(
{"schema": "gb-asset-source-registry.v1", "domain": domain, "sources": sources}), encoding="utf-8")
return tmp
def opener_for(payload: bytes):
calls = []
def opener(request):
calls.append(request["url"])
return payload
opener.calls = calls
return opener
def quiet(fn, *args, **kwargs):
with contextlib.redirect_stdout(io.StringIO()) as out:
result = fn(*args, **kwargs)
return result, out.getvalue()
class SchemaTests(unittest.TestCase):
def test_good_record_passes(self):
self.assertEqual(schema.validate_datacentre(good_datacentre()), [])
def test_ambiguous_mw_field_is_rejected(self):
for key in schema.FORBIDDEN_DATACENTRE_MW_KEYS:
problems = schema.validate_datacentre(good_datacentre(**{key: 50}))
self.assertTrue(any("ambiguous" in p for p in problems), key)
def test_it_load_and_grid_connection_both_required_as_keys(self):
rec = good_datacentre()
del rec["it_load_mw"]
self.assertTrue(any("it_load_mw missing" in p for p in schema.validate_datacentre(rec)))
def test_unknown_is_null_not_zero(self):
self.assertTrue(schema.validate_datacentre(good_datacentre(it_load_mw=0)))
self.assertTrue(schema.validate_datacentre(good_datacentre(name="")))
def test_no_commitment_status(self):
self.assertTrue(schema.validate_datacentre(good_datacentre(status="committed")))
def test_location_precision_rules(self):
self.assertTrue(schema.validate_datacentre(good_datacentre(
location={"lon": -1, "lat": 52, "precision": "unknown"})))
self.assertEqual(schema.validate_datacentre(good_datacentre(
location={"lon": None, "lat": None, "precision": "unknown"})), [])
self.assertTrue(schema.validate_datacentre(good_datacentre(
location={"lon": 10.0, "lat": 52, "precision": "site"})))
def test_evidence_url_must_be_https(self):
rec = good_datacentre()
rec["source"]["evidence_url"] = "http://example.org/x"
self.assertTrue(schema.validate_datacentre(rec))
def test_conventional_capacity_needs_a_basis(self):
rec = good_datacentre()
for key in ("it_load_mw", "grid_connection_mw", "dates"):
rec.pop(key)
rec.update({"fuel": "gas", "status": "operational", "capacity_mw": 1200})
self.assertTrue(any("capacity_basis" in p for p in schema.validate_conventional(rec)))
rec["capacity_basis"] = "DUKES 5.11 installed capacity"
self.assertEqual(schema.validate_conventional(rec), [])
self.assertTrue(schema.validate_conventional({**rec, "fuel": "wind"}))
def test_feature_has_null_geometry_when_location_unknown(self):
feature = schema.record_to_feature(good_datacentre(
location={"lon": None, "lat": None, "precision": "unknown"}))
self.assertIsNone(feature["geometry"])
class PipelineTests(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp(prefix="assets-test-"))
self.payload = json.dumps(FAKE_ROWS).encode("utf-8")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def fetch(self, root, payload=None, **kw):
opener = opener_for(payload or self.payload)
quiet(pipeline.fetch_domain, "datacentres", root=root, opener=opener,
fetched_at="2026-10-29T00:00:00Z", **kw)
return opener
def test_fetch_pins_and_refetch_is_stable(self):
root = make_root(self.tmp)
opener = self.fetch(root)
self.assertEqual(opener.calls, ["https://example.org/sites.json"]) # the closed source is never requested
manifest_path = root / "datacentres/raw/MANIFEST.json"
first = manifest_path.read_bytes()
meta = json.loads(first)["files"]["fake-src/sites.json"]
self.assertEqual(meta["sha256"], pipeline.sha256_bytes(self.payload))
quiet(pipeline.fetch_domain, "datacentres", root=root, opener=opener_for(self.payload),
fetched_at="2026-10-30T00:00:00Z")
self.assertEqual(manifest_path.read_bytes(), first, "an unchanged re-fetch must leave no diff")
def test_changed_upstream_fails_until_update_pins(self):
root = make_root(self.tmp)
self.fetch(root)
changed = json.dumps(FAKE_ROWS[:1]).encode("utf-8")
with self.assertRaises(pipeline.PipelineError):
self.fetch(root, changed)
self.fetch(root, changed, update_pins=True)
meta = json.loads((root / "datacentres/raw/MANIFEST.json").read_text())["files"]["fake-src/sites.json"]
self.assertEqual(meta["sha256"], pipeline.sha256_bytes(changed))
def test_unverified_source_is_not_fetched_by_default_and_never_normalised(self):
root = make_root(self.tmp, open_value="unverified")
opener = self.fetch(root)
self.assertEqual(opener.calls, [])
self.fetch(root, include_unverified=True)
index, _ = quiet(pipeline.normalise_domain, "datacentres", root=root)
self.assertEqual(index["outputs"], {})
def test_normalise_verify_reproduce_round_trip(self):
root = make_root(self.tmp)
self.fetch(root)
quiet(pipeline.normalise_domain, "datacentres", root=root)
out = root / "datacentres/normalised/fake-src.geojson"
obj = json.loads(out.read_text())
self.assertEqual([f["id"] for f in obj["features"]], ["fake-src:a", "fake-src:b"]) # sorted
self.assertEqual(obj["metadata"]["licence"], "OGL-3.0")
rc, text = quiet(verify.main, ["--root", str(root)])
self.assertEqual(rc, 0, text)
rc, text = quiet(reproduce.main, ["check", "--root", str(root), "--json", str(self.tmp / "s1.json")])
self.assertEqual(rc, 0, text)
summary = json.loads((self.tmp / "s1.json").read_text())
src = summary["domains"]["datacentres"]["sources"]["fake-src"]
self.assertEqual(src["rebuilt"], "identical")
head = src["headline"]
self.assertEqual(head["it_load_mw"], {"known": 1, "unknown": 1, "sum_of_known": 40})
self.assertEqual(head["grid_connection_mw"], {"known": 1, "unknown": 1, "sum_of_known": 60})
rc, _ = quiet(reproduce.main, ["check", "--root", str(root), "--expect", summary["summary_sha256"]])
self.assertEqual(rc, 0, "the same commit must give the same summary_sha256")
def test_verify_fails_on_tampered_raw_output_or_licence(self):
root = make_root(self.tmp)
self.fetch(root)
quiet(pipeline.normalise_domain, "datacentres", root=root)
pristine = self.tmp.parent / (self.tmp.name + "-copy")
shutil.copytree(root, pristine)
try:
cases = {
"raw": lambda r: (r / "datacentres/raw/fake-src/sites.json").write_bytes(b"[]"),
"output": lambda r: (r / "datacentres/normalised/fake-src.geojson").write_text(
(r / "datacentres/normalised/fake-src.geojson").read_text().replace("Site A", "Site Z")),
"orphan": lambda r: (r / "datacentres/raw/fake-src/extra.bin").write_bytes(b"x"),
"notice": lambda r: (r / "datacentres/NOTICE").write_text("closed-src (open: no)\n"),
# registry and NOTICE agree that the source is unverified: the published output must fail
"licence": lambda r: ((r / "datacentres/sources.json").write_text(
(r / "datacentres/sources.json").read_text().replace('"open": "yes"', '"open": "unverified"')),
(r / "datacentres/NOTICE").write_text(
(r / "datacentres/NOTICE").read_text().replace("(open: yes)", "(open: unverified)"))),
}
for name, damage in cases.items():
work = self.tmp.parent / (self.tmp.name + "-" + name)
shutil.copytree(pristine, work)
try:
damage(work)
rc, text = quiet(verify.main, ["--root", str(work)])
self.assertEqual(rc, 1, f"{name}: verify passed a damaged tree\n{text}")
if name == "licence":
self.assertIn("not marked fully open", text)
finally:
shutil.rmtree(work, ignore_errors=True)
finally:
shutil.rmtree(pristine, ignore_errors=True)
def test_nondeterministic_normaliser_is_caught_by_reproduce(self):
flaky = FAKE_FETCHER.replace('"name": row["name"]', '"name": row["name"] + " " + str(id(row))')
root = make_root(self.tmp, fetcher=flaky)
self.fetch(root)
quiet(pipeline.normalise_domain, "datacentres", root=root)
rc, text = quiet(reproduce.main, ["check", "--root", str(root)])
self.assertEqual(rc, 1, text)
self.assertIn("not byte-identical", text)
def test_schema_problem_blocks_normalised_output(self):
bad = FAKE_FETCHER.replace('"grid_connection_mw": row.get("grid")', '"mw": row.get("grid")')
root = make_root(self.tmp, fetcher=bad)
self.fetch(root)
with self.assertRaises(pipeline.PipelineError):
quiet(pipeline.normalise_domain, "datacentres", root=root)
self.assertFalse((root / "datacentres/normalised/fake-src.geojson").exists())
def test_network_failure_is_reported_and_keeps_previous_snapshot(self):
root = make_root(self.tmp)
self.fetch(root)
before = (root / "datacentres/raw/MANIFEST.json").read_bytes()
def blocked(request):
raise OSError("Tunnel connection failed: 403 Forbidden")
manifest, out = quiet(pipeline.fetch_domain, "datacentres", root=root, opener=blocked)
self.assertEqual(manifest["failures"], ["fake-src/sites.json"])
self.assertIn("unknown, not zero", out)
self.assertEqual((root / "datacentres/raw/MANIFEST.json").read_bytes(), before)
def test_unsafe_raw_file_name_is_refused(self):
evil = FAKE_FETCHER.replace('"file": "sites.json"', '"file": "../../escape.json"')
root = make_root(self.tmp, fetcher=evil)
with self.assertRaises(pipeline.PipelineError):
self.fetch(root)
class RepositoryTests(unittest.TestCase):
def test_committed_tree_verifies(self):
rc, text = quiet(verify.main, ["--root", str(ROOT)])
self.assertEqual(rc, 0, text)
def test_committed_tree_reproduces(self):
rc, text = quiet(reproduce.main, ["check", "--root", str(ROOT)])
self.assertEqual(rc, 0, text)
def test_every_registered_fetcher_loads_and_placeholders_do_not_pretend(self):
for domain in ("datacentres", "conventional"):
for entry in pipeline.load_registry(domain)["sources"]:
module = pipeline.load_module(domain, entry)
if module is None:
self.assertEqual(entry["open"], "no", entry["id"])
continue
self.assertIn(module.STATUS, ("ready", "snapshot", "placeholder"))
if module.STATUS in ("placeholder", "snapshot"):
if module.STATUS == "placeholder":
self.assertEqual(module.raw_requests(), [])
with self.assertRaises(NotImplementedError):
module.normalise({})
if module.STATUS != "placeholder":
self.assertNotEqual(entry["open"], "no", f"{entry['id']}: fetcher on a source that is not open")
if module.STATUS == "ready":
self.assertEqual(entry["open"], "yes", f"{entry['id']}: ready fetcher on a source not fully open")
for request in module.raw_requests():
self.assertTrue(request["url"].startswith("https://"), request["url"])
def test_pinned_data_is_exempt_from_line_ending_conversion(self):
text = (ROOT / ".gitattributes").read_text(encoding="utf-8")
for domain in ("datacentres", "conventional"):
self.assertIn(f"{domain}/** -text", text, "eol=lf would rewrite CRLF snapshots and break their pins")
def test_fetch_workflow_is_manual_only(self):
text = (ROOT / ".github/workflows/fetch-assets.yml").read_text(encoding="utf-8")
self.assertIn("workflow_dispatch:", text)
self.assertNotIn("schedule:", text)
self.assertNotIn("git push origin main", text)
def test_test_workflow_runs_with_and_without_requirements(self):
text = (ROOT / ".github/workflows/test-assets.yml").read_text(encoding="utf-8")
self.assertIn("deps: [requirements, bare]", text)
self.assertIn("ASSETS_REQUIRE_DEPS", text)
class XlsxTests(unittest.TestCase):
def test_sheet_rows_round_trip(self):
if not xlsx.available():
if REQUIRE_DEPS:
self.fail("openpyxl is missing but ASSETS_REQUIRE_DEPS=1 (the requirements leg)")
with self.assertRaises(xlsx.MissingDependency):
xlsx.sheet_rows(b"not a workbook", "5.11")
self.skipTest("openpyxl not installed (bare leg)")
import openpyxl
book = openpyxl.Workbook()
sheet = book.active
sheet.title = "5.11"
sheet.append(["Station", "Fuel", "Installed Capacity (MW)"])
sheet.append(["Example", "CCGT", 1200])
buffer = io.BytesIO()
book.save(buffer)
rows = xlsx.sheet_rows(buffer.getvalue(), "5.11")
self.assertEqual(rows[1], ["Example", "CCGT", 1200])
with self.assertRaises(KeyError):
xlsx.sheet_rows(buffer.getvalue(), "missing")
if __name__ == "__main__":
unittest.main()Test DC Address Locations
A test in the tests folder of Data Grid GB that checks Build and Pipeline, using SHA-256. It makes snapshot (`make_snapshot`), sets up (`setUp`) and runs build (`run_build`).
testdata-grid-gb / tests/test_dc_address_locations.py · lines 1–242 of 242 · Entry point · pattern run_build (shared by 2 files)
- What it does
- It tests postcodes. Defines 27 functions or classes, including claim, fixtures, make_snapshot, AddressLocationTests, setUp. Uses libraries copy, importlib.util, json, pathlib, tempfile. Side effects: reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'dc'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: postcodes.
- Inputs & outputs
- In: JSON file cohort.json; JSON file wikidata-000.json; JSON file postcodes-000.json; JSON file inputs.json; JSON file x.json; JSON file accepted.json; JSON file source-snapshot.json; GeoJSON file datacentre-locations.geojson. Out: JSON file source-snapshot.json; JSON file cohort.json; JSON file wikidata-000.json.
- Downstream impact
- Used directly by 2 files: Datacentre Addresses Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb).
- What it achieves
- Offline synthetic checks for address provenance, uncertainty and source joins. It reads `x.json`.
- Why it matters
- Run by Datacentre Addresses Workflow. Checked by Test Assets Workflow.
- Application
- data-grid-gb · tests · test
- Uses
- Build (import), Pipeline (import), copy, importlib.util, json, pathlib, tempfile, tarfile, unittest, unittest.mock
- Used by
- run by Datacentre Addresses Workflow (workflow run), run by Test Assets Workflow (workflow run)
- Produces
- claim, fixtures, make_snapshot, AddressLocationTests
- Defines here
- claim, fixtures, make_snapshot, AddressLocationTests, setUp, run_build, test_street_address_claim_and_postcode_precision_remain_attributable, test_missing_address_or_point_is_null_and_source_record_is_retained, test_preferred_wikidata_point_beats_postcode_and_preserves_precision, test_conflicting_points_are_not_silently_replaced_by_a_postcode, test_multiple_postcodes_require_review, test_northern_ireland_postcode_scope_is_not_silently_licensed, test_geocoder_cannot_substitute_another_postcode_or_country, test_nonfinite_false_origin_boolean_and_out_of_range_points_reject, test_source_country_cannot_drift_from_original_country_identity, test_duplicate_or_missing_source_identity_fails, test_name_candidate_does_not_assign_geometry_or_verified_identity, test_explicit_source_qid_is_separate_from_operator_and_name_matching, test_collector_refuses_arbitrary_source_or_internal_endpoint, test_collector_validates_path_before_network_or_existing_file_writes, test_collector_cannot_replace_an_existing_captured_resource, test_offline_snapshot_requires_actual_source_bytes, test_snapshot_path_traversal_is_rejected, test_existing_generation_is_never_replaced, test_offline_replays_are_byte_identical, test_full_feature_rows_and_nulls_roundtrip_in_zstd_parquet, test_committed_actual_generation_rebuilds_from_its_complete_source_archive
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 tests/test_dc_address_locations.py:1-242 · blob 27338aff957ef199d15e0f72669f82b3a14940e6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Offline synthetic checks for address provenance, uncertainty and source joins."""
import copy
import importlib.util
import json
from pathlib import Path
import tempfile
import tarfile
import unittest
from unittest.mock import patch
from datacentres.locations.build import build, encoded, point, sha, write_parquet
from datacentres.locations.pipeline import Collector, load_snapshot, main
def claim(prop, value, rank='normal'):
return {'id': 'Q1$' + prop, 'rank': rank, 'mainsnak': {'snaktype': 'value', 'datavalue': {'value': value}},
'references': [{'snaks': {'P854': [{'snaktype': 'value', 'datavalue': {'value': 'https://fixture.example/source'}}]}}]}
def fixtures():
cohort = {'schema': 'globalgrid2050.global-datacentres.projects.v1', 'record_count': 1,
'records': [{'id': 'DC-WD-Q1', 'name': 'Synthetic DC',
'country': {'code': 'GB', 'wikidata_id': 'Q145', 'name': 'United Kingdom'},
'source': {'revision_url': 'https://www.wikidata.org/w/index.php?title=Q1&oldid=1'}}]}
entity = {'id': 'Q1', 'lastrevid': 2, 'claims': {
'P17': [claim('P17', {'id': 'Q145'})],
'P6375': [claim('P6375', {'text': '1 Synthetic Street, London SW1A 1AA', 'language': 'en'})]}}
geocodes = {'SW1A 1AA': {'postcode': 'SW1A 1AA', 'latitude': 51.501, 'longitude': -0.141,
'quality': 1, 'country': 'England'}}
return cohort, {'Q1': entity}, geocodes, {'retrieved_at': '2026-11-17T00:00:00Z'}
def make_snapshot(folder):
cohort, entities, geocodes, _ = fixtures()
payloads = {'cohort.json': cohort, 'wikidata-000.json': {'entities': entities},
'postcodes-000.json': {'status': 200, 'result': [{'query': k, 'result': v} for k, v in geocodes.items()]}}
payloads['inputs.json'] = {'cohort': {'url': 'https://fixture.example/cohort', 'sha256': sha(encoded(cohort))}, 'references': []}
resources = []
for name, data in payloads.items():
raw = encoded(data)
(folder / name).write_bytes(raw)
resources.append({'path': name, 'bytes': len(raw), 'sha256': sha(raw),
'request_json': {'postcodes': list(geocodes)} if name.startswith('postcodes') else None})
snapshot = {'retrieved_at': '2026-11-17T00:00:00Z', 'resources': resources}
(folder / 'source-snapshot.json').write_bytes(encoded(snapshot))
class AddressLocationTests(unittest.TestCase):
def setUp(self):
self.cohort, self.entities, self.geocodes, self.receipt = fixtures()
def run_build(self, references=()):
return build(self.cohort, self.entities, self.geocodes, self.receipt, references)
def test_street_address_claim_and_postcode_precision_remain_attributable(self):
doc = self.run_build()
p = doc['features'][0]['properties']
self.assertEqual(doc['counts']['postcode_centroids'], 1)
self.assertEqual(p['addresses'][0]['statement_id'], 'Q1$P6375')
self.assertEqual(p['addresses'][0]['reference_urls'], ['https://fixture.example/source'])
self.assertEqual(p['location_precision'], 'POSTCODE_CENTROID_APPROXIMATE')
self.assertEqual(p['source_statement_licence'], 'CC0-1.0')
self.assertIn('OS OpenData', p['geometry_licence'])
self.assertEqual(len(p['geometry_attribution']), 4)
self.assertNotIn('source_licence', p)
self.assertIn('oldid=2', p['source_revision_url'])
self.assertIn('oldid=1', p['original_pipeline_revision_url'])
self.assertFalse(p['grid_connection_assessed'])
self.assertIn('longitude=-0.141', p['screening_url'])
self.assertNotIn('repd_ref', p['screening_url'])
def test_missing_address_or_point_is_null_and_source_record_is_retained(self):
self.entities['Q1']['claims'].pop('P6375')
doc = self.run_build()
self.assertEqual(doc['counts']['records'], 1)
self.assertIsNone(doc['features'][0]['geometry'])
self.assertIsNone(doc['features'][0]['properties']['screening_url'])
def test_preferred_wikidata_point_beats_postcode_and_preserves_precision(self):
values = {'longitude': -1, 'latitude': 52, 'precision': 0.01, 'globe': 'http://www.wikidata.org/entity/Q2'}
self.entities['Q1']['claims']['P625'] = [claim('P625-old', {**values, 'longitude': -2}), claim('P625', values, 'preferred')]
p = self.run_build()['features'][0]['properties']
self.assertEqual(p['location_precision'], 'WIKIDATA_REPORTED_POINT')
self.assertEqual(p['location_source']['precision_degrees'], 0.01)
def test_conflicting_points_are_not_silently_replaced_by_a_postcode(self):
value = {'longitude': -1, 'latitude': 52, 'precision': 0.01, 'globe': 'http://www.wikidata.org/entity/Q2'}
self.entities['Q1']['claims']['P625'] = [claim('P625-a', value), claim('P625-b', {**value, 'longitude': -2})]
self.assertIsNone(self.run_build()['features'][0]['geometry'])
def test_multiple_postcodes_require_review(self):
self.entities['Q1']['claims']['P281'] = [claim('P281', 'M1 1AA')]
self.assertIsNone(self.run_build()['features'][0]['geometry'])
def test_northern_ireland_postcode_scope_is_not_silently_licensed(self):
self.entities['Q1']['claims']['P6375'][0]['mainsnak']['datavalue']['value']['text'] = 'Synthetic Belfast BT1 1AA'
self.geocodes['BT1 1AA'] = {'postcode': 'BT1 1AA', 'latitude': 54.6, 'longitude': -5.9, 'country': 'Northern Ireland'}
doc = self.run_build()
self.assertIsNone(doc['features'][0]['geometry'])
self.assertIn('distinct reuse terms', doc['features'][0]['properties']['notes'][0])
def test_geocoder_cannot_substitute_another_postcode_or_country(self):
for wrong in ({'postcode': 'M1 1AA'}, {'country': 'France'}, {'latitude': 48.8566, 'longitude': 2.3522}):
with self.subTest(wrong=wrong):
original = copy.deepcopy(self.geocodes)
self.geocodes['SW1A 1AA'].update(wrong)
with self.assertRaises(ValueError):
self.run_build()
self.geocodes = original
def test_nonfinite_false_origin_boolean_and_out_of_range_points_reject(self):
for lon, lat in [(0, 0), (float('nan'), 52), (-1, float('inf')), (True, 52), (181, 52), (-1, 91)]:
with self.subTest(lon=lon, lat=lat), self.assertRaises(ValueError):
point(lon, lat)
def test_source_country_cannot_drift_from_original_country_identity(self):
self.entities['Q1']['claims']['P17'] = [claim('P17', {'id': 'Q142'})]
with self.assertRaisesRegex(ValueError, 'country conflicts'):
self.run_build()
def test_duplicate_or_missing_source_identity_fails(self):
self.cohort['records'] *= 2
self.cohort['record_count'] = 2
with self.assertRaisesRegex(ValueError, 'duplicate'):
self.run_build()
def test_name_candidate_does_not_assign_geometry_or_verified_identity(self):
self.entities['Q1']['claims'].pop('P6375')
refs = [{'id': 'synthetic-source', 'url': 'https://fixture.example/data', 'sha256': 'a'*64,
'licence': 'SYNTHETIC', 'attribution': 'Synthetic fixture', 'document': {'features': [
{'type': 'Feature', 'geometry': point(-1, 52), 'properties': {'id': 'OT-C-1', 'name': 'Synthetic DC', 'operator:wikidata': 'Q1'}}]}}]
f = self.run_build(refs)['features'][0]
self.assertIsNone(f['geometry'])
self.assertEqual(f['properties']['cross_references'][0]['method'], 'EXACT_NAME_CANDIDATE')
self.assertFalse(f['properties']['cross_references'][0]['geometry_adopted'])
def test_explicit_source_qid_is_separate_from_operator_and_name_matching(self):
refs = [{'id': 'synthetic-source', 'url': 'https://fixture.example/data', 'sha256': 'a'*64,
'licence': 'SYNTHETIC', 'attribution': 'Synthetic fixture', 'document': {'features': [
{'type': 'Feature', 'geometry': point(-1, 52), 'properties': {'id': 'wd:Q1', 'name': 'Another label', 'sources': [{'source': 'Wikidata', 'source_id': 'wd:Q1'}]}}]}}]
ref = self.run_build(refs)['features'][0]['properties']['cross_references'][0]
self.assertEqual(ref['method'], 'EXPLICIT_WIKIDATA_SOURCE_ID')
self.assertGreater(ref['distance_m'], 1000)
self.assertFalse(ref['geometry_adopted'])
def test_collector_refuses_arbitrary_source_or_internal_endpoint(self):
with tempfile.TemporaryDirectory() as folder, patch('datacentres.locations.pipeline.urlopen') as network:
with self.assertRaises(ValueError):
Collector(Path(folder)).fetch('x.json', 'https://127.0.0.1/private')
network.assert_not_called()
def test_collector_validates_path_before_network_or_existing_file_writes(self):
with tempfile.TemporaryDirectory() as folder, patch('datacentres.locations.pipeline.urlopen') as network:
root = Path(folder)
target = root / 'accepted.json'
target.write_bytes(b'accepted bytes')
stage = root / 'scratch'
stage.mkdir()
for name in ('../accepted.json', 'references/../../accepted.json', 'references/C:accepted.geojson'):
with self.assertRaisesRegex(ValueError, 'Unsafe'):
Collector(stage).fetch(name, 'https://www.wikidata.org/w/api.php')
self.assertEqual(target.read_bytes(), b'accepted bytes')
network.assert_not_called()
def test_collector_cannot_replace_an_existing_captured_resource(self):
with tempfile.TemporaryDirectory() as folder, patch('datacentres.locations.pipeline.urlopen') as network:
root = Path(folder)
(root / 'cohort.json').write_bytes(b'accepted source bytes')
with self.assertRaises(FileExistsError):
Collector(root).fetch('cohort.json', 'https://raw.githubusercontent.com/owner/repo/pinned/file')
self.assertEqual((root / 'cohort.json').read_bytes(), b'accepted source bytes')
network.assert_not_called()
def test_offline_snapshot_requires_actual_source_bytes(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
make_snapshot(root)
self.assertEqual(load_snapshot(root)['counts']['with_geometry'], 1)
(root / 'wikidata-000.json').write_bytes(b'{}')
with self.assertRaisesRegex(ValueError, 'bytes'):
load_snapshot(root)
def test_snapshot_path_traversal_is_rejected(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
make_snapshot(root)
p = root / 'source-snapshot.json'
d = json.loads(p.read_bytes())
d['resources'][0]['path'] = '../cohort.json'
p.write_bytes(encoded(d))
with self.assertRaisesRegex(ValueError, 'Unsafe'):
load_snapshot(root)
def test_existing_generation_is_never_replaced(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
(root / 'accepted.txt').write_text('accepted bytes')
with self.assertRaises(FileExistsError):
main(['build', '--output', str(root)])
self.assertEqual((root / 'accepted.txt').read_text(), 'accepted bytes')
def test_offline_replays_are_byte_identical(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
source = root / 'source'
source.mkdir()
make_snapshot(source)
for name in ('first', 'second'):
main(['build', '--snapshot', str(source), '--output', str(root / name)])
self.assertEqual((root / 'first/datacentre-locations.geojson').read_bytes(), (root / 'second/datacentre-locations.geojson').read_bytes())
@unittest.skipUnless(importlib.util.find_spec('duckdb'), 'Optional DuckDB is installed by the address workflow')
def test_full_feature_rows_and_nulls_roundtrip_in_zstd_parquet(self):
with tempfile.TemporaryDirectory() as folder:
p = Path(folder) / 'locations.parquet'
proof = write_parquet(self.run_build(), p)
self.assertEqual(proof['rows'], 1)
self.assertEqual(proof['full_row_readback'], 'PASS')
def test_committed_actual_generation_rebuilds_from_its_complete_source_archive(self):
folder = Path(__file__).parents[1] / 'datacentres/locations/data/20261117T002200Z'
manifest = json.loads((folder / 'manifest.json').read_bytes())
source = folder / manifest['source_archive']['path']
self.assertEqual(sha(source.read_bytes()), manifest['source_archive']['sha256'])
for name, proof in manifest['products'].items():
self.assertEqual(sha((folder / name).read_bytes()), proof['sha256'])
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
with tarfile.open(source) as archive:
archive.extractall(root, filter='data')
document = load_snapshot(root)
self.assertEqual(encoded(document), (folder / 'datacentre-locations.geojson').read_bytes())
cohort = json.loads((root / 'cohort.json').read_bytes())
self.assertEqual({f['id'] for f in document['features']}, {r['id'] for r in cohort['records']})
if importlib.util.find_spec('duckdb'):
path = root / 'reproduced.parquet'
write_parquet(document, path)
self.assertEqual(path.read_bytes(), (folder / 'datacentre-locations.parquet').read_bytes())
if __name__ == '__main__':
unittest.main()