Skip to content

Commit fcd3c00

Browse files
authored
Feat/lbos that have ended 2487 (#630)
* test new changes * more test changes * updated function details
1 parent a4e57a8 commit fcd3c00

4 files changed

Lines changed: 373 additions & 0 deletions

File tree

‎digital_land/expectations/checkpoints/dataset.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
fetch_all_resources_for_dataset,
2222
name_is_a_code_check,
2323
name_is_a_placeholder_check,
24+
lbos_have_no_ended_date_check,
2425
)
2526

2627

@@ -49,6 +50,7 @@ def operation_factory(self, operation_string: str):
4950
"duplicate_name_check": duplicate_name_check,
5051
"name_is_a_code_check": name_is_a_code_check,
5152
"name_is_a_placeholder_check": name_is_a_placeholder_check,
53+
"lbos_have_no_ended_date_check": lbos_have_no_ended_date_check,
5254
}
5355
operation = operation_map[operation_string]
5456
return operation

‎digital_land/expectations/operations/dataset.py‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -936,3 +936,100 @@ def check_fields_required_after_plan_event(
936936
}
937937

938938
return result, message, details
939+
940+
941+
def lbos_have_no_ended_date_check(conn, listed_building_path, placeholders=None):
942+
"""
943+
Checks for listed-building-outline entities that are open (blank end-date) but link to a listed building that has an end-date
944+
945+
args:
946+
conn: connection to the dataset being checked, created by the checkpoint class
947+
listed_building_path: path to a local copy of the built listed-building sqlite,
948+
fetched as a published artifact during assemble
949+
placeholders: list of placeholder strings; falls back to
950+
DEFAULT_PLACEHOLDER_NAMES when absent or empty, so a parameters cell
951+
carrying only the path still works
952+
"""
953+
# if not placeholders:
954+
# placeholders = DEFAULT_PLACEHOLDER_NAMES
955+
# a single string in config would otherwise iterate as characters and match any
956+
# one-character name, so treat it as one placeholder
957+
# if isinstance(placeholders, str):
958+
# placeholders = [placeholders]
959+
960+
# placeholder_set = {_normalise_name(placeholder) for placeholder in placeholders}
961+
962+
# a missing artifact must never fail the build, the check just can't run
963+
if not listed_building_path or not os.path.isfile(listed_building_path):
964+
message = (
965+
f"listed-building not available at '{listed_building_path}', check skipped"
966+
)
967+
logging.warning(message)
968+
return True, message, {"skipped": True, "failures": []}
969+
970+
# listed-building is not a core entity column, so it lives in the json blob.
971+
query = """
972+
select
973+
e.entity,
974+
e.reference,
975+
e.name,
976+
e.organisation_entity,
977+
lb.name as listed_building_name,
978+
e.end_date as lbo_end_date,
979+
lb.end_date as lb_end_date
980+
from entity e
981+
inner join listed_building_check.entity lb
982+
on lb.reference = json_extract(e.json, '$."listed-building"')
983+
where e.reference is not null
984+
and (e.end_date is null or e.end_date = '')
985+
and (lb.end_date is not null and lb.end_date !='')
986+
"""
987+
988+
conn.execute(
989+
"ATTACH DATABASE ? AS listed_building_check", (str(listed_building_path),)
990+
)
991+
try:
992+
rows = conn.execute(query).fetchall()
993+
finally:
994+
conn.execute("DETACH DATABASE listed_building_check")
995+
996+
failures = [
997+
{
998+
"organisation_entity": organisation_entity,
999+
"entity": entity,
1000+
"reference": reference,
1001+
"name": name,
1002+
"listed_building_name": listed_building_name,
1003+
"lbo_end_date": lbo_end_date,
1004+
"lb_end_date": lb_end_date,
1005+
}
1006+
for entity, reference, name, organisation_entity, listed_building_name, lbo_end_date, lb_end_date in rows
1007+
# the listed-building name must be a real name too - swapping one placeholder
1008+
# for another is not a fix worth asking an organisation to make
1009+
# if _normalise_name(name) in placeholder_set
1010+
# and _normalise_name(listed_building_name) not in placeholder_set
1011+
]
1012+
1013+
failures.sort(
1014+
key=lambda failure: (
1015+
failure["organisation_entity"] or "",
1016+
failure["reference"] or "",
1017+
failure["entity"] or "",
1018+
failure["lbo_end_date"] or "",
1019+
failure["lb_end_date"] or "",
1020+
)
1021+
)
1022+
1023+
result = len(failures) == 0
1024+
message = (
1025+
f"{len(failures)} listed building outlines have a blank end date "
1026+
"but their linked listed buildings have an end date"
1027+
)
1028+
details = {
1029+
"failures": failures,
1030+
"field": "end_date",
1031+
"actual": len(failures),
1032+
"expected": 0,
1033+
}
1034+
1035+
return result, message, details

