File size: 37,492 Bytes
51eaa60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
"""AX MENU tests for DB Browser for SQLite (Qt6) — generated from recon.md ## MENUS.

Every fact asserted here was OBSERVED on the reference app and recorded in recon.md
(`## MENUS`, `## AX_TREE`, `## STRUCTURE`, `## TEXT`, `## VISUAL`).

Locator contract: menus are ALWAYS scoped
    menu_bar_item -> find(role="menu", root_id=mbi.id, max_depth=1)
                  -> find(role="menu_item", root_id=menu.id, max_depth=1)
because a global find(role="menu_item") returns ~200 Apple-menu items.

Destructive items are NEVER pressed: Quit, Close Database, Delete Table..., Compact
Database..., Load Extension..., Enter Full Screen, any Window Layout item, any Help item,
New Database..., Open Database..., Open Project..., any Save..., any Import/Export leaf
(they raise native file panels that hang the test).
"""

import json
import os
import subprocess
import time

import pytest
import rb_testgen_kit as kit

RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__)))


def screenshot_assert(test_name, description, results_dir):
    ss_dir = os.path.join(results_dir, "screenshots")
    os.makedirs(ss_dir, exist_ok=True)
    ss_path = os.path.join(ss_dir, f"{test_name}.png")
    try:
        subprocess.run(["screencapture", "-x", ss_path], timeout=5)
    except Exception:
        pass
    assertions_file = os.path.join(ss_dir, "assertions.json")
    assertions = {}
    if os.path.exists(assertions_file):
        try:
            with open(assertions_file) as f:
                assertions = json.load(f)
        except Exception:
            assertions = {}
    assertions[f"{test_name}.png"] = description
    with open(assertions_file, "w") as f:
        json.dump(assertions, f, indent=2)


def _esc(times=1):
    for _ in range(times):
        subprocess.run(["osascript", "-e",
                        'tell application "System Events" to key code 53'],
                       capture_output=True)
        time.sleep(0.3)


def open_menu(ax, top):
    """Open a top-level app menu; returns its `menu` element or None."""
    mb = ax.find(role="menu_bar_item", name=top, max_results=1)
    if not mb:
        return None
    ax.action(mb[0].id, "AXPress")
    time.sleep(0.6)
    m = ax.find(role="menu", root_id=mb[0].id, max_results=1, max_depth=1)
    return m[0] if m else None


def items_of(ax, menu):
    return ax.find(role="menu_item", root_id=menu.id, max_results=80, max_depth=1)


def item_named(ax, menu, name):
    for it in items_of(ax, menu):
        if (it.name or "") == name:
            return it
    return None


def submenu_of(ax, item):
    m = ax.find(role="menu", root_id=item.id, max_results=1, max_depth=1)
    return m[0] if m else None


def item_attrs(ax, it):
    return ax.get(it.id, ["AXEnabled", "AXMenuItemMarkChar",
                          "AXMenuItemCmdChar", "AXMenuItemCmdModifiers"])


def rb_reach_menu_item(ax, top, item_name):
    """Open `top` and AXPress the menu item named exactly `item_name`."""
    m = open_menu(ax, top)
    if m is None:
        return False
    it = item_named(ax, m, item_name)
    if it is None:
        _esc(2)
        return False
    ok = ax.action(it.id, "AXPress")
    time.sleep(1.4)
    return bool(ok)


def find_window(ax, title_substr):
    for w in ax.find(role="window", max_results=10, max_depth=1):
        if title_substr.lower() in (w.name or "").lower():
            return w
    return None


def untitled_dialog(ax):
    """The Qt message-box window (AXTitle == '')."""
    for w in ax.find(role="window", max_results=10, max_depth=1):
        if (w.name or "") == "":
            return w
    return None


def close_dialog(ax, window, button_name="Cancel"):
    if window is None:
        return False
    b = ax.find(role="button", name=button_name, root_id=window.id, max_results=2)
    if b:
        ax.action(b[0].id, "AXPress")
        time.sleep(1.0)
        return True
    return False


def rb_enter_inmemory_db(ax):
    """File > New In-Memory Database, then dismiss the auto-opened table dialog."""
    rb_reach_menu_item(ax, "File", "New In-Memory Database")
    w = find_window(ax, "Edit table definition")
    if w is not None:
        close_dialog(ax, w, "Cancel")
    return find_window(ax, "Edit table definition") is None


def pref_item(ax, menu):
    """The app-menu Preferences/Settings item — AXTitle is UNSTABLE across runs."""
    for it in items_of(ax, menu):
        n = (it.name or "").lower()
        if "services" in n:
            continue
        if "prefer" in n or "etting" in n:
            return it
    return None


