File size: 29,333 Bytes
966ca88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
#!/usr/bin/env python3
"""COMPUTATION lane — PlusPlusBattery (Jetpack Compose battery info viewer).

This lane owns the app's ARITHMETIC: input -> recomputed output. Every test drives
an INPUT (current multiplier, dual-cell toggle, temperature-unit swap) and asserts
the EXACT recomputed VALUE the running app renders on a Dashboard card. Because the
emulator reports FIXED battery values, exact-string equality is a valid oracle.

The two engines exercised here (verified live against the original app):

  (1) Current multiplier:  shown_current = 900000 * (Multiply ? 10^mag : 1/10^mag)
      Open the Calibrate dialog (content-desc "Calibrate"); pick Multiply/Divide
      (2 RadioButtons, Divide = the 2nd); pick the magnitude from the "10^0"
      spinner. Integer results drop the decimal ("900 mA", never "900.00 mA").

  (2) Power = current(mA) * voltage(mV) * dualMultiplier / 1_000_000, unit "W",
      formatted "clean": integer -> no decimals, else 2dp.
        baseline            900000*5000*1/1e6 = 4500   -> "4500 W"
        Divide 10^3 (cur 900)   900*5000/1e6   = 4.5    -> "4.50 W"
        Divide 10^2 (cur 9000)  9000*5000/1e6  = 45     -> "45 W"
        Divide 10^4 (cur 90)    90*5000/1e6    = 0.45   -> "0.45 W"
        Divide 10^3 + Dual ON   (*2)           = 9.0    -> "9 W"  (integer -> no dp)

  (3) Temperature C<->F: tap "Swap Unit" -> "25.0°C" becomes "77.0°F" (C*9/5+32).

ALL expected strings below were confirmed by running this file against the original
and reading the [PASS]/[FAIL] lines — never derived purely from the formula, because
the integer-vs-decimal formatting is easy to get wrong.

Each test opens its own entry via restart_app(); after any multiplier / dual-cell /
unit change it RESTORES the default (Reset the multiplier, toggle dual off, swap the
unit back) so later tests and other lanes see raw 900000 / 4500 / 25.0°C. A VLM
screenshot, when a test has one, is captured while the changed value is STILL on the
card — before the restore.
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403,F401
import android_testgen_kit as _kit          # for the private depth counter only

RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__))


# ── Observed constants (each read off the running original) ──────────────────────
CUR_DEFAULT = "900000 mA"          # Battery Current, no multiplier
CUR_MUL1 = "9000000 mA"            # Multiply 10^1
CUR_DIV1 = "90000 mA"             # Divide 10^1
CUR_DIV2 = "9000 mA"              # Divide 10^2
CUR_DIV3 = "900 mA"               # Divide 10^3
CUR_DIV4 = "90 mA"                # Divide 10^4
CUR_DIV5 = "9 mA"                # Divide 10^5

POW_DEFAULT = "4500 W"            # baseline power
POW_DIV2 = "45 W"                # Divide 10^2 (current 9000)  -> integer, no dp
POW_DIV3 = "4.50 W"              # Divide 10^3 (current 900)   -> 2dp
POW_DIV4 = "0.45 W"             # Divide 10^4 (current 90)    -> 2dp
POW_DIV3_DUAL = "9 W"           # Divide 10^3 + Dual ON (*2)  -> integer, no dp
POW_DUAL = "9000 W"             # baseline + Dual ON (*2)     -> integer, no dp

TEMP_C = "25.0°C"
TEMP_F = "77.0°F"

DUAL_NO = "No"
DUAL_YES = "Yes"

CD_CALIBRATE = "Calibrate"
CD_SWAP = "Swap Unit"
CD_DUAL = "Toggle Dual Battery"

CAL_TITLE = "Calibrate via Multiplier"
CAL_CLOSE = "Close"
CAL_RESET = "Reset"
SPINNER_LABEL = "10^0"            # the collapsed spinner's EditText text


# ══════════════════════════════════════════════════════════════════════════════
# Small readers — read the recomputed value straight out of a FRESH dump. The
# card value TextViews are identified by their unit suffix (" mA" / " W" / "°").
# ══════════════════════════════════════════════════════════════════════════════

def _dec_depth() -> int:
    """Pop one surface from the kit's depth counter WITHOUT a hardware BACK — for a
    dialog dismissed by its own Close/Reset affordance."""
    _kit._DEPTH = max(0, _kit._DEPTH - 1)
    return _kit._DEPTH


def cur_value(nodes=None) -> str:
    """The Battery Current label ("... mA"), or "" if absent this frame. The
    Full-Charge-Capacity card can also read "N mAh"; that suffix is " mAh", so it
    never collides with the current card's " mA"."""
    nodes = ui() if nodes is None else nodes
    for n in nodes:
        t = n.get("text", "")
        if t.endswith(" mA"):
            return t
    return ""


