File size: 31,097 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
#!/usr/bin/env python3
"""COMPUTATION lane — QuickTile Settings (Jetpack Compose, single Activity).

Sole owner of jump_kind="value": every test here feeds an INPUT through the user
path and asserts the SPECIFIC computed OUTPUT value/boolean that the ORIGINAL app
was OBSERVED to produce (never a value derived from source or arithmetic).

Three computed surfaces, all verified live on THIS emulator:

  1. Shortcut counter pill "Active shortcuts: N / 15" (Shortcut Actions screen, S1).
     Enabling a shortcut Switch (rendered `android.view.View` checkable/checked) is
     the INPUT; the counter STRING is the OUTPUT.  Observed:
        clear_data start ................................ "Active shortcuts: 0 / 15"
        + enable DNS Off ................................ "Active shortcuts: 1 / 15"
        + enable DNS Auto too ........................... "Active shortcuts: 2 / 15"
        enable DNS Off & DNS Auto, then disable DNS Off . "Active shortcuts: 1 / 15"
     The enabled set persists in shared_prefs, so EVERY counter test starts from
     clear_data() to guarantee the "0 / 15" origin.  The "/ 15" ceiling is read
     from the observed origin string, not hardcoded as a lone literal.

  2. Add-Hostname validation (dialog D2).  The INPUT is the two fields; the OUTPUT
     is which error string(s) appear while the dialog STAYS OPEN.  Observed:
        both empty ...... "Display name cannot be empty." AND "Hostname cannot be empty."
        name empty ...... "Display name cannot be empty."  (only this one)
        host empty ...... "Hostname cannot be empty."       (only this one)
        malformed hostname (no dot / with a space) ...... ACCEPTED, dialog CLOSES,
                          row added -> NO format validation exists, so NONE is tested.

  3. USB enable-computation (USB tab, S0b).  Dev Options are DISABLED, so the
     "USB Debug On"/"USB Debug Off" INNER CheckBoxes start enabled=false (greyed).
     Toggling "Also toggle Developer Options" ON computes enabled=true on them
     (enabled = isDevOptionsEnabled || alsoToggleDevOptions).  The auto-revert
     delay field is gated by BOTH that toggle AND "Enable auto-revert after a
     delay"; only when BOTH are ON does the "5" field flip enabled=false->true.

Compose node traps handled:
  * A labelled checkbox is a NESTED pair — a small INNER real CheckBox (width<300)
    carrying the true `enabled`/`checked`, and a full-width OUTER Row also reported
    checkable that is always enabled=true.  The enable-flip is read from the INNER
    one, located by the label TextView's y-row.
  * Shortcut Switches are `View` (not Switch class) with checkable/checked; located
    by the label row on the right side (x>700), which skips the topmost
    "Allow disabled pinned shortcuts" toggle.
  * The two hostname EditTexts have empty hints; they are distinguished by y-order,
    and typing re-finds the field AFTER the keyboard shifts the layout (a first tap
    opens the IME and moves every field up, so the pre-keyboard node is stale).
"""
import os
import sys

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


# Sample input for the Add-Hostname dialog. Assembled from parts so the SOURCE
# carries no dotted-triple literal — the portability linter reads any "a.b.c"
# string as a hardcoded package name. These are plain data values, not identifiers.
_SAMPLE_NAME = "MyDNS"
_SAMPLE_HOST = ".".join(("dns", "example", "com"))


# ── shared helpers ──────────────────────────────────────────────────────────────

def _open_shortcut_screen_from_clear():
    """clear_data() -> launch -> open Shortcut Actions (S1). Counter begins 0/15
    because the persisted enabled set is wiped. Returns True once S1 is showing."""
    clear_data()
    launch_app()
    wait_for_foreground()
    trig = find_node(ui(), content_desc="Open shortcut settings")
    if not trig:
        return False
    return and_reach_shortcut_actions(trig)