def result_cells(ax):
    cols, cells = [], []
    for t in ax.find(role="table", max_results=10):
        if (t.name or "") == "search result":
            continue
        ch = (ax.tree(max_depth=3, root_id=t.id).get("children") or [])
        c = [x.get("name") for x in ch if x.get("role") == "column"]
        v = [x.get("name") for x in ch if x.get("role") == "label"]
        if c or v:
            cols, cells = c, v
    return cols, cells


# ── local additions (semantic locators, no framework internals) ──────────────

APP_MENU = "DB Browser for SQLite"

TOP_MENUS = [APP_MENU, "File", "Edit", "View", "Tools", "Help"]

# recon ## MENUS — minimum app-authored named items per menu (macOS may ADD more)
MIN_NAMED = {APP_MENU: 6, "File": 18, "Edit": 4, "View": 13, "Tools": 7, "Help": 6}

FILE_ITEMS = [
    "New Database...", "New In-Memory Database", "Open Database...",
    "Open Database Read Only...", "Attach Database...", "Recent Files",
    "Save Database As...", "Close Database", "Write Changes", "Revert Changes",
    "Undo", "Import", "Export", "Open Project...", "Save Project",
    "Save Project As...", "Close Project", "Save All",
]

VIEW_TOGGLES = [
    "SQL Log", "Plot", "DB Schema", "Edit Database Cell", "Remote",
    "DB Toolbar", "Extra DB Toolbar", "Project Toolbar",
    "Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL",
]

TOOLS_ITEMS = [
    "Compact Database...", "Load Extension...", "Integrity Check",
    "Quick Integrity Check", "Foreign-Key Check", "Optimize", "Show Row Counts",
]

HELP_ITEMS = [
    "What's This?", "Website", "Wiki", "Bug Report...",
    "Feature Request...", "Donate on Patreon...",
]

FILE_IMPORT_ITEMS = ["Database from SQL file...", "Table from CSV file...",
                     "Table from CSV data in Clipboard..."]
FILE_EXPORT_ITEMS = ["Database to SQL file...", "Table(s) as CSV file...",
                     "Table to JSON..."]
FILE_RECENT_ITEMS = ["Automatically load the last opened DB file at startup",
                     "Clear List"]
WINDOW_LAYOUT_ITEMS = ["Reset Window Layout", "Simplify Window Layout",
                       "Dock Windows at Bottom", "Dock Windows at Left Side",
                       "Dock Windows at Top"]

PREFS_TABS = ["General", "Database", "Data Browser", "SQL", "Extensions", "Remote"]

TABLE_PREVIEW_FRESH = 'CREATE TABLE "" (\n\n);'
INTEGRITY_CONFIRM_TEXT = (
    "This action will open a new SQL tab for running:\n"
    "PRAGMA integrity_check;\n"
    "Press Help for opening the corresponding SQLite reference page."
)
ABOUT_DESCRIPTION = ("DB Browser for SQLite is an open source, freeware visual tool "
                     "used to create, design and edit SQLite")


def _norm(s):
    """Compare menu labels SEMANTICALLY: the unicode ellipsis and '...' are the same
    label; leading/trailing whitespace is irrelevant."""
    return str(s or "").replace("…", "...").strip()


def named_items(ax, menu):
    """Normalised names of the menu's non-separator items (separators have name '')."""
    return [_norm(it.name) for it in items_of(ax, menu) if _norm(it.name)]


def named_submenu_items(ax, item):
    sub = submenu_of(ax, item)
    if sub is None:
        return None
    return [_norm(i.name) for i in items_of(ax, sub) if _norm(i.name)]


def item_by_label(ax, menu, label):
    """Locate a menu item by its VISIBLE label (ellipsis-tolerant)."""
    want = _norm(label)
    for it in items_of(ax, menu):
        if _norm(it.name) == want:
            return it
    return None


def item_by_prefix(ax, menu, prefix):
    p = _norm(prefix).lower()
    for it in items_of(ax, menu):
        if _norm(it.name).lower().startswith(p):
            return it
    return None


def enabled_map(ax, menu, labels):
    """{label: bool AXEnabled} — value is None when the item is absent."""
    present = {}
    for it in items_of(ax, menu):
        n = _norm(it.name)
        if n and n not in present:
            present[n] = it
    out = {}
    for lb in labels:
        it = present.get(_norm(lb))
        out[lb] = None if it is None else bool(item_attrs(ax, it).get("AXEnabled"))
    return out


