from datetime import date, timedelta import pytest from economic_engine import compare, simulate from timing_oracle import lp_ceiling, optimize_window, oracle def fixture(): days = [(date(2025, 1, 1) + timedelta(days=i)).isoformat() for i in range(45)] v = dict(tank_liters=40, consumption=6, min_range_km=50, monthly_km=1500, min_gain_eur=1) prices = [1.8 + i * 0.003 for i in range(45)] return days, v, prices @pytest.mark.parametrize("extra", [False, True]) def test_feasible_oracle(extra): d, v, p = fixture() b = simulate(d, p, v) r = oracle(d, p, v, b, noextra=not extra) assert r["stock_final"] == pytest.approx(b["stock_final"]) assert r["reserve_ok"] and r["comfort_ok"] assert abs(r["conservation_error"]) < 1e-7 net_cost = r["stock_adjusted_cost"] + 3 * max(0, r["passages"] - b["passages"]) assert net_cost <= b["stock_adjusted_cost"] + 1e-5 if not extra: assert r["passages"] <= b["passages"] def test_oracle_does_not_read_prices_beyond_horizon(): d, v, p = fixture() b = simulate(d, p, v) q = [0.0] * len(d) for i, x in zip(b["visits"], b["purchases"], strict=True): q[i] = x["litres"] a, _ = optimize_window(d, p, v, q, 0, 15, b["passages"], False) changed = p[:15] + [1000.0] * 30 other, _ = optimize_window(d, changed, v, q, 0, 15, b["passages"], False) assert a == pytest.approx(other) def test_lp_ceiling_is_optimistic_not_realizable(): d, v, p = fixture() b = simulate(d, p, v) ceiling = lp_ceiling(d, p, v, b) assert ceiling["certified"] is True assert ceiling["optimistic_saving"] >= -1e-6 assert ceiling["total_visits"] <= b["passages"] + 1e-9 def test_anticipation_uses_same_stock_and_delays_next_need(): d, v, p = fixture() b = simulate(d, p, v) i = b["visits"][0] - 2 r = simulate(d, p, v, "local", {d[i]: 100}) assert i in r["visits"] assert b["visits"][0] not in r["visits"] assert r["stock_final"] == pytest.approx(b["stock_final"]) def test_omniscient_bound_cannot_be_worse_than_reference(): """Le plan de référence est réalisable : un plafond négatif est un bug, pas un résultat.""" d, v, p = fixture() b = simulate(d, p, v) ceiling = oracle(d, p, v, b, noextra=True, full=True) saving = b["stock_adjusted_cost"] - ceiling["stock_adjusted_cost"] assert saving >= -1e-5, f"plafond omniscient négatif : {saving}" assert ceiling["passages"] <= b["passages"] assert abs(ceiling["conservation_error"]) < 1e-7 def test_penalty_is_charged_once_for_oracle_plans(): """Les plans d'oracle facturent déjà la pénalité : `compare` ne doit pas la repayer.""" d, v, p = fixture() b = simulate(d, p, v) plan = oracle(d, p, v, b, noextra=False) once = compare(b, plan, d, penalty_included=True) twice = compare(b, plan, d) assert once["net"] >= twice["net"] - 1e-9