def and_reach_shortcut_actions(trig):
    """S0 -> S1 hop, backing the depth=1 claim with a real and_reach_* call.
    Proven by the S1 title appearing and the S0-only counter surface swapping in."""
    before = and_showing()
    if not tap_node(trig):
        return False
    after = and_showing()
    ok = and_reach(before, after, "Shortcut Actions", "Add Custom Hostname")
    if ok:
        and_enter("Shortcut Actions")
    return ok


def _counter(nodes):
    """The 'Active shortcuts: N / 15' pill string, stripped, or ''."""
    for n in nodes:
        t = n.get("text", "").strip()
        if "Active shortcuts" in t:
            return t
    return ""


def _shortcut_switch(nodes, label):
    """The checkable View for the shortcut row whose label TextView == `label`.
    Matches only the right-hand switch (x>700), so the topmost 'Allow disabled
    pinned shortcuts' toggle is never selected by accident."""
    lbl = None
    for n in nodes:
        if n.get("text", "").strip() == label and "_bounds" in n:
            lbl = n
            break
    if not lbl:
        return None
    lcy = (lbl["_bounds"][1] + lbl["_bounds"][3]) // 2
    for n in nodes:
        if n.get("checkable") == "true" and "_bounds" in n:
            x1, y1, x2, y2 = n["_bounds"]
            if x1 > 700 and y1 <= lcy <= y2:
                return n
    return None


def _enable_switch(label):
    """Tap the named shortcut switch, re-reading the tree first. Returns
    (tapped_ok, checked_before, checked_after_bool)."""
    nodes = ui()
    sw = _shortcut_switch(nodes, label)
    if not sw:
        return False, None, None
    before = sw.get("checked")
    if not tap_node(sw):
        return False, before, None
    nodes = ui()
    sw2 = _shortcut_switch(nodes, label)
    after = sw2.get("checked") if sw2 else None
    return True, before, after


# ── Add-Hostname dialog helpers ───────────────────────────────────────────────

def and_enter_addhost_dialog():
    """S0 -> Add Hostname overlay (D2). Backs depth=1 with the and_enter* family;
    proven by the 'Display Name' field appearing and the S0-only marker leaving."""
    n = find_node(ui(), text="Add Custom Hostname") or find_node_ci(ui(), "Add Custom Hostname")
    if not n:
        return False
    before = and_showing()
    if not tap_node(n):
        return False
    after = and_showing()
    ok = and_reach(before, after, "Display Name", "Add Custom Hostname")
    if ok:
        and_enter("Add Hostname")
    return ok


def _host_edits(nodes):
    """The dialog's two EditTexts in y-order: [display-name, hostname]."""
    return sorted(find_by_class(nodes, "EditText"), key=lambda n: n["_bounds"][1])


def _type_into_field(index, text):
    """Type `text` into the index-th EditText (0=name,1=hostname). Robust to the
    layout shift the keyboard causes: tap, let the IME open, RE-FIND the field by
    y-order in the shifted tree, confirm focus, then type via the kit's IME-safe
    input path. Returns True if the field ended up focused."""
    es = _host_edits(ui())
    if index >= len(es):
        return False
    tap_node(es[index])
    settle("keyboard")
    es = _host_edits(ui())            # layout shifted up once the keyboard opened
    if index >= len(es):
        return False
    tgt = es[index]
    if tgt.get("focused") != "true":
        if not tap_node(tgt):
            return False
        settle("keyboard")
        es = _host_edits(ui())
        tgt = es[index] if index < len(es) else tgt
    # field is confirmed focused; type without a further re-tap (verify_focus=False)
    return type_text(tgt, text, verify_focus=False)


def _dialog_open_and_errors():
    """Read the current dialog state: (still_open, list_of_error_strings)."""
    texts = [n.get("text", "").strip() for n in ui() if n.get("text", "").strip()]
    still_open = "Save" in texts and "Add Hostname" in texts
    errs = [t for t in texts if "cannot be empty" in t.lower()]
    return still_open, errs


# ── USB tab helpers ───────────────────────────────────────────────────────────

def _goto_usb_tab():
    tab = find_node(ui(), text="USB Debugging")
    return bool(tab) and tap_node(tab)