def shortcut_of(ax, menu, label):
    """(AXMenuItemCmdChar, AXMenuItemCmdModifiers) of a menu item, or (None, None)."""
    it = item_by_label(ax, menu, label)
    if it is None:
        return (None, None)
    a = item_attrs(ax, it)
    ch = a.get("AXMenuItemCmdChar")
    md = a.get("AXMenuItemCmdModifiers")
    ch = None if ch is None else str(ch)
    try:
        md = None if md is None else int(md)
    except Exception:
        md = None
    return (ch, md)


def rb_enter_main_window(ax):
    """Reveal the app's UI before any window-dependent check. The reference is a plain
    windowed app (recon REVEAL_STEPS), but a recreation may need a reveal path —
    ensure_ui_visible() tries them all."""
    try:
        ax.ensure_ui_visible()
    except Exception:
        pass
    return find_window(ax, "DB Browser for SQLite")


def main_window_title(ax):
    for w in ax.find(role="window", max_results=10, max_depth=1):
        n = str(w.name or "")
        if n.startswith("DB Browser for SQLite"):
            return n
    return ""


def label_texts(ax, window, limit=30):
    """AXValue (and AXTitle) of every label under a window — a recreation may carry the
    text in either attribute."""
    out = []
    if window is None:
        return out
    for lb in ax.find(role="label", root_id=window.id, max_results=limit):
        v = ax.get(lb.id, ["AXValue"]).get("AXValue")
        if v is not None:
            out.append(str(v))
        n = str(lb.name or "")
        if n:
            out.append(n)
    return out


def button_names(ax, window, limit=15):
    if window is None:
        return []
    return [str(b.name or "")
            for b in ax.find(role="button", root_id=window.id, max_results=limit)]


def text_area_containing(ax, window, needle):
    if window is None:
        return ""
    for t in ax.find(role="text_area", root_id=window.id, max_results=8):
        v = ax.get(t.id, ["AXValue"]).get("AXValue")
        s = "" if v is None else str(v)
        if needle in s:
            return s
    return ""


def combobox_options(ax, window):
    opts = []
    if window is None:
        return opts
    for c in ax.find(role="combobox", root_id=window.id, max_results=6):
        opts.append(str(c.name or ""))
        for lb in ax.find(role="label", root_id=c.id, max_results=40):
            opts.append(str(lb.name or ""))
    return [o for o in opts if o]


def tabbar_group(ax, root_id, expected_radios):
    """The tab bar is the `group` whose direct radio children are exactly
    `expected_radios`; its AXTitle equals the SELECTED tab (recon ST1/ST5)."""
    groups = ax.find(role="group", root_id=root_id, max_results=40)
    for depth in (1, 2):
        for g in groups:
            kids = [_norm(k.name) for k in
                    ax.find(role="radio", root_id=g.id, max_results=12, max_depth=depth)]
            if kids == [_norm(x) for x in expected_radios]:
                return g
    return None


def group_title(ax, group):
    if group is None:
        return None
    return str(ax.get(group.id, ["AXTitle"]).get("AXTitle") or "")


def rb_reach_about_dialog(ax):
    """app menu -> 'About DB Browser for SQLite' (window|About DB Browser for SQLite)."""
    m = open_menu(ax, APP_MENU)
    if m is None:
        return False
    it = item_by_prefix(ax, m, "About")
    if it is None:
        _esc(2)
        return False
    ok = ax.action(it.id, "AXPress")
    time.sleep(1.5)
    return bool(ok)


def rb_reach_preferences(ax):
    """app menu -> Preferences…/Settings… (window|Preferences)."""
    m = open_menu(ax, APP_MENU)
    if m is None:
        return False
    it = pref_item(ax, m)
    if it is None:
        _esc(2)
        return False
    ok = ax.action(it.id, "AXPress")
    time.sleep(1.6)
    return bool(ok)


