"""Tests de régression de l'analyse MA7D_DROP, sur données réelles uniquement (spec §9).""" import functools import io import json import shutil import sys import tempfile import unittest from contextlib import redirect_stderr, redirect_stdout from datetime import datetime, timedelta, timezone from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) import energy_check as ec # noqa: E402 DATA, VERMONT = ROOT / "data", ROOT / "vermont" VERMONT_V = VERMONT / "VERMONT_BusVoltage_2026_04_09_15_00 to 2026_10_09_15_00.csv" VERMONT_THERMAL = VERMONT / "VERMONT_sensor_thermal_deg_c_2026_02_22_15_00 to 2026_10_09_15_00.csv" JUNGFRAU_V = DATA / "JUNGFRAU_BusVoltage_2026_09_11_14_00 to 2026_10_09_14_00.csv" def at(*args): return datetime(*args, tzinfo=timezone.utc) @functools.cache def stations(): return ec.load_stations([str(DATA), str(VERMONT)]) @functools.cache def result(name): return ec.run(stations()[name]) def first_anomaly(res): return next((p["t"] for p in res["points"] if p["anomaly"] is True), None) class Loading(unittest.TestCase): def test_parse_name_metric_with_underscores(self): self.assertEqual(ec.parse_name(str(VERMONT_THERMAL)), ("VERMONT", "sensor_thermal_deg_c")) def test_parse_name_rejects_unknown_pattern(self): self.assertIsNone(ec.parse_name("data/metadata.csv")) def test_load_csv_empty_value_is_none(self): s = ec.load_csv(VERMONT_V) self.assertIsNone(s[at(2026, 4, 9, 15)]) self.assertAlmostEqual(s[at(2026, 4, 9, 16)], 14.011) def test_load_stations_groups_by_station(self): self.assertEqual(sorted(stations()), ["FLORIDA", "JUNGFRAU", "MISSISSIPPI", "VERMONT", "WILDSTRUBEL"]) self.assertEqual(len(stations()["VERMONT"]), 7) def test_same_file_given_twice_is_not_a_duplicate(self): self.assertIn("BusVoltage", ec.load_stations([str(DATA), str(JUNGFRAU_V)])["JUNGFRAU"]) def test_two_files_same_station_metric_raise(self): with tempfile.TemporaryDirectory() as d: shutil.copy(JUNGFRAU_V, Path(d) / "JUNGFRAU_BusVoltage_2026_09_12_14_00 to 2026_10_09_14_00.csv") with self.assertRaises(ValueError): ec.load_stations([str(DATA), d]) def test_unknown_csv_name_is_skipped_with_message(self): with tempfile.TemporaryDirectory() as d: shutil.copy(JUNGFRAU_V, Path(d) / "export.csv") shutil.copy(JUNGFRAU_V, d) err = io.StringIO() with redirect_stderr(err): st = ec.load_stations([d]) self.assertEqual(list(st), ["JUNGFRAU"]) self.assertIn("export.csv", err.getvalue()) class Ma7dDrop(unittest.TestCase): def test_florida_never_anomalous(self): self.assertIsNone(first_anomaly(result("FLORIDA"))) def test_jungfrau_never_anomalous(self): self.assertIsNone(first_anomaly(result("JUNGFRAU"))) def test_vermont_first_anomaly_before_first_cut(self): t = first_anomaly(result("VERMONT")) self.assertIsNotNone(t) self.assertTrue(at(2026, 9, 20) <= t < at(2026, 9, 27, 1), t) def test_wildstrubel_first_anomaly_before_cut(self): t = first_anomaly(result("WILDSTRUBEL")) self.assertIsNotNone(t) self.assertLess(t, at(2026, 9, 9, 22)) def test_mississippi_first_anomaly_before_first_cut(self): t = first_anomaly(result("MISSISSIPPI")) self.assertIsNotNone(t) self.assertLess(t, at(2025, 12, 25, 14)) def test_causal(self): t = at(2026, 9, 24, 7) truncated = {"BusVoltage": {k: x for k, x in stations()["VERMONT"]["BusVoltage"].items() if k <= t}} last = ec.run(truncated)["points"][-1] full = next(p for p in result("VERMONT")["points"] if p["t"] == t) self.assertEqual(last["t"], t) self.assertEqual((last["value"], last["anomaly"]), (full["value"], full["anomaly"])) def test_one_point_per_timestamp(self): self.assertEqual([p["t"] for p in result("VERMONT")["points"]], sorted(stations()["VERMONT"]["BusVoltage"])) def test_facts_trace_the_verdict(self): p = next(p for p in result("VERMONT")["points"] if p["anomaly"] is True) self.assertEqual(set(p["facts"]), {"coverage", "ma_v", "ref_v", "ref_t"}) self.assertLess(p["facts"]["ref_t"], p["t"]) def test_short_history_is_unknown(self): v = stations()["JUNGFRAU"]["BusVoltage"] short = {"BusVoltage": {t: x for t, x in v.items() if t < min(v) + timedelta(days=5)}} self.assertTrue(all(p["anomaly"] is None for p in ec.run(short)["points"])) def test_empty_series_gives_no_points(self): self.assertEqual(ec.run({"BusVoltage": {}})["points"], []) def test_off_grid_timestamp_raises(self): v = dict(stations()["JUNGFRAU"]["BusVoltage"]) v[min(v) + timedelta(minutes=30)] = None with self.assertRaises(ValueError): ec.run({"BusVoltage": v}) class Reporting(unittest.TestCase): def test_vermont_period_is_ongoing(self): per = ec.periods(result("VERMONT")["points"]) self.assertEqual(per[-1]["start"], at(2026, 9, 24, 7)) self.assertIsNone(per[-1]["end"]) def test_mississippi_first_period_is_closed(self): per = ec.periods(result("MISSISSIPPI")["points"]) self.assertEqual((per[0]["start"], per[0]["end"]), (at(2025, 12, 9, 12), at(2025, 12, 18, 6))) def test_florida_has_no_period(self): self.assertEqual(ec.periods(result("FLORIDA")["points"]), []) def test_summary_vocabulary(self): for name, word in [("FLORIDA", "not observed"), ("VERMONT", "consistent with")]: res = result(name) self.assertIn(word, ec.summary(name, res, ec.periods(res["points"]))) def test_summary_short_history_is_insufficient_evidence(self): v = stations()["JUNGFRAU"]["BusVoltage"] res = ec.run({"BusVoltage": {t: x for t, x in v.items() if t < min(v) + timedelta(days=5)}}) self.assertIn("insufficient evidence", ec.summary("JUNGFRAU", res, ec.periods(res["points"]))) def test_cli_writes_json_and_summary(self): out = io.StringIO() with tempfile.TemporaryDirectory() as d, redirect_stdout(out): ec.main([str(VERMONT), "--out", d]) doc = json.loads((Path(d) / "VERMONT_energy.json").read_text()) self.assertEqual((doc["station"], doc["analysis"]), ("VERMONT", "MA7D_DROP")) self.assertIsNone(doc["periods"][-1]["end"]) self.assertIn("VERMONT : anomalie énergétique", out.getvalue()) def test_cli_skips_station_without_busvoltage(self): out = io.StringIO() with tempfile.TemporaryDirectory() as d, redirect_stdout(out): ec.main([str(VERMONT_THERMAL), "--out", d]) self.assertIn("ignorée, pas de BusVoltage", out.getvalue()) if __name__ == "__main__": unittest.main()