File size: 38,333 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
#!/usr/bin/env python3
"""INTERACTION module for openScale (a body-weight / health tracker).

EFFECT-BY-CONSEQUENCE on USER DATA: CRUD lifecycle, multi-step sequences,
multi-record integrity, DATA persistence across process death, and the
long-press / context-menu style selection sequence. Every test drives the app
to a surface via the user path, performs the action, then reads the consequence
back out of a fresh ui() and asserts it equals what was observed on the original.

Run:
    python3 test_android_interaction.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 helpers ───────────────────────────────────────────────────────
# depth is backed by the and_enter_* NAMES below (the depth auditor descends into
# file-local helpers that call and_enter()).

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 button or
    the top-bar '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_edit_measurement():
    """From the Overview, open the Edit Measurement screen of the first entry via
    its cd='Edit measurement from <date>'."""
    em = [n for n in ui() if n.get("content-desc", "").startswith("Edit measurement from")]
    if not em or not tap_node(em[0]):
        return False
    settle("launch")
    and_enter("edit_measurement")
    return True


def and_enter_weight_dialog():
    """From the New/Edit Measurement screen, open the Edit Weight NumberInputDialog."""
    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_drawer_dest(cd_label):
    """Open the nav drawer (cd='Open menu') and tap a destination by content-desc."""
    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=cd_label) or find_node_ci(ui(), cd_label)
    if dest is None or not tap_node(dest):
        return False
    settle("launch")
    and_enter(cd_label)
    return True


def and_enter_select_mode():
    """From the Table screen, enter selection mode (cd='Select items')."""
    n = find_node(ui(), content_desc="Select items")
    if n is None or not tap_node(n):
        return False
    settle("launch")
    and_enter("select_mode")
    return True


# The PROVEN reliable numeric-entry recipe (copied 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 verify the
# returned field text == str(val).
def set_dialog_value(val):            # a NumberInputDialog must be open
    c = find_node_ci(ui(), "Clear")
    if c:
        tap_node(c)
        settle("keyboard")
    et = find_by_class(ui(), "EditText")[0]
    tap_node(et)
    settle("keyboard")
    settle("keyboard")                # let focus settle
    for ch in str(val):
        adb_shell("input", "text", ch)
        settle("text")                # ONE char at a time
    settle("text")
    return find_by_class(ui(), "EditText")[0].get("text", "")


def create_user(height="180", name="TestUser"):
    """clear_data() -> launch -> fill Name+Height -> Save. Returns True on success.
    Uses and_enter_user_form() so the surface cross is backed."""
    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 True


def add_measurement(weight):
    """From the Overview (user must exist): open New Measurement, set Weight via the
    proven recipe, OK, Save measurement. Returns True iff the dialog held the value."""
    if not and_enter_new_measurement():
        return False
    if not and_enter_weight_dialog():
        return False
    got = set_dialog_value(weight)
    ok_btn = find_node_ci(ui(), "OK")
    if ok_btn:
        tap_node(ok_btn)
        settle("tap")
    sm = find_node(ui(), content_desc="Save measurement")
    if sm:
        tap_node(sm)
        settle("launch")
    return got == str(weight)


def weight_row_texts():
    """On the New/Edit Measurement screen, the value texts on the Weight row (e.g.
    ['80.1 kg'])."""
    nodes = ui()
    lab = find_node(nodes, text="Weight")
    if not lab:
        return []
    wb = lab.get("_bounds", (0, 0, 0, 0))
    return [m.get("text", "") for m in nodes
            if m.get("text", "").strip() and m is not lab
            and abs(m.get("_bounds", (0, 0, 0, 0))[1] - wb[1]) < 160]


def has_text(marker):
    return find_node_ci(ui(), marker) is not None


# ══════════════════════════════════════════════════════════════════════════════
# 1) CREATE USER — from the virgin 'No User Active' state.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_create_user",
                   "interaction_create_user_form_vlm"))
def test_create_user():
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    absent_before = has_text("No User Active")
    if not and_enter_user_form():
        record("interaction_create_user", False,
               "feature_missing: no 'Add User' control on the No-User surface",
               depth=1, jump_kind="value", expect="Overview drops 'No User Active'")
        record("interaction_create_user_form_vlm", False,
               "setup_failed: never reached the Add-User form",
               depth=1, jump_kind="value", tag="layout")
        return
    # VLM on the form surface — is the Name input field rendered above the Height field?
    vlm_assert("interaction_create_user_form",
               "Is there a text input field labelled 'Name' and, below it, a field "
               "labelled 'Height' with a 'CM' unit indicator on its right side?",
               depth=1, jump_kind="value", tag="position")
    ets = sorted(find_by_class(ui(), "EditText"), key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    if len(ets) < 2:
        record("interaction_create_user", False,
               "setup_failed: fewer than 2 EditText on the Add-User form",
               depth=1, jump_kind="value", expect="Overview drops 'No User Active'")
        return
    type_text(ets[0], "TestUser")
    settle("text")
    ets = sorted(find_by_class(ui(), "EditText"), key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    type_text(ets[1], "180")
    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:
        record("interaction_create_user", False,
               "setup_failed: no top-right Save button on the Add-User form",
               depth=1, jump_kind="value", expect="Overview drops 'No User Active'")
        return
    tap_node(btns[0])
    settle("launch")
    nodes = ui()
    no_user_gone = find_node_ci(nodes, "No User Active") is None
    empty_meas = (find_node_ci(nodes, "No Measurements Yet") is not None
                  or find_node_ci(nodes, "Add Measurement") is not None)
    ok = absent_before and no_user_gone and empty_meas
    record("interaction_create_user", ok,
           "" if ok else "behavior_wrong: user not created (Overview still 'No User "
                          "Active' or missing the empty-measurement state)",
           depth=1, jump_kind="value",
           expect="user created; Overview shows 'No Measurements Yet'/'Add Measurement'")


# ══════════════════════════════════════════════════════════════════════════════
# 2) CREATE FIRST MEASUREMENT — Overview shows a card with '80 kg'.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_create_measurement",
                   "interaction_create_measurement_chart_vlm",
                   "interaction_create_measurement_card_vlm"))
def test_create_measurement():
    if not create_user():
        record("interaction_create_measurement", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="Overview card shows '80 kg'")
        record("interaction_create_measurement_chart_vlm", False,
               "setup_failed: no user", depth=2, jump_kind="value", tag="content")
        record("interaction_create_measurement_card_vlm", False,
               "setup_failed: no user", depth=2, jump_kind="value", tag="layout")
        return
    absent_before = has_text("80 kg")
    if not add_measurement("80"):
        record("interaction_create_measurement", False,
               "behavior_wrong: measurement entry (Weight=80) not saved via the "
               "New Measurement -> Edit Weight dialog path",
               depth=2, jump_kind="value", expect="Overview card shows '80 kg'")
        record("interaction_create_measurement_chart_vlm", False,
               "setup_failed: measurement not saved", depth=2, jump_kind="value", tag="content")
        record("interaction_create_measurement_card_vlm", False,
               "setup_failed: measurement not saved", depth=2, jump_kind="value", tag="layout")
        return
    nodes = ui()
    present_after = find_node_ci(nodes, "80 kg") is not None
    ok = (not absent_before) and present_after
    record("interaction_create_measurement", ok,
           "" if ok else "behavior_wrong: Overview card does not show '80 kg' after save",
           depth=2, jump_kind="value", expect="Overview card shows '80 kg'")
    # VLM: after saving, the chart area now shows a plotted data point (was empty before).
    vlm_assert("interaction_create_measurement_chart",
               "Does the chart / graph area near the top of the screen show at least "
               "one plotted data point or line, rather than a completely empty chart?",
               depth=2, jump_kind="value", tag="content")
    # VLM: the entry is presented as a card grouping the date with the value rows,
    # with a trash (delete) and pencil (edit) icon in the top-right of the card.
    vlm_assert("interaction_create_measurement_card",
               "In the measurement card, are the trash-can (delete) icon and the "
               "pencil (edit) icon positioned in the TOP-RIGHT corner of the card, to "
               "the right of the date heading?",
               depth=2, jump_kind="value", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 3) MULTI-RECORD INTEGRITY — add 2 measurements; both survive & are ordered.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_multi_record_integrity",
                   "interaction_multi_record_stacked_vlm"))
def test_multi_record_integrity():
    if not create_user():
        record("interaction_multi_record_integrity", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="two entries (80 kg & 70 kg) both present")
        record("interaction_multi_record_stacked_vlm", False,
               "setup_failed: no user", depth=2, jump_kind="value", tag="layout")
        return
    ok1 = add_measurement("80")
    ok2 = add_measurement("70")
    nodes = ui()
    edits = [n.get("content-desc") for n in nodes
             if n.get("content-desc", "").startswith("Edit measurement from")]
    both_values = (find_node_ci(nodes, "80 kg") is not None
                   and find_node_ci(nodes, "70 kg") is not None)
    ok = ok1 and ok2 and len(edits) >= 2 and both_values
    record("interaction_multi_record_integrity", ok,
           "" if ok else f"behavior_wrong: expected >=2 entries with 80 kg & 70 kg, "
                         f"got {len(edits)} edit-cards, 80={find_node_ci(nodes, '80 kg') is not None}, "
                         f"70={find_node_ci(nodes, '70 kg') is not None} (a recreation that "
                         f"keeps only one row fails here)",
           depth=2, jump_kind="value",
           expect="two entries (80 kg & 70 kg) both present as separate cards")
    # VLM: the Overview now shows multiple stacked entry cards.
    vlm_assert("interaction_multi_record_stacked",
               "Are there at least two separate measurement cards arranged one ABOVE "
               "the other (stacked vertically), each with its own date heading and a "
               "'Weight' value?",
               depth=2, jump_kind="value", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 4) EDIT A MEASUREMENT VALUE — 80 -> 90; Overview shows 90 kg, not 80 kg.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_edit_measurement",
                   "interaction_edit_measurement_value_vlm"))
def test_edit_measurement():
    if not create_user():
        record("interaction_edit_measurement", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="card updated to '90 kg'")
        record("interaction_edit_measurement_value_vlm", False,
               "setup_failed: no user", depth=2, jump_kind="value", tag="content")
        return
    if not add_measurement("80"):
        record("interaction_edit_measurement", False,
               "setup_failed: could not create the base measurement (Weight=80)",
               depth=2, jump_kind="value", expect="card updated to '90 kg'")
        record("interaction_edit_measurement_value_vlm", False,
               "setup_failed: base measurement not saved", depth=2, jump_kind="value", tag="content")
        return
    # Overview -> Edit Measurement -> Edit Weight dialog -> set 90 -> OK -> Save.
    if not and_enter_edit_measurement():
        record("interaction_edit_measurement", False,
               "feature_missing: no 'Edit measurement from ...' control on the card",
               depth=2, jump_kind="value", expect="card updated to '90 kg'")
        record("interaction_edit_measurement_value_vlm", False,
               "setup_failed: could not open edit screen", depth=2, jump_kind="value", tag="content")
        return
    if not and_enter_weight_dialog():
        record("interaction_edit_measurement", False,
               "setup_failed: no 'Edit Weight' control on the Edit Measurement screen",
               depth=3, jump_kind="value", expect="card updated to '90 kg'")
        record("interaction_edit_measurement_value_vlm", False,
               "setup_failed: could not open weight dialog", depth=3, jump_kind="value", tag="content")
        return
    got = set_dialog_value("90")
    ok_btn = find_node_ci(ui(), "OK")
    if ok_btn:
        tap_node(ok_btn)
        settle("tap")
    sm = find_node(ui(), content_desc="Save measurement")
    if sm:
        tap_node(sm)
        settle("launch")
    nodes = ui()
    now_90 = find_node_ci(nodes, "90 kg") is not None
    no_80 = find_node_ci(nodes, "80 kg") is None
    ok = (got == "90") and now_90 and no_80
    record("interaction_edit_measurement", ok,
           "" if ok else f"behavior_wrong: edit 80->90 did not land "
                         f"(dialog held {got!r}, 90 kg={now_90}, 80 kg gone={no_80})",
           depth=3, jump_kind="value", expect="card updated to '90 kg' (no longer '80 kg')")
    # VLM: the card renders the updated value 90.
    vlm_assert("interaction_edit_measurement_value",
               "In the measurement card, does the Weight value read '90 kg'?",
               depth=3, jump_kind="value", tag="content")


# ══════════════════════════════════════════════════════════════════════════════
# 5) NUMBER-INPUT STEPPER — Increase/Decrease Weight shape the row value.
# The in-dialog stepper does not re-render its EditText text in the dump, but the
# New Measurement detail-row steppers (Increase Weight / Decrease Weight) do:
# 80 kg -> 80.1 -> back to 80.0. This is a data-shaping interaction on the input.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_stepper_value",
                   "interaction_stepper_dialog_vlm"))
def test_stepper_value():
    if not create_user():
        record("interaction_stepper_value", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="Weight row 80 -> 80.1 -> 80.0")
        record("interaction_stepper_dialog_vlm", False,
               "setup_failed: no user", depth=2, jump_kind="value", tag="layout")
        return
    if not and_enter_new_measurement():
        record("interaction_stepper_value", False,
               "feature_missing: no 'Add Measurement' control",
               depth=1, jump_kind="value", expect="Weight row 80 -> 80.1 -> 80.0")
        record("interaction_stepper_dialog_vlm", False,
               "setup_failed: no new-measurement screen", depth=1, jump_kind="value", tag="layout")
        return
    # Seed the weight to a known 80 via the dialog, then capture the dialog VLM.
    if not and_enter_weight_dialog():
        record("interaction_stepper_value", False,
               "setup_failed: no 'Edit Weight' control", depth=2, jump_kind="value",
               expect="Weight row 80 -> 80.1 -> 80.0")
        record("interaction_stepper_dialog_vlm", False,
               "setup_failed: no weight dialog", depth=2, jump_kind="value", tag="layout")
        return
    set_dialog_value("80")
    # VLM: the NumberInputDialog is a modal, centered dialog overlaying the screen,
    # with Clear / Cancel / OK buttons.
    vlm_assert("interaction_stepper_dialog",
               "Is a modal dialog box centered over a dimmed background, containing "
               "an input value field and three text buttons labelled 'Clear', "
               "'Cancel' and 'OK'?",
               depth=2, jump_kind="value", tag="position")
    ok_btn = find_node_ci(ui(), "OK")
    if ok_btn:
        tap_node(ok_btn)
        settle("tap")
    # Now on the New Measurement screen, exercise the row steppers.
    base = weight_row_texts()
    base_ok = any("80 kg" in t for t in base)
    inc = find_node(ui(), content_desc="Increase Weight")
    if inc is None or not tap_node(inc):
        record("interaction_stepper_value", False,
               "feature_missing: no 'Increase Weight' stepper on the row",
               depth=2, jump_kind="value", expect="Weight row 80 -> 80.1 -> 80.0")
        return
    settle("tap")
    after_inc = weight_row_texts()
    inc_ok = any("80.1 kg" in t for t in after_inc)
    dec = find_node(ui(), content_desc="Decrease Weight")
    dec_ok = False
    if dec is not None and tap_node(dec):
        settle("tap")
        after_dec = weight_row_texts()
        dec_ok = any(("80 kg" in t) or ("80.0 kg" in t) for t in after_dec)
    ok = base_ok and inc_ok and dec_ok
    record("interaction_stepper_value", ok,
           "" if ok else f"behavior_wrong: stepper did not shape the row value "
                         f"(base={base}, after_inc={after_inc}, dec_ok={dec_ok})",
           depth=2, jump_kind="value",
           expect="Weight row 80 kg -> 80.1 kg after Increase, back to 80.0/80 kg after Decrease")


# ══════════════════════════════════════════════════════════════════════════════
# 6) PERSISTENCE ACROSS PROCESS DEATH — THE key test.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_persist_process_death",))
def test_persist_process_death():
    if not create_user():
        record("interaction_persist_process_death", False,
               "setup_failed: could not create the prerequisite user",
               depth=0, jump_kind="value", expect="'80 kg' survives process kill")
        return
    if not add_measurement("80"):
        record("interaction_persist_process_death", False,
               "setup_failed: could not save the Weight=80 measurement",
               depth=0, jump_kind="value", expect="'80 kg' survives process kill")
        return
    # Confirm it is present BEFORE the kill (guards a false pass on a stale screen).
    present_before = has_text("80 kg")
    force_stop_and_relaunch()
    wait_for_foreground()
    settle("launch")
    nodes = ui()
    survives = find_node_ci(nodes, "80 kg") is not None
    no_user = find_node_ci(nodes, "No User Active") is not None
    no_meas = find_node_ci(nodes, "No Measurements Yet") is not None
    ok = present_before and survives and (not no_user) and (not no_meas)
    record("interaction_persist_process_death", ok,
           "" if ok else "behavior_wrong: saved measurement did NOT survive "
                         "force-stop + relaunch (an in-memory-only recreation fails here)",
           depth=0, jump_kind="value",
           expect="'80 kg' still shown after force-stop+relaunch; not 'No User Active'/'No Measurements Yet'")


# ══════════════════════════════════════════════════════════════════════════════
# 7) TABLE SELECTION SEQUENCE — 0 selected -> 1 selected -> cancel.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_table_selection",
                   "interaction_table_selection_highlight_vlm"))
def test_table_selection():
    if not create_user():
        record("interaction_table_selection", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="selection count 0 -> 1 then cancelled")
        record("interaction_table_selection_highlight_vlm", False,
               "setup_failed: no user", depth=2, jump_kind="value", tag="color")
        return
    if not add_measurement("80"):
        record("interaction_table_selection", False,
               "setup_failed: could not save a measurement to select",
               depth=2, jump_kind="value", expect="selection count 0 -> 1 then cancelled")
        record("interaction_table_selection_highlight_vlm", False,
               "setup_failed: no measurement", depth=2, jump_kind="value", tag="color")
        return
    if not and_reach_drawer_dest("Table"):
        record("interaction_table_selection", False,
               "setup_failed: could not reach the Table screen via the drawer",
               depth=1, jump_kind="value", expect="selection count 0 -> 1 then cancelled")
        record("interaction_table_selection_highlight_vlm", False,
               "setup_failed: no Table screen", depth=1, jump_kind="value", tag="color")
        return
    if not and_enter_select_mode():
        record("interaction_table_selection", False,
               "feature_missing: no 'Select items' control on the Table screen",
               depth=2, jump_kind="value", expect="selection count 0 -> 1 then cancelled")
        record("interaction_table_selection_highlight_vlm", False,
               "setup_failed: no select mode", depth=2, jump_kind="value", tag="color")
        return
    count0 = has_text("0 selected")
    # Toggle the DATA-ROW checkbox: the header holds a select-all checkbox at the
    # top, each data row a checkbox below it. Tapping the lowest checkbox (the data
    # row) reliably flips the count to '1 selected'. The checkbox column can lag a
    # frame behind entering select-mode, so poll a few fresh dumps for it first,
    # then retry the toggle once if the count does not flip.
    def data_row_checkboxes():
        return sorted([n for n in ui() if "CheckBox" in n.get("class", "")
                       and n.get("clickable") == "true"],
                      key=lambda c: c.get("_bounds", (0, 0, 0, 0))[1])

    def tap_data_row_checkbox():
        cbs = data_row_checkboxes()
        return safe_tap(cbs[-1]) if len(cbs) >= 2 else False

    for _ in range(4):
        if len(data_row_checkboxes()) >= 2:
            break
        settle("tap")
    tapped = tap_data_row_checkbox()
    settle("tap")
    count1 = has_text("1 selected")
    if tapped and not count1:
        tap_data_row_checkbox()          # a fresh-dump retry for a missed toggle
        settle("tap")
        count1 = has_text("1 selected")
    # VLM while a row is selected: exactly one measurement row is highlighted/checked.
    vlm_assert("interaction_table_selection_highlight",
               "In this table, is there a data row whose checkbox is filled with a "
               "coloured tick (checked) AND whose row background is a different "
               "(highlighted) colour from the white header area?",
               depth=2, jump_kind="transition", tag="color")
    # Cancel selection -> back to normal Table (Select items reappears, no 'selected').
    cancel = find_node(ui(), content_desc="Cancel selection")
    cancelled = False
    if cancel and tap_node(cancel):
        settle("launch")
        nn = ui()
        cancelled = (find_node(nn, content_desc="Select items") is not None
                     and find_node_ci(nn, "1 selected") is None)
    ok = count0 and tapped and count1 and cancelled
    record("interaction_table_selection", ok,
           "" if ok else f"behavior_wrong: selection sequence failed "
                         f"(0-sel={count0}, tapped={tapped}, 1-sel={count1}, cancelled={cancelled})",
           depth=2, jump_kind="value",
           expect="'0 selected' -> tap row -> '1 selected' -> Cancel -> normal Table")


# ══════════════════════════════════════════════════════════════════════════════
# 8) USER-FORM GENDER EDIT — Male -> Female persists in the field within session.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_gender_change",))
def test_gender_change():
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    if not and_enter_user_form():
        record("interaction_gender_change", False,
               "feature_missing: no 'Add User' control", depth=1, jump_kind="transition",
               expect="Gender field 'Male' -> 'Female'")
        return
    ets = sorted(find_by_class(ui(), "EditText"), key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    gender_before = [e for e in ets if e.get("text", "") == "Male"]
    before_ok = bool(gender_before)
    if not before_ok:
        record("interaction_gender_change", False,
               "setup_failed: Gender field did not start as 'Male'",
               depth=1, jump_kind="transition", expect="Gender field 'Male' -> 'Female'")
        return
    tap_node(gender_before[0])
    settle("tap")
    fem = find_node(ui(), text="Female") or find_node_ci(ui(), "Female")
    picked = fem is not None and tap_node(fem)
    settle("tap")
    ets = sorted(find_by_class(ui(), "EditText"), key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    now_female = any(e.get("text", "") == "Female"
                     and 900 < e.get("_bounds", (0, 0, 0, 0))[1] < 1200 for e in ets)
    no_male = not any(e.get("text", "") == "Male" for e in ets)
    ok = before_ok and picked and now_female and no_male
    record("interaction_gender_change", ok,
           "" if ok else f"behavior_wrong: Gender did not flip Male->Female "
                         f"(picked={picked}, now_female={now_female}, no_male={no_male})",
           depth=1, jump_kind="transition", expect="Gender field 'Male' -> 'Female'")


# ══════════════════════════════════════════════════════════════════════════════
# 9) USER-FORM ACTIVITY-LEVEL EDIT — Sedentary -> Moderate persists in the field.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_activity_change",))
def test_activity_change():
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    if not and_enter_user_form():
        record("interaction_activity_change", False,
               "feature_missing: no 'Add User' control", depth=1, jump_kind="transition",
               expect="Activity Level 'Sedentary' -> 'Moderate'")
        return
    ets = sorted(find_by_class(ui(), "EditText"), key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    act = [e for e in ets if e.get("text", "") == "Sedentary"]
    before_ok = bool(act)
    if not before_ok:
        record("interaction_activity_change", False,
               "setup_failed: Activity Level did not start as 'Sedentary'",
               depth=1, jump_kind="transition", expect="Activity Level 'Sedentary' -> 'Moderate'")
        return
    tap_node(act[0])
    settle("tap")
    target = find_node(ui(), text="Moderate")
    picked = target is not None and tap_node(target)
    settle("tap")
    ets = sorted(find_by_class(ui(), "EditText"), key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    now_moderate = any(e.get("text", "") == "Moderate"
                       and 1150 < e.get("_bounds", (0, 0, 0, 0))[1] < 1450 for e in ets)
    no_sedentary = not any(e.get("text", "") == "Sedentary" for e in ets)
    ok = before_ok and picked and now_moderate and no_sedentary
    record("interaction_activity_change", ok,
           "" if ok else f"behavior_wrong: Activity Level did not change to Moderate "
                         f"(picked={picked}, now_moderate={now_moderate}, no_sedentary={no_sedentary})",
           depth=1, jump_kind="transition", expect="Activity Level 'Sedentary' -> 'Moderate'")


# ══════════════════════════════════════════════════════════════════════════════
# 10) EDIT PERSISTS ACROSS PROCESS DEATH — 80 -> 90, kill, 90 kg survives.
# A multi-step sequence (create -> edit -> kill) whose consequence is durable.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_edit_persists_death",))
def test_edit_persists_process_death():
    if not create_user():
        record("interaction_edit_persists_death", False,
               "setup_failed: could not create the prerequisite user",
               depth=0, jump_kind="value", expect="edited '90 kg' survives process kill")
        return
    if not add_measurement("80"):
        record("interaction_edit_persists_death", False,
               "setup_failed: could not save the base Weight=80 measurement",
               depth=0, jump_kind="value", expect="edited '90 kg' survives process kill")
        return
    if not and_enter_edit_measurement():
        record("interaction_edit_persists_death", False,
               "setup_failed: could not open the Edit Measurement screen",
               depth=2, jump_kind="value", expect="edited '90 kg' survives process kill")
        return
    if not and_enter_weight_dialog():
        record("interaction_edit_persists_death", False,
               "setup_failed: could not open the Edit Weight dialog",
               depth=3, jump_kind="value", expect="edited '90 kg' survives process kill")
        return
    got = set_dialog_value("90")
    ok_btn = find_node_ci(ui(), "OK")
    if ok_btn:
        tap_node(ok_btn)
        settle("tap")
    sm = find_node(ui(), content_desc="Save measurement")
    if sm:
        tap_node(sm)
        settle("launch")
    edited_before = has_text("90 kg")
    force_stop_and_relaunch()
    wait_for_foreground()
    settle("launch")
    nodes = ui()
    survives = find_node_ci(nodes, "90 kg") is not None
    old_gone = find_node_ci(nodes, "80 kg") is None
    ok = (got == "90") and edited_before and survives and old_gone
    record("interaction_edit_persists_death", ok,
           "" if ok else f"behavior_wrong: edited value did not persist across process "
                         f"death (dialog={got!r}, 90 kg after relaunch={survives}, 80 kg gone={old_gone})",
           depth=0, jump_kind="value",
           expect="edited '90 kg' still shown after force-stop+relaunch; not '80 kg'")


# ==============================================================================
# 11) USER PERSISTS ACROSS PROCESS DEATH - created user survives a kill (no
# measurement). Distinct durable-data check: the empty-measurement state proves
# the USER record was persisted, not the (absent) measurement.
# ==============================================================================
@and_test(expects=("interaction_user_persists_death",))
def test_user_persists_process_death():
    if not create_user():
        record("interaction_user_persists_death", False,
               "setup_failed: could not create the user",
               depth=0, jump_kind="value", expect="user survives kill; 'No User Active' absent")
        return
    # Right after creation the Overview must NOT say 'No User Active'.
    created_ok = not has_text("No User Active")
    force_stop_and_relaunch()
    wait_for_foreground()
    settle("launch")
    nodes = ui()
    no_user = find_node_ci(nodes, "No User Active") is not None
    empty_meas = (find_node_ci(nodes, "No Measurements Yet") is not None
                  or find_node_ci(nodes, "Add Measurement") is not None)
    ok = created_ok and (not no_user) and empty_meas
    record("interaction_user_persists_death", ok,
           "" if ok else "behavior_wrong: created user did not survive force-stop + "
                         "relaunch (Overview reverted to 'No User Active')",
           depth=0, jump_kind="value",
           expect="after relaunch: not 'No User Active'; shows the empty-measurement state")


TESTS = [
    test_create_user,
    test_create_measurement,
    test_multi_record_integrity,
    test_edit_measurement,
    test_stepper_value,
    test_persist_process_death,
    test_table_selection,
    test_gender_change,
    test_activity_change,
    test_edit_persists_process_death,
    test_user_persists_process_death,
]


if __name__ == "__main__":
    if not device_online():
        print("Device is not online — the adb tunnel may have dropped.")
        sys.exit(1)
    run_suite(TESTS, "interaction")