def rb_enter_table_t1(ax):
    """Edit ▸ Create Table… -> name it t1, Add one field, OK. Returns True when the
    dialog closed (table created). Needs a DB already open."""
    rb_reach_menu_item(ax, "Edit", "Create Table...")
    dlg = find_window(ax, "Edit table definition")
    if dlg is None:
        return False
    tf = ax.find(role="text_field", name="Table", root_id=dlg.id, max_results=3)
    if not tf:
        tf = ax.find(role="text_field", root_id=dlg.id, max_results=3)
    if tf:
        ax.set_value(tf[0].id, "t1")
        time.sleep(0.6)
    add = ax.find(role="button", name="Add", root_id=dlg.id, max_results=3)
    if add:
        ax.action(add[0].id, "AXPress")
        time.sleep(0.6)
    ok = ax.find(role="button", name="OK", root_id=dlg.id, max_results=3)
    if ok and bool(ax.get(ok[0].id, ["AXEnabled"]).get("AXEnabled")):
        ax.action(ok[0].id, "AXPress")
        time.sleep(1.2)
    if find_window(ax, "Edit table definition") is not None:
        close_dialog(ax, find_window(ax, "Edit table definition"), "Cancel")
        return False
    return True


# ── A) structure of every menu in recon ## MENUS ─────────────────────────────

