File size: 30,515 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
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403

# ══════════════════════════════════════════════════════════════════════════════
# NAVIGATION module — surface REACHABILITY + back-stack integrity for openScale.
#
# openScale is a Jetpack Compose single-Activity app. Navigation is a
# ModalNavigationDrawer opened via the "Open menu" hamburger, with items
# Overview / Charts / Table / Statistics / Insights / Settings; Settings is a
# sub-menu (General, User, Measurement Types, Bluetooth, Chart, Data Management,
# About). Every screen carries a TopAppBar title. Surfaces are Compose screens,
# discriminated with and_showing()/and_reach() (never activities).
#
# A reach is PROVEN, not assumed: the TARGET surface's element APPEARED and the
# SOURCE surface's element DISAPPEARED. All navigation happens inside one live
# app session; the process relaunch that seeds a clean entry point lives ONLY in
# the setup helpers (_fresh_overview_*), never in a test body, so the depth
# auditor never sees a reach achieved by relaunching.
#
# Discriminating keys below were observed empirically on the running original:
#   Overview (empty)  : "No User Active"/"Add User"; toolbar "Setup Bluetooth scale"
#   Overview (user)   : "No Measurements Yet"/"Add Measurement"
#   Overview (data)   : "80 kg", "24.7", "Drag to resize the chart..."
#   Drawer open       : "openScale" header, cd="Close navigation menu", "App Logo"
#   Charts            : "All Days (1 entries)", cd="Time range icon"
#   Table             : "Date"/"Weight" headers, cd="Select items"
#   Statistics        : "Min: 80 kg"/"Avg: 24.7", "BMR", "TDEE"
#   Insights          : "Your Weekly Habits", "Your Body Composition"
#   Settings          : rows "Data Management", "Measurement Types" (menu)
#   General           : "Dynamic colors", "High contrast", "Language"
#   Chart (settings)  : "Show data points", "Smoothing Algorithm"
#   Measurement Types : cd="On right Y-axis", cd="Pinned", cd="Lean Body Mass Formula"
#   About             : "Software license details", "Project on GitHub"
#   User (settings)   : "Users", cd="Add new user", cd="Edit user"
#   New Measurement   : title "New Measurement", cd="Save measurement", cd="Edit Weight"
#   Edit Weight dialog: "Edit Weight", "Input value", "Clear"/"Cancel"/"OK"
#   Table select mode : "0 selected", cd="Cancel selection", cd="Delete selected items"
# ══════════════════════════════════════════════════════════════════════════════

TESTS = []


def _register(fn):
    TESTS.append(fn)
    return fn


# ── shared setup helpers (SETUP only — never called inside a reach's snapshot) ──

def _open_menu():
    """Tap the TopAppBar hamburger to open the ModalNavigationDrawer."""
    m = find_node(ui(), content_desc="Open menu")
    if m:
        tap_node(m)
        settle("tap")
    return m is not None


def and_enter_user():
    """SETUP: create a user from the first-run empty state (Name + Height, Save).
    Returns True once Overview shows the 'No Measurements Yet' / 'Add Measurement'
    state (or already-populated data)."""
    nodes = ui()
    if find_node_ci(nodes, "No Measurements Yet") or find_node_ci(nodes, "80 kg"):
        return True                                   # user already exists
    add = find_node_ci(nodes, "Add User")
    if not add:
        return False
    tap_node(add)
    settle("launch")
    ets = find_by_class(ui(), "EditText")
    if len(ets) < 2:
        return False
    tap_node(ets[0]); settle("keyboard")              # Name
    for ch in "Alex":
        adb_shell("input", "text", ch); settle("text")
    settle("text")
    ets = find_by_class(ui(), "EditText")
    tap_node(ets[1]); settle("keyboard")              # Height
    for ch in "180":
        adb_shell("input", "text", ch); settle("text")
    settle("text")
    nodes = ui()
    save = find_node(nodes, content_desc="Save") or find_node_ci(nodes, "Save")
    if not save:
        s = get_screen_info()
        cands = [b for b in nodes
                 if b.get("clickable") == "true" and b.get("_center")
                 and b["_center"][0] > s["width"] * 0.75
                 and b["_center"][1] < s["height"] * 0.18]
        save = cands[0] if cands else None
    if not save:
        return False
    tap_node(save)
    settle("launch")
    return find_node_ci(ui(), "No Measurements Yet") is not None \
        or find_node_ci(ui(), "80 kg") is not None