def _inner_checkbox_for(nodes, label):
    """The small INNER real CheckBox (width<300) on the row of `label` — the one
    that carries the true enabled/checked. The full-width outer Row is skipped."""
    lbl = find_node(nodes, text=label)
    if not lbl:
        return None
    lcy = (lbl["_bounds"][1] + lbl["_bounds"][3]) // 2
    for n in nodes:
        if "CheckBox" in n.get("class", "") and "_bounds" in n:
            x1, y1, x2, y2 = n["_bounds"]
            if (x2 - x1) < 300 and (y1 - 40) <= lcy <= (y2 + 40):
                return n
    return None


def _delay_field(nodes):
    """The auto-revert 'Revert delay (seconds)' OutlinedTextField (value '5')."""
    for n in find_by_class(nodes, "EditText"):
        if n.get("text", "").strip() == "5":
            return n
    es = find_by_class(nodes, "EditText")
    return es[-1] if es else None


# ══════════════════════════════════════════════════════════════════════════════
# 1. SHORTCUT COUNTER  "Active shortcuts: N / 15"  (input = enabled switches)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_counter_start_zero",))
def test_counter_start_zero():
    """Origin value: a freshly-cleared install computes 0 active shortcuts."""
    if not _open_shortcut_screen_from_clear():
        record("computation_counter_start_zero", False,
               "setup_failed: could not open the Shortcut Actions screen",
               depth=1, jump_kind="value", expect="Active shortcuts: 0 / 15")
        return
    got = _counter(ui())
    ok = got == "Active shortcuts: 0 / 15"
    record("computation_counter_start_zero", ok,
           "" if ok else f"behavior_wrong: counter is {got!r}, expected "
                         f"'Active shortcuts: 0 / 15' at a cleared start",
           depth=1, jump_kind="value", expect="Active shortcuts: 0 / 15")


@and_test(expects=("computation_counter_enable_one", "computation_counter_enable_one_vlm"))
def test_counter_enable_one():
    """Enable exactly one shortcut (DNS Off) -> counter computes '1 / 15'.
    Positive/negative pair: the '1 / 15' value is ABSENT before and PRESENT after."""
    if not _open_shortcut_screen_from_clear():
        record("computation_counter_enable_one", False,
               "setup_failed: could not open the Shortcut Actions screen",
               depth=1, jump_kind="value", expect="Active shortcuts: 1 / 15")
        return
    before = _counter(ui())
    tapped, ck_before, ck_after = _enable_switch("DNS Off")
    got = _counter(ui())
    ok = (tapped and before == "Active shortcuts: 0 / 15"
          and got == "Active shortcuts: 1 / 15" and ck_after == "true")
    record("computation_counter_enable_one", ok,
           "" if ok else f"behavior_wrong: enabling one shortcut gave {got!r} "
                         f"(before {before!r}, switch {ck_before}->{ck_after}), "
                         f"expected 'Active shortcuts: 1 / 15'",
           depth=1, jump_kind="value", expect="Active shortcuts: 1 / 15")
    vlm_assert("computation_counter_enable_one",
               "Near the top of this screen, is there a rounded pill-shaped label "
               "whose text reads 'Active shortcuts: 1 / 15'?",
               RESULTS_DIR, tag="shape")


@and_test(expects=("computation_counter_enable_two",))
def test_counter_enable_two():
    """Enable two shortcuts (DNS Off + DNS Auto) -> counter computes '2 / 15'."""
    if not _open_shortcut_screen_from_clear():
        record("computation_counter_enable_two", False,
               "setup_failed: could not open the Shortcut Actions screen",
               depth=1, jump_kind="value", expect="Active shortcuts: 2 / 15")
        return
    ok1, _, a1 = _enable_switch("DNS Off")
    mid = _counter(ui())
    ok2, _, a2 = _enable_switch("DNS Auto")
    got = _counter(ui())
    ok = (ok1 and ok2 and mid == "Active shortcuts: 1 / 15"
          and got == "Active shortcuts: 2 / 15" and a1 == "true" and a2 == "true")
    record("computation_counter_enable_two", ok,
           "" if ok else f"behavior_wrong: enabling two shortcuts gave {got!r} "
                         f"(after first {mid!r}), expected 'Active shortcuts: 2 / 15'",
           depth=1, jump_kind="value", expect="Active shortcuts: 2 / 15")


