File size: 3,060 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 | """Regenerate the report and validate it again against changed data."""
import csv
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from analysis_entry import run_analysis
def candidate_field_sets(data):
if isinstance(data, list) and data and isinstance(data[0], dict):
yield set(data[0])
if isinstance(data, dict):
yield set(data)
for item in data.values():
if isinstance(item, dict):
yield set(item)
if isinstance(data.get("columns"), list):
yield set(str(column) for column in data["columns"])
if isinstance(data.get("data"), list):
yield from candidate_field_sets(data["data"])
def clear_generated_reports(root):
(root / "report.html").unlink(missing_ok=True)
for path in root.glob("*.json"):
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (ValueError, OSError):
continue
if any({"country", "year", "continent"} <= fields for fields in candidate_field_sets(data)):
path.unlink()
def generate(root):
source = root / "gapminderDataFiveYear.csv"
original = source.read_bytes()
clear_generated_reports(root)
run_analysis(root)
assert source.read_bytes() == original, "analysis must preserve the input CSV"
def run_validators(root, screenshot):
for script in ("validate_outputs.py", "validate_enhancement.py"):
subprocess.run([sys.executable, str(TESTS / script)], cwd=root, check=True, timeout=20)
env = {**os.environ, "GAPMINDER_SCREENSHOT": screenshot}
subprocess.run(["node", str(TESTS / "validate_aaav_dynamic.js")], cwd=root, env=env, check=True, timeout=45)
def mutate_input(root):
source = root / "gapminderDataFiveYear.csv"
with source.open(encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle)
fields, rows = reader.fieldnames, list(reader)
changed = next(row for row in rows if row["year"] == "2007")
population = int(float(changed["pop"])) + 200_017
changed["pop"] = str(population)
gdp_per_capita = float(changed["gdpPercap"]) * 1.14
changed["gdpPercap"] = repr(gdp_per_capita)
changed["gdpTotal"] = repr(gdp_per_capita * population)
changed["lifeExp"] = repr(float(changed["lifeExp"]) - 1.7)
with source.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fields)
writer.writeheader()
writer.writerows(reversed(rows))
if __name__ == "__main__":
TESTS = Path(__file__).resolve().parent
root = Path.cwd()
generate(root)
run_validators(root, "gapminder-report")
with tempfile.TemporaryDirectory(prefix="gapminder-") as directory:
work = Path(directory) / "candidate"
shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "__pycache__", ".git"))
mutate_input(work)
generate(work)
run_validators(work, "gapminder-report-mutated")
|