"""Instruction-derived deterministic checks for Task 43.""" import csv import html import math import os import pathlib import re import shutil import statistics import subprocess import tempfile from collections import Counter from analysis_entry import run_analysis from report_values import assert_top_rows ROOT = pathlib.Path.cwd() def read_csv(name): with (ROOT / name).open(encoding="utf-8-sig", newline="") as handle: return list(csv.DictReader(handle)) def field(row, *terms): for name in row: normalized = name.strip().lower().replace('_', ' ') if any(re.search(r'(?= 0, 'count must be a nonnegative integer' return int(number) fixture = read_csv("diamonds.csv") assert fixture, "diamonds fixture is empty" # ENHANCED_CASE_1: grouped cut output must contain fixture-derived counts and # the requested average and median prices. def enhanced_case_1(): cut_rows = read_csv("cut_price_stats.csv") assert cut_rows, "cut_price_stats.csv is empty" cut_key = field(cut_rows[0], "cut") count_key = next((name for name in cut_rows[0] if name.lower() in ('count', '数量', '频数')), None) mean_key = field(cut_rows[0], "mean", "avg", "average", "平均") median_key = field(cut_rows[0], "median", "中位") actual_cuts = {row[cut_key].strip(): row for row in cut_rows} assert len(actual_cuts) == len(cut_rows), 'duplicate cut rows' expected_cuts = {} for cut in {row["cut"] for row in fixture}: prices = [float(row["price"]) for row in fixture if row["cut"] == cut] expected_cuts[cut] = (len(prices), statistics.mean(prices)) assert set(actual_cuts) == set(expected_cuts), ( f"cut groups differ: actual={set(actual_cuts)}, expected={set(expected_cuts)}" ) for cut, (expected_count, expected_mean) in expected_cuts.items(): row = actual_cuts[cut] if count_key: assert count(row[count_key]) == expected_count, f"wrong count for cut {cut}" assert close(row[mean_key], expected_mean), f"wrong mean price for cut {cut}" assert close(row[median_key], statistics.median( float(r["price"]) for r in fixture if r["cut"] == cut )), f"wrong median price for cut {cut}" def signature(row, pkey, ckey, depth_key): return tuple(round(float(row[key]), 8) for key in (pkey, ckey, depth_key)) # ENHANCED_CASE_2: validate the complete top-N result using only the fields the # instruction asks to inspect. Counter comparison remains correct for ties and # duplicate diamonds and does not require an unspecified identifier column. def enhanced_case_2(): top_rows = read_csv("top_10_diamonds.csv") assert top_rows, "top_10_diamonds.csv is empty" price_key = field(top_rows[0], "price", "价格") carat_key = field(top_rows[0], "carat", "克拉") z_key = field(top_rows[0], "z", "深度") expected_top = sorted(fixture, key=lambda row: float(row["price"]), reverse=True)[:10] assert len(top_rows) == len(expected_top), "top-N row count does not match the fixture" actual_prices = [float(row[price_key]) for row in top_rows] assert actual_prices == sorted(actual_prices, reverse=True), "top-N rows are not price-descending" actual_signatures = Counter(signature(row, price_key, carat_key, z_key) for row in top_rows) expected_signatures = Counter(signature(row, "price", "carat", "z") for row in expected_top) assert actual_signatures == expected_signatures, "top-N price/carat/z values do not match the fixture" # ENHANCED_CASE_3: a metamorphic fixture check rejects hard-coded cut averages. # It changes one input price in an isolated copy, reruns the submitted program, # and checks the affected cut average. No particular dataframe/API is assumed. def rerun_analysis(work): for name in ("report.html", "cut_price_stats.csv", "price_bin_stats.csv", "top_10_diamonds.csv"): (work / name).unlink(missing_ok=True) run_analysis(work) def enhanced_case_3(): with tempfile.TemporaryDirectory(prefix="task43_case3_") as tmp_name: work = pathlib.Path(tmp_name) / "work" shutil.copytree( ROOT, work, ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__"), ) mutated = [] with (work / "diamonds.csv").open(encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle) names = reader.fieldnames mutated = list(reader) assert names and mutated, "cannot prepare mutated diamonds fixture" changed_cut = mutated[0]["cut"] mutated[0]["price"] = str(float(mutated[0]["price"]) + 1337.0) with (work / "diamonds.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=names) writer.writeheader() writer.writerows(mutated) env = os.environ.copy() for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): env.pop(key, None) env["PYTHONHASHSEED"] = "1" rerun_analysis(work) with (work / "cut_price_stats.csv").open(encoding="utf-8-sig", newline="") as handle: changed_rows = list(csv.DictReader(handle)) assert changed_rows, "rerun did not emit cut_price_stats.csv" cut_key = field(changed_rows[0], "cut") mean_key = field(changed_rows[0], "mean", "avg", "average", "平均") matches = [row for row in changed_rows if row[cut_key].strip() == changed_cut] assert len(matches) == 1, f"rerun does not contain exactly one {changed_cut} cut row" expected = statistics.mean( float(row["price"]) for row in mutated if row["cut"] == changed_cut ) assert close(matches[0][mean_key], expected), ( f"cut average did not follow the mutated fixture: expected {expected}" ) # The HTML chart and tables must follow changed data too, not just the CSV. env['REPORT_REVIEW_DIR']='/logs/verifier/report-review-mutated' tests=pathlib.Path(__file__).resolve().parent subprocess.run(['node',str(tests/'review_report.js')],cwd=work,env=env,timeout=45,check=True) subprocess.run(['python3',str(tests/'review_report.py')],cwd=work,env=env,timeout=30,check=True) def enhanced_case_4(): bins = read_csv("price_bin_stats.csv") assert bins, "price_bin_stats.csv is empty" bin_key = field(bins[0], "bin", "分档") count_key = field(bins[0], "count", "数量", "频数") expected = Counter( "0-1000" if float(row["price"]) < 1000 else "1000-5000" if float(row["price"]) < 5000 else "5000+" for row in fixture ) for label in ('0-1000','1000-5000','5000+'): expected.setdefault(label,0) actual = {row[bin_key].strip(): count(row[count_key]) for row in bins} assert len(actual) == len(bins), 'duplicate price bin rows' assert actual == expected, f"price bins mismatch: {actual} != {expected}" report = html.unescape((ROOT / "report.html").read_text(encoding="utf-8")).lower() assert_top_rows(report, sorted(fixture, key=lambda item: float(item["price"]), reverse=True)[:10]) # ENHANCED_CASE_5: an injected price exactly at 1000 belongs to the second, # left-closed bin. Recompute outputs from the changed fixture, not constants. def enhanced_case_5(all_high=False): with tempfile.TemporaryDirectory(prefix="task43_boundary_") as tmp_name: work = pathlib.Path(tmp_name) / "work" shutil.copytree(ROOT, work, ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__")) with (work / "diamonds.csv").open(encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle) names, rows = reader.fieldnames, list(reader) assert names and rows rows[0]["price"] = "1000" rows[1]["price"] = "5000" if all_high: for index,row in enumerate(rows): row['price']=str(6000+index) with (work / "diamonds.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=names) writer.writeheader() writer.writerows(rows) rerun_analysis(work) with (work / "price_bin_stats.csv").open(encoding="utf-8-sig", newline="") as handle: bins = list(csv.DictReader(handle)) assert bins bin_key, count_key = field(bins[0], "bin", "分档"), field(bins[0], "count", "数量", "频数") actual = {row[bin_key].strip(): count(row[count_key]) for row in bins} assert len(actual) == len(bins), 'duplicate price bin rows' expected = Counter("0-1000" if float(row["price"]) < 1000 else "1000-5000" if float(row["price"]) < 5000 else "5000+" for row in rows) for label in ('0-1000','1000-5000','5000+'): expected.setdefault(label,0) assert actual == expected, f"exact boundaries 1000 and 5000 must enter their left-closed bins: {actual} != {expected}" all_cases = ( ("ENHANCED_CASE_1", enhanced_case_1), ("ENHANCED_CASE_2", enhanced_case_2), ("ENHANCED_CASE_3", enhanced_case_3), ("ENHANCED_CASE_4", enhanced_case_4), ("ENHANCED_CASE_5", enhanced_case_5), ("ENHANCED_CASE_6", lambda: enhanced_case_5(all_high=True)), ) selected = os.environ.get("ENHANCED_CASE") assert selected is None or selected in dict(all_cases), f"unknown ENHANCED_CASE: {selected}" failures = [] for case_id, validator in all_cases: if selected and case_id != selected: continue try: validator() print(f"PASS {case_id}") except Exception as error: # keep cases independently executable/reportable failures.append((case_id, error)) print(f"FAIL {case_id}: {error}") assert not failures, f"{len(failures)} enhanced case(s) failed"