"""EV-16: the Car Why does not alternate between "are at {pct}" and "give all they can" while the car-over row holds and the guard's floor flag toggles. `python3 -B test_ev16.py` Display only: the text is held in `c._car_why_hold`; control never reads it. Mutant: pick the text from the live `floor_limited` again (T1, T2, T7, T8, T9 go red). Mutating a module this file grades? Read MUTATION.md first. """ import dataclasses import hashlib import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "tools")) from app import ctl_car, homeview, chargers as CH # noqa: E402 import ev04_peak as P # noqa: E402 import safety81_sim as s81 # noqa: E402 fails = [] def check(name, cond): print(f" {'ok ' if cond else 'FAIL'} {name}") if not cond: fails.append(name) OVER = "are at" FULL = "give all they can" Q = 900.0 STEP = 5.0 @dataclasses.dataclass class G: floor_limited: bool = True soc: object = 20.0 saturated: bool = False floor_w: float = 0.0 able_w: object = None ceiling_w: float = 4500.0 engaged: bool = True blind: object = None wanted_w: float = 300.0 within_aim: bool = False class Proj: projected_w = 14500.0 held_w = 14500.0 elapsed_s = 400.0 block_start = None class S(ctl_car.CarMixin): def __init__(self, cover=True): self.o = {"ev_batt_cover": cover} self._now = 0.0 self.w = 11000.0 self.site_batt_w, self.site_rating_w = 8100.0, 9600.0 self.shadow, self.auto, self.peak_guard = False, True, None self.state = "charging" self.car_init({}, type("St", (), {"data": {}, "set": lambda s, k, v: 0})()) self.car_over = True def car_now(self): return self._now def car_alarm_w(self): return self.w @property def car(self): me = self class _C: @staticmethod def status(*_a): return me.state return _C def why(c): return homeview._car_manual_why(c, "charging") def kind(t): return "over" if OVER in t else "full" if FULL in t else t def run(c, secs, g_of, t0=0.0): """Read the Why once per 5 s cycle; returns [(t, kind)].""" out = [] t = t0 while t < t0 + secs: c._now = t c.peak_guard = g_of(t - t0) out.append((t, kind(why(c)))) t += STEP return out def changes(seq): return [i for i in range(1, len(seq)) if seq[i][1] != seq[i - 1][1]] def toggle(period, first=True): return lambda t: G(floor_limited=(int(t // period) % 2 == 0) == first) HOUSE = s81.constant(1100.0) def real_run(read, eventful=True): """The T1 shape through the real controller: the batteries toggle across the reserve every 10 s. Returns the control digest, the per-cycle rows and flags, and the Why texts read (if `read`).""" texts, rows, flags = [], [], [] def ev(plant, c): plant.soc = 19.0 if int(plant.t // 10) % 2 == 0 else 60.0 pg = c.peak_guard flags.append(None if pg is None else pg.floor_limited) rows.append(tuple((x["id"], x["ok"], x["warn"]) for x in c.checks() if x["id"] in ("peak_guard", "car_over"))) if read and c.car_over: texts.append(homeview.car_block(c, None)["why"]) r = P.drive(HOUSE, dur=900, events={k: ev for k in range(0, 900)}, cap=3500.0) ctl = ([s[1:] for s in r["snaps"]], list(r["raised"]), r["sim"].writes(), r["sim"].setpoint_a) return ctl, rows, flags, texts def digest(x): return hashlib.sha256(repr(x).encode()).hexdigest()[:16] if "--digest" in sys.argv: ctl, rows, flags, _t = real_run(False) print("DIGEST control", digest(ctl), "rows", digest(rows), "flags", digest(flags)) sys.exit(0) print("1. the hold: a toggling flag shows one text") c = S() a = run(c, Q, toggle(10.0, True)) check("T1 quarter starts floor-limited, toggles every 10 s: one distinct text", len({k for _, k in a}) == 1 and a[0][1] == "over") for per in (20.0, 30.0, 10.0): c = S() a = run(c, Q, toggle(per, False)) check(f"T2 starts not limited, toggles every {per:.0f} s: at most one " f"change, none back", len(changes(a)) <= 1) c = S() a = run(c, Q, lambda t: G(floor_limited=False, soc=38.0)) check("T3 never limited: 'give all they can' every cycle, never 'are at'", {k for _, k in a} == {"full"}) c = S() a = run(c, Q, lambda t: G()) check("T4 limited and steady: 'are at' 20 % from the first cycle", {k for _, k in a} == {"over"} and "20 %" in why(c)) print("\n2. real changes still show") c = S() a = run(c, 300.0, lambda t: G(floor_limited=False, soc=30.0)) a += run(c, 600.0, lambda t: G(), t0=300.0) ch = changes(a) check("T5 full for 300 s then steady limited: one change, full -> over, " "within 185 s", len(ch) == 1 and a[ch[0]][1] == "over" and a[ch[0]][0] - 300.0 <= 185.0) c = S() a = run(c, 300.0, lambda t: G()) a += run(c, 600.0, lambda t: G(floor_limited=False, soc=30.0), t0=300.0) ch = changes(a) check("T6 limited for 300 s then steady not limited: one change back to " "'give all they can' within 185 s", len(ch) == 1 and a[ch[0]][1] == "full" and a[ch[0]][0] - 300.0 <= 185.0) for steady_false in (True, False): c = S() a = run(c, Q, toggle(10.0, True)) a += run(c, Q, (lambda t: G(floor_limited=False, soc=30.0)) if steady_false else (lambda t: G()), t0=Q) ch = changes(a) first_q = {k for t, k in a if t < Q} check(f"T7 toggling across the edge, new quarter steady " f"{'False' if steady_false else 'True'}: nothing before the edge, " f"at most one change near it, to the new state", len(first_q) == 1 and len(ch) <= 1 and all(a[i][0] >= Q for i in ch) and len(a) > 0 and a[-1][1] == ("full" if steady_false else "over")) near = [i for i in ch if abs(a[i][0] - Q) <= 60.0] check("T7 (cont.) at most one change in the 60 s around the edge", len(near) <= 1) print("\n3. failure modes") c = S() a = run(c, Q, lambda t: G(soc=None)) check("T8 SoC unread, guard limited: never 'are at', one text", {k for _, k in a} == {"full"}) c = S() a = run(c, Q, lambda t: G(soc=None if int(t // 10) % 2 == 0 else 20.0)) check("T8 SoC toggling None / 20 % every 10 s, starting unread: one text, " "never 'are at'", {k for _, k in a} == {"full"}) c = S() seq = [] for t in range(0, 900, 5): c._now = float(t) c.peak_guard = None if 400 <= t < 410 else G(floor_limited=(t // 10) % 2 == 0) try: seq.append((t, kind(why(c)))) except Exception as e: # noqa: BLE001 seq.append((t, "TRACE " + repr(e))) check("T9 guard None for a cycle: no Traceback, one text through it", not any("TRACE" in k for _, k in seq) and len({k for _, k in seq}) == 1) c = S() c.peak_guard = None c._now = 0.0 check("T9 (cont.) guard None from the very first read: a text, no Traceback", kind(why(c)) in ("full", "over")) # T10: the car stops, car_over drops after 180 s, a later episode c = S() run(c, 100.0, lambda t: G()) check("T10 held 'are at' to start", kind(why(c)) == "over") for k in range(0, 200): c._now = 100.0 + k c.w = None c.car_cycle(Proj(), G(), 14000.0, None) check("T10 car_over dropped after the stop", c.car_over is False) check("T10 the Why left the over wording", OVER not in why(c) and FULL not in why(c)) c.car_over = True # a new episode, later, SoC 60 % c._now = 5000.0 c.peak_guard = G(floor_limited=False, soc=60.0) check("T10 the new episode shows 'give all they can' from its first cycle", kind(why(c)) == "full") # T10b: no read between the drop and the new episode (the hold is cleared at # the drop, not at a read) c = S() run(c, 100.0, lambda t: G()) for k in range(0, 200): c._now = 100.0 + k c.w = None c.car_cycle(Proj(), G(), 14000.0, None) c.car_over = True c._now = 9000.0 c.peak_guard = G(floor_limited=False, soc=60.0) check("T10 no /status between the drop and the new episode: still 'full'", kind(why(c)) == "full") # T11: unplug c = S() run(c, 100.0, lambda t: G()) c._car_prev_state = "charging" c.state = CH.NONE_ c._now = 105.0 c.car_cycle(Proj(), G(), 14000.0, None) c.car_over = False check("T11 after the unplug cycle there is no over wording", OVER not in homeview._car_manual_why(c, "none") and FULL not in homeview._car_manual_why(c, "none") and "set when a car is connected" in homeview._car_manual_why(c, "none")) c.state = "charging" c.car_over = True c.peak_guard = G(floor_limited=False, soc=60.0) c._now = 400.0 check("T11 a replug starts with no held text", kind(why(c)) == "full") # the hold is also gone when the unplug itself ends car_over (no read between) c = S() run(c, 100.0, lambda t: G()) c._car_prev_state = "charging" c.state = CH.NONE_ c._now = 105.0 c.car_cycle(Proj(), G(), 14000.0, None) check("T11 (cont.) the unplug clears the hold itself", c.car_over is False and getattr(c, "_car_why_hold", "x") is None) # T12: cover off while car_over holds c = S() run(c, 100.0, lambda t: G()) c.o["ev_batt_cover"] = False c._now = 105.0 check("T12 cover off: 'ignores the car' at the next read", "ignores the car" in why(c)) c.o["ev_batt_cover"] = True c.peak_guard = G(floor_limited=False, soc=60.0) c._now = 110.0 check("T12 cover on again, steady not limited: 'give all they can', not " "the old 'are at'", kind(why(c)) == "full") # T13: restart c = S() a = run(c, 450.0, toggle(10.0, True)) c2 = S() b = run(c2, 450.0, toggle(10.0, True), t0=450.0) check("T13 restart mid-quarter: no Traceback, a text, at most one change " "after", kind(why(c2)) in ("full", "over") and len(changes(b)) <= 1) print("\n4. control unchanged; the rows follow the live flag") ctl1, rows1, flags1, sts = real_run(True) ctl0, rows0, flags0, _t = real_run(False) check("T14 reading the Why every cycle changes no command, alarm or row", ctl1 == ctl0 and rows1 == rows0 and flags1 == flags0) shown = [t for t in sts if OVER in t or FULL in t] flips = sum(1 for a, b in zip(flags1, flags1[1:]) if a != b) BASE_8150608 = ("e6034b0c78f23776", "5ffb80fa428cd6ee", "689a5b0e4bf7c897") check("T14/T15 commands, alarms, charger writes and the peak_guard/car_over " "rows equal those of base 8150608 (digests taken there with --digest)", (digest(ctl1), digest(rows1), digest(flags1)) == BASE_8150608) check("PRECONDITION: the real guard's floor flag toggles many times and " "car_over is on for most of the run", flips > 20 and len(shown) > 200) check("T1/T2 through the real guard: at most one Why change in the quarter", sum(1 for a, b in zip(shown, shown[1:]) if a != b) <= 1) check("T15 the peak_guard row follows the live flag (it changes as often as " "the flag), the hold is only in the Why", sum(1 for a, b in zip(rows1, rows1[1:]) if a != b) >= 1 and len({r for r in rows1 if r}) >= 1) print(" DIGEST control", digest(ctl1), "rows", digest(rows1), "flags", digest(flags1)) print("\n5. text, hold and wiring") check("the hold equals the car_over row's own off hold", homeview.WHY_HOLD_S == ctl_car.OVER_OFF_HOLD_S) src = open(os.path.join(HERE, "app", "homeview.py")).read() check("the live flag is read only by the hold helper, not by the Why branch", 'pg.floor_limited else' not in src) import json for lang, over, full in ( ("en", "You set {a} A. The batteries are at {pct}, so this charge " "sets the peak.", "You set {a} A. The batteries give all they can, so this charge " "sets the peak."), ("nl", "U stelde {a} A in. De batterijen staan op {pct}, dus deze " "lading bepaalt de piek.", "U stelde {a} A in. De batterijen geven alles, dus deze lading " "bepaalt de piek.")): d = json.load(open(os.path.join(HERE, "app", "ui_text", lang + ".json"))) d = d["home_words"]["car"]["why"] check(f"T17 {lang}.json wording of manual_over / manual_full unchanged", d["manual_over"] == over and d["manual_full"] == full) check("a held peak_guard row is not touched: the module still has no hold " "in ctl_status", "_car_why_hold" not in open(os.path.join( HERE, "app", "ctl_status.py")).read()) print() print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") sys.exit(1 if fails else 0)