def power_value(nodes=None) -> str:
    """The Battery Power label ("... W"), or ""."""
    nodes = ui() if nodes is None else nodes
    for n in nodes:
        t = n.get("text", "")
        if t.endswith(" W"):
            return t
    return ""


def temp_value(nodes=None) -> str:
    """The Battery Temperature label ("25.0°C"/"77.0°F"), or ""."""
    nodes = ui() if nodes is None else nodes
    for n in nodes:
        if "°" in n.get("text", ""):
            return n["text"]
    return ""


def dual_value(nodes=None) -> str:
    """The Dual Cell value string ("No"/"Yes"), or ""."""
    nodes = ui() if nodes is None else nodes
    if find_node(nodes, text=DUAL_YES):
        return DUAL_YES
    if find_node(nodes, text=DUAL_NO):
        return DUAL_NO
    return ""


def read_first(reader, want: str = "", tries: int = 5) -> str:
    """Poll `reader` across fresh dumps until it returns a non-empty value (or
    `want` when given). The dashboard can re-dump empty for one frame right after a
    dialog closes; this makes the read robust without ever fabricating a value."""
    val = ""
    for _ in range(tries):
        val = reader(ui())
        if val and (not want or val == want):
            return val
        settle("tap")
    return val


def radio_buttons(nodes=None) -> list:
    nodes = ui() if nodes is None else nodes
    return [n for n in nodes if n.get("class", "").endswith("RadioButton")]


# ══════════════════════════════════════════════════════════════════════════════
# depth-family helper — named and_enter_* so the depth auditor counts the declared
# depth=1 as backed by a real navigation call. Opens the Calibrate dialog and
# confirms its title appeared.
# ══════════════════════════════════════════════════════════════════════════════

def and_enter_calibrate(nodes=None) -> bool:
    """Dashboard -> Calibrate dialog. Confirms the dialog title appeared, then
    counts one surface via the kit's depth counter."""
    nodes = ui() if nodes is None else nodes
    trig = find_node(nodes, content_desc=CD_CALIBRATE)
    if trig is None or not tap_node(trig):
        return False
    if find_node(ui(), text=CAL_TITLE) is None:
        return False
    and_enter("calibrate_dialog")
    return True


# ── Calibrate dialog sub-steps (an open dialog is assumed) ───────────────────────

def cal_pick_multiply() -> bool:
    """Tap the 1st RadioButton (Multiply). True iff it is checked afterwards."""
    rb = radio_buttons()
    if len(rb) < 2 or not tap_node(rb[0]):
        return False
    rb = radio_buttons()
    return len(rb) >= 1 and rb[0].get("checked") == "true"


def cal_pick_divide() -> bool:
    """Tap the 2nd RadioButton (Divide). True iff it is checked afterwards."""
    rb = radio_buttons()
    if len(rb) < 2 or not tap_node(rb[1]):
        return False
    rb = radio_buttons()
    return len(rb) >= 2 and rb[1].get("checked") == "true"


