File size: 5,259 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | import csv
import math
import pathlib
import re
import sys
ROOT = pathlib.Path.cwd()
def read_csv(path):
with path.open(encoding="utf-8-sig", newline="") as handle:
return list(csv.DictReader(handle))
def keyed(rows):
result = {}
for row in rows:
key = float(row["fare"])
assert key not in result, "fixture fare values must be unique"
result[key] = row
return result
def boolean_value(value):
token = re.sub(r"[^a-z0-9]+", "", str(value).lower())
if token in {"true", "1", "yes", "y"}:
return True
if token in {"false", "0", "no", "n"}:
return False
raise AssertionError(f"is_alone is not boolean-like: {value!r}")
def matching_rows():
source = keyed(read_csv(ROOT / "titanic.csv"))
output = keyed(read_csv(ROOT / "titanic_clean.csv"))
assert output and set(output) <= set(source), "clean export must contain only fixture records"
for key, before in source.items():
if key not in output:
assert not before.get('age', '').strip() or not before.get('deck', '').strip(), 'only records with missing age/deck may be deleted'
for key, after in output.items():
before = source[key]
for field in ('survived', 'pclass', 'sibsp', 'parch'):
assert float(after[field]) == float(before[field]), f'non-cleaning field changed: {field}'
assert after['sex'] == before['sex'], 'sex label changed'
return source, output
# ENHANCED_CASE_1
def case_age_imputation():
"""Every age is finite, observed ages survive, and fixture gaps get a plausible fill."""
source, output = matching_rows()
observed = [float(row["age"]) for row in source.values() if row.get("age", "").strip()]
assert observed and any(not row.get("age", "").strip() for row in source.values()), "fixture must exercise age filling"
for key in output:
before = source[key]
try:
age = float(output[key].get("age", ""))
except ValueError as exc:
raise AssertionError(f"age is not numeric for fare={key}") from exc
assert math.isfinite(age), f"age is not finite for fare={key}"
if before.get("age", "").strip():
assert age == float(before["age"]), f"observed age changed for fare={key}"
else:
assert min(observed) <= age <= max(observed), f"age fill is outside the fixture range for fare={key}"
# ENHANCED_CASE_2
def case_deck_fill_and_categories():
"""Deck gaps are filled and embarked/class remain valid categorical values."""
source, output = matching_rows()
assert any(not row.get("deck", "").strip() for row in source.values()), "fixture must exercise deck filling"
for key in output:
before = source[key]
after = output[key]
assert after.get("deck", "").strip(), f"deck remains empty for fare={key}"
if before.get("deck", "").strip():
assert after["deck"].strip() == before["deck"].strip(), f"observed deck changed for fare={key}"
for name in ("embarked", "class"):
assert after.get(name, "").strip(), f"{name} is empty for fare={key}"
if before.get(name, "").strip():
assert after[name].strip() == before[name].strip(), f"observed {name} changed for fare={key}"
encoded = all(f"{name}_code" in next(iter(output.values())) for name in ("embarked", "class"))
assert encoded, "CSV must expose embarked_code and class_code as categorical evidence"
for name in ("embarked", "class"):
mapping = {}
for row in output.values():
label = row[name].strip()
code = int(row[f"{name}_code"])
assert code >= 0, f"{name}_code must be non-negative"
mapping.setdefault(label, code)
assert mapping[label] == code, f"{name} category has inconsistent codes"
assert len(set(mapping.values())) == len(mapping), f"distinct {name} categories share a code"
# ENHANCED_CASE_3
def case_is_alone_truth_table():
"""is_alone follows sibsp + parch == 0 for every fixture record."""
source, output = matching_rows()
assert "is_alone" in next(iter(output.values())), "clean export lacks is_alone"
expected_values = set()
for key in output:
before = source[key]
expected = float(before.get("sibsp") or 0) + float(before.get("parch") or 0) == 0
expected_values.add(expected)
assert boolean_value(output[key].get("is_alone")) is expected, f"is_alone mismatch for fare={key}"
assert expected_values, "cleaning may not delete every record"
CASES = [
("ENHANCED_CASE_1", case_age_imputation),
("ENHANCED_CASE_2", case_deck_fill_and_categories),
("ENHANCED_CASE_3", case_is_alone_truth_table),
]
failures = []
requested = set(sys.argv[1:])
known = {case_id for case_id, _ in CASES}
assert requested <= known, f"unknown case id(s): {sorted(requested - known)}"
for case_id, validator in CASES:
if requested and case_id not in requested:
continue
try:
validator()
print(f"{case_id}: PASS")
except Exception as exc:
failures.append((case_id, exc))
print(f"{case_id}: FAIL: {exc}", file=sys.stderr)
if failures:
raise SystemExit(1)
|