"""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 by `ctl_car._car_why_tick` on the control cycle's clock (control writes `_car_why_rec`, never reads it; /status reads do not move it). `c._car_over_ep` is bumped when car_over ends; a record of another episode is never used. 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 tick(c, g, t): """One control cycle's display tick (what car_cycle ends with).""" c._now = t c.peak_guard = g c._car_why_tick(g, 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: tick(c, g_of(t - t0), t) 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): tick(c, None if 400 <= t < 410 else G(floor_limited=(t // 10) % 2 == 0), float(t)) 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() tick(c, None, 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 % tick(c, G(floor_limited=False, soc=60.0), 5000.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.peak_guard = G(floor_limited=False, soc=60.0) c._now = 9000.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 tick(c, G(floor_limited=False, soc=60.0), 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 ep_before = c._car_over_ep c.car_cycle(Proj(), G(), 14000.0, None) check("T11 (cont.) the unplug ends the episode (control bumps it)", c.car_over is False and c._car_over_ep > ep_before) # T12: cover off while car_over holds c = S() run(c, 100.0, lambda t: G()) c.o["ev_batt_cover"] = False tick(c, G(), 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 tick(c, G(floor_limited=False, soc=60.0), 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_rec" not in open(os.path.join( HERE, "app", "ctl_status.py")).read()) print("\n6. EV-16 review round 1: the race, T16, T18, the N-ids") # the race: a read takes the hold, control ends the episode, the read writes # its old hold back; the next episode must not show it c = S() run(c, 100.0, lambda t: G()) stale = c._car_why_rec check("race: the read holds 'are at' before the end", 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) c._car_why_rec = stale # the late write-back c.car_over = True c._now = 6000.0 c.peak_guard = G(floor_limited=False, soc=60.0) check("N4 race: a read interleaved with the clear cannot bring the old " "'are at' into the next episode", kind(why(c)) == "full") c = S() run(c, 100.0, lambda t: G()) stale = c._car_why_rec c._car_prev_state = "charging" c.state = CH.NONE_ c._now = 105.0 c.car_cycle(Proj(), G(), 14000.0, None) c._car_why_rec = stale # write-back after an unplug c.state = "charging" c.car_over = True c.peak_guard = G(floor_limited=False, soc=60.0) c._now = 110.0 check("N4 race (unplug): a stale write-back after the unplug is not used", kind(why(c)) == "full") # T16: the existing checks this one must leave alone are present and run in CI for f in ("test_ev04.py", "test_ev10.py", "test_ev10b.py", "test_ev18.py", "test_ev19.py", "test_home.py", "test_named_absence.py", "test_bytecode.py"): check(f"T16 {f} exists (run unchanged by CI's run-tests.sh)", os.path.exists(os.path.join(HERE, f))) t04 = open(os.path.join(HERE, "test_ev04.py")).read() check("T16 test_ev04's Manual Why assertion 'batteries give all they can' " "is still there", 'batteries give all they can" in cardwhy' in t04) # T18: the mutant, in process: the live flag picks the text again real = homeview._over_why_is_floor homeview._over_why_is_floor = lambda c, pg: bool( pg is not None and pg.floor_limited) try: m = run(S(), Q, toggle(10.0, True)) m8 = run(S(), Q, lambda t: G(soc=None)) finally: homeview._over_why_is_floor = real check("T18 mutant (live flag): T1 shape alternates and T8 shows 'are at', so " "T1, T2, T7 and T8 would go red", len(changes(m)) > 20 and any(k == "over" for _, k in m8)) # the N-ids, by name a = run(S(), Q, toggle(10.0, True)) check("N1 control: batteries, charger writes and setpoint equal base " "(digests, section 4)", (digest(ctl1), digest(rows1), digest(flags1)) == BASE_8150608) check("N2 `floor_limited`, `car_explains`, `car_over`, the peak_guard row " "are not changed by the hold: the guard flag toggles as in base " "(flags digest) and the rows digest equals base", digest(flags1) == BASE_8150608[2] and digest(rows1) == BASE_8150608[1]) n3 = run(S(), Q, lambda t: G(soc=None)) + run( S(), Q, lambda t: G(floor_limited=False, soc=40.0)) check("N3 never 'are at' with SoC unread or with the guard never limited", {k for _, k in n3} == {"full"}) c = S() run(c, 100.0, lambda t: G()) c.car_over = False n4 = homeview._car_manual_why(c, "charging") check("N4 no over wording once car_over is off", OVER not in n4 and FULL not in n4) check("N5 at most one Why change in a quarter while the guard toggles", len(changes(a)) <= 1) try: for g in (None, G(soc=None), G(), G(floor_limited=False, soc=1.0)): c = S() c.peak_guard = g why(c) n6 = True except Exception: # noqa: BLE001 n6 = False check("N6 no Traceback for a guard of None, SoC unread, limited, not " "limited", n6) en = open(os.path.join(HERE, "app", "ui_text", "en.json")).read() nl = open(os.path.join(HERE, "app", "ui_text", "nl.json")).read() check("N7 wording unchanged: the four texts are in the files verbatim", "The batteries are at {pct}, so this charge sets the peak." in en and "The batteries give all they can, so this charge sets the peak." in en and "De batterijen staan op {pct}, dus deze lading bepaalt de " "piek." in nl and "De batterijen geven alles, dus deze lading bepaalt " "de piek." in nl) print("\n7. EV-16 review round 2: the hold runs on the control clock") def gap_run(c, g_of, read_at, end=2300.0): """Control cycles every 5 s; the Why is read only at the `read_at` times.""" out = [] t = 0.0 while t < end: tick(c, g_of(t), t) if any(a <= t < b for a, b in read_at): out.append((t, kind(why(c)))) t += STEP return out pages = ((0, 60), (2000, 2300)) c = S() r = gap_run(c, lambda t: G(floor_limited=t >= 300.0, soc=20.0), pages) late = [(t, k) for t, k in r if t >= 2000] check("review A: drained to the reserve while the page was closed: the " "first read at t=2000 already shows 'are at'", len(late) > 0 and late[0][1] == "over" and {k for _, k in late} == {"over"}) c = S() r = gap_run(c, lambda t: G(floor_limited=t < 300.0, soc=20.0 if t < 300.0 else 45.0), pages) late = [(t, k) for t, k in r if t >= 2000] check("review B: off the reserve while the page was closed: the first " "read at t=2000 shows 'give all they can', never a false 'are at'", len(late) > 0 and late[0][1] == "full" and {k for _, k in late} == {"full"}) c = S() r = [] for t in range(0, 400, 5): cov = not (100 <= t < 200) c.o["ev_batt_cover"] = cov tick(c, G(floor_limited=t < 100, soc=20.0 if t < 100 else 45.0), float(t)) if t in (95, 205): r.append(kind(why(c))) check("review: cover off and on with no read between: back on, the state " "now not limited shows 'give all they can' at the first read", r == ["over", "full"]) # lower bound of the hold: a real change is NOT shown before the hold ends c = S() r = [] for t in range(0, 600, 5): tick(c, G(floor_limited=t >= 300.0, soc=20.0), float(t)) r.append((t, kind(why(c)))) check("review: a real change is held for the full 180 s: still the old " "text 170 s after it, the new one by 185 s", dict(r)[470] == "full" and dict(r)[485] == "over") # M7: guard None for 180 s or more under car_over for steady, want in ((True, "over"), (False, "full")): c = S() seq = [] for t in range(0, 1200, 5): g = G(floor_limited=steady, soc=20.0 if steady else 45.0) \ if t < 100 else None tick(c, g, float(t)) seq.append(kind(why(c))) check(f"T9 (long) guard None for 1100 s after a steady " f"{'limited' if steady else 'not limited'} state: the text stays " f"'{want}', no flip", set(seq) == {want}) c = S() seq = [] for t in range(0, 1200, 5): tick(c, None, float(t)) seq.append(kind(why(c))) check("T9 (long) guard None from the start for 1200 s: one text, 'full'", set(seq) == {"full"}) # review round 2: the live fallback (no record yet, or one of an ended # episode) keeps the unread-SoC rule too for label, rec in (("no record yet", None), ("a record of an ended episode", [True, None, -1])): c = S() c._now = 0.0 c._car_why_rec = rec c.peak_guard = G(soc=None) check(f"N3 {label}: limited with SoC unread is not 'are at'", kind(why(c)) == "full") c.peak_guard = G() check(f"N3 {label}: limited with SoC read shows 'are at' (live state)", kind(why(c)) == "over") print() print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") sys.exit(1 if fails else 0)