File size: 42,010 Bytes
c1c6a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
#!/usr/bin/env python3
"""COMPUTATION module for openScale (a body-weight / health tracker).

CORE FUNCTION: input -> output. This lane is the sole owner of jump_kind="value".
openScale's core transform is: you enter a Weight (and the user's Height/Gender/
age/activity from the profile), and the app DERIVES a set of values:

    BMI  = weight / (height/100)^2      -> shown on the Overview card AND Statistics
    BMR  (Mifflin-St Jeor)              -> Statistics card, "kcal"
    TDEE = BMR * activity multiplier    -> Statistics card, "kcal"
    Weight echo                         -> Overview card AND Statistics ("kg")

Every EXPECTED string below was OBSERVED on the RUNNING ORIGINAL (a user with
Height 180, Male, born 2008 (age ~18), Sedentary; one measurement), never computed
from a formula or read from source:

    weight 80  -> BMI "24.7"   weight 60 -> "18.5"   weight 100 -> "30.9"
    BMR  "1840 kcal"           TDEE "2208 kcal"
    weight echo "80 kg"        Statistics Min/Max/Avg == the single value
    height 200 + weight 80 -> BMI "20"  (whole-number BMI renders without ".0")

RELIABLE OBSERVATION POINT: on the Edit-Measurement DETAIL screen BMI does NOT
reliably recompute live from a dialog edit, so we always SAVE -> read on
Overview / Statistics. The one in-page value transition we assert directly is the
NumberInputDialog stepper effect on the EditText string (Weight step +0.1).

DROPPED: WHR / WHtR. On this build the derived WHR/WHtR rows render "-" on the
detail screen even after waist+hips are entered and saved (observed WHR="-",
WHtR="-"), so no value is reproducibly observable — recon permits dropping these.

Run:
    python3 test_android_computation.py <PACKAGE> <RESULTS_DIR>
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403,E402


# ══════════════════════════════════════════════════════════════════════════════
# file-local depth helpers — the and_enter_* / and_reach_* NAMES back every
# declared depth>=1 (the depth auditor descends into file-local helpers that call
# and_enter()/and_reach()).
# ══════════════════════════════════════════════════════════════════════════════

def and_enter_user_form():
    """From the Overview 'No User Active' surface, open the Add-User form."""
    n = find_node_ci(ui(), "Add User")
    if n is None or not tap_node(n):
        return False
    settle("launch")
    and_enter("user_form")
    return True


def and_enter_new_measurement():
    """From the Overview, open the New Measurement screen (empty-state 'Add
    Measurement' button, or the top-bar cd='Add new measurement')."""
    n = (find_node_ci(ui(), "Add Measurement")
         or find_node(ui(), content_desc="Add new measurement"))
    if n is None or not tap_node(n):
        return False
    settle("launch")
    and_enter("new_measurement")
    return True


def and_enter_weight_dialog():
    """From the New/Edit Measurement screen, open the Edit Weight
    NumberInputDialog (cd='Edit Weight')."""
    n = find_node(ui(), content_desc="Edit Weight")
    if n is None or not tap_node(n):
        return False
    settle("tap")
    and_enter("weight_dialog")
    return True


def and_reach_statistics():
    """From the Overview, reach the Statistics screen, PROVING the jump.

    'before' MUST be snapshotted while the Overview is showing — the 'Statistics'
    title is genuinely absent there, so tapping through the drawer makes it newly
    APPEAR (and_reach). Opening the drawer FIRST would place the 'Statistics'
    drawer item into 'before' and defeat the appeared-check (this was the bug in
    the first run). Counts one surface via and_enter.
    """
    before = and_showing()                       # Overview surface (no 'Statistics')
    menu = find_node(ui(), content_desc="Open menu")
    if menu is None or not tap_node(menu):
        return False
    settle("launch")
    dest = (find_node(ui(), content_desc="Statistics")
            or find_node_ci(ui(), "Statistics"))
    if dest is None or not tap_node(dest):
        return False
    settle("launch")
    after = and_showing()
    ok = and_reach(before, after, "Statistics")  # title absent on Overview -> appears
    if ok:
        and_enter("statistics")
    return ok


# ══════════════════════════════════════════════════════════════════════════════
# The PROVEN reliable numeric-entry recipe (verbatim from recon): the
# NumberInputDialog EditText APPENDS to "0.0" and type_text drops the 2nd digit,
# so Clear -> tap -> type ONE char at a time with settle("text"), then RETURN the
# field text so the caller can verify it == str(val) before asserting a value.
# ══════════════════════════════════════════════════════════════════════════════

def set_dialog_value(val):            # a NumberInputDialog must be open
    c = find_node_ci(ui(), "Clear")
    if c:
        tap_node(c)
        settle("keyboard")
    ets = find_by_class(ui(), "EditText")
    if not ets:
        return ""
    et = ets[0]
    tap_node(et)
    settle("keyboard")
    settle("keyboard")                # let focus settle
    for ch in str(val):
        adb_shell("input", "text", ch)  # ONE char at a time (kit injects serial)
        settle("text")
    settle("text")
    ets = find_by_class(ui(), "EditText")
    return ets[0].get("text", "") if ets else ""


def _tap_dialog_ok():
    ok_btn = find_node_ci(ui(), "OK")
    if ok_btn:
        tap_node(ok_btn)
        settle("tap")


def create_user(height="180", name="TestUser"):
    """clear_data() -> launch -> fill Name+Height -> tap the top-right Save button
    DIRECTLY (no hide_keyboard(); its BACK fallback would discard the form).
    Returns True once the 'No User Active' state is gone."""
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    if not and_enter_user_form():
        return False
    ets = sorted(find_by_class(ui(), "EditText"),
                 key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    if len(ets) < 2:
        return False
    type_text(ets[0], name)
    settle("text")
    ets = sorted(find_by_class(ui(), "EditText"),
                 key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    type_text(ets[1], height)
    settle("text")
    btns = [n for n in ui()
            if n.get("class", "").endswith("Button")
            and n.get("clickable") == "true"
            and n.get("_bounds", (0, 0, 0, 0))[0] > 800]
    if not btns:
        return False
    tap_node(btns[0])
    settle("launch")
    return find_node_ci(ui(), "No User Active") is None


def add_weight_measurement(weight):
    """From the Overview (user must already exist): open New Measurement, set
    Weight via the proven recipe, OK, Save measurement. Returns the field string
    the dialog actually held (caller verifies == str(weight))."""
    if not and_enter_new_measurement():
        return None
    if not and_enter_weight_dialog():
        return None
    got = set_dialog_value(weight)
    _tap_dialog_ok()
    sm = find_node(ui(), content_desc="Save measurement")
    if sm:
        tap_node(sm)
        settle("launch")
    return got


def user_with_weight(weight, height="180"):
    """End-to-end fixture: clean user + one saved weight measurement, left on the
    Overview. Returns (ok, dialog_field_string)."""
    if not create_user(height=height):
        return False, ""
    got = add_weight_measurement(weight)
    return (got == str(weight)), (got or "")


# ── value readers ─────────────────────────────────────────────────────────────

def _norm(s):
    """Normalise a numeric display for comparison: drop spaces & thousands
    separators, lowercase the unit."""
    return s.replace(",", "").replace(" ", "").strip().lower()


def overview_card_texts():
    """Every text on the Overview that carries a digit (date, '80 kg', '24.7')."""
    return [n.get("text", "").strip() for n in ui()
            if n.get("text", "").strip() and any(c.isdigit() for c in n.get("text", ""))]


def stat_value(metric_label, kind):
    """On the Statistics screen, the 'Min:'/'Max:'/'Avg:' value for a metric card.

    Each metric card is a TIGHT vertical cluster whose 'Kind:' rows straddle the
    label (OBSERVED geometry: 'Min: 80 kg' y=360, 'Weight' y=389, 'Max: 80 kg'
    y=402, 'Avg: 80 kg' y=444 — the label sits BETWEEN Min and Max, and the next
    card is ~500px away). So the right row is the 'Kind:' row whose y is CLOSEST
    to the label's y (not merely the first one below it — that reads the NEXT
    card). `kind` in {'Min','Max','Avg'}. Returns the value part, or "".
    """
    nodes = ui()
    prefix = f"{kind}:"
    lab = None
    for n in nodes:
        if n.get("text", "").strip() == metric_label:
            lab = n
            break
    if lab is None:
        return ""
    ly = lab.get("_bounds", (0, 0, 0, 0))[1]
    cands = [n for n in nodes if n.get("text", "").strip().startswith(prefix)]
    if not cands:
        return ""
    # nearest by absolute vertical distance, and only if it truly belongs to this
    # card (within ~120px of the label) — otherwise the metric has no such row.
    nearest = min(cands, key=lambda n: abs(n.get("_bounds", (0, 0, 0, 0))[1] - ly))
    if abs(nearest.get("_bounds", (0, 0, 0, 0))[1] - ly) > 120:
        return ""
    return nearest.get("text", "").split(":", 1)[1].strip()


def dialog_field_value():
    ets = find_by_class(ui(), "EditText")
    return ets[0].get("text", "") if ets else ""


# ══════════════════════════════════════════════════════════════════════════════
# 1) BMI from weight 80 -> "24.7" on the Overview card  (+ the single VLM: chart)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_bmi_80_overview",
                   "computation_overview_chart_vlm"))
def test_bmi_80_overview():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_bmi_80_overview", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="24.7")
        record("computation_overview_chart_vlm", False,
               "setup_failed: no saved measurement to chart",
               depth=1, jump_kind="value", tag="position")
        return
    texts = overview_card_texts()
    present = any(_norm(t) == "24.7" for t in texts)
    record("computation_bmi_80_overview", present,
           "" if present else f"behavior_wrong: Overview BMI not '24.7'; saw {texts!r}",
           depth=1, jump_kind="value", expect="24.7")
    # The ONE VLM in this lane: the Overview chart is a canvas (not in the view
    # tree). With one entry it renders a single small colored dot plotted in the
    # graph region above a date-axis label — a position property no dump exposes.
    vlm_assert("computation_overview_chart",
               "In the upper area of this screen, is there a small colored dot "
               "plotted in a graph/plot region, with a date label (such as a day "
               "and month) shown along the horizontal axis below it?",
               RESULTS_DIR, depth=1, jump_kind="value", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 2) BMI from weight 60 -> "18.5"  (a different operand -> a different output)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_bmi_60_overview",))
def test_bmi_60_overview():
    ok_setup, got = user_with_weight("60")
    if not ok_setup:
        record("computation_bmi_60_overview", False,
               f"setup_failed: could not enter weight 60 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="18.5")
        return
    texts = overview_card_texts()
    present = any(_norm(t) == "18.5" for t in texts)
    # negative: 24.7 (the 80-weight answer) must be ABSENT for a 60 kg entry.
    wrong = any(_norm(t) == "24.7" for t in texts)
    ok = present and not wrong
    record("computation_bmi_60_overview", ok,
           "" if ok else f"behavior_wrong: Overview BMI not '18.5'; saw {texts!r}",
           depth=1, jump_kind="value", expect="18.5")


# ══════════════════════════════════════════════════════════════════════════════
# 3) BMI from weight 100 -> "30.9"  (large operand)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_bmi_100_overview",))
def test_bmi_100_overview():
    ok_setup, got = user_with_weight("100")
    if not ok_setup:
        record("computation_bmi_100_overview", False,
               f"setup_failed: could not enter weight 100 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="30.9")
        return
    texts = overview_card_texts()
    present = any(_norm(t) == "30.9" for t in texts)
    record("computation_bmi_100_overview", present,
           "" if present else f"behavior_wrong: Overview BMI not '30.9'; saw {texts!r}",
           depth=1, jump_kind="value", expect="30.9")


# ══════════════════════════════════════════════════════════════════════════════
# 4) Weight ECHO -> "80 kg" on the Overview card (the input is echoed verbatim)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_weight_echo_overview",))
def test_weight_echo_overview():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_weight_echo_overview", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="80 kg")
        return
    texts = overview_card_texts()
    present = any(_norm(t) == _norm("80 kg") for t in texts)
    record("computation_weight_echo_overview", present,
           "" if present else f"behavior_wrong: card weight not '80 kg'; saw {texts!r}",
           depth=1, jump_kind="value", expect="80 kg")


# ══════════════════════════════════════════════════════════════════════════════
# 5) BMI on STATISTICS — Min == "24.7"  (depth 2: measurement + drawer->Statistics)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_bmi_min",))
def test_stats_bmi_min():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_bmi_min", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="24.7")
        return
    if not and_reach_statistics():
        record("computation_stats_bmi_min", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="24.7")
        return
    val = stat_value("BMI", "Min")
    ok = _norm(val) == "24.7"
    record("computation_stats_bmi_min", ok,
           "" if ok else f"behavior_wrong: Statistics BMI Min not '24.7'; saw {val!r}",
           depth=2, jump_kind="value", expect="24.7")


# ══════════════════════════════════════════════════════════════════════════════
# 6) BMI on STATISTICS — Max == "24.7"
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_bmi_max",))
def test_stats_bmi_max():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_bmi_max", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="24.7")
        return
    if not and_reach_statistics():
        record("computation_stats_bmi_max", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="24.7")
        return
    val = stat_value("BMI", "Max")
    ok = _norm(val) == "24.7"
    record("computation_stats_bmi_max", ok,
           "" if ok else f"behavior_wrong: Statistics BMI Max not '24.7'; saw {val!r}",
           depth=2, jump_kind="value", expect="24.7")


# ══════════════════════════════════════════════════════════════════════════════
# 7) BMI on STATISTICS — Avg == "24.7"
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_bmi_avg",))
def test_stats_bmi_avg():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_bmi_avg", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="24.7")
        return
    if not and_reach_statistics():
        record("computation_stats_bmi_avg", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="24.7")
        return
    val = stat_value("BMI", "Avg")
    ok = _norm(val) == "24.7"
    record("computation_stats_bmi_avg", ok,
           "" if ok else f"behavior_wrong: Statistics BMI Avg not '24.7'; saw {val!r}",
           depth=2, jump_kind="value", expect="24.7")


# ══════════════════════════════════════════════════════════════════════════════
# 8) BMR on STATISTICS — Min == "1840 kcal"  (Mifflin-St Jeor, male)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_bmr_min",))
def test_stats_bmr_min():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_bmr_min", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="1840 kcal")
        return
    if not and_reach_statistics():
        record("computation_stats_bmr_min", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="1840 kcal")
        return
    val = stat_value("BMR", "Min")
    ok = _norm(val) == _norm("1840 kcal")
    record("computation_stats_bmr_min", ok,
           "" if ok else f"behavior_wrong: Statistics BMR Min not '1840 kcal'; saw {val!r}",
           depth=2, jump_kind="value", expect="1840 kcal")


# ══════════════════════════════════════════════════════════════════════════════
# 9) BMR on STATISTICS — Avg == "1840 kcal"
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_bmr_avg",))
def test_stats_bmr_avg():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_bmr_avg", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="1840 kcal")
        return
    if not and_reach_statistics():
        record("computation_stats_bmr_avg", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="1840 kcal")
        return
    val = stat_value("BMR", "Avg")
    ok = _norm(val) == _norm("1840 kcal")
    record("computation_stats_bmr_avg", ok,
           "" if ok else f"behavior_wrong: Statistics BMR Avg not '1840 kcal'; saw {val!r}",
           depth=2, jump_kind="value", expect="1840 kcal")


# ══════════════════════════════════════════════════════════════════════════════
# 10) TDEE on STATISTICS — Min == "2208 kcal"  (BMR * Sedentary 1.2)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_tdee_min",))
def test_stats_tdee_min():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_tdee_min", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="2208 kcal")
        return
    if not and_reach_statistics():
        record("computation_stats_tdee_min", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="2208 kcal")
        return
    val = stat_value("TDEE", "Min")
    ok = _norm(val) == _norm("2208 kcal")
    record("computation_stats_tdee_min", ok,
           "" if ok else f"behavior_wrong: Statistics TDEE Min not '2208 kcal'; saw {val!r}",
           depth=2, jump_kind="value", expect="2208 kcal")


# ══════════════════════════════════════════════════════════════════════════════
# 11) TDEE on STATISTICS — Avg == "2208 kcal"
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_tdee_avg",))
def test_stats_tdee_avg():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_tdee_avg", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="2208 kcal")
        return
    if not and_reach_statistics():
        record("computation_stats_tdee_avg", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="2208 kcal")
        return
    val = stat_value("TDEE", "Avg")
    ok = _norm(val) == _norm("2208 kcal")
    record("computation_stats_tdee_avg", ok,
           "" if ok else f"behavior_wrong: Statistics TDEE Avg not '2208 kcal'; saw {val!r}",
           depth=2, jump_kind="value", expect="2208 kcal")


# ══════════════════════════════════════════════════════════════════════════════
# 12) Weight echo on STATISTICS — Min == "80 kg"
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_weight_min",))
def test_stats_weight_min():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_weight_min", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="80 kg")
        return
    if not and_reach_statistics():
        record("computation_stats_weight_min", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="80 kg")
        return
    val = stat_value("Weight", "Min")
    ok = _norm(val) == _norm("80 kg")
    record("computation_stats_weight_min", ok,
           "" if ok else f"behavior_wrong: Statistics Weight Min not '80 kg'; saw {val!r}",
           depth=2, jump_kind="value", expect="80 kg")


# ══════════════════════════════════════════════════════════════════════════════
# 13) Weight echo on STATISTICS — Avg == "80 kg"
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_weight_avg",))
def test_stats_weight_avg():
    ok_setup, got = user_with_weight("80")
    if not ok_setup:
        record("computation_stats_weight_avg", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="80 kg")
        return
    if not and_reach_statistics():
        record("computation_stats_weight_avg", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="80 kg")
        return
    val = stat_value("Weight", "Avg")
    ok = _norm(val) == _norm("80 kg")
    record("computation_stats_weight_avg", ok,
           "" if ok else f"behavior_wrong: Statistics Weight Avg not '80 kg'; saw {val!r}",
           depth=2, jump_kind="value", expect="80 kg")


# ══════════════════════════════════════════════════════════════════════════════
# 14) BMI differs by operand on STATISTICS: weight 60 -> Avg "18.5", NOT "24.7".
#     A second operand proves Statistics recomputes rather than showing a constant.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_bmi_60",))
def test_stats_bmi_60():
    ok_setup, got = user_with_weight("60")
    if not ok_setup:
        record("computation_stats_bmi_60", False,
               f"setup_failed: could not enter weight 60 (dialog held {got!r})",
               depth=2, jump_kind="value", expect="18.5")
        return
    if not and_reach_statistics():
        record("computation_stats_bmi_60", False,
               "setup_failed: could not reach the Statistics screen",
               depth=2, jump_kind="value", expect="18.5")
        return
    val = stat_value("BMI", "Avg")
    ok = _norm(val) == "18.5"
    record("computation_stats_bmi_60", ok,
           "" if ok else f"behavior_wrong: Statistics BMI Avg not '18.5' for weight 60; saw {val!r}",
           depth=2, jump_kind="value", expect="18.5")


# ══════════════════════════════════════════════════════════════════════════════
# 15) NumberInputDialog stepper: Increase raises the field by the step (+0.1).
#     depth 2 (New Measurement -> Weight dialog). A dump-readable value transition.
#     cd on the stepper is 'Increase ' (trailing space) -> match with find_node_ci.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stepper_increase",))
def test_stepper_increase():
    if not create_user():
        record("computation_stepper_increase", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="80.1")
        return
    if not and_enter_new_measurement():
        record("computation_stepper_increase", False,
               "setup_failed: could not open New Measurement",
               depth=2, jump_kind="value", expect="80.1")
        return
    if not and_enter_weight_dialog():
        record("computation_stepper_increase", False,
               "setup_failed: could not open the Edit Weight dialog",
               depth=2, jump_kind="value", expect="80.1")
        return
    before = set_dialog_value("80")     # normalise the field to a known 80
    if before != "80":
        record("computation_stepper_increase", False,
               f"setup_failed: dialog field did not hold '80' before stepping (held {before!r})",
               depth=2, jump_kind="value", expect="80.1")
        return
    inc = find_node_ci(ui(), "Increase")   # cd is 'Increase ' (trailing space)
    if inc is None or not tap_node(inc):
        record("computation_stepper_increase", False,
               "feature_missing: no 'Increase' stepper in the dialog",
               depth=2, jump_kind="value", expect="80.1")
        return
    settle("tap")
    after = dialog_field_value()
    ok = _norm(after) == "80.1"
    record("computation_stepper_increase", ok,
           "" if ok else f"behavior_wrong: Increase did not step 80 -> 80.1; field now {after!r}",
           depth=2, jump_kind="value", expect="80.1")


# ══════════════════════════════════════════════════════════════════════════════
# 16) NumberInputDialog stepper: Decrease lowers the field by the step.
#     From a known 80 -> Decrease -> "79.9". Pairs the positive (Increase) with
#     the opposite operation.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stepper_decrease",))
def test_stepper_decrease():
    if not create_user():
        record("computation_stepper_decrease", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="79.9")
        return
    if not and_enter_new_measurement():
        record("computation_stepper_decrease", False,
               "setup_failed: could not open New Measurement",
               depth=2, jump_kind="value", expect="79.9")
        return
    if not and_enter_weight_dialog():
        record("computation_stepper_decrease", False,
               "setup_failed: could not open the Edit Weight dialog",
               depth=2, jump_kind="value", expect="79.9")
        return
    before = set_dialog_value("80")
    if before != "80":
        record("computation_stepper_decrease", False,
               f"setup_failed: dialog field did not hold '80' before stepping (held {before!r})",
               depth=2, jump_kind="value", expect="79.9")
        return
    dec = find_node_ci(ui(), "Decrease")   # cd is 'Decrease ' (trailing space)
    if dec is None or not tap_node(dec):
        record("computation_stepper_decrease", False,
               "feature_missing: no 'Decrease' stepper in the dialog",
               depth=2, jump_kind="value", expect="79.9")
        return
    settle("tap")
    after = dialog_field_value()
    ok = _norm(after) == "79.9"
    record("computation_stepper_decrease", ok,
           "" if ok else f"behavior_wrong: Decrease did not step 80 -> 79.9; field now {after!r}",
           depth=2, jump_kind="value", expect="79.9")


# ══════════════════════════════════════════════════════════════════════════════
# 17) Multi-digit numeric ENTRY round-trip: the proven recipe must land "100"
#     verbatim in the dialog field (openScale's own input path -> field value).
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_input_roundtrip_100",))
def test_input_roundtrip_100():
    if not create_user():
        record("computation_input_roundtrip_100", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="100")
        return
    if not and_enter_new_measurement():
        record("computation_input_roundtrip_100", False,
               "setup_failed: could not open New Measurement",
               depth=2, jump_kind="value", expect="100")
        return
    if not and_enter_weight_dialog():
        record("computation_input_roundtrip_100", False,
               "setup_failed: could not open the Edit Weight dialog",
               depth=2, jump_kind="value", expect="100")
        return
    got = set_dialog_value("100")
    ok = got == "100"
    record("computation_input_roundtrip_100", ok,
           "" if ok else f"behavior_wrong: entering '100' left the field {got!r}",
           depth=2, jump_kind="value", expect="100")


# ══════════════════════════════════════════════════════════════════════════════
# 18) Weight unit context: the Weight NumberInputDialog shows the "kg" unit label.
#     The unit is the context the computed weight is echoed in (Overview "80 kg").
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_weight_unit_kg",))
def test_weight_unit_kg():
    if not create_user():
        record("computation_weight_unit_kg", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="kg")
        return
    if not and_enter_new_measurement():
        record("computation_weight_unit_kg", False,
               "setup_failed: could not open New Measurement",
               depth=2, jump_kind="value", expect="kg")
        return
    if not and_enter_weight_dialog():
        record("computation_weight_unit_kg", False,
               "setup_failed: could not open the Edit Weight dialog",
               depth=2, jump_kind="value", expect="kg")
        return
    has_kg = find_node(ui(), text="kg") is not None
    record("computation_weight_unit_kg", has_kg,
           "" if has_kg else "behavior_wrong: Weight dialog does not show the 'kg' unit label",
           depth=2, jump_kind="value", expect="kg")


# ══════════════════════════════════════════════════════════════════════════════
# 19) BMI is ABSENT before a measurement exists, PRESENT after (positive+negative
#     pair): on the fresh 'No Measurements Yet' Overview there is no '24.7'; after
#     saving weight 80 there is.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_bmi_absent_then_present",))
def test_bmi_absent_then_present():
    if not create_user():
        record("computation_bmi_absent_then_present", False,
               "setup_failed: could not create the prerequisite user",
               depth=1, jump_kind="value", expect="24.7 absent-then-present")
        return
    # BEFORE: no measurement -> the derived BMI value must be absent.
    before_texts = [n.get("text", "").strip() for n in ui()]
    bmi_before = any(_norm(t) == "24.7" for t in before_texts)
    got = add_weight_measurement("80")
    if got != "80":
        record("computation_bmi_absent_then_present", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="24.7 absent-then-present")
        return
    after_texts = overview_card_texts()
    bmi_after = any(_norm(t) == "24.7" for t in after_texts)
    ok = (not bmi_before) and bmi_after
    record("computation_bmi_absent_then_present", ok,
           "" if ok else (f"behavior_wrong: BMI '24.7' before={bmi_before} after={bmi_after} "
                          f"(expected absent then present)"),
           depth=1, jump_kind="value", expect="24.7 absent-then-present")


# ══════════════════════════════════════════════════════════════════════════════
# 20) TALLER user -> LOWER BMI for the same weight. Height 200 with weight 80
#     -> "20" (OBSERVED: openScale drops the trailing .0 for a whole-number BMI,
#     80/(2.0^2)=20 renders as "20"). Proves height feeds the derivation.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_bmi_height_200",))
def test_bmi_height_200():
    ok_setup, got = user_with_weight("80", height="200")
    if not ok_setup:
        record("computation_bmi_height_200", False,
               f"setup_failed: could not create user h=200 / weight 80 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="20")
        return
    texts = overview_card_texts()
    # BMI "20" (whole number, no trailing .0).
    present = any(_norm(t) == "20" for t in texts)
    # negative: the height-180 answer 24.7 must NOT appear.
    wrong = any(_norm(t) == "24.7" for t in texts)
    ok = present and not wrong
    record("computation_bmi_height_200", ok,
           "" if ok else f"behavior_wrong: BMI for h=200,w=80 not '20'; saw {texts!r}",
           depth=1, jump_kind="value", expect="20")


TESTS = [
    test_bmi_80_overview,
    test_bmi_60_overview,
    test_bmi_100_overview,
    test_weight_echo_overview,
    test_stats_bmi_min,
    test_stats_bmi_max,
    test_stats_bmi_avg,
    test_stats_bmr_min,
    test_stats_bmr_avg,
    test_stats_tdee_min,
    test_stats_tdee_avg,
    test_stats_weight_min,
    test_stats_weight_avg,
    test_stats_bmi_60,
    test_stepper_increase,
    test_stepper_decrease,
    test_input_roundtrip_100,
    test_weight_unit_kg,
    test_bmi_absent_then_present,
    test_bmi_height_200,
]

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