def _set_dialog_value(val):
    """A NumberInputDialog is open. Clear, then type one char at a time (the
    field APPENDS and races focus otherwise). Returns the field's text."""
    c = find_node_ci(ui(), "Clear")
    if c:
        tap_node(c); settle("keyboard")
    ets = find_by_class(ui(), "EditText")
    if not ets:
        return ""
    tap_node(ets[0]); settle("keyboard"); settle("keyboard")
    for ch in str(val):
        adb_shell("input", "text", ch); settle("text")
    settle("text")
    ets = find_by_class(ui(), "EditText")
    return ets[0].get("text", "") if ets else ""


def and_enter_measurement():
    """SETUP: from Overview (user exists) create one measurement of Weight 80.
    Returns True once Overview shows the saved '80 kg' card."""
    nodes = ui()
    if find_node_ci(nodes, "80 kg"):
        return True                                   # a measurement already exists
    trigger = find_node_ci(nodes, "Add Measurement") \
        or find_node(nodes, content_desc="Add new measurement")
    if not trigger:
        return False
    tap_node(trigger)
    settle("launch")
    ew = find_node(ui(), content_desc="Edit Weight")
    if ew:
        tap_node(ew); settle("tap")
        _set_dialog_value("80")
        ok = find_node_ci(ui(), "OK")
        if ok:
            tap_node(ok); settle("tap")
    sm = find_node(ui(), content_desc="Save measurement")
    if not sm:
        return False
    tap_node(sm)
    settle("launch")
    return find_node_ci(ui(), "80 kg") is not None


def _fresh_overview_with_user():
    """SETUP: clean-launch to an Overview that has a user (empty measurements ok).
    Kept in a helper so the process relaunch never appears in a test body (the
    depth auditor treats an in-body relaunch as non-navigation)."""
    restart_app()
    wait_for_foreground()
    settle("launch")
    if not device_online():
        return False
    return and_enter_user()


def _fresh_overview_with_data():
    """SETUP: clean-launch to a populated Overview (user + one measurement)."""
    if not _fresh_overview_with_user():
        return False
    return and_enter_measurement()


# ── depth-family reach helpers (the and_reach_* NAME is what backs depth) ──────

def and_reach_drawer_dest(dest_cd, target_key, source_key):
    """Open the drawer, tap a destination item, PROVE the reach.
    before = drawer-open snapshot (source_key='Close navigation menu' lives here
    and must vanish); target_key is a destination element absent from the drawer.
    Returns (ok, note). Backs depth via and_reach_surface."""
    if not _open_menu():
        return False, "setup_failed: Open menu hamburger not found"
    node = find_node(ui(), content_desc=dest_cd) or find_node_ci(ui(), dest_cd)
    if not node:
        return False, f"setup_failed: drawer item '{dest_cd}' not found"
    ok = and_reach_surface(node, target_key, source_key)
    return ok, "" if ok else (f"behavior_wrong: '{target_key}' did not appear or "
                              f"'{source_key}' still present after tapping {dest_cd}")


def and_reach_settings_sub(sub_cd, target_key, source_key="Data Management"):
    """From the Settings menu, tap a sub-row and PROVE the sub-screen appeared and
    the Settings menu (source_key) left. Assumes Settings is already showing."""
    node = find_node(ui(), content_desc=sub_cd) or find_node_ci(ui(), sub_cd)
    if not node:
        return False, f"setup_failed: Settings row '{sub_cd}' not found"
    ok = and_reach_surface(node, target_key, source_key)
    return ok, "" if ok else (f"behavior_wrong: '{target_key}' not reached or "
                              f"Settings menu still present after tapping {sub_cd}")