def cal_set_exponent(exp_text: str) -> bool:
    """Open the spinner (collapsed it shows "10^0") and pick `exp_text` (e.g.
    "10^3"). True iff the collapsed spinner then shows the chosen exponent."""
    ed = find_node(ui(), text=SPINNER_LABEL)
    if ed is None or not tap_node(ed):
        return False
    item = find_node(ui(), text=exp_text)
    if item is None or not tap_node(item):
        return False
    return find_node(ui(), text=exp_text) is not None


def cal_close() -> bool:
    """Tap the dialog's Close button (tap_node — Close is a DANGEROUS_TEXT so
    safe_tap would refuse; it only dismisses the dialog)."""
    c = find_node(ui(), text=CAL_CLOSE)
    return c is not None and tap_node(c)


def cal_reset() -> bool:
    """Tap the dialog's Reset button (tap_node — Reset is a DANGEROUS_TEXT, but the
    app's Reset only resets the multiplier PREFERENCE, never user data). OBSERVED:
    Reset restores the value to 900000 mA AND dismisses the dialog."""
    r = find_node(ui(), text=CAL_RESET)
    return r is not None and tap_node(r)


def apply_multiplier(mode: str, exp_text: str) -> bool:
    """Open Calibrate, select Multiply/Divide, set the exponent, Close. Leaves the
    Dashboard showing and pops the dialog off the depth counter. Returns True iff
    every sub-step succeeded."""
    if not and_enter_calibrate():
        return False
    pick = cal_pick_multiply() if mode == "multiply" else cal_pick_divide()
    ok = pick and cal_set_exponent(exp_text) and cal_close()
    _dec_depth()  # dialog dismissed by Close
    return ok


def restore_multiplier() -> None:
    """Open Calibrate and Reset (restores 900000 AND closes), balancing depth."""
    if and_enter_calibrate():
        cal_reset()
        _dec_depth()
        read_first(cur_value, CUR_DEFAULT)


def restore_dual_off() -> None:
    """Toggle Dual Cell back OFF if it is currently ON."""
    if dual_value(ui()) == DUAL_YES:
        d = find_node(ui(), content_desc=CD_DUAL)
        if d:
            tap_node(d)
            read_first(dual_value, DUAL_NO)


def restore_temp_c() -> None:
    """Swap the temperature unit back to Celsius if it is currently Fahrenheit."""
    if temp_value(ui()) == TEMP_F:
        sw = find_node(ui(), content_desc=CD_SWAP)
        if sw:
            tap_node(sw)
            read_first(temp_value, TEMP_C)


def ready() -> bool:
    """restart_app + wait; True once the Dashboard is up."""
    restart_app()
    return wait_for_foreground()


# ══════════════════════════════════════════════════════════════════════════════
# CURRENT MULTIPLIER — six exact-value cases across Divide 10^1..10^5 + Multiply
# 10^1. Each opens the Calibrate dialog (depth=1), applies the multiplier, and
# asserts the exact recomputed "N mA" string, then Resets back to 900000.
# ══════════════════════════════════════════════════════════════════════════════

def _current_case(name: str, mode: str, exp_text: str, expected: str, vlm=None):
    """Shared body: assert Battery Current == `expected` after mode+exponent, with a
    positive/negative pair (the answer must be ABSENT before and PRESENT after). An
    optional `vlm` callback fires while the changed value is STILL on the card —
    before the multiplier is Reset."""
    if not ready():
        record(name, False, "setup_failed: app did not reach foreground",
               depth=1, jump_kind="value", expect=f"Battery Current {expected}")
        return
    before = read_first(cur_value, CUR_DEFAULT)
    if find_node(ui(), content_desc=CD_CALIBRATE) is None:
        record(name, False,
               "feature_missing: no 'Calibrate' control on the Battery Current card",
               depth=1, jump_kind="value", expect=f"Battery Current {expected}")
        return
    steps_ok = apply_multiplier(mode, exp_text)
    if not steps_ok:
        record(name, False,
               f"setup_failed: could not apply {mode} {exp_text} in the Calibrate dialog",
               depth=1, jump_kind="value", expect=f"Battery Current {expected}")
        restore_multiplier()
        return
    after = read_first(cur_value, expected)
    # positive/negative: expected value ABSENT at baseline, PRESENT after.
    ok = (before == CUR_DEFAULT) and (after == expected) and (expected != CUR_DEFAULT)
    record(name, ok,
           "" if ok else
           f"behavior_wrong: {mode} {exp_text} should give Battery Current "
           f"{expected!r}; saw before={before!r} after={after!r}",
           depth=1, jump_kind="value", expect=f"Battery Current {expected}")
    if vlm:
        vlm(name)               # screenshot WHILE the divided value is on screen
    restore_multiplier()