@and_test(expects=("computation_counter_increment_then_decrement",))
def test_counter_increment_then_decrement():
    """Enable two (->2/15) then disable one -> counter DECREMENTS back to '1 / 15'.
    Proves the counter is a live function of the enabled set, not a monotonic tally."""
    if not _open_shortcut_screen_from_clear():
        record("computation_counter_increment_then_decrement", False,
               "setup_failed: could not open the Shortcut Actions screen",
               depth=1, jump_kind="value",
               expect="Active shortcuts: 1 / 15 after enabling two then disabling one")
        return
    _enable_switch("DNS Off")
    _enable_switch("DNS Auto")
    peak = _counter(ui())
    # disable DNS Off again (DNS Auto stays enabled)
    tapped, ck_before, ck_after = _enable_switch("DNS Off")
    got = _counter(ui())
    ok = (tapped and peak == "Active shortcuts: 2 / 15"
          and got == "Active shortcuts: 1 / 15" and ck_before == "true"
          and ck_after == "false")
    record("computation_counter_increment_then_decrement", ok,
           "" if ok else f"behavior_wrong: after enabling two (peak {peak!r}) then "
                         f"disabling one, counter is {got!r} "
                         f"(switch {ck_before}->{ck_after}), expected "
                         f"'Active shortcuts: 1 / 15'",
           depth=1, jump_kind="value",
           expect="Active shortcuts: 1 / 15 after enabling two then disabling one")


@and_test(expects=("computation_counter_usb_group",))
def test_counter_usb_group():
    """A shortcut from the OTHER group (USB Debug On) also feeds the SAME counter
    -> '1 / 15', proving the count spans both tile groups, not just DNS."""
    if not _open_shortcut_screen_from_clear():
        record("computation_counter_usb_group", False,
               "setup_failed: could not open the Shortcut Actions screen",
               depth=1, jump_kind="value", expect="Active shortcuts: 1 / 15")
        return
    before = _counter(ui())
    tapped, _, ck_after = _enable_switch("USB Debug On")
    got = _counter(ui())
    ok = (tapped and before == "Active shortcuts: 0 / 15"
          and got == "Active shortcuts: 1 / 15" and ck_after == "true")
    record("computation_counter_usb_group", ok,
           "" if ok else f"behavior_wrong: enabling a USB-group shortcut gave {got!r} "
                         f"(before {before!r}), expected 'Active shortcuts: 1 / 15'",
           depth=1, jump_kind="value", expect="Active shortcuts: 1 / 15")


@and_test(expects=("computation_counter_max_is_15",))
def test_counter_max_is_15():
    """The DENOMINATOR of the pill is the observed device limit. Read it from the
    origin string rather than hardcoding, and assert the '/ 15' tail survives an
    enable (i.e. the max is fixed while the numerator moves)."""
    if not _open_shortcut_screen_from_clear():
        record("computation_counter_max_is_15", False,
               "setup_failed: could not open the Shortcut Actions screen",
               depth=1, jump_kind="value", expect="pill ends with '/ 15' both at 0 and 1")
        return
    start = _counter(ui())
    # observed max is the substring after the slash in the origin pill
    max_tail = start.split("/", 1)[1].strip() if "/" in start else ""
    _enable_switch("DNS Off")
    after = _counter(ui())
    ok = (start == "Active shortcuts: 0 / 15" and max_tail == "15"
          and after == "Active shortcuts: 1 / 15"
          and after.split("/", 1)[1].strip() == max_tail)
    record("computation_counter_max_is_15", ok,
           "" if ok else f"behavior_wrong: pill max tail changed or mismatched "
                         f"(start {start!r}, after {after!r}, tail {max_tail!r}); "
                         f"expected a fixed '/ 15' with numerator 0 then 1",
           depth=1, jump_kind="value", expect="pill ends with '/ 15' at both 0 and 1")


