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)