class TestMenuStructure:

    @pytest.mark.rb(depth=1, jump_kind="none",
                    expect="menu bar exposes the 6 app menus; every menu has >=1 item "
                           "and File/View/app own submenus")
    def test_menu_bar_top_level_menus_and_item_counts(self, ax_with_reset):
        ax = ax_with_reset
        tops = [_norm(m.name) for m in
                ax.find(role="menu_bar_item", max_results=15, max_depth=3)]
        totals, named_totals, submenus = {}, {}, {}
        for top in TOP_MENUS:
            menu = open_menu(ax, top)
            if menu is None:
                totals[top], named_totals[top], submenus[top] = 0, 0, 0
                continue
            items = items_of(ax, menu)
            totals[top] = len(items)
            named_totals[top] = len([i for i in items if _norm(i.name)])
            submenus[top] = len([i for i in items if submenu_of(ax, i) is not None])
            _esc(2)
        _esc(2)

        assert set(TOP_MENUS).issubset(set(tops)), \
            f"menu bar is missing app menus: got {tops}"
        for top in TOP_MENUS:
            assert totals[top] >= 1, f"menu {top!r} has no children at all"
            assert named_totals[top] >= MIN_NAMED[top], (
                f"menu {top!r}: {named_totals[top]} named items, "
                f"expected >= {MIN_NAMED[top]}")
        # separators are menu_items with an empty name -> total >= named
        assert all(totals[t] >= named_totals[t] for t in TOP_MENUS)
        assert submenus["File"] >= 3, (
            f"File must own the Recent Files/Import/Export submenus, "
            f"found {submenus['File']}")
        assert submenus["View"] >= 1, "View must own the Window Layout submenu"
        assert submenus[APP_MENU] >= 1, "app menu must own the Services submenu"
        assert sum(named_totals.values()) >= 50, (
            f"total named menu items {sum(named_totals.values())} "
            f"(recon: 62 across the 6 app menus)")


    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="all 12 View toggles carry AXMenuItemMarkChar '/' (checkmark) "
                           "on a fresh app, plus Window Layout + Enter Full Screen")
    def test_view_menu_full_item_list_and_checkmarks(self, ax_with_reset):
        ax = ax_with_reset
        menu = open_menu(ax, "View")
        assert menu is not None, "View menu did not open"
        names = named_items(ax, menu)
        marks = []
        for lb in VIEW_TOGGLES:
            it = item_by_label(ax, menu, lb)
            marks.append(None if it is None
                         else item_attrs(ax, it).get("AXMenuItemMarkChar"))
        screenshot_assert(
            "menus_view_menu_checkmarks",
            "The View dropdown lists SQL Log, Plot, DB Schema, Edit Database Cell, "
            "Remote, DB Toolbar, Extra DB Toolbar, Project Toolbar, Database Structure, "
            "Browse Data, Edit Pragmas, Execute SQL — each with a checkmark — plus a "
            "'Window Layout' submenu and 'Enter Full Screen'.",
            RESULTS_DIR)
        _esc(2)

        missing = [n for n in VIEW_TOGGLES if _norm(n) not in names]
        assert not missing, f"View menu missing toggles {missing}; got {names}"
        assert _norm("Window Layout") in names, f"View lacks Window Layout: {names}"
        assert _norm("Enter Full Screen") in names, \
            f"View lacks Enter Full Screen: {names}"
        marks = [None if m is None else str(m) for m in marks]
        assert kit.rb_value(sorted({str(m) for m in marks}), ["✓"]), (
            f"every View toggle must be CHECKED on a fresh app, marks={marks}")
        assert marks == ["✓"] * 12, f"marks={marks}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="all 7 Tools items exist and report AXEnabled False with no "
                           "database open")
    def test_tools_menu_all_disabled_without_database(self, ax_with_reset):
        ax = ax_with_reset
        menu = open_menu(ax, "Tools")
        assert menu is not None, "Tools menu did not open"
        names = named_items(ax, menu)
        state = enabled_map(ax, menu, TOOLS_ITEMS)
        _esc(2)

        missing = [n for n in TOOLS_ITEMS if _norm(n) not in names]
        assert not missing, f"Tools menu missing {missing}; got {names}"
        vals = [state[n] for n in TOOLS_ITEMS]
        assert kit.rb_value(sorted({str(v) for v in vals}), ["False"]), (
            f"with NO database every Tools item must be DISABLED, got "
            f"{dict(zip(TOOLS_ITEMS, vals))}")
        assert vals == [False] * 7, dict(zip(TOOLS_ITEMS, vals))

    @pytest.mark.rb(depth=1, jump_kind="none",
                    expect="Help menu lists the 6 recorded items (never pressed — they "
                           "open a browser)")
    def test_help_menu_items(self, ax_with_reset):
        ax = ax_with_reset
        menu = open_menu(ax, "Help")
        assert menu is not None, "Help menu did not open"
        names = named_items(ax, menu)
        _esc(2)

        missing = [n for n in HELP_ITEMS if _norm(n) not in names]
        assert not missing, f"Help menu missing {missing}; got {names}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="app menu: About item, Preferences/Settings with cmd ',', "
                           "Quit cmd 'Q', Hide cmd 'H' mods 0, Hide Others 'H' mods 2")
    def test_app_menu_items_and_shortcuts(self, ax_with_reset):
        ax = ax_with_reset
        menu = open_menu(ax, APP_MENU)
        assert menu is not None, "app menu did not open"
        names = named_items(ax, menu)
        about = item_by_prefix(ax, menu, "About DB Browser for SQLite")
        about_actions = list(about.actions) if about is not None else []
        prefs = pref_item(ax, menu)
        prefs_attrs = {} if prefs is None else item_attrs(ax, prefs)
        prefs_actions = list(prefs.actions) if prefs is not None else []
        quit_sc = shortcut_of(ax, menu, "Quit DB Browser for SQLite")
        hide_sc = shortcut_of(ax, menu, "Hide DB Browser for SQLite")
        hide_others_sc = shortcut_of(ax, menu, "Hide Others")
        _esc(2)

        assert about is not None, f"no 'About DB Browser for SQLite' item: {names}"
        assert "AXPress" in about_actions, \
            f"About item has no action interface: {about_actions}"
        assert prefs is not None, f"no Preferences/Settings item: {names}"
        assert "AXPress" in prefs_actions, \
            f"Preferences item has no action interface: {prefs_actions}"
        prefs_cmd = prefs_attrs.get("AXMenuItemCmdChar")
        observed = [None if prefs_cmd is None else str(prefs_cmd),
                    quit_sc[0], hide_sc[0], hide_others_sc[0]]
        assert kit.rb_value(observed, [",", "Q", "H", "H"]), (
            f"app-menu cmd chars {observed} != [',', 'Q', 'H', 'H']")
        assert quit_sc[1] == 0, f"Quit modifiers {quit_sc[1]} (expected 0 = plain cmd)"
        assert hide_sc[1] == 0, f"Hide modifiers {hide_sc[1]} (expected 0)"
        assert hide_others_sc[1] == 2, \
            f"Hide Others modifiers {hide_others_sc[1]} (expected 2 = alt+cmd)"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="New Database (N,0), Open Database (O,0), Open Database Read "
                           "Only (O,1), Close Project (W,1), Save All (S,1), Write "
                           "Changes cmd 'S'")
    def test_file_menu_keyboard_shortcuts(self, ax_with_reset):
        ax = ax_with_reset
        menu = open_menu(ax, "File")
        assert menu is not None, "File menu did not open"
        pairs = [shortcut_of(ax, menu, lb) for lb in
                 ["New Database...", "Open Database...", "Open Database Read Only...",
                  "Close Project", "Save All"]]
        write_changes = shortcut_of(ax, menu, "Write Changes")
        _esc(2)

        expected = [("N", 0), ("O", 0), ("O", 1), ("W", 1), ("S", 1)]
        assert kit.rb_value(pairs, expected), (
            f"File-menu shortcuts {pairs} != {expected}")
        assert write_changes[0] == "S", \
            f"Write Changes cmd char {write_changes[0]!r} (expected 'S')"




# ── B) safe-item activation ──────────────────────────────────────────────────