@and_test(expects=("computation_current_divide_10p1",))
def test_current_divide_10p1():
    _current_case("computation_current_divide_10p1", "divide", "10^1", CUR_DIV1)


@and_test(expects=("computation_current_divide_10p2",))
def test_current_divide_10p2():
    _current_case("computation_current_divide_10p2", "divide", "10^2", CUR_DIV2)


@and_test(expects=("computation_current_divide_10p3",))
def test_current_divide_10p3():
    _current_case("computation_current_divide_10p3", "divide", "10^3", CUR_DIV3)


@and_test(expects=("computation_current_divide_10p4",))
def test_current_divide_10p4():
    _current_case("computation_current_divide_10p4", "divide", "10^4", CUR_DIV4)


@and_test(expects=("computation_current_divide_10p5", "computation_current_divide_10p5_vlm"))
def test_current_divide_10p5():
    def _vlm(_name):
        # VLM (content track): with Divide 10^5 applied, the Battery Current card
        # renders a TINY value ("9 mA") instead of the six-digit default 900000 —
        # visible proof the multiplier recomputation happened. Captured before the
        # value is Reset, so the small number is actually on screen.
        vlm_assert("computation_current_divide_10p5",
                   "Look at the 'Battery Current' row. Is its value a SMALL number of "
                   "just one or two characters (for example '9'), rather than a long "
                   "six-digit number like '900000'?",
                   RESULTS_DIR, depth=0, jump_kind="none", tag="content")
    _current_case("computation_current_divide_10p5", "divide", "10^5", CUR_DIV5, vlm=_vlm)


@and_test(expects=("computation_current_multiply_10p1",))
def test_current_multiply_10p1():
    _current_case("computation_current_multiply_10p1", "multiply", "10^1", CUR_MUL1)


# ══════════════════════════════════════════════════════════════════════════════
# POWER — recomputed from the (possibly multiplied) current. Baseline is depth=0
# (no dialog); the multiplier cases are depth=1. Every case asserts the exact "N W"
# string, watching the integer-vs-decimal "clean" formatting.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_power_baseline",))
def test_power_baseline():
    if not ready():
        record("computation_power_baseline", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="value", expect=f"Battery Power {POW_DEFAULT}")
        return
    got = read_first(power_value, POW_DEFAULT)
    ok = got == POW_DEFAULT
    record("computation_power_baseline", ok,
           "" if ok else
           f"behavior_wrong: baseline Battery Power should be {POW_DEFAULT!r} "
           f"(900000*5000/1e6); saw {got!r}",
           depth=0, jump_kind="value", expect=f"Battery Power {POW_DEFAULT}")


