In this section
- Conftest test · neural-link-between-agents / FIXES/NL-012/review-b967360d/tests/conftest.py lines 1–143
- Test Date Rule Unit test · neural-link-between-agents / FIXES/NL-012/review-b967360d/tests/test_date_rule_unit.py lines 1–193
- Test Ingest Regression test · neural-link-between-agents / FIXES/NL-012/review-b967360d/tests/test_ingest_regression.py lines 1–256
- Test Unpatched Defects test · neural-link-between-agents / FIXES/NL-012/review-b967360d/tests/test_unpatched_defects.py lines 1–87
Conftest
A Python module in the tests folder of Neural Link Between Agents that tests the Renewable Energy Planning Database (REPD) register. It makes CSV (`make_csv`) and makes xlsx (`make_xlsx`).
testneural-link-between-agents / FIXES/NL-012/review-b967360d/tests/conftest.py · lines 1–143 of 143 · Not reached from any entry point (candidate for review) · pattern _csv_text (shared by 2 files)
- What it does
- It tests the REPD register. Defines 10 functions or classes, including base_rows, _csv_text, make_csv, make_xlsx, ingest. Uses libraries __future__, csv, inspect, io, os. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: the REPD register.
- Inputs & outputs
- Out: CSV file.
- Downstream impact
- Used directly by 3 files: Test Date Rule Unit (neural-link-between-agents); Test Ingest Regression (neural-link-between-agents); Test Unpatched Defects (neural-link-between-agents).
- What it achieves
- Shared synthetic-release builders. No network, no real data.
- Why it matters
- Checked by 3 tests, including Test Date Rule Unit.
- Application
- neural-link-between-agents · FIXES/NL-012/review-b967360d/tests · Python module
- Uses
- __future__, csv, inspect, io, os, sys, datetime, pathlib
- Used by
- imported by Test Date Rule Unit (import), imported by Test Ingest Regression (import), imported by Test Unpatched Defects (import)
- Produces
- base_rows, make_csv, make_xlsx, ingest, q2, rule, run, candidate_bytes
- Defines here
- base_rows, _csv_text, make_csv, make_xlsx, ingest, q2, rule, run, _run, candidate_bytes
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-012/review-b967360d/tests/conftest.py:1-143 · blob f238111d572003e1d0ad919d83eb99c3203fffc7 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Shared synthetic-release builders. No network, no real data.
REPD_TEST_TARGET selects the scripts under test:
patched (default) work8/patched/scripts = commit b967360d + proposed.patch
original work8/tiproot/scripts = commit b967360d as delivered
"""
from __future__ import annotations
import csv
import inspect
import io
import os
import sys
from datetime import date, datetime
from pathlib import Path
import openpyxl
import pytest
WORK = Path(__file__).resolve().parents[1]
TARGET = os.environ.get("REPD_TEST_TARGET", "patched")
SCRIPTS = WORK / {"patched": "patched", "original": "tiproot"}[TARGET] / "scripts"
sys.path.insert(0, str(SCRIPTS))
sys.path.insert(0, str(WORK)) # standalone repd_date_rule (identical to the patched copy)
# Official header order in miniature, keeping the real quirks: a trailing space
# and a double space inside two headers.
COLUMNS = [
"Old Ref ID", "Ref ID", "Record Last Updated (dd/mm/yyyy)", "Operator (or Applicant)",
"Site Name", "Technology Type", "Installed Capacity (MWelec)", "Development Status (short)",
"Are they re-applying (Old REPD Ref) ", "Planning Authority", "Planning Application Reference",
"Planning Application Submitted", "Planning Application Withdrawn", "Planning Permission Refused",
"Appeal Lodged", "Planning Permission Granted", "Planning Permission Expired",
"Under Construction", "Operational",
]
LOCALE_SHORT_DATE = "mm-dd-yy" # built-in format 14: what almost every official date cell carries
MONTH_FIRST = "m/d/yyyy" # explicit custom format carried by the 25 October cells
def base_rows(n: int = 6) -> list[dict]:
rows = []
for i in range(1, n + 1):
rows.append({
"Old Ref ID": "", "Ref ID": 100 + i,
"Record Last Updated (dd/mm/yyyy)": date(2026, 10, 8),
"Operator (or Applicant)": f"Operator {i} Ltd", "Site Name": f"Site {i}",
"Technology Type": "Solar Photovoltaics" if i % 2 else "Battery",
"Installed Capacity (MWelec)": 49.9 if i % 2 else 120,
"Development Status (short)": "Application Submitted",
"Are they re-applying (Old REPD Ref) ": "", "Planning Authority": "Shropshire",
"Planning Application Reference": f"26/0{i}/FUL",
"Planning Application Submitted": date(2026, 8, 20 + i),
"Planning Application Withdrawn": None, "Planning Permission Refused": None,
"Appeal Lodged": date(2026, 9, 13 + i) if i == 2 else None,
"Planning Permission Granted": None, "Planning Permission Expired": None,
"Under Construction": None, "Operational": None,
})
return rows
def _csv_text(value) -> str:
if value is None:
return ""
if isinstance(value, (date, datetime)):
return value.strftime("%d/%m/%Y")
return str(value)
def make_csv(rows: list[dict], overrides: dict | None = None, columns: list[str] | None = None,
newline: str = "\r\n", encoding: str = "cp1252") -> bytes:
"""Official-style CSV: cp1252, CRLF. overrides[(ref, column)] = literal CSV text."""
overrides = overrides or {}
columns = columns or COLUMNS
buffer = io.StringIO(newline="")
writer = csv.writer(buffer, lineterminator=newline)
writer.writerow(columns)
for row in rows:
writer.writerow([overrides.get((row["Ref ID"], c), _csv_text(row.get(c))) for c in columns])
return buffer.getvalue().encode(encoding)
def make_xlsx(rows: list[dict], formats: dict | None = None, overrides: dict | None = None,
columns: list[str] | None = None) -> bytes:
"""Workbook with a notes sheet first and typed date cells.
formats[(ref, column)] = number format; overrides[(ref, column)] = raw cell value."""
formats, overrides = formats or {}, overrides or {}
columns = columns or COLUMNS
book = openpyxl.Workbook()
book.active.title = "Definition Sheet"
book.active.append(["notes"])
sheet = book.create_sheet("REPD")
sheet.append(columns)
for r, row in enumerate(rows, start=2):
for c, name in enumerate(columns, start=1):
key = (row["Ref ID"], name)
value = overrides.get(key, row.get(name))
if isinstance(value, date) and not isinstance(value, datetime):
value = datetime(value.year, value.month, value.day)
if value is None or value == "":
continue
cell = sheet.cell(row=r, column=c, value=value)
if isinstance(value, datetime):
cell.number_format = formats.get(key, LOCALE_SHORT_DATE)
out = io.BytesIO()
book.save(out)
return out.getvalue()
@pytest.fixture(scope="session")
def ingest():
import repd_q3_2026_ingest
return repd_q3_2026_ingest
@pytest.fixture(scope="session")
def q2():
import repd_sources_v6
return repd_sources_v6
@pytest.fixture(scope="session")
def rule():
import repd_date_rule
return repd_date_rule
@pytest.fixture
def run(ingest):
"""Run reconcile() on synthetic bytes. previous defaults to a clean six-row release."""
def _run(csv_bytes: bytes, xlsx_bytes: bytes, previous: bytes | None = None):
kwargs = {}
if "minimum_refs" in inspect.signature(ingest.reconcile).parameters:
kwargs["minimum_refs"] = 0 # the 14,657 floor is a real-release constant
return ingest.reconcile(csv_bytes, xlsx_bytes, previous if previous is not None else make_csv(base_rows()),
"synthetic previous release", True, **kwargs)
return _run
def candidate_bytes(canonical) -> bytes:
"""Serialise exactly as main() does in the patched script."""
out = io.BytesIO()
canonical.to_csv(out, index=False, encoding="utf-8-sig", lineterminator="\n")
return out.getvalue()Test Date Rule Unit
A test in the tests folder of Neural Link Between Agents that checks Conftest. It is built from the xcell step (`xcell`).
Set aside from the main view: 99% of its lines are the same as automation/repd/tests/test_date_rule.py (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Test Date Rule; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9855 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd/tests/test_date_rule.py:1-193 8b1ae839f33eb55fd0eadcb529b8bc69c242f2bc
- sha256 5ad7a0b5f2288fb2097d31fd9207ce5db500fedc77ee9b61d5761f43f2d5b99c
- target sha256 c39f2ea553a2da7a8b73fd67ca6d63c667b42729f0ff1772e6e579f0fb40ccc6
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
testneural-link-between-agents / FIXES/NL-012/review-b967360d/tests/test_date_rule_unit.py · lines 1–193 of 193 · Not reached from any entry point (candidate for review) · pattern test_number_formatted_as_date_in_a_text_column_is_reported_not_treated_as_date_column (shared by 2 files)
- What it does
- It tests its inputs. Defines 21 functions or classes, including xcell, test_number_format_classification, test_day_first_text_matches_typed_date, test_unpadded_day_first_text_is_repadded, test_month_first_text_needs_month_first_format. Uses libraries __future__, datetime, pytest.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: CSV file p.csv.
- What it achieves
- Unit tests of the standalone general date rule (`work8/repd_date_rule.py`).
- Why it matters
- Guards the behaviour of Conftest.
- Application
- neural-link-between-agents · FIXES/NL-012/review-b967360d/tests · test
- Uses
- Conftest (import), __future__, datetime, pytest
- Used by
- none found
- Produces
- xcell, test_number_format_classification, test_day_first_text_matches_typed_date, test_unpadded_day_first_text_is_repadded, test_month_first_text_needs_month_first_format, test_ambiguous_swap_is_corrected_only_with_month_first_format, test_month_first_format_with_day_equal_month_is_invariant, test_day_first_text_under_month_first_format_is_accepted_as_day_first, test_iso_text, test_failures_against_a_typed_date, test_time_component_is_not_silently_truncated, test_blank_equivalents
- Defines here
- xcell, test_number_format_classification, test_day_first_text_matches_typed_date, test_unpadded_day_first_text_is_repadded, test_month_first_text_needs_month_first_format, test_ambiguous_swap_is_corrected_only_with_month_first_format, test_month_first_format_with_day_equal_month_is_invariant, test_day_first_text_under_month_first_format_is_accepted_as_day_first, test_iso_text, test_failures_against_a_typed_date, test_time_component_is_not_silently_truncated, test_blank_equivalents, test_true_blank_is_not_a_provenance_event, test_csv_date_with_blank_or_untyped_excel, test_table_rule_discovers_date_columns_and_month_first_cells_without_being_told, test_number_formatted_as_date_in_a_text_column_is_reported_not_treated_as_date_column, test_required_date_column_holding_text_fails, test_structural_failures, test_strict_csv_reader_refuses_short_record, test_future_and_serial_artefact_flags_do_not_fail, test_provenance_records_every_non_empty_cell
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-012/review-b967360d/tests/test_date_rule_unit.py:1-193 · blob de8a599f4759d8acec719a542661d8941d59e406 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
"""Unit tests of the standalone general date rule (work8/repd_date_rule.py)."""
from __future__ import annotations
from datetime import date, datetime
import pytest
from conftest import COLUMNS, LOCALE_SHORT_DATE, MONTH_FIRST, base_rows, make_csv, make_xlsx
D = datetime(2026, 9, 11)
def xcell(rule, value=D, fmt=LOCALE_SHORT_DATE, fmt_id=14):
return rule.XCell(value, isinstance(value, datetime), fmt, fmt_id)
@pytest.mark.parametrize("code,fmt_id,expected", [
("mm-dd-yy", 14, "locale_short_date"), # built-in 14 is the system short date
("mm-dd-yy", None, "locale_short_date"), # id unknown: stay conservative
("m/d/yy h:mm", 22, "locale_short_date"),
("m/d/yyyy", 164, "month_first"),
("mm/dd/yyyy", 170, "month_first"),
("[$-409]m/d/yy h:mm AM/PM;@", 171, "month_first"),
("dd/mm/yyyy;@", 165, "day_first"),
("[$-10452]dd/mm/yyyy;@", 166, "day_first"),
("d-mmm-yy", 15, "day_first"),
("yyyy-mm-dd", 172, "year_first"),
("General", 0, "not_date"),
("0.00", 2, "not_date"),
("h:mm:ss", 21, "not_date"),
])
def test_number_format_classification(rule, code, fmt_id, expected):
assert rule.classify_number_format(code, fmt_id) == expected
def test_day_first_text_matches_typed_date(rule):
r = rule.resolve_cell("11/09/2026", xcell(rule))
assert (r["rule"], r["output"]) == (rule.OK_DAY_FIRST, "11/09/2026")
def test_unpadded_day_first_text_is_repadded(rule):
r = rule.resolve_cell("1/9/2026", xcell(rule, datetime(2026, 9, 1)))
assert (r["rule"], r["output"]) == (rule.OK_DAY_FIRST_REPADDED, "01/09/2026")
def test_month_first_text_needs_month_first_format(rule):
ok = rule.resolve_cell("9/14/2026", xcell(rule, datetime(2026, 9, 14), MONTH_FIRST, 164))
assert (ok["rule"], ok["output"], ok["csv_valid_day_first"]) == (rule.OK_MONTH_FIRST, "14/09/2026", False)
bad = rule.resolve_cell("9/14/2026", xcell(rule, datetime(2026, 9, 14)))
assert bad["rule"] == rule.FAIL_SWAP and bad["output"] == ""
def test_ambiguous_swap_is_corrected_only_with_month_first_format(rule):
ok = rule.resolve_cell("09/11/2026", xcell(rule, D, MONTH_FIRST, 164))
assert (ok["rule"], ok["output"]) == (rule.OK_MONTH_FIRST, "11/09/2026")
assert ok["csv_valid_day_first"] is True and ok["csv_day_first_reading"] == "2026-11-09"
for fmt, fmt_id in ((LOCALE_SHORT_DATE, 14), ("dd/mm/yyyy;@", 165)):
assert rule.resolve_cell("09/11/2026", xcell(rule, D, fmt, fmt_id))["rule"] == rule.FAIL_SWAP
def test_month_first_format_with_day_equal_month_is_invariant(rule):
r = rule.resolve_cell("09/09/2026", xcell(rule, datetime(2026, 9, 9), MONTH_FIRST, 164))
assert (r["rule"], r["output"]) == (rule.OK_MONTH_FIRST_INVARIANT, "09/09/2026")
def test_day_first_text_under_month_first_format_is_accepted_as_day_first(rule):
"""A publisher who fixes the CSV but leaves the cell format must not be failed."""
r = rule.resolve_cell("14/09/2026", xcell(rule, datetime(2026, 9, 14), MONTH_FIRST, 164))
assert (r["rule"], r["output"]) == (rule.OK_DAY_FIRST, "14/09/2026")
def test_iso_text(rule):
assert rule.resolve_cell("2026-09-11", xcell(rule))["rule"] == rule.OK_ISO
assert rule.resolve_cell("2026-09-12", xcell(rule))["rule"] == rule.FAIL_MISMATCH
@pytest.mark.parametrize("text,expected", [
("12/09/2026", "FAIL_DIFFERENT_DATES"),
("11/09/2025", "FAIL_DIFFERENT_DATES"),
("eleven Sept", "FAIL_CSV_UNPARSEABLE"),
("31/02/2026", "FAIL_CSV_UNPARSEABLE"),
("11/09/26", "FAIL_CSV_UNPARSEABLE"),
("", "FAIL_EXCEL_DATE_CSV_BLANK"),
("NA", "FAIL_EXCEL_DATE_CSV_BLANK"),
])
def test_failures_against_a_typed_date(rule, text, expected):
r = rule.resolve_cell(text, xcell(rule))
assert r["rule"] == expected and r["output"] == ""
def test_time_component_is_not_silently_truncated(rule):
r = rule.resolve_cell("11/09/2026", xcell(rule, datetime(2026, 9, 11, 12, 0)))
assert r["rule"] == rule.FAIL_TIME
@pytest.mark.parametrize("csv_text,xl_value,token", [
("NA", "NA", "NA"), ("N/A", None, "N/A"), (" ", " ", "<whitespace>"), (" ", None, "<whitespace>"),
("", "na", "na"),
])
def test_blank_equivalents(rule, csv_text, xl_value, token):
r = rule.resolve_cell(csv_text, rule.XCell(xl_value))
assert (r["rule"], r["output"], r["blank_token"]) == (rule.OK_BLANK_EQUIVALENT, "", token)
def test_true_blank_is_not_a_provenance_event(rule):
assert rule.resolve_cell("", rule.XCell(None))["rule"] == "BLANK"
def test_csv_date_with_blank_or_untyped_excel(rule):
assert rule.resolve_cell("11/09/2026", rule.XCell(None))["rule"] == rule.FAIL_CSV_ONLY
assert rule.resolve_cell("11/09/2026", rule.XCell(46276))["rule"] == rule.FAIL_EXCEL_NOT_DATE
# text in both files: accepted only when no day/month reading is possible but one
assert rule.resolve_cell("14/09/2026", rule.XCell("14/09/2026"))["rule"] == rule.OK_TEXT_UNAMBIGUOUS
assert rule.resolve_cell("09/11/2026", rule.XCell("09/11/2026"))["rule"] == rule.FAIL_TEXT_AMBIGUOUS
assert rule.resolve_cell("TBC", rule.XCell("TBC"))["rule"] == rule.FAIL_UNPARSEABLE
def test_table_rule_discovers_date_columns_and_month_first_cells_without_being_told(rule):
rows = base_rows()
rows[4]["Planning Application Submitted"] = date(2026, 9, 14)
rows[5]["Planning Application Submitted"] = date(2026, 9, 11)
csv_bytes = make_csv(rows, {(105, "Planning Application Submitted"): "9/14/2026",
(106, "Planning Application Submitted"): "09/11/2026"})
xlsx_bytes = make_xlsx(rows, {(105, "Planning Application Submitted"): MONTH_FIRST,
(106, "Planning Application Submitted"): MONTH_FIRST})
result = rule.evaluate(csv_bytes, xlsx_bytes) # no refs, no column names
assert result.ok
assert result.date_columns == ["Record Last Updated (dd/mm/yyyy)", "Planning Application Submitted",
"Appeal Lodged"]
assert [(c["ref"], c["output"]) for c in result.month_first_cells] == [("105", "14/09/2026"),
("106", "11/09/2026")]
assert result.output[("101", "Planning Application Submitted")] == "21/08/2026"
assert result.summary()["month_first_cells_also_valid_day_first"] == 1
def test_number_formatted_as_date_in_a_text_column_is_reported_not_treated_as_date_column(rule):
"""October's Offshore Wind Round: rounds 1-3 stored as numbers with a date format."""
rows = base_rows()
xlsx = make_xlsx(rows, overrides={(101, "Planning Authority"): datetime(1900, 1, 2)})
result = rule.evaluate(make_csv(rows, {(101, "Planning Authority"): "02/01/1900"}), xlsx)
assert "Planning Authority" not in result.date_columns
assert [(s["ref"], s["column"], s["likely_number_formatted_as_date"]) for s in result.stray_excel_dates] == [
("101", "Planning Authority", True)]
assert result.ok
def test_required_date_column_holding_text_fails(rule):
rows = base_rows()
result = rule.evaluate(make_csv(rows, {(103, "Operational"): "pending"}),
make_xlsx(rows, overrides={(103, "Operational"): "pending"}),
required_date_columns=["Operational"])
assert not result.ok and result.failures[0]["rule"] == rule.FAIL_UNPARSEABLE
def test_structural_failures(rule):
rows = base_rows()
assert any("Ref ID sets differ" in m for m in
rule.evaluate(make_csv(rows), make_xlsx(rows[:-1])).structural_failures)
reordered = COLUMNS[:3] + [COLUMNS[4], COLUMNS[3]] + COLUMNS[5:]
assert any("headers differ" in m for m in
rule.evaluate(make_csv(rows), make_xlsx(rows, columns=reordered)).structural_failures)
clash = dict(rows[2]); clash["Site Name"] = "other"
assert any("conflicting duplicate" in m for m in
rule.evaluate(make_csv(rows + [clash]), make_xlsx(rows + [clash])).structural_failures)
same = rule.evaluate(make_csv(rows + [dict(rows[2])]), make_xlsx(rows + [dict(rows[2])]))
assert same.ok and same.duplicates["csv"][0]["ref"] == "103" and len(same.refs) == 6
def test_strict_csv_reader_refuses_short_record(rule):
data = make_csv(base_rows())
with pytest.raises(ValueError, match="fields"):
rule.read_csv_table(data + b",107,08/10/2026\r\n")
def test_future_and_serial_artefact_flags_do_not_fail(rule):
rows = base_rows()
rows[0]["Planning Permission Granted"] = date(2026, 12, 15)
rows[1]["Planning Permission Expired"] = date(2029, 12, 15)
result = rule.evaluate(make_csv(rows), make_xlsx(rows), as_of=date(2026, 11, 13),
future_ok_columns=["Planning Permission Expired"])
assert result.ok
assert [(f["ref"], f["column"], f["flag"]) for f in result.plausibility_flags] == [
("101", "Planning Permission Granted", "AFTER_AS_OF_DATE")]
def test_provenance_records_every_non_empty_cell(rule, tmp_path):
rows = base_rows()
result = rule.evaluate(make_csv(rows), make_xlsx(rows))
# 6 last-updated + 6 submitted + 1 appeal lodged
assert len(result.provenance) == 13
assert {p["rule"] for p in result.provenance} == {rule.OK_DAY_FIRST}
rule.write_provenance_csv(result, tmp_path / "p.csv")
assert (tmp_path / "p.csv").read_text(encoding="utf-8").count("\n") == 14Test Ingest Regression
A test in the tests folder of Neural Link Between Agents that checks Conftest. It is built from the cell step (`cell`).
testneural-link-between-agents / FIXES/NL-012/review-b967360d/tests/test_ingest_regression.py · lines 1–256 of 256 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Defines 24 functions or classes, including cell, test_00_clean_release_is_staged, test_01_identical_duplicate_kept_once, test_01b_previous_release_with_identical_duplicate_is_usable_as_baseline, test_02_conflicting_duplicate_rejects. Uses libraries __future__, csv, io, re, datetime. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- What it achieves
- End-to-end regression tests: synthetic CSV + XLSX bytes through `reconcile`.
- Why it matters
- Guards the behaviour of Conftest.
- Application
- neural-link-between-agents · FIXES/NL-012/review-b967360d/tests · test
- Uses
- Conftest (import), __future__, csv, io, re, datetime, pytest
- Used by
- none found
- Produces
- cell, test_00_clean_release_is_staged, test_01_identical_duplicate_kept_once, test_01b_previous_release_with_identical_duplicate_is_usable_as_baseline, test_02_conflicting_duplicate_rejects, test_02b_duplicate_in_one_file_only_rejects, test_03_month_first_cell_corrected_from_excel, test_03b_month_first_cell_that_is_also_a_valid_day_first_date, test_03c_month_first_correction_is_not_limited_to_one_column, test_04_ambiguous_day_month_swap_detected, test_04b_swap_detected_in_a_date_column_outside_the_original_eight, test_05_unparseable_non_blank_date_rejects
- Defines here
- cell, test_00_clean_release_is_staged, test_01_identical_duplicate_kept_once, test_01b_previous_release_with_identical_duplicate_is_usable_as_baseline, test_02_conflicting_duplicate_rejects, test_02b_duplicate_in_one_file_only_rejects, test_03_month_first_cell_corrected_from_excel, test_03b_month_first_cell_that_is_also_a_valid_day_first_date, test_03c_month_first_correction_is_not_limited_to_one_column, test_04_ambiguous_day_month_swap_detected, test_04b_swap_detected_in_a_date_column_outside_the_original_eight, test_05_unparseable_non_blank_date_rejects, test_05b_unparseable_date_present_in_both_files_rejects, test_06_na_is_blanked_and_counted, test_06b_na_in_csv_but_date_in_excel_rejects, test_07_fewer_refs_than_previous_release_rejects, test_07b_same_or_more_refs_than_previous_release_passes, test_08_csv_and_excel_ref_sets_differing_rejects, test_09_candidate_column_order_equals_official, test_10_last_record_complete, test_10b_source_without_final_newline_rejects, test_10c_source_with_truncated_final_record_rejects, test_11_output_round_trips_byte_stable, test_11b_every_date_column_of_the_candidate_is_strict_day_first
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-012/review-b967360d/tests/test_ingest_regression.py:1-256 · blob 3ccbca6fe2d9b5f3ea243e38a76a22d2c4406820 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""End-to-end regression tests: synthetic CSV + XLSX bytes through reconcile().
One test (or group) per item of the owner's list; the numbering matches it.
"""
from __future__ import annotations
import csv
import io
import re
from datetime import date
import pytest
from conftest import (COLUMNS, LOCALE_SHORT_DATE, MONTH_FIRST, base_rows, candidate_bytes,
make_csv, make_xlsx)
STAGED = "STAGED_WITH_SOURCE_DATE_LOCALE_NORMALISATIONS"
SUBMITTED = "Planning Application Submitted"
def cell(canonical, ref, column):
return canonical.loc[canonical["Ref ID"] == str(ref), column].iloc[0]
def test_00_clean_release_is_staged(run):
rows = base_rows()
canonical, report = run(make_csv(rows), make_xlsx(rows))
assert report["failures"] == []
assert report["stage"] == STAGED
assert len(canonical) == len(rows)
assert report["source_locale_date_normalisation_count"] == 0
# 1 ---------------------------------------------------------------------------
def test_01_identical_duplicate_kept_once(run):
rows = base_rows()
rows.insert(3, dict(rows[2])) # ref 103 twice, byte-identical
canonical, report = run(make_csv(rows), make_xlsx(rows))
assert report["failures"] == []
assert list(canonical["Ref ID"]).count("103") == 1
assert len(canonical) == 6 and report["original_csv_rows"] == 7
evidence = report["identical_source_duplicates_quarantined"]
assert [e["repd_ref"] for e in evidence["csv"]] == ["103"] == [e["repd_ref"] for e in evidence["xlsx"]]
assert evidence["csv"][0]["exactly_identical"] is True
assert evidence["source_rows_not_in_candidate"] == 1
def test_01b_previous_release_with_identical_duplicate_is_usable_as_baseline(run):
"""Next quarter the baseline is the October CSV, which contains ref 7679 twice."""
rows = base_rows()
previous = base_rows()
previous.insert(3, dict(previous[2]))
canonical, report = run(make_csv(rows), make_xlsx(rows), make_csv(previous))
assert report["failures"] == [] and len(canonical) == 6
assert report["comparison_baseline_rows"] == 6
# 2 ---------------------------------------------------------------------------
def test_02_conflicting_duplicate_rejects(run):
rows = base_rows()
clash = dict(rows[2])
clash["Site Name"] = "A different site"
rows.insert(3, clash)
canonical, report = run(make_csv(rows), make_xlsx(rows))
assert canonical is None and report["stage"] == "REJECTED"
assert any("conflicting duplicate" in f.lower() for f in report["failures"])
def test_02b_duplicate_in_one_file_only_rejects(run):
rows = base_rows()
doubled = rows[:3] + [dict(rows[2])] + rows[3:]
canonical, report = run(make_csv(doubled), make_xlsx(rows))
assert canonical is None and report["stage"] == "REJECTED"
# 3 ---------------------------------------------------------------------------
def test_03_month_first_cell_corrected_from_excel(run):
rows = base_rows()
rows[4][SUBMITTED] = date(2026, 9, 14) # CSV wrote 9/14/2026
canonical, report = run(make_csv(rows, {(105, SUBMITTED): "9/14/2026"}),
make_xlsx(rows, {(105, SUBMITTED): MONTH_FIRST}))
assert report["failures"] == []
assert cell(canonical, 105, SUBMITTED) == "14/09/2026"
events = report["source_locale_date_normalisations"]
assert [(e["repd_ref"], e["field"], e["official_csv"], e["official_xlsx"], e["candidate_value"])
for e in events] == [("105", SUBMITTED, "9/14/2026", "2026-09-14", "14/09/2026")]
def test_03b_month_first_cell_that_is_also_a_valid_day_first_date(run):
"""The dangerous five of October: 09/11/2026 parses day-first as 9 November."""
rows = base_rows()
rows[4][SUBMITTED] = date(2026, 9, 11)
canonical, report = run(make_csv(rows, {(105, SUBMITTED): "09/11/2026"}),
make_xlsx(rows, {(105, SUBMITTED): MONTH_FIRST}))
assert report["failures"] == []
assert cell(canonical, 105, SUBMITTED) == "11/09/2026"
assert [e["repd_ref"] for e in report["formerly_ambiguous_date_representations"]] == ["105"]
def test_03c_month_first_correction_is_not_limited_to_one_column(run):
rows = base_rows()
canonical, report = run(make_csv(rows, {(102, "Appeal Lodged"): "9/15/2026"}),
make_xlsx(rows, {(102, "Appeal Lodged"): MONTH_FIRST}))
assert report["failures"] == []
assert cell(canonical, 102, "Appeal Lodged") == "15/09/2026"
# 4 ---------------------------------------------------------------------------
def test_04_ambiguous_day_month_swap_detected(run):
"""CSV 09/11/2026 against Excel 11 September under the ordinary locale format."""
rows = base_rows()
rows[4][SUBMITTED] = date(2026, 9, 11)
canonical, report = run(make_csv(rows, {(105, SUBMITTED): "09/11/2026"}),
make_xlsx(rows, {(105, SUBMITTED): LOCALE_SHORT_DATE}))
assert canonical is None and report["stage"] == "REJECTED"
assert any("105" in f for f in report["failures"])
def test_04b_swap_detected_in_a_date_column_outside_the_original_eight(run):
rows = base_rows()
rows[1]["Appeal Lodged"] = date(2026, 9, 11)
canonical, report = run(make_csv(rows, {(102, "Appeal Lodged"): "09/11/2026"}), make_xlsx(rows))
assert canonical is None and report["stage"] == "REJECTED"
# 5 ---------------------------------------------------------------------------
@pytest.mark.parametrize("text", ["sometime in 2026", "31/02/2026", "14/09/26", "2026.09.14"])
def test_05_unparseable_non_blank_date_rejects(run, text):
rows = base_rows()
canonical, report = run(make_csv(rows, {(104, SUBMITTED): text}), make_xlsx(rows))
assert canonical is None and report["stage"] == "REJECTED"
def test_05b_unparseable_date_present_in_both_files_rejects(run):
rows = base_rows()
canonical, report = run(make_csv(rows, {(104, "Operational"): "Q3 2026"}),
make_xlsx(rows, overrides={(104, "Operational"): "Q3 2026"}))
assert canonical is None and report["stage"] == "REJECTED"
# 6 ---------------------------------------------------------------------------
def test_06_na_is_blanked_and_counted(run):
rows = base_rows()
rows[0]["Operational"] = date(2025, 3, 1)
canonical, report = run(
make_csv(rows, {(103, "Operational"): "NA", (104, "Operational"): "NA", (105, "Operational"): " "}),
make_xlsx(rows, overrides={(103, "Operational"): "NA", (104, "Operational"): "NA",
(105, "Operational"): " "}))
assert report["failures"] == []
assert [cell(canonical, r, "Operational") for r in (101, 103, 104, 105)] == ["01/03/2025", "", "", ""]
assert report["date_rule"]["blank_equivalent_counts"]["Operational"] == {"<whitespace>": 1, "NA": 2}
def test_06b_na_in_csv_but_date_in_excel_rejects(run):
rows = base_rows()
rows[2]["Operational"] = date(2025, 3, 1)
canonical, report = run(make_csv(rows, {(103, "Operational"): "NA"}), make_xlsx(rows))
assert canonical is None and report["stage"] == "REJECTED"
# 7 ---------------------------------------------------------------------------
def test_07_fewer_refs_than_previous_release_rejects(run):
previous = make_csv(base_rows(6))
rows = base_rows(5)
canonical, report = run(make_csv(rows), make_xlsx(rows), previous)
assert canonical is None and report["stage"] == "REJECTED"
assert any("floor" in f or "below" in f for f in report["failures"])
def test_07b_same_or_more_refs_than_previous_release_passes(run):
rows = base_rows(6)
canonical, report = run(make_csv(rows), make_xlsx(rows), make_csv(base_rows(5)))
assert report["failures"] == [] and len(canonical) == 6
assert report["reference_changes_vs_comparison_baseline"]["new_refs"] == 1
# 8 ---------------------------------------------------------------------------
def test_08_csv_and_excel_ref_sets_differing_rejects(run):
rows = base_rows()
canonical, report = run(make_csv(rows), make_xlsx(rows[:-1]), make_csv(base_rows(5)))
assert canonical is None and report["stage"] == "REJECTED"
assert report["csv_excel_id_sets_match"] is False
assert "CSV and Excel REPD reference sets differ" in report["failures"]
assert not any("floor" in f for f in report["failures"]) # rejected for this reason alone
# 9 ---------------------------------------------------------------------------
def test_09_candidate_column_order_equals_official(run):
rows = base_rows()
canonical, report = run(make_csv(rows), make_xlsx(rows))
official = [re.sub(r"\s+", " ", name.strip()) for name in COLUMNS]
assert list(canonical.columns) == official
header = next(csv.reader(io.StringIO(candidate_bytes(canonical).decode("utf-8-sig"), newline="")))
assert header == official
# 10 --------------------------------------------------------------------------
def test_10_last_record_complete(run):
rows = base_rows()
source = make_csv(rows)
canonical, report = run(source, make_xlsx(rows))
data = candidate_bytes(canonical)
assert data.endswith(b"\n")
records = list(csv.reader(io.StringIO(data.decode("utf-8-sig"), newline="")))
assert len(records[-1]) == len(COLUMNS) and records[-1][1] == "106"
assert records[-1][COLUMNS.index("Record Last Updated (dd/mm/yyyy)")] == "08/10/2026"
assert all(len(record) == len(COLUMNS) for record in records)
def test_10b_source_without_final_newline_rejects(run):
rows = base_rows()
canonical, report = run(make_csv(rows).rstrip(b"\r\n"), make_xlsx(rows))
assert canonical is None and "Q3 source CSV has no final newline" in report["failures"]
def test_10c_source_with_truncated_final_record_rejects(run):
rows = base_rows()
source = make_csv(rows)
truncated = source[:source.rstrip(b"\r\n").rindex(b"\n") + 1] + b",106,08/10/2026\r\n"
try:
canonical, report = run(truncated, make_xlsx(rows))
except (ValueError, RuntimeError):
return # refused outright: acceptable
assert canonical is None and report["stage"] == "REJECTED"
# 11 --------------------------------------------------------------------------
def test_11_output_round_trips_byte_stable(run, q2):
rows = base_rows()
rows[0]["Site Name"] = "Café – “North” Solar, Phase 2" # non-ASCII, comma, quotes
rows[1]["Planning Application Reference"] = "007"
rows[4][SUBMITTED] = date(2026, 9, 14)
csv_bytes = make_csv(rows, {(105, SUBMITTED): "9/14/2026"})
xlsx_bytes = make_xlsx(rows, {(105, SUBMITTED): MONTH_FIRST})
canonical, report = run(csv_bytes, xlsx_bytes)
assert report["failures"] == []
first = candidate_bytes(canonical)
assert first.startswith(b"\xef\xbb\xbf") and b"\r" not in first
assert candidate_bytes(q2.read_csv(first)) == first # read back, write again
again, _ = run(csv_bytes, xlsx_bytes)
assert candidate_bytes(again) == first # deterministic rebuild
assert cell(canonical, 101, "Site Name") == rows[0]["Site Name"]
assert cell(canonical, 102, "Planning Application Reference") == "007"
def test_11b_every_date_column_of_the_candidate_is_strict_day_first(run):
rows = base_rows()
rows[3]["Planning Permission Granted"] = date(2026, 12, 15) # future, like ref 20029: kept, flagged
canonical, report = run(make_csv(rows), make_xlsx(rows))
assert report["failures"] == []
for column in report["date_rule"]["date_columns"]:
for value in canonical[column]:
assert value == "" or re.fullmatch(r"\d{2}/\d{2}/\d{4}", value), (column, value)
assert "Appeal Lodged" in report["date_rule"]["date_columns"]
assert cell(canonical, 104, "Planning Permission Granted") == "15/12/2026"
assert [(f["ref"], f["flag"]) for f in report["date_rule_plausibility_flags"]] == [("104", "AFTER_AS_OF_DATE")]Test Unpatched Defects
A test in the tests folder of Neural Link Between Agents that checks Conftest. It is built from the original step (`original`) and the original q2 helper (`original_q2`).
testneural-link-between-agents / FIXES/NL-012/review-b967360d/tests/test_unpatched_defects.py · lines 1–87 of 87 · Not reached from any entry point (candidate for review) · pattern original (shared by 2 files)
- What it does
- It tests its inputs. Defines 12 functions or classes, including _load, original, original_q2, test_unpatched_rejects_every_release_that_lacks_the_25_hard_coded_refs, test_unpatched_floor_and_allow_list_are_not_parameters. Uses libraries __future__, importlib.util, inspect, datetime, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- What it achieves
- Defects of the scripts AS DELIVERED at (`work8/tiproot/scripts`).
- Why it matters
- Guards the behaviour of Conftest.
- Application
- neural-link-between-agents · FIXES/NL-012/review-b967360d/tests · test
- Uses
- Conftest (import), __future__, importlib.util, inspect, datetime, pathlib, pytest
- Used by
- none found
- Produces
- original, original_q2, test_unpatched_rejects_every_release_that_lacks_the_25_hard_coded_refs, test_unpatched_floor_and_allow_list_are_not_parameters, test_unpatched_read_xlsx_turns_the_text_NA_into_missing, test_unpatched_build_canonical_blanks_a_planning_reference_of_NA, test_unpatched_read_csv_pads_a_truncated_record_instead_of_refusing, test_unpatched_strict_date_iso_drops_a_time_of_day_silently, test_unpatched_shared_norm_date_still_guesses_month_first, test_unpatched_baseline_with_an_identical_duplicate_raises, test_unpatched_collapse_rewrites_nbsp_tabs_and_line_breaks
- Defines here
- _load, original, original_q2, test_unpatched_rejects_every_release_that_lacks_the_25_hard_coded_refs, test_unpatched_floor_and_allow_list_are_not_parameters, test_unpatched_read_xlsx_turns_the_text_NA_into_missing, test_unpatched_build_canonical_blanks_a_planning_reference_of_NA, test_unpatched_read_csv_pads_a_truncated_record_instead_of_refusing, test_unpatched_strict_date_iso_drops_a_time_of_day_silently, test_unpatched_shared_norm_date_still_guesses_month_first, test_unpatched_baseline_with_an_identical_duplicate_raises, test_unpatched_collapse_rewrites_nbsp_tabs_and_line_breaks
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-012/review-b967360d/tests/test_unpatched_defects.py:1-87 · blob 12c0163d7e3999391569e262d6e9fc3e34bcbc52 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Defects of the scripts AS DELIVERED at b967360d (work8/tiproot/scripts).
Each test asserts the defective behaviour, so a PASS here means "defect
reproduced". They always load the unpatched copy, whatever REPD_TEST_TARGET is.
"""
from __future__ import annotations
import importlib.util
import inspect
from datetime import date, datetime
from pathlib import Path
import pytest
from conftest import MONTH_FIRST, base_rows, make_csv, make_xlsx
ORIGINAL = Path(__file__).resolve().parents[1] / "tiproot" / "scripts"
def _load(name):
spec = importlib.util.spec_from_file_location(f"unpatched_{name}", ORIGINAL / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.fixture(scope="module")
def original():
return _load("repd_q3_2026_ingest")
@pytest.fixture(scope="module")
def original_q2():
return _load("repd_sources_v6")
def test_unpatched_rejects_every_release_that_lacks_the_25_hard_coded_refs(original):
rows = base_rows()
canonical, report = original.reconcile(make_csv(rows), make_xlsx(rows), make_csv(rows), "synthetic", True)
assert canonical is None
assert sum("Expected month-first Q3 date ref is missing" in f for f in report["failures"]) == 25
assert any("14,657" in f for f in report["failures"]) # hard-coded floor, not the baseline
def test_unpatched_floor_and_allow_list_are_not_parameters(original):
assert set(inspect.signature(original.reconcile).parameters) == {
"csv_data", "xlsx_data", "old_data", "baseline_name", "baseline_is_q2"}
def test_unpatched_read_xlsx_turns_the_text_NA_into_missing(original_q2):
rows = base_rows()
frame, _ = original_q2.read_xlsx(make_xlsx(rows, overrides={(101, "Planning Application Reference"): "NA"}))
assert original_q2.collapse(frame.loc[0, "Planning Application Reference"]) == "" # official text was "NA"
def test_unpatched_build_canonical_blanks_a_planning_reference_of_NA(original_q2):
rows = base_rows()
key = (101, "Planning Application Reference")
csv_frame = original_q2.read_csv(make_csv(rows, {key: "NA"}))
xlsx_frame, _ = original_q2.read_xlsx(make_xlsx(rows, overrides={key: "NA"}))
canonical = original_q2.build_canonical(csv_frame, xlsx_frame)
assert canonical["Planning Application Reference"].iloc[0] == "" # both files say "NA"
def test_unpatched_read_csv_pads_a_truncated_record_instead_of_refusing(original_q2):
frame = original_q2.read_csv(make_csv(base_rows()) + b",107,08/10/2026\r\n")
assert len(frame) == 7 and frame.iloc[-1].isna().sum() == 16
def test_unpatched_strict_date_iso_drops_a_time_of_day_silently(original):
assert original.strict_date_iso(datetime(1900, 1, 2, 12, 0)) == "1900-01-02"
def test_unpatched_shared_norm_date_still_guesses_month_first(original_q2):
assert original_q2.norm_date("9/14/2026") == "2026-09-14" # used by the Q2 reconcile path
def test_unpatched_baseline_with_an_identical_duplicate_raises(original):
"""The October CSV (ref 7679 twice) cannot be next quarter's baseline."""
rows = base_rows()
previous = rows[:3] + [dict(rows[2])] + rows[3:]
with pytest.raises(RuntimeError, match="duplicates=1"):
original.reconcile(make_csv(rows), make_xlsx(rows), make_csv(previous), "synthetic", True)
def test_unpatched_collapse_rewrites_nbsp_tabs_and_line_breaks(original_q2):
assert original_q2.collapse("12 High St\r\nLydney\t") == "12 High St Lydney"