class TestMenuItemActivation:

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="modal window 'Edit table definition' appears with the "
                           "preview CREATE TABLE \"\" (\\n\\n);")
    def test_new_inmemory_database_opens_table_dialog(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        before = kit.rb_showing(ax)
        pressed = rb_reach_menu_item(ax, "File", "New In-Memory Database")
        after = kit.rb_showing(ax)
        assert pressed, "could not press File > New In-Memory Database"
        dlg = find_window(ax, "Edit table definition")
        preview = text_area_containing(ax, dlg, "CREATE")
        screenshot_assert(
            "menus_new_inmemory_table_dialog",
            "A modal window titled 'Edit table definition' is in front of the main "
            "window: a 'Table' name field, an 'Advanced' checkbox, a field grid headed "
            "Name, Type, NN, PK, AI, U, Default, Check, Collation, Foreign Key, "
            "Add/Remove/move buttons, a read-only SQL box showing CREATE TABLE \"\" ( ); "
            "tabs Fields / Index Constraints / Foreign Keys / Check Constraints, and "
            "OK / Cancel buttons.",
            RESULTS_DIR)
        closed = close_dialog(ax, dlg, "Cancel")
        gone = find_window(ax, "Edit table definition") is None
        _esc(2)

        assert kit.rb_reach(before, after, target="window|Edit table definition"), (
            "File > New In-Memory Database did not open the 'Edit table definition' "
            "window")
        assert dlg is not None
        assert preview == TABLE_PREVIEW_FRESH, (
            f"fresh CREATE-TABLE preview {preview!r} != {TABLE_PREVIEW_FRESH!r}")
        assert closed, "the dialog exposes no scoped Cancel button"
        assert gone, "'Edit table definition' is still open after Cancel"

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="main window title 'DB Browser for SQLite' -> "
                           "'DB Browser for SQLite - In-Memory database'")
    def test_new_inmemory_database_changes_window_title(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        before_title = main_window_title(ax)
        opened = rb_enter_inmemory_db(ax)
        after_title = main_window_title(ax)
        _esc(2)

        assert before_title == "DB Browser for SQLite", (
            f"fresh main window title {before_title!r}")
        assert opened, "the auto-opened 'Edit table definition' dialog did not close"
        assert kit.rb_flip(before_title, after_title), (
            f"window title did not change: {before_title!r} -> {after_title!r}")
        assert kit.rb_value(after_title, "In-Memory database"), (
            f"title after opening the in-memory DB = {after_title!r}")

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="Edit > Create Table.../Create Index... AXEnabled False->True "
                           "once a database is open; Modify/Delete Table stay False")
    def test_edit_menu_items_enable_after_database_opened(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        edit_labels = ["Create Table...", "Create Index...",
                       "Modify Table...", "Delete Table..."]
        menu = open_menu(ax, "Edit")
        assert menu is not None, "Edit menu did not open"
        names = named_items(ax, menu)
        s0 = enabled_map(ax, menu, edit_labels)
        _esc(2)

        rb_enter_inmemory_db(ax)

        menu2 = open_menu(ax, "Edit")
        assert menu2 is not None, "Edit menu did not open with a database"
        s1 = enabled_map(ax, menu2, edit_labels)
        _esc(2)

        missing = [n for n in edit_labels if _norm(n) not in names]
        assert not missing, f"Edit menu missing {missing}; got {names}"
        before_pair = (s0["Create Table..."], s0["Create Index..."])
        after_pair = (s1["Create Table..."], s1["Create Index..."])
        assert kit.rb_flip(before_pair, after_pair), (
            f"Create Table/Create Index did not change enabled state: "
            f"{before_pair} -> {after_pair}")
        assert before_pair == (False, False), f"no DB: {before_pair}"
        assert after_pair == (True, True), f"DB open: {after_pair}"
        assert (s1["Modify Table..."], s1["Delete Table..."]) == (False, False), (
            f"Modify/Delete Table must stay disabled without a selected table, got "
            f"{(s1['Modify Table...'], s1['Delete Table...'])}")

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="all 7 Tools items AXEnabled False->True after File > New "
                           "In-Memory Database")
    def test_tools_menu_items_enable_after_database_opened(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        menu = open_menu(ax, "Tools")
        assert menu is not None, "Tools menu did not open"
        s0 = enabled_map(ax, menu, TOOLS_ITEMS)
        _esc(2)

        rb_enter_inmemory_db(ax)

        menu2 = open_menu(ax, "Tools")
        assert menu2 is not None, "Tools menu did not open with a database"
        s1 = enabled_map(ax, menu2, TOOLS_ITEMS)
        _esc(2)

        before_vals = [s0[n] for n in TOOLS_ITEMS]
        after_vals = [s1[n] for n in TOOLS_ITEMS]
        assert kit.rb_flip(before_vals, after_vals), (
            f"Tools items did not change enabled state: {before_vals} -> {after_vals}")
        assert before_vals == [False] * 7, dict(zip(TOOLS_ITEMS, before_vals))
        assert after_vals == [True] * 7, dict(zip(TOOLS_ITEMS, after_vals))


# ── depth >= 2 chains reached through the menus ──────────────────────────────

class TestMenuDepthChains:

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="window 'Edit Index Schema' with the table list holding t1 "
                           "and the preview CREATE INDEX \"\" ON \"t1\" (...)")
    def test_edit_create_index_opens_index_dialog(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        assert rb_enter_inmemory_db(ax), "could not open the in-memory database"
        table_created = rb_enter_table_t1(ax)

        before = kit.rb_showing(ax)
        pressed = rb_reach_menu_item(ax, "Edit", "Create Index...")
        after = kit.rb_showing(ax)
        assert pressed, "could not press Edit > Create Index..."
        idx = find_window(ax, "Edit Index Schema")
        options = combobox_options(ax, idx)
        preview = text_area_containing(ax, idx, "CREATE")
        close_dialog(ax, idx, "Cancel")
        _esc(2)

        assert kit.rb_reach(before, after, target="window|Edit Index Schema"), (
            "Edit > Create Index... did not open the 'Edit Index Schema' window")
        assert idx is not None
        if table_created:
            assert any("t1" == o or "t1" in o for o in options), (
                f"the index dialog's table list does not offer t1: {options}")
            assert 'ON "t1"' in preview, (
                f"CREATE-INDEX preview {preview!r} does not target t1")
        else:
            assert "CREATE" in preview or preview == "", (
                f"unexpected index preview {preview!r}")

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="untitled confirm window with the exact text 'PRAGMA "
                           "integrity_check;' block and OK / Cancel / Help buttons")
    def test_tools_integrity_check_confirmation_dialog(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        assert rb_enter_inmemory_db(ax), "could not open the in-memory database"

        before = kit.rb_showing(ax)
        pressed = rb_reach_menu_item(ax, "Tools", "Integrity Check")
        after = kit.rb_showing(ax)
        assert pressed, "could not press Tools > Integrity Check"
        dlg = untitled_dialog(ax)
        btns = button_names(ax, dlg)
        texts = label_texts(ax, dlg)
        screenshot_assert(
            "menus_integrity_check_confirm",
            "A modal alert in front of the DB Browser for SQLite window with a warning "
            "icon and the text 'This action will open a new SQL tab for running: PRAGMA "
            "integrity_check; Press Help for opening the corresponding SQLite reference "
            "page.' plus OK / Cancel / Help buttons.",
            RESULTS_DIR)
        close_dialog(ax, dlg, "Cancel")
        _esc(2)

        assert kit.rb_reach(before, after, target="PRAGMA integrity_check"), (
            "Tools > Integrity Check did not raise the PRAGMA integrity_check confirm "
            "dialog")
        assert dlg is not None, "no untitled Qt message-box window appeared"
        assert {"OK", "Cancel", "Help"}.issubset(set(btns)), \
            f"confirm dialog buttons {btns}"
        assert any(t == INTEGRITY_CONFIRM_TEXT for t in texts), (
            f"confirm text not found verbatim; observed {texts}")

    @pytest.mark.rb(depth=3, jump_kind="value",
                    expect="pressing OK runs PRAGMA integrity_check; in a new SQL tab "
                           "'Integrity Check*' whose results column 'integrity_check' "
                           "holds the cell 'ok'")
    def test_tools_integrity_check_runs_and_reports_ok(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        assert rb_enter_inmemory_db(ax), "could not open the in-memory database"
        assert rb_reach_menu_item(ax, "Tools", "Integrity Check"), \
            "could not press Tools > Integrity Check"
        dlg = untitled_dialog(ax)
        assert dlg is not None, "no confirm dialog for Integrity Check"
        ok = ax.find(role="button", name="OK", root_id=dlg.id, max_results=2)
        assert ok, f"confirm dialog has no OK button: {button_names(ax, dlg)}"
        ax.action(ok[0].id, "AXPress")
        time.sleep(2.6)

        cols, cells = result_cells(ax)
        radios = [str(r.name or "") for r in ax.find(role="radio", max_results=40)]
        screenshot_assert(
            "menus_integrity_check_result",
            "The Execute SQL tab is active with TWO sub-tabs ('SQL 1' and 'Integrity "
            "Check*'), the editor holds PRAGMA integrity_check; and a results grid whose "
            "single column 'integrity_check' contains the value ok.",
            RESULTS_DIR)
        _esc(2)

        assert cols == ["integrity_check"], f"results columns {cols}"
        assert kit.rb_value(cells, "ok"), f"results cells {cells} (expected 'ok')"
        assert any(n.startswith("Integrity Check") for n in radios), (
            f"no 'Integrity Check*' SQL sub-tab was created: {radios}")


class TestAppMenuSurfaces:

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="window 'About DB Browser for SQLite' with the freeware "
                           "description sentence and a 'DB Browser for SQLite Version' "
                           "line")
    def test_app_menu_about_dialog(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        before = kit.rb_showing(ax)
        pressed = rb_reach_about_dialog(ax)
        after = kit.rb_showing(ax)
        assert pressed, "could not press the app menu's About item"
        about = find_window(ax, "About DB Browser for SQLite")
        texts = label_texts(ax, about)
        btns = button_names(ax, about)
        screenshot_assert(
            "menus_about_dialog",
            "A small window titled 'About DB Browser for SQLite' showing the app logo "
            "image, a version line beginning 'DB Browser for SQLite Version', the "
            "sentence 'DB Browser for SQLite is an open source, freeware visual tool "
            "used to create, design and edit SQLite', and a Close button.",
            RESULTS_DIR)
        closed = close_dialog(ax, about, "Close")
        _esc(2)

        assert kit.rb_reach(before, after,
                            target="window|About DB Browser for SQLite"), (
            "the About item did not open the About window")
        assert about is not None
        assert any(ABOUT_DESCRIPTION in t for t in texts), (
            f"About description sentence missing; observed {texts}")
        # NEVER assert the version NUMBER — it is build specific.
        assert any("DB Browser for SQLite Version" in t for t in texts), (
            f"About window has no version line; observed {texts}")
        assert "Close" in btns, f"About window buttons {btns}"
        assert closed, "the About window exposes no scoped Close button"

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="Preferences > Database tab: 'Prefetch block size' appears "
                           "and 'Max Recent Files' (General tab) disappears; tab-bar "
                           "group AXTitle 'General' -> 'Database'")
    def test_preferences_window_tab_navigation(self, ax_with_reset):
        ax = ax_with_reset
        rb_enter_main_window(ax)
        opened = rb_reach_preferences(ax)
        prefs = find_window(ax, "Preferences")
        assert opened and prefs is not None, \
            "app menu > Preferences.../Settings... did not open the Preferences window"
        tabs = [_norm(r.name) for r in
                ax.find(role="radio", root_id=prefs.id, max_results=20)]
        bar = tabbar_group(ax, prefs.id, PREFS_TABS)
        title_general = group_title(ax, bar)
        screenshot_assert(
            "menus_preferences_general",
            "A separate 'Preferences' window with a tab strip General, Database, Data "
            "Browser, SQL, Extensions, Remote (General selected), a Language dropdown "
            "reading 'English (United States) [System Language]', Font size 13, Max "
            "Recent Files 5, toolbar-style dropdowns, and Save / Cancel / Restore "
            "Defaults buttons.",
            RESULTS_DIR)

        db_tab = ax.find(role="radio", name="Database", root_id=prefs.id, max_results=2)
        assert db_tab, f"Preferences has no 'Database' tab; radios {tabs}"
        before = kit.rb_showing(ax)
        ax.action(db_tab[0].id, "AXPress")
        time.sleep(1.1)
        after = kit.rb_showing(ax)
        title_database = group_title(ax, bar)

        close_dialog(ax, prefs, "Cancel")
        remaining = len(ax.find(role="window", max_results=10, max_depth=1))
        _esc(2)

        assert [t for t in tabs if t in PREFS_TABS][:6] == PREFS_TABS, \
            f"Preferences tab radios {tabs}"
        assert title_general == "General", (
            f"Preferences opens on the General tab; tab-bar AXTitle {title_general!r}")
        assert kit.rb_reach(before, after, target="Prefetch block size",
                            source="Max Recent Files"), (
            "pressing the Database tab did not swap the General page for the Database "
            "page")
        assert title_database == "Database", (
            f"tab-bar AXTitle after pressing Database = {title_database!r}")
        assert remaining == 1, (
            f"{remaining} windows left after Preferences > Cancel (expected only the "
            f"main window)")