def and_reach_new_measurement():
    """From Overview, tap 'Add new measurement' and PROVE New Measurement appeared
    (cd='Save measurement') and the Overview empty-state ('Setup Bluetooth scale')
    left. Assumes a populated/empty Overview is showing."""
    trigger = find_node(ui(), content_desc="Add new measurement")
    if not trigger:
        return False, "setup_failed: 'Add new measurement' toolbar action not found"
    ok = and_reach_surface(trigger, "Save measurement", "Setup Bluetooth scale")
    return ok, "" if ok else ("behavior_wrong: New Measurement not reached "
                              "(Save measurement absent / Setup Bluetooth scale kept)")


def and_reach_edit_weight_dialog():
    """From New Measurement, tap 'Edit Weight' and PROVE the NumberInputDialog
    appeared ('Input value') and the screen's Save action ('Save measurement')
    left the tree. Assumes New Measurement is showing."""
    ew = find_node(ui(), content_desc="Edit Weight")
    if not ew:
        return False, "setup_failed: 'Edit Weight' row action not found"
    ok = and_reach_surface(ew, "Input value", "Save measurement")
    return ok, "" if ok else ("behavior_wrong: Edit Weight dialog not reached "
                              "(Input value absent / Save measurement still in tree)")


def and_reach_table_select():
    """From Table, tap 'Select items' and PROVE selection mode appeared
    ('0 selected') and the 'Select items' action left. Assumes Table is showing."""
    si = find_node(ui(), content_desc="Select items")
    if not si:
        return False, "setup_failed: 'Select items' action not found on Table"
    ok = and_reach_surface(si, "0 selected", "Select items")
    return ok, "" if ok else ("behavior_wrong: selection mode not reached "
                              "('0 selected' absent / 'Select items' still present)")


# Shared SETUP steps that reach a hub surface WITHIN the live session. Each does
# exactly one and_reach (via and_reach_drawer_dest) so a chain that then reaches
# a sub-surface measures the true depth of 2. Named _reach_* so the depth family
# recognises the backing call.

def _reach_settings_then():
    """drawer -> Settings, proven by a reach. True when the Settings menu is up."""
    ok, _ = and_reach_drawer_dest("Settings", "Data Management", "Close navigation menu")
    return ok


def _reach_table_then():
    """drawer -> Table, proven by a reach. True when the 'Select items' action is up."""
    ok, _ = and_reach_drawer_dest("Table", "Select items", "Close navigation menu")
    return ok


# ══════════════════════════════════════════════════════════════════════════════
# 1. Drawer host: opening the navigation sheet (shape delta, single none record)
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_drawer_host_opens",))
def test_drawer_host_opens():
    ok = _fresh_overview_with_data()
    changed = False
    if ok:
        before = and_showing()
        _open_menu()
        after = and_showing()
        # The drawer sheet adds its own identity (header + close handle) that the
        # bare Overview never has; that is the host appearing.
        changed = surface_changed(before, after) \
            and find_node(ui(), content_desc="Close navigation menu") is not None \
            and find_node_ci(ui(), "openScale") is not None
    record("nav_drawer_host_opens", ok and changed,
           "" if (ok and changed) else
           ("setup_failed: could not reach a populated Overview" if not ok
            else "feature_missing: navigation drawer host did not open"),
           depth=0, jump_kind="none",
           expect="Drawer sheet ('openScale' header + 'Close navigation menu') "
                  "overlays Overview after tapping the hamburger")