def _power_multiplier_case(name: str, exp_text: str, expected: str, vlm=None):
    """Divide the current by 10^N, then assert the recomputed Battery Power. The
    default power (4500 W) must be ABSENT and `expected` PRESENT after."""
    if not ready():
        record(name, False, "setup_failed: app did not reach foreground",
               depth=1, jump_kind="value", expect=f"Battery Power {expected}")
        return
    before = read_first(power_value, POW_DEFAULT)
    if find_node(ui(), content_desc=CD_CALIBRATE) is None:
        record(name, False,
               "feature_missing: no 'Calibrate' control on the Battery Current card",
               depth=1, jump_kind="value", expect=f"Battery Power {expected}")
        return
    steps_ok = apply_multiplier("divide", exp_text)
    if not steps_ok:
        record(name, False,
               f"setup_failed: could not apply divide {exp_text} in the Calibrate dialog",
               depth=1, jump_kind="value", expect=f"Battery Power {expected}")
        restore_multiplier()
        return
    after = read_first(power_value, expected)
    ok = (before == POW_DEFAULT) and (after == expected) and (expected != POW_DEFAULT)
    record(name, ok,
           "" if ok else
           f"behavior_wrong: divide {exp_text} should give Battery Power "
           f"{expected!r}; saw before={before!r} after={after!r}",
           depth=1, jump_kind="value", expect=f"Battery Power {expected}")
    if vlm:
        vlm(name)               # screenshot WHILE the recomputed power is on screen
    restore_multiplier()


@and_test(expects=("computation_power_divide_10p2",))
def test_power_divide_10p2():
    _power_multiplier_case("computation_power_divide_10p2", "10^2", POW_DIV2)


@and_test(expects=("computation_power_divide_10p3", "computation_power_divide_10p3_vlm"))
def test_power_divide_10p3():
    def _vlm(_name):
        # VLM (content track): with Divide 10^3 applied, the Battery Power card
        # renders a small decimal ("4.50 W"), not the large default 4500. Captured
        # before the multiplier is Reset.
        vlm_assert("computation_power_divide_10p3",
                   "Look at the 'Battery Power' row. Is its value a SMALL decimal "
                   "number like '4.50', rather than a large number like '4500'?",
                   RESULTS_DIR, depth=0, jump_kind="none", tag="content")
    _power_multiplier_case("computation_power_divide_10p3", "10^3", POW_DIV3, vlm=_vlm)


@and_test(expects=("computation_power_divide_10p4",))
def test_power_divide_10p4():
    _power_multiplier_case("computation_power_divide_10p4", "10^4", POW_DIV4)


@and_test(expects=("computation_power_divide_10p3_dual",))
def test_power_divide_10p3_dual():
    """Divide 10^3 then Dual Cell ON: power 4.50 doubles to a rendered "9 W"
    (integer -> the ".00" is dropped)."""
    if not ready():
        record("computation_power_divide_10p3_dual", False,
               "setup_failed: app did not reach foreground",
               depth=1, jump_kind="value",
               expect=f"Battery Power {POW_DIV3_DUAL} at Divide 10^3 + Dual ON")
        return
    if find_node(ui(), content_desc=CD_CALIBRATE) is None:
        record("computation_power_divide_10p3_dual", False,
               "feature_missing: no 'Calibrate' control on the Battery Current card",
               depth=1, jump_kind="value",
               expect=f"Battery Power {POW_DIV3_DUAL} at Divide 10^3 + Dual ON")
        return
    calc_ok = apply_multiplier("divide", "10^3")
    pow_div3 = read_first(power_value, POW_DIV3)
    dual = find_node(ui(), content_desc=CD_DUAL)
    dual_ok = dual is not None and tap_node(dual)
    pow_dual = read_first(power_value, POW_DIV3_DUAL)
    ok = (calc_ok and pow_div3 == POW_DIV3 and dual_ok
          and pow_dual == POW_DIV3_DUAL and dual_value(ui()) == DUAL_YES)
    record("computation_power_divide_10p3_dual", ok,
           "" if ok else
           f"behavior_wrong: Divide 10^3 should give Power {POW_DIV3}; Dual ON "
           f"should double it to {POW_DIV3_DUAL}; saw pow3={pow_div3!r} "
           f"powdual={pow_dual!r}",
           depth=1, jump_kind="value",
           expect=f"Battery Power {POW_DIV3_DUAL} at Divide 10^3 + Dual ON")
    # RESTORE: dual OFF then Reset multiplier.
    restore_dual_off()
    restore_multiplier()