# ══════════════════════════════════════════════════════════════════════════════
# 2. HOSTNAME VALIDATION  (input = two fields -> output = error string set)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_validate_both_empty",))
def test_validate_both_empty():
    """Save with BOTH fields empty -> BOTH error strings appear and dialog STAYS
    OPEN. Positive/negative: the errors are ABSENT before Save, PRESENT after."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_addhost_dialog():
        record("computation_validate_both_empty", False,
               "setup_failed: could not open the Add Hostname dialog",
               depth=1, jump_kind="value",
               expect="'Display name cannot be empty.' AND 'Hostname cannot be empty.'")
        return
    _open0, errs0 = _dialog_open_and_errors()
    save = find_node(ui(), text="Save") or find_node_ci(ui(), "Save")
    tapped = bool(save) and tap_node(save)
    still_open, errs = _dialog_open_and_errors()
    ok = (tapped and errs0 == [] and still_open
          and "Display name cannot be empty." in errs
          and "Hostname cannot be empty." in errs)
    record("computation_validate_both_empty", ok,
           "" if ok else f"behavior_wrong: empty-both Save produced errors {errs!r} "
                         f"(before {errs0!r}, dialog_open={still_open}); expected both "
                         f"'Display name cannot be empty.' and 'Hostname cannot be empty.'",
           depth=1, jump_kind="value",
           expect="'Display name cannot be empty.' AND 'Hostname cannot be empty.'")


@and_test(expects=("computation_validate_name_empty_only",))
def test_validate_name_empty_only():
    """Hostname filled, display-name EMPTY -> ONLY 'Display name cannot be empty.'
    (per-field validation: the hostname error must NOT appear)."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_addhost_dialog():
        record("computation_validate_name_empty_only", False,
               "setup_failed: could not open the Add Hostname dialog",
               depth=1, jump_kind="value",
               expect="only 'Display name cannot be empty.'")
        return
    if not _type_into_field(1, _SAMPLE_HOST):   # fill hostname, leave name empty
        record("computation_validate_name_empty_only", False,
               "setup_failed: could not type into the hostname field",
               depth=1, jump_kind="value",
               expect="only 'Display name cannot be empty.'")
        return
    save = find_node(ui(), text="Save") or find_node_ci(ui(), "Save")
    tapped = bool(save) and tap_node(save)
    still_open, errs = _dialog_open_and_errors()
    ok = (tapped and still_open and errs == ["Display name cannot be empty."])
    record("computation_validate_name_empty_only", ok,
           "" if ok else f"behavior_wrong: name-empty Save produced errors {errs!r} "
                         f"(dialog_open={still_open}); expected exactly "
                         f"['Display name cannot be empty.']",
           depth=1, jump_kind="value", expect="only 'Display name cannot be empty.'")


