UXInteract / task_025 /tests /validate_enhancement.py
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
12.5 kB
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"(?<![a-z])[-+]?\d[\d,]*(?:\.\d+)?(?:e[-+]?\d+)?", re.I)
for start in starts:
for match in number.finditer(report[start : start + 500]):
candidate = float(match.group(0).replace(",", ""))
if abs(candidate - value) <= max(0.011, abs(value) * 1e-6):
return True
return False
def report_has_value(report, value):
number = re.compile(r"(?<![a-z])[-+]?\d[\d,]*(?:\.\d+)?(?:e[-+]?\d+)?", re.I)
return any(abs(float(match.group(0).replace(",", "")) - value) <= max(0.011, abs(value) * 1e-6)
for match in number.finditer(report))
# ENHANCED_CASE_1
def case_complete_2007_json_slice():
"""The JSON export contains exactly the countries and records from 2007."""
def check(record, source):
check_source_value("year", record.get("year"), source["year"], record["country"])
require_export(expected_2007(), check)
# ENHANCED_CASE_2
def case_scatter_fields_and_per_capita_values():
"""Every input field and the separately computed GDP field survive export."""
def check(record, source):
country = record["country"]
missing = (source.keys() | {"gdp_per_capita"}) - record.keys()
assert not missing, f"{country} lacks JSON fields: {', '.join(sorted(missing))}"
for column, source_value in source.items():
check_source_value(column, record[column], source_value, country)
label = f"{country}: gdp_per_capita"
computed = decimal_value(record["gdp_per_capita"], label)
assert_close(float(computed), float(source["gdpTotal"]) / float(source["pop"]), label)
require_export(expected_2007(), check)
# ENHANCED_CASE_3
def case_continent_population_and_growth_report():
"""The report exposes the requested mean-population chart data and fastest-growth country."""
rows = list(expected_2007().values())
report = (ROOT / "report.html").read_text(encoding="utf-8", errors="ignore").lower()
assert "2007" in report, "report lacks the requested 2007 analysis"
continents = sorted({row["continent"] for row in rows})
for continent in continents:
members = [row for row in rows if row["continent"] == continent]
mean_population = sum(float(row["pop"]) for row in members) / len(members)
assert continent.lower() in report, f"report lacks continent {continent}"
assert report_has_value(report, mean_population), f"report lacks mean population for {continent}"
all_rows = read_csv(ROOT / "gapminderDataFiveYear.csv")
by_country = {}
for row in all_rows:
by_country.setdefault(row["country"], {})[row["year"]] = float(row["pop"])
eligible = {country: years["2007"] - years["1952"] for country, years in by_country.items()
if "1952" in years and "2007" in years}
fastest = max(eligible, key=eligible.get)
assert fastest.lower() in report, f"report lacks fastest-growing country {fastest}"
class VisualReportParser(HTMLParser):
def __init__(self):
super().__init__()
self.scattering = False
self.barring = False
self.table = False
self.points = []
self.bars = []
self.table_rows = []
self.fastest = None
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "svg" and attrs.get("id") == "gdp-life-scatter":
self.scattering = True
elif tag == "svg" and attrs.get("id") == "continent-population-bars":
self.barring = True
elif tag == "table" and attrs.get("id") == "continent-population":
self.table = True
elif self.scattering and attrs.get('data-country'):
self.points.append(attrs)
elif tag == "rect" and self.barring:
self.bars.append(attrs)
elif tag == "tr" and self.table and attrs.get("data-continent"):
self.table_rows.append(attrs)
elif attrs.get("id") == "fastest-growth":
self.fastest = attrs
def handle_endtag(self, tag):
if tag == "svg":
self.scattering = False
self.barring = False
elif tag == "table":
self.table = False
# ENHANCED_CASE_4
def case_actual_visuals():
"""The report's marks and their metadata are derived from the fixture."""
rows = list(expected_2007().values())
parsed = VisualReportParser()
parsed.feed((ROOT / "report.html").read_text(encoding="utf-8"))
assert len(parsed.points) == len(rows), "scatter chart needs one point per 2007 country"
expected = {row["country"]: row for row in rows}
colors = {}
coordinates = set()
for point in parsed.points:
country = point.get("data-country")
assert country in expected, f"unexpected scatter point {country}"
before = expected.pop(country)
continent = before["continent"]
assert point.get("data-continent") == continent, f"{country} has wrong continent color group"
assert_close(float(point.get("data-gdp", "nan")), float(before["gdpTotal"]) / float(before["pop"]), f"{country} chart GDP")
assert_close(float(point.get("data-life", "nan")), float(before["lifeExp"]), f"{country} chart life")
assert not expected, "scatter points are missing"
# Actual rendered coordinates and computed CSS colors are checked in the
# browser, not inferred from a particular SVG element or inline style.
continents = sorted({row["continent"] for row in rows})
means = {continent: sum(float(row["pop"]) for row in rows if row["continent"] == continent) /
sum(row["continent"] == continent for row in rows) for continent in continents}
assert len(parsed.table_rows) == len(means), "report needs one mean-population table row per continent"
assert len(parsed.bars) == len(means), "bar chart needs one bar per continent"
table_seen = set()
for row in parsed.table_rows:
continent = row.get("data-continent")
assert continent in means and continent not in table_seen, f"bad table continent {continent}"
table_seen.add(continent)
assert_close(float(row.get("data-mean-pop", "nan")), means[continent], f"{continent} table mean", 0.02)
sizes = {}
for bar in parsed.bars:
continent = bar.get("data-continent")
assert continent in means and continent not in sizes, f"bad bar continent {continent}"
assert_close(float(bar.get("data-mean-pop", "nan")), means[continent], f"{continent} bar mean", 0.02)
sizes[continent] = (float(bar.get('width', 'nan')), float(bar.get('height', 'nan')))
assert all(math.isfinite(value) and value > 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)