@and_test(expects=("computation_power_dual_only",))
def test_power_dual_only():
    """Dual Cell ON at the DEFAULT multiplier doubles power 4500 -> "9000 W"
    (integer -> no decimals). Depth 0 (no dialog)."""
    if not ready():
        record("computation_power_dual_only", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="value",
               expect=f"Battery Power {POW_DUAL} with Dual Cell ON")
        return
    before = read_first(power_value, POW_DEFAULT)
    dual = find_node(ui(), content_desc=CD_DUAL)
    if dual is None:
        record("computation_power_dual_only", False,
               "feature_missing: no 'Toggle Dual Battery' control",
               depth=0, jump_kind="value",
               expect=f"Battery Power {POW_DUAL} with Dual Cell ON")
        return
    dual_ok = tap_node(dual)
    after = read_first(power_value, POW_DUAL)
    ok = (before == POW_DEFAULT) and dual_ok and (after == POW_DUAL) \
        and dual_value(ui()) == DUAL_YES
    record("computation_power_dual_only", ok,
           "" if ok else
           f"behavior_wrong: Dual Cell ON should double Power {POW_DEFAULT} to "
           f"{POW_DUAL}; saw before={before!r} after={after!r}",
           depth=0, jump_kind="value",
           expect=f"Battery Power {POW_DUAL} with Dual Cell ON")
    restore_dual_off()


# ══════════════════════════════════════════════════════════════════════════════
# TEMPERATURE C<->F — exact recomputed unit string. Both directions, depth 0.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_temp_c_to_f",))
def test_temp_c_to_f():
    if not ready():
        record("computation_temp_c_to_f", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_F}")
        return
    before = read_first(temp_value, TEMP_C)
    sw = find_node(ui(), content_desc=CD_SWAP)
    if sw is None or not tap_node(sw):
        record("computation_temp_c_to_f", False,
               "feature_missing: no 'Swap Unit' control on the temperature card",
               depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_F}")
        return
    after = read_first(temp_value, TEMP_F)
    ok = (before == TEMP_C) and (after == TEMP_F)
    record("computation_temp_c_to_f", ok,
           "" if ok else
           f"behavior_wrong: swap should convert {TEMP_C} -> {TEMP_F} (C*9/5+32); "
           f"saw before={before!r} after={after!r}",
           depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_F}")
    restore_temp_c()


@and_test(expects=("computation_temp_f_to_c",))
def test_temp_f_to_c():
    """Second swap converts Fahrenheit back to the exact "25.0°C"."""
    if not ready():
        record("computation_temp_f_to_c", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_C}")
        return
    start = read_first(temp_value, TEMP_C)
    sw = find_node(ui(), content_desc=CD_SWAP)
    if sw is None or not tap_node(sw):
        record("computation_temp_f_to_c", False,
               "feature_missing: no 'Swap Unit' control on the temperature card",
               depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_C}")
        return
    to_f = read_first(temp_value, TEMP_F)
    sw = find_node(ui(), content_desc=CD_SWAP)
    back_ok = sw is not None and tap_node(sw)
    to_c = read_first(temp_value, TEMP_C)
    ok = (start == TEMP_C) and (to_f == TEMP_F) and back_ok and (to_c == TEMP_C)
    record("computation_temp_f_to_c", ok,
           "" if ok else
           f"behavior_wrong: second swap should convert {TEMP_F} -> {TEMP_C}; "
           f"saw start={start!r} to_f={to_f!r} to_c={to_c!r}",
           depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_C}")
    restore_temp_c()