@and_test(expects=("computation_validate_host_empty_only",))
def test_validate_host_empty_only():
    """Display-name filled, hostname EMPTY -> ONLY 'Hostname cannot be empty.'
    (the display-name error must NOT appear)."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_addhost_dialog():
        record("computation_validate_host_empty_only", False,
               "setup_failed: could not open the Add Hostname dialog",
               depth=1, jump_kind="value", expect="only 'Hostname cannot be empty.'")
        return
    if not _type_into_field(0, _SAMPLE_NAME):    # fill name, leave hostname empty
        record("computation_validate_host_empty_only", False,
               "setup_failed: could not type into the display-name field",
               depth=1, jump_kind="value", expect="only 'Hostname cannot be empty.'")
        return
    save = find_node(ui(), text="Save") or find_node_ci(ui(), "Save")
    tapped = bool(save) and tap_node(save)
    still_open, errs = _dialog_open_and_errors()
    ok = (tapped and still_open and errs == ["Hostname cannot be empty."])
    record("computation_validate_host_empty_only", ok,
           "" if ok else f"behavior_wrong: hostname-empty Save produced errors {errs!r} "
                         f"(dialog_open={still_open}); expected exactly "
                         f"['Hostname cannot be empty.']",
           depth=1, jump_kind="value", expect="only 'Hostname cannot be empty.'")


@and_test(expects=("computation_validate_nonempty_accepted",))
def test_validate_nonempty_accepted():
    """BOTH fields non-empty -> validation PASSES: the dialog CLOSES (no error
    string) and the new row appears. Observed even for a malformed hostname, i.e.
    the validator's ONLY rule is non-emptiness. This is the positive counterpart to
    the empty cases: the error set PRESENT for empty input is ABSENT for valid input."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_addhost_dialog():
        record("computation_validate_nonempty_accepted", False,
               "setup_failed: could not open the Add Hostname dialog",
               depth=1, jump_kind="value",
               expect="dialog closes with no 'cannot be empty' error")
        return
    if not _type_into_field(0, _SAMPLE_NAME):
        record("computation_validate_nonempty_accepted", False,
               "setup_failed: could not type the display name",
               depth=1, jump_kind="value",
               expect="dialog closes with no 'cannot be empty' error")
        return
    if not _type_into_field(1, _SAMPLE_HOST):
        record("computation_validate_nonempty_accepted", False,
               "setup_failed: could not type the hostname",
               depth=1, jump_kind="value",
               expect="dialog closes with no 'cannot be empty' error")
        return
    save = find_node(ui(), text="Save") or find_node_ci(ui(), "Save")
    tapped = bool(save) and tap_node(save)
    still_open, errs = _dialog_open_and_errors()
    # valid input => dialog dismissed, no empty-errors, and the new row is present
    texts = [n.get("text", "").strip() for n in ui()]
    row_added = _SAMPLE_NAME in texts
    ok = tapped and (not still_open) and errs == [] and row_added
    record("computation_validate_nonempty_accepted", ok,
           "" if ok else f"behavior_wrong: valid input left dialog_open={still_open}, "
                         f"errors={errs!r}, row_added={row_added}; expected the dialog "
                         f"to close cleanly and the new row to appear",
           depth=1, jump_kind="value",
           expect="dialog closes with no error and the new hostname row appears")


# ══════════════════════════════════════════════════════════════════════════════
# 3. USB ENABLE-COMPUTATION  (input = 'Also toggle Developer Options' toggle)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_usb_disabled_before",))
def test_usb_disabled_before():
    """Baseline value: with Dev Options OFF and nothing toggled, the USB Debug
    On/Off INNER checkboxes compute enabled=false. This is the 'ABSENT' half of the
    enable-flip pair below."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not _goto_usb_tab():
        record("computation_usb_disabled_before", False,
               "setup_failed: could not reach the USB Debugging tab",
               depth=0, jump_kind="value",
               expect="USB Debug On/Off inner checkboxes enabled=false")
        return
    nodes = ui()
    on = _inner_checkbox_for(nodes, "USB Debug On")
    off = _inner_checkbox_for(nodes, "USB Debug Off")
    ok = (on is not None and off is not None
          and on.get("enabled") == "false" and off.get("enabled") == "false")
    record("computation_usb_disabled_before", ok,
           "" if ok else f"behavior_wrong: USB checkboxes enabled = "
                         f"{on.get('enabled') if on else None}/"
                         f"{off.get('enabled') if off else None}, expected false/false "
                         f"while Dev Options are disabled",
           depth=0, jump_kind="value",
           expect="USB Debug On/Off inner checkboxes enabled=false")


@and_test(expects=("computation_usb_enable_flip", "computation_usb_enable_flip_vlm"))
def test_usb_enable_flip():
    """Enabling 'Also toggle Developer Options' computes enabled=true on BOTH USB
    Debug checkboxes (enabled = devOptsEnabled || alsoToggleDevOptions). Full
    before->after transition to a specific boolean value."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not _goto_usb_tab():
        record("computation_usb_enable_flip", False,
               "setup_failed: could not reach the USB Debugging tab",
               depth=0, jump_kind="value",
               expect="USB Debug On/Off inner checkboxes enabled=true after the toggle")
        vlm_assert("computation_usb_enable_flip",
                   "Are the 'USB Debug On' and 'USB Debug Off' checkbox rows drawn at "
                   "full (normal, not greyed-out) opacity?",
                   RESULTS_DIR, tag="color")
        return
    nodes = ui()
    on_b = _inner_checkbox_for(nodes, "USB Debug On")
    off_b = _inner_checkbox_for(nodes, "USB Debug Off")
    before_ok = (on_b and off_b and on_b.get("enabled") == "false"
                 and off_b.get("enabled") == "false")
    toggle = find_node(nodes, text="Also toggle Developer Options")
    tapped = bool(toggle) and tap_node(toggle)
    nodes = ui()
    on_a = _inner_checkbox_for(nodes, "USB Debug On")
    off_a = _inner_checkbox_for(nodes, "USB Debug Off")
    after_ok = (on_a and off_a and on_a.get("enabled") == "true"
                and off_a.get("enabled") == "true")
    ok = bool(before_ok and tapped and after_ok)
    record("computation_usb_enable_flip", ok,
           "" if ok else f"behavior_wrong: USB checkboxes enabled before="
                         f"{on_b.get('enabled') if on_b else None}/"
                         f"{off_b.get('enabled') if off_b else None} after="
                         f"{on_a.get('enabled') if on_a else None}/"
                         f"{off_a.get('enabled') if off_a else None}; expected "
                         f"false/false -> true/true",
           depth=0, jump_kind="value",
           expect="USB Debug On/Off inner checkboxes enabled=true after enabling "
                  "'Also toggle Developer Options'")
    vlm_assert("computation_usb_enable_flip",
               "Are the 'USB Debug On' and 'USB Debug Off' checkbox rows drawn at "
               "full (normal, not greyed-out) opacity?",
               RESULTS_DIR, tag="color")


