Files
goodwe-addon/goodwe_controller/test_ev59.py
T
Claude 7628cacdb7
checks / unit (pull_request) Successful in 50m12s
infra-pin / fresh (pull_request) Successful in 1s
EV-59 review: CHANGELOG line; T21 power-unknown check exact
Reviewer fixes, Minor only, no implementation change:
- CHANGELOG.md: the user-visible change under "Not in a release yet".
- test_ev59 T21 (power unknown): assert the 3 restore tries at 20, 25, 30,
  the give-up and one REF, instead of "at most 3" (which passed with 0).
  Red on 1b909fb (20, 25, 30, 90, 150).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 09:19:38 +01:00

821 lines
33 KiB
Python

"""EV-59: Manual gives one value at most MAX_TRIES tries per user change, the
phase-change closes included. `python3 -B test_ev59.py`
Rows T1-T25 and N1-N14 of reports/EV-59-test-plan.md. Here: T1-T13, T14c, T15
(the answering charger, writer level), T16, T17, T18 (source checks on the
edited test files), T20-T25, T11c and N1-N14 (N8, N10, N11 as source checks).
Carried by other suites, green and unedited: T14a, T14b, T14d (test_ev56 T8,
T11, T12, T13, T19b and their T20 digests), T15's T20 digests (test_ev56
[A]), T12b/T12c's EV-28 side (test_ev28 T11-T13), T19 (the listed suites).
EDITED, not unedited: test_ev56 T5, T5b and the golden "T20 T5 [R]" (Q1, Q2),
test_ev28 T15 (Q3, T11c), test_ev13 T13 text and T26 goldens (rulings).
The `ManualWriter` / `SolarWriter` on a stub driver, a stub tracker
and a stub reading; time is the 1 s step counter, never wall time. The close
of the plan's T5 world: 0 A at t=0 and the select at t=1, both taken, so the
settle ends at s=11 and the closes are at 11, 16, 21.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import logging
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode as CM # noqa: E402
fails = []
CLOCK = {"t": 0}
LOG = []
BIG = 1e12
REF = "CHARGER_REFUSED"
REC = "The car charger step failed"
class Cap(logging.Handler):
def emit(self, rec):
LOG.append((CLOCK["t"], rec.levelname, rec.getMessage()))
logging.getLogger("goodwe").addHandler(Cap())
logging.getLogger("goodwe").setLevel(logging.DEBUG)
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
class Rd:
def __init__(self, a, ph=1, power=None, state="C"):
self.available = True
self.allowed_a = self.setpoint_a = a
self.phases_allowed = ph
self.power_w = power
self.state = state
self.error = False
self.charging = True
self.current_a = ()
self.station_a = None
class Trk:
obs_at = None
def __init__(self):
self.notes = []
def begin_write(self):
pass
def end_write(self, *_):
pass
def note_write(self, now, was, a, ok, polls=()):
self.notes.append((now, a, ok))
def stuck(self, now):
return False
class Drv:
"""answer(a, n) -> True | False | "raise"; True sets the charger. `sel`:
the answer to write_phases. `phases_log`: (t, n, the power seen then)."""
def __init__(self, cur, answer, ph=1, sel=True):
self.cur, self.ph, self.answer, self.sel = cur, ph, answer, sel
self.calls, self.now, self.polls = [], 0.0, ()
self.phases_log, self.power = [], None
async def write_current(self, a, **kw):
self.calls.append((self.now, float(a)))
r = self.answer(float(a), len(self.calls))
if r == "raise":
raise RuntimeError("HA call error")
if r:
self.cur = float(a)
return bool(r)
async def write_phases(self, n):
self.phases_log.append((self.now, n, self.power))
if self.sel:
self.ph = n
return self.sel
def refuse(a, n):
return a == 0.0
def raises(a, n):
return True if a == 0.0 else "raise"
def snap(w):
q = w.seq
return dict(fails=w.fails, gave_up=w.gave_up, fail_at=w.fail_at,
seq=None if q is None else (q["stage"], q["tries"]),
last_a=w.last_a, reapply=w.reapply, rev_applied=w.rev_applied,
phase_done_at=w.phase_done_at, phase_fails=w.phase_fails)
class Run:
pass
def run(answer, secs, *, cls=CM.ManualWriter, cb=None, a=6.0, n=3, cur=10.0,
sel=True, power=None, avail=None, clamp=16.0, mode=CM.MANUAL,
rd_none=False, w=None):
"""One writer run, one step per second. `cb(t, st, w, drv)` may change the
request in `st` (a, n, rev, clamp, mode) or call `w.user_changed()` (use
`uc`); it may be a coroutine. Per step: the state before and after."""
LOG.clear()
w, trk = w or cls(), Trk()
drv = Drv(cur, answer, sel=sel)
st = dict(a=a, n=n, rev=1, clamp=clamp, mode=mode)
out = Run()
out.w, out.drv, out.trk, out.st = w, drv, trk, st
out.rows, out.errs, out.ucs = {}, [], []
async def main():
for t in range(secs):
drv.now = float(t)
CLOCK["t"] = t
if cb:
x = cb(t, st, w, drv)
if asyncio.iscoroutine(x):
await x
pw = power(t, drv) if power else (
0.0 if drv.cur == 0 else 1380.0)
drv.power = pw
r = Rd(None if rd_none else drv.cur, drv.ph, power=pw)
if avail is not None and not avail(t):
r.available = False
seq0 = w.seq is not None
try:
await w.step(drv, r, mode=st["mode"], want_a=st["a"],
want_phases=st["n"], rev=st["rev"],
clamp=st["clamp"], now=float(t), tracker=trk,
writing=True, status="charging")
except Exception as e: # noqa: BLE001
out.errs.append((t, e))
d = snap(w)
d["seq0"], d["ncalls"] = seq0, len(drv.calls)
out.rows[t] = d
asyncio.run(main())
out.log = list(LOG)
return out
def uc(st, w, t, out_ucs=None, **kw):
w.user_changed()
st["rev"] += 1
st.update(kw)
UCS.append(t)
UCS = []
def at(t0, **kw):
"""A callback: one user change at t0 with these request changes."""
def cb(t, st, w, drv):
if t == t0:
uc(st, w, t, **kw)
return cb
def nz(r, lo=-BIG, hi=BIG, a=None):
return [int(t) for t, x in r.drv.calls
if x > 0 and lo <= t < hi and (a is None or abs(x - a) < 0.01)]
def zeros(r):
return [int(t) for t, x in r.drv.calls if x == 0.0]
def refs(r):
return [t for t, lv, m in r.log if lv == "WARNING" and REF in m]
def recs(r):
return [t for t, lv, m in r.log if lv == "ERROR" and m == REC]
def near(got_, want, tol=1):
return len(got_) == len(want) and all(abs(g - w_) <= tol
for g, w_ in zip(got_, want))
def never(name, r, *, ucs=(), clamp=16.0):
"""N1 (no non-zero write while given up before a user change), N2 (one
REF per give-up), N5 (no select under load), N6 (nothing above the clamp
or in 0-6 A), N9 (no exception out of a step), N13 (closes at least 5 s
apart, normal tries RETRY_S apart)."""
bad1, bad3, up = [], [], 0
t_prev, gv = None, False
for t in sorted(r.rows):
row = r.rows[t]
before = r.rows.get(t - 1)
n_new = row["ncalls"] - (before["ncalls"] if before else 0)
if gv and n_new and not any(u <= t and u > (t_prev or -1) for u in ucs) \
and any(x > 0 for tt, x in r.drv.calls if tt == t):
bad1.append(t)
if row["gave_up"] and not (before or {}).get("gave_up"):
up += 1
# N3: not before MAX_TRIES tries of the value owed since the
# last user change (the last call's value, from that change on).
u0 = max([u for u in ucs if u <= t], default=-1)
last = [(tt, x) for tt, x in r.drv.calls if tt <= t and x > 0]
if last:
v = last[-1][1]
n_v = len([1 for tt, x in last if tt >= u0])
if n_v < CM.MAX_TRIES:
bad3.append((t, v, n_v))
if not row["gave_up"] and (before or {}).get("gave_up"):
gv = False
if any(u == t for u in ucs):
gv = False
elif row["gave_up"]:
gv = True
t_prev = t
nzc = [(t, x) for t, x in r.drv.calls if x > 0]
bad13 = []
for (ta, aa), (tb, ab) in zip(nzc, nzc[1:]):
inseq = r.rows[int(tb)]["seq0"]
lim = 5.0 if inseq else CM.RETRY_S
user = any(ta < u <= tb for u in ucs)
if tb - ta < lim - 1e-9 and not (user and not inseq) \
and abs(aa - ab) < 0.01:
bad13.append((ta, tb))
bad5 = [x for x in r.drv.phases_log if x[2] is not None
and x[2] >= CM.QUIET_W]
bad6 = [x for _t, x in nzc if x > clamp + 1e-9 or x < 6.0 - 1e-9]
check(f"{name}: N3 no give-up before MAX_TRIES tries of the value owed "
f"({bad3[:3]})", not bad3)
check(f"{name}: N1 no write while given up ({bad1[:3]}); N2 one REF per "
f"give-up ({len(refs(r))} for {up}); N5 no select under load "
f"({bad5[:2]}); N6 nothing above the clamp or under 6 A "
f"({bad6[:3]}); N9 no exception ({r.errs[:1]}); N13 spacing "
f"({bad13[:3]})",
not bad1 and len(refs(r)) == up and not bad5 and not bad6
and not r.errs and not bad13)
print("1. THE REPLAY, THE STATE AT THE CAP (T1, T2, T3, T23)")
UCS.clear()
R1 = run(refuse, 600)
check(f"T1: 6 A tried at {nz(R1)}: 11, 16, 21 and nothing after to 600 s; "
"the car stays at 0 A",
nz(R1) == [11, 16, 21] and R1.drv.cur == 0.0
and all(x == 6.0 for _t, x in R1.drv.calls if x > 0))
r21, r20 = R1.rows[21], R1.rows[20]
check(f"T2: at the 3rd refused close: seq None, last_a None, reapply, "
f"rev_applied None, fails MAX_TRIES, gave_up, fail_at 21, "
f"phase_done_at None ({r21}); one REF in that step ({refs(R1)})",
r21["seq"] is None and r21["last_a"] is None and r21["reapply"] is True
and r21["rev_applied"] is None and r21["fails"] == CM.MAX_TRIES
and r21["gave_up"] is True and r21["fail_at"] == 21
and r21["phase_done_at"] is None and r21["phase_fails"] == 0
and refs(R1) == [21] and r20["gave_up"] is False and r20["fails"] == 0)
check("T23: offByOne: the 2nd close (16) does not end the sequence and the "
"3rd (21) does; the states up to 16 are the base's",
R1.rows[11]["seq"] == ("settle", 1) and R1.rows[16]["seq"] ==
("settle", 2) and R1.rows[16]["fails"] == 0
and not R1.rows[16]["gave_up"] and R1.rows[21]["seq"] is None
and not any(refs(R1)[i] < 21 for i in range(len(refs(R1)))))
never("T1", R1)
RX = run(raises, 600)
strip = lambda d: {k: v for k, v in d.items() if k not in ("ncalls",)} # noqa
check("T3a: every close raises: calls, states and cycle by cycle as R; 1 "
f"ERROR record at 11 ({recs(RX)}), REF at 21 ({refs(RX)}); the "
"tracker is not told of a raise",
RX.drv.calls == R1.drv.calls
and all(strip(RX.rows[t]) == strip(R1.rows[t]) for t in range(600))
and recs(RX) == [11] and refs(RX) == [21]
and not [x for x in RX.trk.notes if x[1] > 0]
and len([x for x in R1.trk.notes if x[1] > 0]) == 3)
never("T3a", RX)
RM = run(lambda a, n: True if a == 0.0 else ("raise" if n in (2, 4)
else False), 600)
check("T3b: raise, refuse, raise: 3 tries, 1 ERROR, 1 REF at 21, fails "
f"{RM.rows[21]['fails']}",
nz(RM) == [11, 16, 21] and recs(RM) == [11] and refs(RM) == [21]
and RM.rows[21]["fails"] == CM.MAX_TRIES and RM.rows[21]["gave_up"]
and [x[1] for x in RM.trk.notes if x[1] > 0] == [6.0])
never("T3b", RM)
print("\n2. TAKEN CLOSES AND FOLLOW-UPS (T4, T5, T6, T7, T8)")
UCS.clear()
R4 = run(lambda a, n: a == 0.0 or n == 2, 400, cb=at(100, a=8.0))
r4 = R4.rows[11]
check(f"T4: the close taken on try 1: seq None, fails 0, no give-up, no REF, "
f"phase_done_at 11 ({r4['phase_done_at']}); 8 A at 100 gets 3 tries "
f"({nz(R4, 100, a=8.0)}) and one REF ({refs(R4)})",
r4["seq"] is None and r4["fails"] == 0 and not r4["gave_up"]
and r4["phase_done_at"] == 11 and near(nz(R4, 100, a=8.0),
[100, 160, 220])
and refs(R4) == [220])
never("T4", R4, ucs=[100])
for tag, tk in (("a", 3), ("b", 4)):
UCS.clear()
R5 = run(lambda a, n, tk=tk: a == 0.0 or n == tk, 400, cb=at(100, a=8.0))
r5 = R5.rows[40]
check(f"T5{tag}: close taken on try {tk - 1}: fails 0, no give-up, no "
f"REF, phase_done_at None ({r5['phase_done_at']}); 8 A at 100 gets "
f"3 full tries ({nz(R5, 100, a=8.0)})",
r5["fails"] == 0 and not r5["gave_up"] and r5["seq"] is None
and r5["phase_done_at"] is None
and near(nz(R5, 100, a=8.0), [100, 160, 220])
and refs(R5) == [220] and R5.rows[21]["fails"] == 0)
never(f"T5{tag}", R5, ucs=[100])
for tag, kw, want in (("a", dict(a=8.0), 8.0), ("b", dict(a=6.0), 6.0)):
UCS.clear()
R6 = run(refuse, 400, cb=at(100, **kw))
got6 = nz(R6, 100, a=want)
check(f"T6{tag}: after the give-up a user change to {want:.0f} A: a "
f"write at 100 and tries at +60, +120, then REF once more, never "
f"a 4th ({got6}, REF {refs(R6)})",
near(got6, [100, 160, 220]) and refs(R6) == [21, 220]
and R6.rows[100]["gave_up"] is False)
never(f"T6{tag}", R6, ucs=[100])
UCS.clear()
R6c = run(refuse, 760, cb=at(700, n=1))
check(f"T6c: after the give-up a 1 phase request (past PHASE_GAP_S): gave_up "
f"does not block it; the 0 A at 700 ({zeros(R6c)}), the select at the "
f"quiet car, then closes ({nz(R6c, 700)})",
near([z for z in zeros(R6c) if z >= 700], [700])
and R6c.rows[700]["gave_up"] is False
and [x[1] for x in R6c.drv.phases_log if x[0] >= 700] == [1]
and near(nz(R6c, 700), [711, 716, 721]) and refs(R6c) == [21, 721])
UCS.clear()
def off_then_manual(t, st, w, drv):
if t == 100:
st["mode"] = "off"
if t == 103:
st["mode"] = CM.MANUAL
uc(st, w, t)
R6d = run(refuse, 400, cb=off_then_manual)
check(f"T6d: Off, then Manual at 103: as T6b from the pick "
f"({nz(R6d, 100, a=6.0)})",
near(nz(R6d, 100, a=6.0), [103, 163, 223]) and refs(R6d) == [21, 223])
UCS.clear()
R7a = run(refuse, 600, avail=lambda t: not 130 <= t < 161)
check(f"T7a: the charger away 130-160, back at 161: no write after the "
f"return to 600 s ({nz(R7a, 100)}); gave_up stays",
nz(R7a, 100) == [] and R7a.rows[599]["gave_up"] and refs(R7a) == [21])
never("T7a", R7a)
R7b = run(refuse, 600, avail=lambda t: not 12 <= t < 31)
check(f"T7b: away between close 1 and 2, back at 31: the count goes on: 3 "
f"tries of 6 A ({nz(R7b)}), then the give-up, REF once ({refs(R7b)})",
len(nz(R7b, a=6.0)) == 3 and R7b.rows[599]["gave_up"]
and len(refs(R7b)) == 1
and all(b - a >= 5 for a, b in zip(nz(R7b), nz(R7b)[1:])))
never("T7b", R7b)
UCS.clear()
R7c = run(raises, 600, avail=lambda t: not 130 <= t < 161,
cb=at(200, a=6.0))
check(f"T7c: X, away and back, then a user change at 200: no write before "
f"200 after the return; the record is armed again: ERROR at "
f"{recs(R7c)} (1 before 200, 1 after)",
not nz(R7c, 100, 200) and len([x for x in recs(R7c) if x < 200]) == 1
and len([x for x in recs(R7c) if x >= 200]) == 1)
UCS.clear()
R8 = run(lambda a, n: a == 0.0 or n == 4, 1200, cb=at(700, n=1))
b_calls = nz(R8, 700)
check(f"T8: sequence A (refused, refused, taken): fails "
f"{R8.rows[21]['fails']}, no give-up; then sequence B: 3 tries "
f"({b_calls}), no give-up after 1 or 2 "
f"({R8.rows[711]['gave_up']}, {R8.rows[716]['gave_up']}), then the "
f"give-up and 1 REF ({refs(R8)})",
R8.rows[21]["fails"] == 0 and not R8.rows[21]["gave_up"]
and near(b_calls, [711, 716, 721])
and not R8.rows[711]["gave_up"] and not R8.rows[716]["gave_up"]
and R8.rows[721]["gave_up"] and refs(R8) == [721])
never("T8", R8, ucs=[700])
print("\n3. A USER CHANGE DURING THE CLOSE RETRIES (T9, T24)")
for tag, t0, kw, want, exp_a, exp_6 in (
("a", 18, dict(a=8.0), 8.0, [21, 81, 141], [11, 16]),
("b", 13, dict(a=8.0), 8.0, [16, 21, 81], [11])):
for how, ans in (("R", refuse), ("X", raises)):
UCS.clear()
R9 = run(ans, 600, cb=at(t0, **kw))
g8 = nz(R9, a=8.0)
refs9 = refs(R9)
check(f"T9{tag} [{how}]: user change to 8 A at {t0}: 8 A gets "
f"exactly 3 tries ({g8}), the 6 A before it ({nz(R9, a=6.0)}); "
f"the REF once, at the 3rd try ({refs9}); fails after the "
f"close end {R9.rows[21]['fails']}",
near(g8, exp_a) and nz(R9, a=6.0) == exp_6
and refs9 == [exp_a[-1]]
and not any(R9.rows[t]["gave_up"] for t in range(exp_a[-1]))
and R9.rows[exp_a[-1]]["gave_up"])
never(f"T9{tag} [{how}]", R9, ucs=[t0])
UCS.clear()
R24 = run(refuse, 600, cb=at(18, a=8.0))
check("T24b: the user change after close 2: at the close end (21) fails 1, "
f"no give-up ({R24.rows[21]['fails']}, {R24.rows[21]['gave_up']}); the "
"normal path gives 2 more tries >= RETRY_S apart, then 1 REF",
R24.rows[21]["fails"] == 1 and not R24.rows[21]["gave_up"]
and R24.rows[81]["fails"] == 2 and R24.rows[141]["fails"] == 3
and R24.rows[141]["gave_up"] and refs(R24) == [141])
check("T24a: no user change: k = 3, fails 3, gave_up, 1 REF at the close end "
f"({R1.rows[21]['fails']}, {refs(R1)})",
R1.rows[21]["fails"] == CM.MAX_TRIES and refs(R1) == [21])
UCS.clear()
R9c = run(refuse, 600, cb=at(18, a=6.0))
after = [t for t in nz(R9c, a=6.0) if t >= 18]
check(f"T9c: the same value again at 18: 3 tries after the change ({after}), "
f"REF once at the last ({refs(R9c)})",
near(after, [21, 81, 141]) and refs(R9c) == [141]
and nz(R9c, a=6.0)[:2] == [11, 16])
never("T9c", R9c, ucs=[18])
UCS.clear()
R9d = run(refuse, 600, cb=at(2, a=8.0))
check(f"T9 (change before the 1st close): 8 A gets 3 tries "
f"({nz(R9d, a=8.0)}), REF {refs(R9d)}",
len(nz(R9d, a=8.0)) == 3 and len(refs(R9d)) == 1)
print("\n4. THE CLAMP, THE RESTORE CLOSES, THE SELECT (T10, T11, T12)")
UCS.clear()
def clamp_falls(t, st, w, drv):
if t == 18:
st["clamp"] = 8.0
R10 = run(refuse, 400, a=10.0, clamp=10.0, cb=clamp_falls)
check(f"T10: the clamp falls to 8 A at 18: tries {nz(R10)} with values "
f"{[x for _t, x in R10.drv.calls if x > 0]}: never above the clamp then, "
f"at most 3 in all, REF once ({refs(R10)})",
len(nz(R10)) == 3 and [x for _t, x in R10.drv.calls if x > 0]
== [10.0, 10.0, 8.0] and refs(R10) == [21])
never("T10", R10, clamp=10.0)
UCS.clear()
R11a = run(refuse, 400, cur=16.0, a=16.0, power=lambda t, d: 1380.0,
cb=at(300))
check(f"T11a: the drawing timeout, the 16 A restore refused: 3 tries 5 s "
f"apart ({nz(R11a, 0, 300)}), fails {R11a.rows[30]['fails']}, "
f"gave_up, REF once ({refs(R11a)}); phase_fails "
f"{R11a.rows[30]['phase_fails']}; no select ({R11a.drv.phases_log}); "
f"a user change writes 16 A at once ({nz(R11a, 300)[:1]})",
near(nz(R11a, 0, 300), [20, 25, 30])
and R11a.rows[30]["fails"] == CM.MAX_TRIES and R11a.rows[30]["gave_up"]
and refs(R11a) == [30] and R11a.rows[30]["phase_fails"] == 1
and R11a.rows[20]["fails"] == 0 and R11a.rows[25]["fails"] == 0
and not R11a.drv.phases_log and nz(R11a, 300)[:1] == [300])
never("T11a", R11a, ucs=[300])
UCS.clear()
R11b = run(refuse, 400, cur=16.0, a=16.0, sel=False, cb=at(300))
check(f"T11b: the select refused, the restore close refused: 3 tries "
f"({nz(R11b, 0, 300)}), fails {R11b.rows[21]['fails']}, gave_up, "
f"REF once ({refs(R11b)}); phase_fails {R11b.rows[21]['phase_fails']}; "
f"1 select try ({len(R11b.drv.phases_log)}); a user change writes at "
"once",
near(nz(R11b, 0, 300), [11, 16, 21])
and R11b.rows[21]["fails"] == CM.MAX_TRIES and R11b.rows[21]["gave_up"]
and refs(R11b) == [21] and R11b.rows[21]["phase_fails"] == 1
and len(R11b.drv.phases_log) == 1 and nz(R11b, 300)[:1] == [300])
never("T11b", R11b, ucs=[300])
UCS.clear()
R12a = run(lambda a, n: a != 0.0, 400)
check(f"T12a: only the 0 A fails (_begin): tries {zeros(R12a)} >= 60 s "
f"apart, at most 3, no select, REF once ({refs(R12a)})",
0 < len(zeros(R12a)) <= 3 and not R12a.drv.phases_log
and all(b - a >= 60 for a, b in zip(zeros(R12a), zeros(R12a)[1:]))
and len(refs(R12a)) == 1 and R12a.rows[399]["gave_up"])
R12b = run(lambda a, n: True, 100, sel=False)
check(f"T12b: a refused select counts for the phases only: close taken, fails "
f"{R12b.rows[60]['fails']}, phase_fails {R12b.rows[60]['phase_fails']}, "
"no REF",
R12b.rows[60]["fails"] == 0 and R12b.rows[60]["phase_fails"] == 1
and R12b.rows[1]["fails"] == 0 and R12b.rows[1]["phase_fails"] == 1
and not refs(R12b) and not R12b.rows[60]["gave_up"])
R12c = run(lambda a, n: True, 100, cur=16.0, a=16.0,
power=lambda t, d: 1380.0)
check(f"T12c: the drawing timeout, the restore taken: fails "
f"{R12c.rows[60]['fails']}, no give-up, phase_fails "
f"{R12c.rows[60]['phase_fails']}",
R12c.rows[60]["fails"] == 0 and not R12c.rows[60]["gave_up"]
and R12c.rows[60]["phase_fails"] == 1 and not refs(R12c))
print("\n5. UNDO, SHUTDOWN, SOLAR, A CHARGER THAT ANSWERS (T13, T14, T15)")
UCS.clear()
def off_at(t0):
def cb(t, st, w, drv):
if t == t0:
st["mode"] = "off"
return cb
R13a = run(refuse, 100, power=lambda t, d: 1380.0, cb=off_at(5))
check(f"T13a: Off in stage zero: 10 A restored once ({nz(R13a)}), undone "
f"{R13a.w.undone}, fails {R13a.rows[99]['fails']}",
near(nz(R13a, a=10.0), [5]) and len(nz(R13a)) == 1
and R13a.w.undone == 1 and R13a.rows[99]["fails"] == 0)
R13b = run(refuse, 100, cb=off_at(12))
check(f"T13b: Off after close 1: the closes go on ({nz(R13b)}), give-up at "
f"21, REF once ({refs(R13b)}), no write after",
nz(R13b) == [11, 16, 21] and R13b.rows[21]["gave_up"]
and refs(R13b) == [21])
box = {}
def abandon_cb(t0, ans_kind):
def cb(t, st, w, drv):
if t == t0 + 1:
async def go():
n0 = len(drv.calls)
try:
await w.abandon(drv, float(t), Trk(), clamp=16.0)
box[ans_kind] = ("ok", len(drv.calls) - n0)
except RuntimeError:
box[ans_kind] = ("raised", len(drv.calls) - n0)
return go()
return cb
R13c = run(refuse, 40, cb=abandon_cb(11, "R"))
check(f"T13c: shutdown between close 1 and 2: the old 10 A restored once, "
f"strict, no exception ({box.get('R')}), seq None, calls {nz(R13c)}",
box.get("R") == ("ok", 1) and R13c.w.seq is None
and near(nz(R13c, a=10.0), [12]))
R13x = run(raises, 40, cb=abandon_cb(11, "X"))
check(f"T13c: X: the raise comes out of abandon, as base, for the caller's "
f"CHARGER_RESTORE ({box.get('X')}); the writer's seq is None",
box.get("X") == ("raised", 1) and R13x.w.seq is None)
R13d = run(refuse, 40, cb=abandon_cb(40, "D"))
n_d = len(R13d.drv.calls)
async def after_giveup():
n0 = len(R13d.drv.calls)
await R13d.w.abandon(R13d.drv, 41.0, Trk(), clamp=16.0)
return len(R13d.drv.calls) - n0
check("T13d: shutdown after the give-up: no write",
asyncio.run(after_giveup()) == 0 and R13d.w.gave_up)
def solar_writer(cur):
w = CM.SolarWriter()
w.engaged, w.mode_was = True, CM.SOLAR
w.fresh_start = w.restart = False
w.was_available = w._seen = True
w.sent_a, w.taken, w.last_a = cur, True, cur
w.plan.a, w.plan.n = cur, 1
w._plan_step = lambda *a, **k: None
return w
def sp3(press, cls=solar_writer):
LOG.clear()
drv = Drv(8.0, refuse)
w, trk = cls(8.0), Trk()
w.plan._set(8.0, 0.0, 3)
pressed = None
async def main():
nonlocal pressed
for t in range(1, 200):
if press and pressed is None and \
len([x for x in drv.calls if x[1] > 0]) == 1:
w.user_changed()
pressed = t
drv.now = float(t)
CLOCK["t"] = t
w.cut_quarter(int(t // 900))
r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
await w.step(drv, r, mode=CM.SOLAR,
sun=CM.SunInputs(target_w=2000.0), clamp=16.0,
now=float(t), tracker=trk, writing=True,
status="charging")
asyncio.run(main())
nzs = [int(t) for t, x in drv.calls if x > 0]
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
return nzs, w.fails, w.gave_up, rf, pressed
S_NONE = sp3(False)
S_PRESS = sp3(True)
check(f"T25/T14 (N14): Solar equals base. No press: 8 A at 12, 17, 22, fails "
f"4, gave_up, REF at 22 ({S_NONE})",
S_NONE == ([12, 17, 22], 4, True, [22], None))
check(f"T25 (resetSuper trap): a Solar press at 13 does not reset Solar's "
f"tries: 8 A at 12, 17, 22, fails 3, gave_up, REF at 22 ({S_PRESS})",
S_PRESS == ([12, 17, 22], 3, True, [22], 13))
def t14c():
"""T14c: Solar's close value changes between the tries (the spare falls
during the settle): `want_a(q)` is a function of the sequence. `_advance`
driven directly on a SolarWriter in stage settle, the close refused."""
LOG.clear()
w, drv, trk = solar_writer(8.0), Drv(0.0, lambda a, n: False), Trk()
w.seq = {"stage": "settle", "t0": 0.0, "n": 3, "tries": 0, "prev": 8.0,
"t1": 0.0}
vals = {10: 8.0, 15: 7.0, 20: 6.0}
async def main():
for t in range(10, 40):
if w.seq is None:
break
drv.now = float(t)
CLOCK["t"] = t
r = Rd(drv.cur, drv.ph, power=0.0)
await w._advance(drv, r, 0.0, float(t), trk,
lambda q: vals.get(t, 5.0), 16.0, 1)
asyncio.run(main())
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
return ([(int(t), x) for t, x in drv.calls], w.fails, w.gave_up, rf,
w.seq)
S14C = t14c()
check(f"T14c (N14): Solar's close value moves between tries: 8, 7, 6 A at "
f"10, 15, 20, then `fails` 4, gave_up, REF at 20, seq None, as base "
f"({S14C})",
S14C == ([(10, 8.0), (15, 7.0), (20, 6.0)], 4, True, [20], None))
print("\n6. THE CAP, RESTART, UNKNOWN, NO CHARGER (T15-T22)")
UCS.clear()
RA = run(lambda a, n: True, 100)
check(f"T15: a charger that answers: 0 A at 0, 6 A at 11, nothing else "
f"({RA.drv.calls}); fails 0, no give-up, phase_done_at "
f"{RA.rows[11]['phase_done_at']}",
RA.drv.calls == [(0.0, 0.0), (11.0, 6.0)]
and RA.rows[99]["fails"] == 0 and RA.rows[11]["phase_done_at"] == 11
and not refs(RA))
for cap in (2, 4):
UCS.clear()
saved = CM.MAX_TRIES
CM.MAX_TRIES = cap
try:
R16 = run(refuse, 400)
finally:
CM.MAX_TRIES = saved
want16 = [11 + 5 * i for i in range(cap)]
check(f"T16: MAX_TRIES {cap}: tries {nz(R16)} (never {cap + 1}), give-up "
f"at {want16[-1]}, REF {refs(R16)}",
nz(R16) == want16 and refs(R16) == [want16[-1]]
and R16.rows[want16[-1]]["fails"] == cap
and R16.rows[want16[-1]]["gave_up"])
UCS.clear()
w20 = CM.ManualWriter()
check("T20: a restart: the new writer starts with 0 fails, no give-up, and "
"no count",
w20.fails == 0 and not w20.gave_up
and getattr(w20, "_close_k", 0) == 0)
R20 = run(refuse, 30, w=w20)
check(f"T20: after the restart the first write goes out once ({zeros(R20)})",
zeros(R20) == [0])
R21 = run(refuse, 400, rd_none=True)
check(f"T21: the read-back unknown (allowed and setpoint None): judged by the "
f"write's result: tries {nz(R21)}, give-up, REF once ({refs(R21)})",
len(nz(R21)) == 3 and R21.rows[399]["gave_up"] and len(refs(R21)) == 1
and not R21.errs)
R21b = run(refuse, 400, power=lambda t, d: None, cur=16.0, a=16.0)
check(f"T21: the power unknown: the drawing timeout's restore is tried 3 "
f"times (20, 25, 30), then the give-up and one REF, no exception "
f"({nz(R21b)}, {refs(R21b)}, {R21b.errs[:1]})",
nz(R21b) == [20, 25, 30] and R21b.rows[30]["gave_up"]
and refs(R21b) == [30] and not R21b.errs)
R22 = run(refuse, 600, avail=lambda t: False)
check("T22: no charger: 0 writes, no lines, no REF",
not R22.drv.calls and not R22.log and not refs(R22))
print("\n6b. A GIVE-UP NEVER BLOCKS THE UNDO, THE SHUTDOWN OR A NEW SEQUENCE (N4)")
def given_up_writer():
w = CM.ManualWriter()
w.gave_up, w.fails = True, CM.MAX_TRIES
w.seq = {"stage": "zero", "t0": 0.0, "n": 3, "tries": 0, "prev": 10.0}
return w, Drv(0.0, lambda a, n: True), Trk()
w13, d13, t13 = given_up_writer()
asyncio.run(w13._undo(d13, 1.0, t13, 16.0, False))
check(f"T13e/N4: `_undo` with gave_up set restores the 10 A ({d13.calls})",
d13.calls == [(0.0, 10.0)] and w13.seq is None)
w13, d13, t13 = given_up_writer()
asyncio.run(w13.abandon(d13, 1.0, t13, clamp=16.0))
check(f"T13e/N4: `abandon` with gave_up set gives the 10 A back "
f"({d13.calls})", d13.calls == [(0.0, 10.0)] and w13.seq is None)
w13, d13, t13 = given_up_writer()
w13.seq = None
asyncio.run(w13._begin(d13, Rd(10.0), 10.0, 3, 1.0, t13))
check(f"T13e/N4: `_begin` with gave_up set still writes the 0 A "
f"({d13.calls})", d13.calls == [(0.0, 0.0)] and w13.seq is not None)
print("\n6c. THE EDITS TO EXISTING TESTS, N7, N12 (T17, T18, T11c, N7, N11, N12)")
def tsrc(name):
return open(os.path.join(HERE, name), encoding="utf-8").read()
s56, s13, s28 = tsrc("test_ev56.py"), tsrc("test_ev13.py"), tsrc("test_ev28.py")
BASE_DIGESTS = ("905c0b8ba89bb307", "343ea01aacfa1019", "ff6306ce56b35c64",
"f1fb141275839562", "369069be9187ab3c", "2cd78dee7ee93aaa",
"f0adb058a5bbefba", "6d7bcb747d1dc5a3", "2be1a760b699b28c",
"a5888e4557b4ee8f", "2fd24ddbb18f14cc", "1ad97e089468d71b",
"7baf8981ab382e05", "54701b140ec6f30b", "0cfd3ccd334f378d",
"1d85595302dc032a", "5fc65dbdc730e539")
check("T17 (Q1, Q2): test_ev56 has the re-taken golden 'T20 T5 [R]' "
"(78ffe9cf72c5e214, the old ba32810fbb40d0f9 gone), T5 asserts "
"fails == MAX_TRIES and gave_up, T5b asserts len == MAX_TRIES",
'"T20 T5 [R]": "78ffe9cf72c5e214"' in s56
and "ba32810fbb40d0f9" not in s56
and 'end5[1]["fails"] == CM.MAX_TRIES' in s56
and 'end5[1]["gave_up"] is True' in s56
and "len(six) == CM.MAX_TRIES" in s56)
check("N11: every other golden digest of test_ev56 is the base's, and "
"GOLDEN['T5b'] still holds base's 5 tries",
all(f'"{d}"' in s56 for d in BASE_DIGESTS)
and '"T5b": [(111.0, 6.0), (116.0, 6.0), (121.0, 6.0), (181.0, 6.0),'
in s56)
check("T18: test_ev13 T13's check text says 'one refusal counted' and its "
"assert is still fails == 1",
"no window left, one refusal counted, the mute set" in s13
and "no refusal counted" not in s13
and "w.c.car_writer.fails == 1 and w.c.car.mute_until > 0" in s13)
check("N11: test_ev13 T26 lost only the 4th and 5th tries (1095, 1155) of "
"'T20-beside' and 'T20-inside'",
s13.count("(1035, 16.0, False)], [(11, 'current', 0.0), "
"(15, 'phases', 1)])") == 2
and "(1095, 16.0, False)" not in s13
and "(1155, 16.0, False)" not in s13)
check("T11c: test_ev28 T15 asserts fails == MAX_TRIES, gave_up, 3 tries and "
"the car at 0 A with no select (the only edit, ruled Q3)",
"w.wr.fails == MAX_TRIES" in s28 and "w.wr.gave_up" in s28
and "w.sim.readback_a == 0 and len(tries) == MAX_TRIES" in s28)
UCS.clear()
RN7 = run(lambda a, n: True, 400, cb=at(100, a=8.0))
check(f"N7: a charger that answers: the calls are 0 A at 0, 6 A at 11, 8 A at "
f"100 and nothing else ({RN7.drv.calls}); no REF, fails 0, no "
"give-up, no ERROR",
RN7.drv.calls == [(0.0, 0.0), (11.0, 6.0), (100.0, 8.0)]
and not refs(RN7) and not recs(RN7)
and RN7.rows[399]["fails"] == 0 and not RN7.rows[399]["gave_up"])
n12 = [x for x in R1.trk.notes if x[1] > 0]
check(f"N12: the tracker is told of each refused close once ({n12}) and of "
f"no raised close ({[x for x in RX.trk.notes if x[1] > 0]}, "
f"begin/end per write {RX.trk.notes[:1]})",
len(n12) == 3 and all(not ok for _t, _a, ok in n12)
and not [x for x in RX.trk.notes if x[1] > 0])
print("\n7. N4, N8, N10")
APP = os.path.join(HERE, "app")
SRC = {f: open(os.path.join(APP, f), encoding="utf-8").read()
for f in sorted(os.listdir(APP)) if f.endswith(".py")}
cm_src = SRC["carmode.py"]
check("N8 (write_phases and the peak-cut rules untouched): carmode.py still "
"has the one `write_phases(` call and no new write path; base had 1",
cm_src.count("write_phases(") == 1
and cm_src.count("drv.write_current(") == 1)
check("N10 (no new store key, setting, notification or timer): `_close_k` "
"lives in carmode.py only, never next to a store or option; the "
"asyncio.sleep, create_task and _LOG.warning counts are the base's "
"(1, 0, 10)",
[f for f, s in SRC.items() if "_close_k" in s] == ["carmode.py"]
and cm_src.count("asyncio.sleep") == 1
and cm_src.count("create_task") == 0
and cm_src.count("_LOG.warning(") == 10
and not any("_close_k" in line and ("store" in line or "opts" in line)
for line in cm_src.splitlines()))
w4 = CM.ManualWriter()
w4.gave_up, w4.fails, w4._close_k = True, 3, 3
w4.user_changed()
check("N4: user_changed clears gave_up, fails and the close count",
not w4.gave_up and w4.fails == 0 and w4._close_k == 0)
R4n = run(refuse, 400, cb=at(100, a=8.0))
check("N4: a give-up does not block the next user change or phase change "
f"({nz(R4n, 100)[:1]})", nz(R4n, 100)[:1] == [100])
print()
if fails:
print(f"FAIL: {len(fails)} check(s)")
for f in fails:
print(" -", f)
sys.exit(1)
print("ok: EV-59")