# ══════════════════════════════════════════════════════════════════════════════
# ROUND-TRIP integrity — the computation is REVERSIBLE to the exact baseline.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_current_divide_then_reset",))
def test_current_divide_then_reset():
    """Divide 10^3 -> Current 900 mA, then Reset -> Current back to EXACTLY
    900000 mA. depth=1 (the Calibrate dialog is entered twice)."""
    if not ready():
        record("computation_current_divide_then_reset", False,
               "setup_failed: app did not reach foreground",
               depth=1, jump_kind="value",
               expect=f"Battery Current {CUR_DEFAULT} after Divide 10^3 then Reset")
        return
    before = read_first(cur_value, CUR_DEFAULT)
    if find_node(ui(), content_desc=CD_CALIBRATE) is None:
        record("computation_current_divide_then_reset", False,
               "feature_missing: no 'Calibrate' control on the Battery Current card",
               depth=1, jump_kind="value",
               expect=f"Battery Current {CUR_DEFAULT} after Divide 10^3 then Reset")
        return
    calc_ok = apply_multiplier("divide", "10^3")
    mid = read_first(cur_value, CUR_DIV3)
    # reopen dialog and Reset (restores AND closes)
    reset_ok = False
    if and_enter_calibrate():
        reset_ok = cal_reset()
        _dec_depth()
    final = read_first(cur_value, CUR_DEFAULT)
    ok = (before == CUR_DEFAULT and calc_ok and mid == CUR_DIV3
          and reset_ok and final == CUR_DEFAULT)
    record("computation_current_divide_then_reset", ok,
           "" if ok else
           f"behavior_wrong: expected {CUR_DEFAULT}->(Divide 10^3)->{CUR_DIV3}->"
           f"(Reset)->{CUR_DEFAULT}; saw before={before!r} mid={mid!r} final={final!r}",
           depth=1, jump_kind="value",
           expect=f"Battery Current {CUR_DEFAULT} after Divide 10^3 then Reset")
    restore_multiplier()


@and_test(expects=("computation_temp_swap_round_trip",))
def test_temp_swap_round_trip():
    """Two swaps return the temperature to EXACTLY "25.0°C" (C->F->C). depth 0."""
    if not ready():
        record("computation_temp_swap_round_trip", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="value",
               expect=f"Battery Temperature {TEMP_C} after two swaps")
        return
    start = read_first(temp_value, TEMP_C)
    sw = find_node(ui(), content_desc=CD_SWAP)
    if sw is None or not tap_node(sw):
        record("computation_temp_swap_round_trip", False,
               "feature_missing: no 'Swap Unit' control on the temperature card",
               depth=0, jump_kind="value",
               expect=f"Battery Temperature {TEMP_C} after two swaps")
        return
    mid = read_first(temp_value, TEMP_F)
    sw = find_node(ui(), content_desc=CD_SWAP)
    back_ok = sw is not None and tap_node(sw)
    final = read_first(temp_value, TEMP_C)
    ok = (start == TEMP_C) and (mid == TEMP_F) and back_ok and (final == TEMP_C)
    record("computation_temp_swap_round_trip", ok,
           "" if ok else
           f"behavior_wrong: two swaps should return to {TEMP_C}; saw start={start!r} "
           f"mid={mid!r} final={final!r}",
           depth=0, jump_kind="value",
           expect=f"Battery Temperature {TEMP_C} after two swaps")
    restore_temp_c()


TESTS = [
    # current multiplier (6, depth 1)
    test_current_divide_10p1,
    test_current_divide_10p2,
    test_current_divide_10p3,
    test_current_divide_10p4,
    test_current_divide_10p5,          # + 1 VLM (content)
    test_current_multiply_10p1,
    # power (5: 1 depth0 + 4 depth1)
    test_power_baseline,
    test_power_divide_10p2,
    test_power_divide_10p3,            # + 1 VLM (content)
    test_power_divide_10p4,
    test_power_divide_10p3_dual,
    test_power_dual_only,
    # temperature (2, depth 0)
    test_temp_c_to_f,
    test_temp_f_to_c,
    # round-trips (2)
    test_current_divide_then_reset,    # depth 1
    test_temp_swap_round_trip,         # depth 0
]


if __name__ == "__main__":
    run_suite(TESTS, "computation")