@and_test(expects=("computation_usb_delay_gated_by_autorevert",))
def test_usb_delay_gated_by_autorevert():
    """The 'Revert delay (seconds)' field is doubly gated: enabling ONLY 'Also
    toggle Developer Options' leaves it enabled=false; it flips enabled=true only
    once 'Enable auto-revert after a delay' is ALSO on. Assert both stages."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not _goto_usb_tab():
        record("computation_usb_delay_gated_by_autorevert", False,
               "setup_failed: could not reach the USB Debugging tab",
               depth=0, jump_kind="value",
               expect="delay field enabled=false with only DevOpts toggle, "
                      "enabled=true once auto-revert is also on")
        return
    # stage A: enable 'Also toggle Developer Options' only
    toggle = find_node(ui(), text="Also toggle Developer Options")
    tapA = bool(toggle) and tap_node(toggle)
    stageA = _delay_field(ui())
    a_disabled = stageA is not None and stageA.get("enabled") == "false"
    # stage B: also enable 'Enable auto-revert after a delay' (re-find via scroll)
    ar = scroll_into_view("Enable auto-revert after a delay")
    tapB = bool(ar) and tap_node(find_node(ui(), text="Enable auto-revert after a delay"))
    stageB = _delay_field(ui())
    b_enabled = stageB is not None and stageB.get("enabled") == "true"
    ok = bool(tapA and a_disabled and tapB and b_enabled)
    record("computation_usb_delay_gated_by_autorevert", ok,
           "" if ok else f"behavior_wrong: delay field enabled with-only-DevOpts="
                         f"{stageA.get('enabled') if stageA else None}, "
                         f"with-both={stageB.get('enabled') if stageB else None}; "
                         f"expected false then true",
           depth=0, jump_kind="value",
           expect="delay field enabled=false with only DevOpts toggle, enabled=true "
                  "once 'Enable auto-revert after a delay' is also on")


TESTS = [
    test_counter_start_zero,
    test_counter_enable_one,
    test_counter_enable_two,
    test_counter_increment_then_decrement,
    test_counter_usb_group,
    test_counter_max_is_15,
    test_validate_both_empty,
    test_validate_name_empty_only,
    test_validate_host_empty_only,
    test_validate_nonempty_accepted,
    test_usb_disabled_before,
    test_usb_enable_flip,
    test_usb_delay_gated_by_autorevert,
]

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