# ══════════════════════════════════════════════════════════════════════════════
# 2. Each top-level drawer destination reached from Overview (depth=1, reach)
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_reach_charts", "nav_reach_charts_vlm"))
def test_reach_charts():
    setup = _fresh_overview_with_data()
    ok, note = (and_reach_drawer_dest("Charts", "All Days", "Close navigation menu")
                if setup else (False, "setup_failed: no populated Overview"))
    record("nav_reach_charts", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="Charts surface ('All Days (1 entries)') shown; drawer's "
                  "'Close navigation menu' handle gone")
    vlm_assert("nav_reach_charts",
               "Does this screen show a data chart or graph area with a "
               "horizontal axis of dates (e.g. 2 Aug, 3 Aug) below it?",
               RESULTS_DIR, tag="layout", depth=1, jump_kind="reach")


@_register
@and_test(expects=("nav_reach_table",))
def test_reach_table():
    setup = _fresh_overview_with_data()
    ok, note = (and_reach_drawer_dest("Table", "Select items", "Close navigation menu")
                if setup else (False, "setup_failed: no populated Overview"))
    record("nav_reach_table", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="Table surface (cd='Select items' action) shown; drawer's "
                  "'Close navigation menu' handle gone")


@_register
@and_test(expects=("nav_reach_statistics", "nav_reach_statistics_vlm"))
def test_reach_statistics():
    setup = _fresh_overview_with_data()
    ok, note = (and_reach_drawer_dest("Statistics", "Min: 80 kg", "Close navigation menu")
                if setup else (False, "setup_failed: no populated Overview"))
    record("nav_reach_statistics", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="Statistics surface ('Min: 80 kg' stat) shown; drawer's "
                  "'Close navigation menu' handle gone")
    vlm_assert("nav_reach_statistics",
               "On each metric card of this screen, is the coloured circular icon "
               "positioned on the LEFT edge of the card and the Min/Max/Avg "
               "statistics text aligned to the RIGHT edge?",
               RESULTS_DIR, tag="position", depth=1, jump_kind="reach")


@_register
@and_test(expects=("nav_reach_insights",))
def test_reach_insights():
    setup = _fresh_overview_with_data()
    ok, note = (and_reach_drawer_dest("Insights", "Your Weekly Habits",
                                      "Close navigation menu")
                if setup else (False, "setup_failed: no populated Overview"))
    record("nav_reach_insights", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="Insights surface ('Your Weekly Habits' card) shown; drawer's "
                  "'Close navigation menu' handle gone")


@_register
@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm"))
def test_reach_settings():
    setup = _fresh_overview_with_data()
    ok, note = (and_reach_drawer_dest("Settings", "Data Management",
                                      "Close navigation menu")
                if setup else (False, "setup_failed: no populated Overview"))
    record("nav_reach_settings", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="Settings menu ('Data Management' row) shown; drawer's "
                  "'Close navigation menu' handle gone")
    vlm_assert("nav_reach_settings",
               "Is a settings screen showing a vertical list of labelled rows "
               "(General, User, Measurement Types, Bluetooth, Chart, ...), each "
               "with a small icon to the LEFT of its text label?",
               RESULTS_DIR, tag="position", depth=1, jump_kind="reach")


# ══════════════════════════════════════════════════════════════════════════════
# 3. Return to Overview from another destination (depth=1, reach)
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_return_overview",))
def test_return_to_overview():
    setup = _fresh_overview_with_data()
    ok = False
    note = "setup_failed: no populated Overview"
    if setup:
        # Leave Overview for Charts first...
        reached, note = and_reach_drawer_dest("Charts", "All Days",
                                              "Close navigation menu")
        if reached:
            # ...then drawer -> Overview and prove Overview came back. The
            # drawer-open snapshot (source) holds 'Close navigation menu', which
            # is gone once the Overview surface (with its toolbar) is restored.
            ok, note = and_reach_drawer_dest("Overview", "Setup Bluetooth scale",
                                             "Close navigation menu")
    record("nav_return_overview", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="Overview restored (toolbar 'Setup Bluetooth scale' back after "
                  "leaving to Charts); drawer 'Close navigation menu' handle gone")


