import csv import json import math import pathlib import re import sys from decimal import Decimal, InvalidOperation from html.parser import HTMLParser ROOT = pathlib.Path.cwd() NUMERIC_COLUMNS = {'year', 'pop', 'lifeExp', 'gdpPercap', 'gdpTotal'} def read_csv(path): with path.open(encoding="utf-8-sig", newline="") as handle: return list(csv.DictReader(handle)) def record_candidates(value): """Yield common JSON table orientations without binding to pandas.""" if isinstance(value, list) and value and all(isinstance(item, dict) for item in value): yield value if not isinstance(value, dict) or not value: return values = list(value.values()) if values and all(isinstance(item, dict) for item in values): yield values index_sets = [set(item) for item in values] if index_sets and all(index == index_sets[0] for index in index_sets): yield [{column: value[column][index] for column in value} for index in sorted(index_sets[0], key=str)] data = value.get("data") if isinstance(data, list) and data: if all(isinstance(item, dict) for item in data): yield data columns = value.get("columns") if ( isinstance(columns, list) and all(isinstance(column, str) for column in columns) and len(set(columns)) == len(columns) and all(isinstance(item, list) and len(item) == len(columns) for item in data) ): yield [dict(zip(columns, item)) for item in data] def expected_2007(): rows = [row for row in read_csv(ROOT / "gapminderDataFiveYear.csv") if row.get("year", "").strip() == "2007"] assert rows, "fixture must contain 2007 records" return {row["country"]: row for row in rows} def matching_exports(expected): for path in sorted(ROOT.glob("*.json")): try: document = json.loads(path.read_text(encoding="utf-8"), parse_float=Decimal) except (OSError, json.JSONDecodeError): continue for records in record_candidates(document): countries = {record["country"] for record in records if isinstance(record.get("country"), str)} if countries == expected.keys() and len(records) == len(expected): yield records def decimal_value(value, label): try: number = Decimal(str(value).strip()) except InvalidOperation as exc: raise AssertionError(f"{label} is not numeric") from exc assert number.is_finite(), f"{label} is not finite" return number def check_source_value(column, value, original, country): label = f"{country}: {column}" if column not in NUMERIC_COLUMNS: assert value == original, f"{label}: expected {original!r}, got {value!r}" return actual = decimal_value(value, label) expected = Decimal(original) if actual == expected: return # Allow normal binary float round trips for measured values. Year and population are integers. tolerance = 0 if column in {"year", "pop"} else Decimal(str(4 * math.ulp(float(expected)))) assert abs(actual - expected) <= tolerance, f"{label}: expected {expected}, got {actual}" def require_export(expected, check): error = None for records in matching_exports(expected): try: for record in records: check(record, expected[record["country"]]) return except AssertionError as exc: if error is None: error = str(exc) raise AssertionError(error or "no JSON export matches the fixture's 2007 country set and row count") def assert_close(got, want, label, tolerance=1e-6): assert math.isfinite(got), f"{label} is not finite" assert abs(got - want) <= max(tolerance, abs(want) * 1e-9), f"{label}: expected {want}, got {got}" def report_has_number_near(report, label, value): starts = [match.start() for match in re.finditer(re.escape(label.lower()), report)] number = re.compile(r"(? 0 for value in sizes[continent]), f"{continent} has invalid bar size" def proportional(dimension): ratios = [sizes[continent][dimension] / means[continent] for continent in continents] return max(ratios) - min(ratios) <= max(ratios) * 0.01 assert proportional(0) or proportional(1), "bar lengths must share a zero-origin population scale" all_rows = read_csv(ROOT / "gapminderDataFiveYear.csv") growth = {} for country in {row["country"] for row in all_rows}: years = {row["year"]: float(row["pop"]) for row in all_rows if row["country"] == country} if "1952" in years and "2007" in years: growth[country] = years["2007"] - years["1952"] fastest = max(growth, key=growth.get) assert parsed.fastest and parsed.fastest.get("data-country") == fastest, "fastest-growth conclusion is wrong" assert_close(float(parsed.fastest.get("data-absolute-growth", "nan")), growth[fastest], "absolute growth") CASES = [ ("ENHANCED_CASE_1", case_complete_2007_json_slice), ("ENHANCED_CASE_2", case_scatter_fields_and_per_capita_values), ("ENHANCED_CASE_3", case_continent_population_and_growth_report), ("ENHANCED_CASE_4", case_actual_visuals), ] if __name__ == "__main__": 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)