‎tests/acceptance/test_run_expectations_on_sqlite.py‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,3 +514,182 @@ def test_run_name_is_a_placeholder_expectation(
514514
assert (
515515
details["failures"][0]["listed_building_name"] == "33, 37 AND 39, BAYFORD GREEN"
516516
), "the real name must reach details so the bridge can quote it back to the LPA"
517+
518+
519+
@pytest.fixture
520+
def end_date_check_dataset_path(tmp_path):
521+
"""a listed-building-outline dataset with one null end date and one end date"""
522+
dataset_path = tmp_path / "end_date_check.sqlite3"
523+
create_entity_table_sql = """
524+
CREATE TABLE entity (
525+
dataset TEXT,
526+
end_date TEXT,
527+
entity INTEGER PRIMARY KEY,
528+
entry_date TEXT,
529+
geojson JSON,
530+
geometry TEXT,
531+
json JSON,
532+
name TEXT,
533+
organisation_entity TEXT,
534+
point TEXT,
535+
prefix TEXT,
536+
reference TEXT,
537+
start_date TEXT,
538+
typology TEXT
539+
);
540+
"""
541+
with spatialite.connect(dataset_path) as con:
542+
con.execute(create_entity_table_sql)
543+
con.executemany(
544+
"INSERT INTO entity (entity, reference, name, organisation_entity, end_date, json)"
545+
" VALUES (?, ?, ?, ?, ?, ?)",
546+
[
547+
(
548+
1,
549+
"CA-59",
550+
"59",
551+
"122",
552+
None,
553+
json.dumps({"listed-building": "CA-59"}),
554+
),
555+
(
556+
2,
557+
"CA-WYM",
558+
"Wymondham Conservation Area",
559+
"122",
560+
"2020-01-01",
561+
json.dumps({"listed-building": "CA-WYM"}),
562+
),
563+
],
564+
)
565+
566+
return dataset_path
567+
568+
569+
@pytest.fixture
570+
def listed_building_end_date_path(tmp_path):
571+
"""stands in for the listed-building sqlite fetched from S3 during assemble"""
572+
artifact_path = tmp_path / "listed-building_end_date.sqlite3"
573+
with spatialite.connect(artifact_path) as con:
574+
con.execute(
575+
"""
576+
CREATE TABLE entity (
577+
entity INTEGER PRIMARY KEY,
578+
reference TEXT,
579+
name TEXT,
580+
organisation_entity TEXT,
581+
end_date TEXT,
582+
json JSON
583+
);
584+
"""
585+
)
586+
con.executemany(
587+
"INSERT INTO entity (entity, reference, name, organisation_entity, end_date, json)"
588+
" VALUES (?, ?, ?, ?, ?, ?)",
589+
[
590+
(
591+
1,
592+
"CA-59",
593+
"59",
594+
"122",
595+
"2020-01-01",
596+
json.dumps({"listed-building": "CA-59"}),
597+
),
598+
(
599+
2,
600+
"CA-WYM",
601+
"Wymondham Conservation Area",
602+
"122",
603+
"2020-01-01",
604+
json.dumps({"listed-building": "CA-WYM"}),
605+
),
606+
],
607+
)
608+
609+
return artifact_path
610+
611+
612+
@pytest.fixture
613+
def end_date_check_config_path(
614+
tmp_path, specification_dir, listed_building_end_date_path
615+
):
616+
"""a configuration enabling name_is_a_code_check, with no organisations and empty
617+
parameters, matching how the rule will be written in config"""
618+
config_path = tmp_path / "end_date_check_config.sqlite3"
619+
rules = [
620+
{
621+
"datasets": "test",
622+
"organisations": "",
623+
"name": "Check no entities have a blank end date",
624+
"operation": "lbos_have_no_ended_date_check",
625+
"parameters": json.dumps(
626+
{"listed_building_path": str(listed_building_end_date_path)}
627+
),
628+
"responsibility": "external",
629+
"severity": "warning",
630+
}
631+
]
632+
expect_path = tmp_path / "expect.csv"
633+
with open(expect_path, mode="w", newline="") as file:
634+
writer = csv.DictWriter(file, fieldnames=rules[0].keys())
635+
writer.writeheader()
636+
writer.writerows(rules)
637+
638+
spec = Specification(specification_dir)
639+
config = Config(path=config_path, specification=spec)
640+
config.create()
641+
config.load({"expect": str(tmp_path)})
642+
return config_path
643+
644+
645+
def test_run_end_date_is_blank_expectation(
646+
tmp_path,
647+
organisation_path,
648+
end_date_check_dataset_path,
649+
end_date_check_config_path,
650+
specification_dir,
651+
):
652+
dataset = "test"
653+
runner = CliRunner()
654+
655+
result = runner.invoke(
656+
expectations_run_dataset_checkpoint,
657+
[
658+
"--dataset",
659+
dataset,
660+
"--file-path",
661+
str(end_date_check_dataset_path),
662+
"--log-dir",
663+
str(tmp_path / "log"),
664+
"--configuration-path",
665+
str(end_date_check_config_path),
666+
"--organisation-path",
667+
str(organisation_path),
668+
"--specification-dir",
669+
str(specification_dir),
670+
],
671+
catch_exceptions=False,
672+
)
673+
674+
assert result.exit_code == 0, result.output
675+
676+
log_path = tmp_path / f"log/expectation/dataset={dataset}/{dataset}.parquet"
677+
assert log_path.exists(), "no logs created"
678+
679+
conn = duckdb.connect()
680+
cursor = conn.execute(f"SELECT * FROM read_parquet('{str(log_path)}')")
681+
columns = [desc[0] for desc in cursor.description]
682+
results = [dict(zip(columns, row)) for row in cursor.fetchall()]
683+
684+
assert len(results) == 1, "expected one expectation to have run"
685+
log = results[0]
686+
assert log["operation"] == "lbos_have_no_ended_date_check"
687+
assert log["passed"] == "False", "the blank end date should have failed the check"
688+
assert log["severity"] == "warning"
689+
assert log["responsibility"] == "external"
690+
assert log["organisation"] == "", "a rule with no end date logs an error"
691+
692+
details = json.loads(log["details"])
693+
assert details["actual"] == 1
694+
assert [failure["name"] for failure in details["failures"]] == ["59"]
695+
assert details["failures"][0]["reference"] == "CA-59"

0 commit comments

Comments
 (0)