# ══════════════════════════════════════════════════════════════════════════════
# 4. Overview -> New Measurement (depth=1, reach)
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_reach_new_measurement", "nav_reach_new_measurement_vlm"))
def test_reach_new_measurement():
    # Only a user is required (an empty Overview still has the toolbar action). The
    # relaunch stays inside _fresh_overview_with_user() so this body is pure nav.
    setup = _fresh_overview_with_user()
    ok, note = (and_reach_new_measurement() if setup
                else (False, "setup_failed: could not create a user"))
    record("nav_reach_new_measurement", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="New Measurement surface (cd='Save measurement') shown; "
                  "Overview toolbar 'Setup Bluetooth scale' gone")
    vlm_assert("nav_reach_new_measurement",
               "On this measurement-entry screen, does each editable metric row "
               "have a pair of stacked up-arrow and down-arrow stepper buttons on "
               "the RIGHT side of the row?",
               RESULTS_DIR, tag="position", depth=1, jump_kind="reach")


# ══════════════════════════════════════════════════════════════════════════════
# 5. Depth-2 chain: Overview -> New Measurement -> Edit Weight dialog
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_chain_edit_weight_dialog",))
def test_chain_edit_weight_dialog():
    setup = _fresh_overview_with_user()
    ok = False
    note = "setup_failed: could not create a user"
    if setup:
        r1, note = and_reach_new_measurement()          # hop 1
        if r1:
            r2, note = and_reach_edit_weight_dialog()    # hop 2
            ok = r2
    record("nav_chain_edit_weight_dialog", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="After Overview->New Measurement->Edit Weight, the dialog "
                  "('Input value') is up and 'Save measurement' left the tree")


# ══════════════════════════════════════════════════════════════════════════════
# 6. Depth-2 chains: Overview -> Settings -> each sub-screen
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_chain_settings_general", "nav_chain_settings_general_vlm"))
def test_chain_settings_general():
    setup = _fresh_overview_with_data() and _reach_settings_then()
    ok, note = (and_reach_settings_sub("General", "Dynamic colors")
                if setup else (False, "setup_failed: Settings menu not reached"))
    record("nav_chain_settings_general", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="Overview->Settings->General: 'Dynamic colors' toggle shown; "
                  "Settings 'Data Management' row gone")
    vlm_assert("nav_chain_settings_general",
               "Is there a left-pointing back arrow at the TOP-LEFT of the toolbar "
               "on this screen (to the left of the screen title)?",
               RESULTS_DIR, tag="position", depth=2, jump_kind="reach")


@_register
@and_test(expects=("nav_chain_settings_chart",))
def test_chain_settings_chart():
    setup = _fresh_overview_with_data() and _reach_settings_then()
    ok, note = (and_reach_settings_sub("Chart", "Show data points")
                if setup else (False, "setup_failed: Settings menu not reached"))
    record("nav_chain_settings_chart", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="Overview->Settings->Chart: 'Show data points' toggle shown; "
                  "Settings 'Data Management' row gone")


@_register
@and_test(expects=("nav_chain_settings_types",))
def test_chain_settings_types():
    setup = _fresh_overview_with_data() and _reach_settings_then()
    ok, note = (and_reach_settings_sub("Measurement Types", "On right Y-axis")
                if setup else (False, "setup_failed: Settings menu not reached"))
    record("nav_chain_settings_types", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="Overview->Settings->Measurement Types: cd='On right Y-axis' "
                  "shown; Settings 'Data Management' row gone")


@_register
@and_test(expects=("nav_chain_settings_about",))
def test_chain_settings_about():
    setup = _fresh_overview_with_data() and _reach_settings_then()
    ok, note = (and_reach_settings_sub("About", "Software license details")
                if setup else (False, "setup_failed: Settings menu not reached"))
    record("nav_chain_settings_about", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="Overview->Settings->About: 'Software license details' shown; "
                  "Settings 'Data Management' row gone")


