Spaces:
Running
Running
Download test_challenge.py from kugguk/electrocheap: direct link, hf CLI and curl.
- Browser
- Download file 8.89 kB
-
https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/test_challenge.py
- Command line
-
hf download hf://spaces/kugguk/electrocheap/test_challenge.py
-
curl -L -o test_challenge.py https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/test_challenge.py
8.89 kB
| """Regression tests for challenge evidence and source completeness.""" | |
| from copy import deepcopy | |
| from io import BytesIO | |
| from zipfile import ZipFile | |
| import csv | |
| import hashlib | |
| import json | |
| import subprocess | |
| import types | |
| import pandas as pd | |
| import pytest | |
| from fastapi.testclient import TestClient | |
| import challenge as subject | |
| import sources | |
| def test_reproduces_archived_baseline_and_all_comparators(country): | |
| packet = subject.challenge_packet({"country": country}) | |
| result = subject.challenge_score(packet["demo_submission"]) | |
| assert result["candidate"]["completion_rate"] == 1 | |
| assert result["candidate"]["mae_gwh"] == pytest.approx(result["comparators"][0]["mae_gwh"]) | |
| with (subject.ARCHIVE/"outputs/test_metrics.csv").open() as f: | |
| archive = {r["model"]: r for r in csv.DictReader(f) if r["country"] == country.lower()} | |
| for comparator in result["comparators"]: | |
| assert comparator["mae_gwh"] == pytest.approx(float(archive[comparator["id"]]["mae_gwh"])) | |
| assert comparator["mase"] == pytest.approx(float(archive[comparator["id"]]["mase"])) | |
| assert len(result["origin_slices"]) == 4 | |
| assert len(result["horizon_slices"]) == 6 | |
| assert result["promotion"] == "not_evaluated" | |
| assert result["model_identity_verified"] is False | |
| def test_malformed_evidence_is_rejected_without_dropping_rows(mutation): | |
| data = deepcopy(subject.challenge_packet({})["demo_submission"]) | |
| rows = data["predictions"] | |
| if mutation == "missing": rows.pop() | |
| elif mutation == "duplicate": rows[1]["id"] = rows[0]["id"] | |
| elif mutation == "unknown": rows[0]["id"] = "unknown" | |
| elif mutation in {"nan", "infinite", "negative", "boolean", "overflow"}: | |
| rows[0]["forecast"] = {"nan": float("nan"), "infinite": float("inf"), "negative": -1, "boolean": True, "overflow": 1e308}[mutation] | |
| elif mutation == "hash": data["panel_sha256"] = "bad" | |
| elif mutation == "model": data["model"] = {"id": "no-revision"} | |
| elif mutation == "country": data["country"] = [] | |
| with pytest.raises(ValueError): subject.challenge_score(data) | |
| def test_failed_attempt_stays_in_denominator_and_cannot_gain_rank(): | |
| data = subject.challenge_packet({})["demo_submission"] | |
| data["predictions"][0] = {"id": data["predictions"][0]["id"], "status": "timeout"} | |
| result = subject.challenge_score(data) | |
| assert result["status"] == "incomplete_predictions" | |
| assert result["candidate"]["eligible"] == 24 | |
| assert result["candidate"]["completed"] == 23 | |
| assert all(c["candidate_mae_gain_gwh"] is None for c in result["comparators"]) | |
| assert result["paired_predictions"][0]["status"] == "timeout" | |
| def test_known_answer_and_submission_order_independence(): | |
| data = subject.challenge_packet({})["demo_submission"] | |
| first = subject.challenge_score(data) | |
| for row, truth in zip(data["predictions"], first["paired_predictions"]): | |
| assert row["id"] == truth["id"] | |
| row["forecast"] = truth["actual"] + 10 | |
| report = subject.challenge_score(data) | |
| assert report["candidate"]["mae_gwh"] == 10 | |
| assert report["candidate"]["rmse_gwh"] == 10 | |
| assert report["candidate"]["bias_gwh"] == 10 | |
| data["predictions"].reverse() | |
| assert report == subject.challenge_score(data) | |
| def test_finetuning_targets_never_enter_validation_or_test(country): | |
| z = ZipFile(BytesIO(subject.challenge_export(country))) | |
| manifest = json.loads(z.read("manifest.json")) | |
| for name, digest in manifest["files_sha256"].items(): | |
| assert hashlib.sha256(z.read(name)).hexdigest() == digest | |
| for row in z.read("train.jsonl").decode().splitlines(): | |
| messages = json.loads(row)["messages"] | |
| task = json.loads(messages[1]["content"]) | |
| assert max(r["timestamp"] for r in task["history"]) <= task["origin"] | |
| assert all(task["origin"] < t["timestamp"] < "2022-10-01" for t in task["targets"]) | |
| assert len(json.loads(messages[2]["content"])["predictions"]) == 6 | |
| for row in z.read("test-prompts.jsonl").decode().splitlines(): | |
| messages = json.loads(row)["messages"] | |
| assert len(messages) == 2 | |
| task = json.loads(messages[1]["content"]) | |
| assert max(r["timestamp"] for r in task["history"]) <= task["origin"] | |
| assert all(t["timestamp"] > task["origin"] and "value" not in t for t in task["targets"]) | |
| def _smard_fixture(monkeypatch, module, missing=False): | |
| start = pd.Timestamp("2025-10-01", tz="Europe/Berlin").tz_convert("UTC") | |
| end = pd.Timestamp("2025-11-01", tz="Europe/Berlin").tz_convert("UTC") | |
| expected = pd.date_range(start, end, freq="h", inclusive="left") | |
| stamps = [int(t.timestamp()*1000) for t in pd.date_range(start-pd.Timedelta(days=2), end, freq="7D")] | |
| def reader(url, *args): | |
| if url.endswith("index_hour.json"): | |
| return {"timestamps": stamps}, "index", "time" | |
| block = int(url.rsplit("_", 1)[1].split(".")[0]) | |
| pos = stamps.index(block) | |
| stop = stamps[pos+1] if pos+1 < len(stamps) else int(end.timestamp()*1000) | |
| price = "/4169/" in url | |
| rows = [[int(t.timestamp()*1000), -20 if price else 1000] | |
| for t in expected if block <= int(t.timestamp()*1000) < stop] | |
| if missing and rows: rows.pop(0) | |
| return {"series": rows}, "block", "time" | |
| monkeypatch.setattr(module, "get_json", reader) | |
| return expected | |
| def test_official_view_returns_every_dst_hour_and_preserves_negative_prices(monkeypatch): | |
| expected = _smard_fixture(monkeypatch, sources) | |
| frame, meta = sources.live_market("DE", "", "2025-10") | |
| assert len(frame) == len(expected) == 745 | |
| assert meta["complete_month"] is True | |
| assert frame.wholesale_EUR_per_MWh.eq(-20).all() | |
| def test_official_view_never_joins_away_missing_publisher_hours(monkeypatch): | |
| _smard_fixture(monkeypatch, sources, missing=True) | |
| with pytest.raises(ValueError, match="missing"): | |
| sources.live_market("DE", "", "2025-10") | |
| def test_original_source_reproduces_incomplete_month(monkeypatch): | |
| # Frozen deployed source, not a fabricated mock implementation. | |
| old = types.ModuleType("baseline_sources") | |
| source = subprocess.check_output(["git", "show", "8fd5d73a73f355ecd4435f3b4e15103bb2228025:sources.py"], text=True) | |
| exec(compile(source, "baseline_sources.py", "exec"), old.__dict__) | |
| expected = _smard_fixture(monkeypatch, old) | |
| frame, _ = old.live_market("DE", "", "2025-10") | |
| assert len(frame) < len(expected) # The new completeness check would reject this baseline. | |
| def test_rest_and_mcp_registration_and_errors(): | |
| from app import api, mcp | |
| # REST handlers do not need an MCP lifespan; smoke_app exercises it. | |
| # The MCP SDK session manager can only be started once per instance. | |
| client = TestClient(api) | |
| try: | |
| p = client.post("/api/challenge_packet", json={"country": "AU"}) | |
| assert p.status_code == 200 | |
| result = client.post("/api/challenge_score", json=p.json()["demo_submission"]) | |
| assert result.status_code == 200 and result.json()["candidate"]["completed"] == 24 | |
| assert client.post("/api/challenge_score", json={}).status_code == 422 | |
| assert client.get("/api/challenge/AU/export").headers["content-type"] == "application/zip" | |
| assert client.get("/api/challenge/unknown/export").status_code == 422 | |
| connections = client.get("/api/connections").json() | |
| assert {"challenge_packet", "challenge_score"} <= set(connections["mcp"]["tools"]) | |
| assert client.get("/health").json()["version"] == "0.5.0" | |
| finally: | |
| client.close() | |
| import asyncio | |
| assert "challenge_packet" in {t.name for t in asyncio.run(mcp.list_tools())} | |
| def test_cli_export_score_and_callable_adapter(tmp_path): | |
| packet = subject.challenge_packet({}) | |
| input_path = tmp_path/"input.json" | |
| input_path.write_text(json.dumps(packet["demo_submission"])) | |
| import sys | |
| subprocess.run([sys.executable, "challenge_cli.py", "export", "--output", str(tmp_path/"kit.zip")], check=True) | |
| subprocess.run([sys.executable, "challenge_cli.py", "score", "--input", str(input_path), "--output", str(tmp_path/"report.json")], check=True) | |
| assert json.loads((tmp_path/"report.json").read_text())["candidate"]["completed"] == 24 | |
| subprocess.run([sys.executable, "challenge_cli.py", "run", "--adapter", "challenge_adapter_example:predict", | |
| "--model-id", "seasonal-naive-adapter", "--revision", subject.VERSION, "--output", str(tmp_path/"run.json")], check=True) | |
| submission = json.loads((tmp_path/"run.json").read_text()) | |
| assert subject.challenge_score(submission)["candidate"]["completed"] == 24 | |