# ══════════════════════════════════════════════════════════════════════════════
# 7. Depth-2 chain: Overview -> Settings -> User (user list surface)
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_chain_settings_user",))
def test_chain_settings_user():
    setup = _fresh_overview_with_data() and _reach_settings_then()
    ok, note = (and_reach_settings_sub("User", "Users")
                if setup else (False, "setup_failed: Settings menu not reached"))
    record("nav_chain_settings_user", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="Overview->Settings->User: 'Users' list ('Add new user') shown; "
                  "Settings 'Data Management' row gone")


# ══════════════════════════════════════════════════════════════════════════════
# 8. Back-stack integrity: Settings -> General, then BACK returns to Settings
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_backstack_general_to_settings",))
def test_backstack_general_to_settings():
    setup = _fresh_overview_with_data() and _reach_settings_then()
    ok = False
    note = "setup_failed: Settings menu not reached"
    if setup:
        entered, note = and_reach_settings_sub("General", "Dynamic colors")
        if entered:
            before = and_showing()                       # General surface
            and_back()                                   # pop one surface
            after = and_showing()
            # Returned to Settings: the menu row reappears, General content leaves.
            ok = and_reach(before, after, "Data Management", "Dynamic colors")
            note = ("" if ok else
                    "behavior_wrong: BACK from General did not restore the "
                    "Settings menu")
    record("nav_backstack_general_to_settings", ok, "" if ok else note,
           depth=1, jump_kind="reach",
           expect="One BACK from General restores the Settings menu "
                  "('Data Management' back, 'Dynamic colors' gone)")


# ══════════════════════════════════════════════════════════════════════════════
# 9. Back-stack unwind: Overview -> Settings -> General, BACK,BACK -> Overview
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_backstack_unwind_to_overview",))
def test_backstack_unwind_to_overview():
    setup = _fresh_overview_with_data() and _reach_settings_then()
    hop2 = False
    at_settings = False
    at_overview = False
    note = "setup_failed: Settings menu not reached"
    if setup:
        entered, note = and_reach_settings_sub("General", "Dynamic colors")  # hop 2
        hop2 = entered
        if hop2:
            b1 = and_showing()
            and_back()                                   # General -> Settings
            a1 = and_showing()
            at_settings = and_reach(b1, a1, "Data Management", "Dynamic colors")
            b2 = and_showing()
            and_back()                                   # Settings -> Overview
            a2 = and_showing()
            at_overview = and_reach(b2, a2, "Setup Bluetooth scale", "Data Management")
            note = ("" if (at_settings and at_overview) else
                    "behavior_wrong: back stack did not unwind Settings->General "
                    "hop by hop to Overview")
    ok = hop2 and at_settings and at_overview
    record("nav_backstack_unwind_to_overview", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="From General, BACK->Settings ('Data Management' back) then "
                  "BACK->Overview ('Setup Bluetooth scale' back)")


# ══════════════════════════════════════════════════════════════════════════════
# 10. Depth-2 chain: Overview -> Table -> Select-items (contextual) mode
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("nav_chain_table_select", "nav_chain_table_select_vlm"))
def test_chain_table_select():
    setup = _fresh_overview_with_data() and _reach_table_then()
    ok, note = (and_reach_table_select()
                if setup else (False, "setup_failed: Table surface not reached"))
    record("nav_chain_table_select", ok, "" if ok else note,
           depth=2, jump_kind="reach",
           expect="Overview->Table->Select items: contextual bar '0 selected' "
                  "shown; the 'Select items' action left the toolbar")
    vlm_assert("nav_chain_table_select",
               "Is there a contextual action bar across the TOP of the screen "
               "showing a '0 selected' style count on the left and action icons "
               "(such as a trash/delete icon and a close X) on the right?",
               RESULTS_DIR, tag="layout", depth=2, jump_kind="reach")


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