File size: 32,796 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
"""AX STRUCTURE tests for `DB Browser for SQLite` (Qt6, net.sourceforge.sqlitebrowser).

Every fact asserted here comes from the recon report's `## APP` / `## AX_TREE` / `## STRUCTURE`
sections (role census, tab-bar radio sets, toolbar button names, column headers, shape deltas).
Widgets are located by AXRole + visible AXTitle/AXValue (never by child index or tree path).

Fresh-app starting state (per recon): main window on screen, NO DATABASE OPEN.
"""

import json
import os
import re
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__)))
MAIN_TABS = ["Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL"]
DOCK_TABS = ["SQL Log", "Plot", "DB Schema", "Remote"]
REMOTE_TABS = ["DBHub.io", "Local", "Current Database"]


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 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
    for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1):
        if (it.name or "") == item_name:
            ok = ax.action(it.id, "AXPress")
            time.sleep(1.4)
            return bool(ok)
    _esc(2)
    return False


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 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:
        c = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2)
        if c:
            ax.action(c[0].id, "AXPress")
            time.sleep(1.0)
    return find_window(ax, "Edit table definition") is None


def switch_tab(ax, name):
    r = ax.find(role="radio", name=name, max_results=1)
    if not r:
        return False
    ok = ax.action(r[0].id, "AXPress")
    time.sleep(1.0)
    return bool(ok)


def tabbar(ax, kids):
    """The tab-bar `group` whose direct radio children == kids. Its AXTitle == selected tab."""
    for g in ax.find(role="group", max_results=250):
        ks = [k.name for k in ax.find(role="radio", root_id=g.id, max_results=10, max_depth=1)]
        if ks == kids:
            return g
    return None


def names(els):
    return [e.name for e in els if e.name]


def find_button(ax, name):
    for b in ax.find(role="button", max_results=80):
        if (b.name or "") == name:
            return b
    return None


# --------------------------------------------------------------------------- #
# recon-derived expectations (## AX_TREE, ## STRUCTURE, ## TEXT, ## BUTTONS)
# --------------------------------------------------------------------------- #

APP_MENU_TITLE = "DB Browser for SQLite"
MAIN_WINDOW_PREFIX = "db browser for sqlite"
TOP_MENUS = ["DB Browser for SQLite", "File", "Edit", "View", "Tools", "Help"]
STD_MENU_NAMES = {"apple", "file", "edit", "view", "tools", "help", "window"}

TOOLBAR_BUTTONS = ["New Database", "Open Database", "Write Changes", "Revert Changes",
                   "Undo", "Open Project", "Save Project", "Attach Database"]
STRUCTURE_TOOLBAR_BUTTONS = ["Create Table", "Create Index", "Modify Table"]

# ## TEXT T3 — column header sets that exist on a FRESH app (no DB)
STRUCTURE_COLUMNS = {"Name", "Object", "Type", "Schema", "Database"}
REMOTE_COLUMNS = {"Name", "Last modified", "Size", "Commit"}
PLOT_COLUMNS = {"Columns", "X", "Y1", "Y2", "Axis Type"}
TABLE_DIALOG_COLUMNS = {"Name", "Type", "NN", "PK", "AI", "U",
                        "Default", "Check", "Collation", "Foreign Key"}

# ## AX_TREE / T1 — one signature label per dock panel (read via AXValue)
DOCK_LABEL_TEXTS = ["Mode:", "Show SQL submitted by", "Line type:", "Point shape:", "Identity"]

# ## STRUCTURE S1 — Execute SQL tab page
EXEC_SQL_BUTTONS = {"Execute SQL", "Execute line", "Stop execution", "Open SQL file(s)",
                    "Save SQL file", "Save results", "New tab", "Find or replace",
                    "Un/comment block"}
# ## STRUCTURE S2 — Browse Data tab page
BROWSE_BUTTONS = {"New Record", "Save Table As", "New Data Browser", "Clear Filters",
                  "Clear Sorting", "Go to:"}
BROWSE_TEXT_FIELDS = ["Filter in any column", "Enter record number to browse"]
# ## STRUCTURE S3 / T6 — the 8 pragma checkboxes (AXTitle is literal HTML -> substring match)
PRAGMA_CHECKBOX_NAMES = ["Automatic Index", "Case Sensitive Like", "Checkpoint Full FSYNC",
                         "Foreign Keys", "Full FSYNC", "Ignore Check Constraints",
                         "Recursive Triggers", "Secure Delete"]
# ## STRUCTURE S6 / ST4 — Edit table definition dialog
TABLE_DIALOG_TABS = {"Fields", "Index Constraints", "Foreign Keys", "Check Constraints"}
TABLE_DIALOG_BUTTONS = {"Add", "Remove", "Move to top", "Move up", "Move down",
                        "Move to bottom", "OK", "Cancel"}
# ## STRUCTURE S7 / ST5 — Preferences window
PREFS_TABS = {"General", "Database", "Data Browser", "SQL", "Extensions", "Remote"}
PREFS_BUTTONS = {"Save", "Cancel", "Restore Defaults", "Import Settings", "Export Settings"}

# role census on a fresh app (## AX_TREE "Role census")
MIN_ROLE_COUNTS = [("button", 30), ("radio", 11), ("combobox", 5), ("checkbox", 4),
                   ("label", 40), ("text_area", 2), ("split_group", 1), ("menubutton", 1)]
ABSENT_ROLES = {"tabgroup", "toolbar", "outline"}
SQL_SUBTAB_RE = re.compile(r"^\s*SQL\s*\d+\s*$")


# --------------------------------------------------------------------------- #
# small, framework-tolerant locator helpers (recon-only, no live exploration)
# --------------------------------------------------------------------------- #

def rb_ensure_ui(ax, tries=3):
    """Best-effort reveal of the app's window before any window-dependent check.

    Recon REVEAL_STEPS: this is a regular windowed app whose main window is already on
    screen at launch, so this normally returns immediately. `ensure_ui_visible` is used
    when the helper exposes it (menu-bar/LSUIElement style recreations).
    """
    wins = []
    for _ in range(tries):
        wins = ax.find(role="window", max_results=10, max_depth=1)
        if wins:
            return wins
        fn = getattr(ax, "ensure_ui_visible", None)
        if callable(fn):
            try:
                fn()
            except Exception:
                pass
        time.sleep(0.7)
    return wins


def role_els(ax, role, root_id=None, limit=200, max_depth=None):
    kw = {"role": role, "max_results": limit}
    if root_id is not None:
        kw["root_id"] = root_id
    if max_depth is not None:
        kw["max_depth"] = max_depth
    try:
        return list(ax.find(**kw) or [])
    except Exception:
        return []


def role_name_set(ax, role, root_id=None, limit=200, max_depth=None):
    return {(e.name or "").strip() for e in role_els(ax, role, root_id, limit, max_depth)}


def _norm_text(s):
    s = (s or "").replace("…", "...")
    s = re.sub(r"\s+", " ", s).strip().lower()
    return s.rstrip(":").strip()


def _norm_role(r):
    r = (r or "").strip().lower()
    if r.startswith("ax"):
        r = r[2:]
    return r.replace("_", "").replace(" ", "").replace("-", "")


def el_value(ax, el):
    try:
        got = ax.get(el.id, ["AXValue"]) or {}
    except Exception:
        return ""
    v = got.get("AXValue") if hasattr(got, "get") else got
    return "" if v is None else str(v)


def label_texts(ax, limit=200):
    """Normalised visible text of every `label`: AXTitle AND AXValue (either may carry it)."""
    out = set()
    for lb in role_els(ax, "label", limit=limit):
        n = _norm_text(lb.name)
        if n:
            out.add(n)
        v = _norm_text(el_value(ax, lb))
        if v:
            out.add(v)
    return out


def walk_tree_nodes(node, depth=1):
    """Yield (level, role, name); the root element is level 1 (== number of levels)."""
    if not isinstance(node, dict):
        return
    yield depth, (node.get("role") or ""), (node.get("name") or "")
    for ch in (node.get("children") or []):
        yield from walk_tree_nodes(ch, depth + 1)


def all_tab_bars(ax):
    """Every `group` that owns direct `radio` children -> {tuple(radio names): group}."""
    out = {}
    for g in role_els(ax, "group", limit=250):
        ks = tuple((k.name or "").strip()
                   for k in role_els(ax, "radio", root_id=g.id, limit=12, max_depth=1))
        ks = tuple(k for k in ks if k)
        if ks:
            out[ks] = g
    return out


def find_tab_bar(ax, kids):
    """Tab-bar group whose direct radio children are exactly `kids` (order-tolerant)."""
    g = tabbar(ax, list(kids))
    if g is not None:
        return g
    want = set(kids)
    for ks, grp in all_tab_bars(ax).items():
        if set(ks) == want:
            return grp
    return None


def rb_press_button(ax, name, root_id=None, settle=1.2):
    """AXPress the `button` whose AXTitle is exactly `name` (optionally scoped)."""
    for b in role_els(ax, "button", root_id=root_id, limit=150):
        if (b.name or "").strip() == name:
            ok = ax.action(b.id, "AXPress")
            time.sleep(settle)
            return bool(ok)
    return False


def rb_open_app_menu(ax):
    """Open the application menu (title == app name; falls back to the non-standard menu)."""
    m = open_menu(ax, APP_MENU_TITLE)
    if m is not None:
        return m
    for mbi in role_els(ax, "menu_bar_item", limit=20):
        n = (mbi.name or "").strip()
        if not n or n.lower() in STD_MENU_NAMES:
            continue
        ax.action(mbi.id, "AXPress")
        time.sleep(0.6)
        got = ax.find(role="menu", root_id=mbi.id, max_results=1, max_depth=1)
        if got:
            return got[0]
        _esc(1)
    return None


def rb_open_preferences(ax):
    """app menu -> Preferences.../Settings...  (recon: that AXTitle is NOT stable -> keyword)."""
    menu = rb_open_app_menu(ax)
    if menu is None:
        return False
    for it in ax.find(role="menu_item", root_id=menu.id, max_results=60, max_depth=1):
        low = (it.name or "").lower()
        if not low or "services" in low:
            continue
        if "prefer" in low or "etting" in low:
            ok = ax.action(it.id, "AXPress")
            time.sleep(1.8)
            return bool(ok)
    _esc(2)
    return False


def close_window_via_cancel(ax, win):
    if win is None:
        _esc(2)
        return
    c = ax.find(role="button", name="Cancel", root_id=win.id, max_results=3)
    hit = [b for b in (c or []) if (b.name or "").strip() == "Cancel"] or list(c or [])
    if hit:
        ax.action(hit[0].id, "AXPress")
        time.sleep(0.9)
    else:
        _esc(2)


def missing(expected, found):
    return sorted(set(expected) - set(found))


# --------------------------------------------------------------------------- #
# A) EXISTENCE GATE  (depth=0, jump_kind="none")
# --------------------------------------------------------------------------- #

class TestStructureGate:

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_app_and_main_window(self, ax):
        wins = rb_ensure_ui(ax)
        root = ax.tree(max_depth=2) or {}
        assert isinstance(root, dict) and root, "app is not reachable through the AX API"
        assert _norm_role(root.get("role")) == "application", \
            f"AX root role is {root.get('role')!r}, expected an application element"
        assert (root.get("children") or []), "application element exposes no AXChildren"

        assert len(wins) == 1, \
            f"expected exactly 1 top-level window on a fresh app, got {len(wins)}: {names(wins)}"
        title = (wins[0].name or "").strip()
        assert title.lower().startswith(MAIN_WINDOW_PREFIX), \
            f"main window AXTitle {title!r} does not start with 'DB Browser for SQLite'"

        screenshot_assert(
            "structure_test_gate_app_and_main_window",
            "Dark-themed application window titled 'DB Browser for SQLite'. Top toolbar row: New "
            "Database, Open Database (with a dropdown chevron), Write Changes, Revert Changes, "
            "Undo, Open Project, Save Project, Attach Database - the last six greyed out. Below "
            "it a 4-tab bar: Database Structure (selected), Browse Data, Edit Pragmas, Execute "
            "SQL. Left pane: an empty tree with Name / Type / Schema headers and Create Table, "
            "Create Index, Modify Table buttons above it. Right side: an 'Edit Database Cell' "
            "dock with a 'Mode:' dropdown showing Text, and a 'Remote' dock with an Identity "
            "dropdown and DBHub.io / Local / Current Database tabs. Bottom-right dock tab strip: "
            "SQL Log, Plot, DB Schema, Remote. Status bar bottom-right reads 'UTF-8'.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_menu_bar_items(self, ax):
        rb_ensure_ui(ax)
        bars = role_els(ax, "menu_bar", limit=5)
        assert bars, "no menu_bar element exposed by the application"

        found = role_name_set(ax, "menu_bar_item", root_id=bars[0].id, limit=30, max_depth=1)
        if not any(n in found for n in TOP_MENUS):
            found = role_name_set(ax, "menu_bar_item", limit=30)
        assert not missing(TOP_MENUS, found), \
            f"menu bar is missing top-level menus {missing(TOP_MENUS, found)}; found {sorted(found)}"

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_three_tab_bars(self, ax):
        rb_ensure_ui(ax)
        bars = all_tab_bars(ax)
        sets = [set(k) for k in bars.keys()]
        for expected, label in ((MAIN_TABS, "main view tab bar"),
                                (DOCK_TABS, "bottom dock tab bar"),
                                (REMOTE_TABS, "Remote sub-tab bar")):
            assert set(expected) in sets, \
                f"{label} not found: no group owns exactly the radios {expected}; " \
                f"radio groups present: {sorted(tuple(sorted(s)) for s in sets)}"

        main_bar = find_tab_bar(ax, MAIN_TABS)
        assert main_bar is not None and (main_bar.name or "").strip() == "Database Structure", \
            f"fresh main tab bar should report AXTitle 'Database Structure', got " \
            f"{getattr(main_bar, 'name', None)!r}"

        screenshot_assert(
            "structure_test_gate_three_tab_bars",
            "The DB Browser for SQLite window shows three tab strips at once: the main 4-tab bar "
            "with Database Structure selected followed by Browse Data, Edit Pragmas, Execute SQL; "
            "the bottom-right dock tab strip SQL Log / Plot / DB Schema / Remote with Remote "
            "highlighted; and inside the Remote dock panel a sub-tab strip DBHub.io / Local / "
            "Current Database with DBHub.io selected above an empty remote file list.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_toolbar_buttons(self, ax):
        rb_ensure_ui(ax)
        found = role_name_set(ax, "button", limit=150)
        assert not missing(TOOLBAR_BUTTONS, found), \
            f"toolbar buttons missing: {missing(TOOLBAR_BUTTONS, found)}"
        assert not missing(STRUCTURE_TOOLBAR_BUTTONS, found), \
            f"Database-Structure toolbar buttons missing: " \
            f"{missing(STRUCTURE_TOOLBAR_BUTTONS, found)}"

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_dock_panel_widgets(self, ax):
        rb_ensure_ui(ax)
        texts = label_texts(ax)
        want = [_norm_text(t) for t in DOCK_LABEL_TEXTS]
        gone = [orig for orig, n in zip(DOCK_LABEL_TEXTS, want) if n not in texts]
        assert not gone, f"dock panel signature labels missing: {gone}"

        assert find_button(ax, "Clear") is not None, \
            "SQL Log dock button 'Clear' not found"

        enc = [lb for lb in role_els(ax, "label", limit=200)
               if _norm_text(lb.name) == "database encoding"]
        assert enc, "status bar label 'Database encoding' not found"
        blob = f"{enc[0].name or ''} {el_value(ax, enc[0])}"
        assert "utf-8" in blob.lower(), \
            f"status bar encoding label should report UTF-8, got {blob!r}"

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_table_column_headers(self, ax):
        rb_ensure_ui(ax)
        cols = role_name_set(ax, "column", limit=100)
        for expected, label in ((STRUCTURE_COLUMNS, "Database Structure / DB Schema tree"),
                                (REMOTE_COLUMNS, "Remote file list"),
                                (PLOT_COLUMNS, "Plot column list")):
            assert not missing(expected, cols), \
                f"{label} column headers missing {missing(expected, cols)}; " \
                f"columns present: {sorted(cols)}"



# --------------------------------------------------------------------------- #
# B) SHAPE DELTAS  (reach / transition, depth >= 1)
# --------------------------------------------------------------------------- #

class TestStructureShapeDeltas:

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="Execute SQL tab page: 'Execute line' appears, 'Create Table' gone")
    def test_shape_execute_sql_tab(self, ax):
        rb_ensure_ui(ax)
        before = kit.rb_showing(ax)
        assert switch_tab(ax, "Execute SQL"), "could not AXPress the radio 'Execute SQL'"
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after,
                            target="button|Execute line",
                            source="button|Create Table"), \
            "switching to Execute SQL did not surface 'Execute line' while retiring 'Create Table'"
        assert len(after) > len(before), \
            f"Execute SQL page should ADD widgets: {len(before)} -> {len(after)} keys"

        btns = role_name_set(ax, "button", limit=150)
        assert not missing(EXEC_SQL_BUTTONS, btns), \
            f"Execute SQL toolbar buttons missing: {missing(EXEC_SQL_BUTTONS, btns)}"
        checks = role_name_set(ax, "checkbox", limit=60)
        assert "Find" in checks, f"Execute SQL 'Find' checkbox missing; checkboxes: {sorted(checks)}"

        screenshot_assert(
            "structure_test_shape_execute_sql_tab",
            "The Execute SQL tab is now the selected tab in the main 4-tab bar (Database "
            "Structure, Browse Data, Edit Pragmas, Execute SQL). The pane shows the SQL editor "
            "toolbar with a green triangular Execute SQL button and Execute line (both greyed out "
            "because no database is open) plus Stop execution, Open SQL file(s), Save SQL file, "
            "New tab, Find or replace and Un/comment block; below it an empty SQL text editor and "
            "an empty results area. The Create Table / Create Index / Modify Table tree toolbar of "
            "the Database Structure page is no longer visible.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="Browse Data tab page: text_field 'Filter in any column' appears, "
                           "'Create Table' gone")
    def test_shape_browse_data_tab(self, ax):
        rb_ensure_ui(ax)
        before = kit.rb_showing(ax)
        assert switch_tab(ax, "Browse Data"), "could not AXPress the radio 'Browse Data'"
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after,
                            target="text_field|Filter in any column",
                            source="button|Create Table"), \
            "Browse Data page did not expose the 'Filter in any column' field / still shows " \
            "'Create Table'"
        assert len(after) > len(before), \
            f"Browse Data page should ADD widgets: {len(before)} -> {len(after)} keys"

        fields = role_name_set(ax, "text_field", limit=60)
        assert not missing(BROWSE_TEXT_FIELDS, fields), \
            f"Browse Data text fields missing: {missing(BROWSE_TEXT_FIELDS, fields)}; " \
            f"text fields: {sorted(fields)}"
        btns = role_name_set(ax, "button", limit=150)
        assert not missing(BROWSE_BUTTONS, btns), \
            f"Browse Data buttons missing: {missing(BROWSE_BUTTONS, btns)}"

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="Edit Pragmas tab page: 'Secure Delete' pragma control appears, "
                           "'Create Table' gone, >= 30 new widgets")
    def test_shape_edit_pragmas_tab(self, ax):
        rb_ensure_ui(ax)
        before = kit.rb_showing(ax)
        assert switch_tab(ax, "Edit Pragmas"), "could not AXPress the radio 'Edit Pragmas'"
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after,
                            target="Secure Delete",
                            source="button|Create Table"), \
            "Edit Pragmas page did not surface the 'Secure Delete' pragma control"
        assert len(after) - len(before) >= 30, \
            f"Edit Pragmas page should add >= 30 widgets, got {len(after) - len(before)} " \
            f"({len(before)} -> {len(after)})"

        boxes = [(c.name or "") for c in role_els(ax, "checkbox", limit=80)]
        pragma_boxes = [n for n in boxes if any(p in n for p in PRAGMA_CHECKBOX_NAMES)]
        assert len(pragma_boxes) >= 8, \
            f"expected >= 8 pragma checkboxes (HTML AXTitles matched by substring), " \
            f"found {len(pragma_boxes)}"

        incs = role_els(ax, "incrementor", limit=40)
        assert len(incs) >= 4, f"expected >= 4 pragma incrementors, found {len(incs)}"

        btns = role_name_set(ax, "button", limit=150)
        assert not missing(["Save", "Cancel"], btns), \
            f"Edit Pragmas Save/Cancel buttons missing: {missing(['Save', 'Cancel'], btns)}"

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="dock tab Remote -> DB Schema: group|DB Schema appears, group|Remote "
                           "gone, dock tab bar AXTitle == 'DB Schema'")
    def test_shape_dock_tab_db_schema(self, ax):
        rb_ensure_ui(ax)
        before = kit.rb_showing(ax)
        assert switch_tab(ax, "DB Schema"), "could not AXPress the dock radio 'DB Schema'"
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after,
                            target="group|DB Schema",
                            source="group|Remote"), \
            "dock tab bar did not move from Remote to DB Schema"

        bar = find_tab_bar(ax, DOCK_TABS)
        assert bar is not None, f"dock tab bar with radios {DOCK_TABS} disappeared"
        assert (bar.name or "").strip() == "DB Schema", \
            f"dock tab bar AXTitle should be 'DB Schema', got {bar.name!r}"

        screenshot_assert(
            "structure_test_shape_dock_tab_db_schema",
            "The bottom-right dock of the DB Browser for SQLite window now shows a schema tree "
            "with the column headers Name / Object / Type / Schema / Database instead of the "
            "Remote panel, and 'DB Schema' is the highlighted tab in the SQL Log / Plot / DB "
            "Schema / Remote tab strip.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="dock tab bar walks Remote->DB Schema->Plot->SQL Log; group|SQL Log "
                           "appears, group|Plot gone")
    def test_shape_dock_tab_plot_then_sql_log(self, ax):
        rb_ensure_ui(ax)
        assert switch_tab(ax, "DB Schema"), "could not AXPress the dock radio 'DB Schema'"

        before1 = kit.rb_showing(ax)
        assert switch_tab(ax, "Plot"), "could not AXPress the dock radio 'Plot'"
        after1 = kit.rb_showing(ax)
        assert kit.rb_reach(before1, after1,
                            target="group|Plot",
                            source="group|DB Schema"), \
            "dock tab bar did not move from DB Schema to Plot"

        before2 = kit.rb_showing(ax)
        assert switch_tab(ax, "SQL Log"), "could not AXPress the dock radio 'SQL Log'"
        after2 = kit.rb_showing(ax)
        assert kit.rb_reach(before2, after2,
                            target="group|SQL Log",
                            source="group|Plot"), \
            "dock tab bar did not move from Plot to SQL Log"

        bar = find_tab_bar(ax, DOCK_TABS)
        assert bar is not None, f"dock tab bar with radios {DOCK_TABS} disappeared"
        assert (bar.name or "").strip() == "SQL Log", \
            f"dock tab bar AXTitle should be 'SQL Log' after the walk, got {bar.name!r}"

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="File > New In-Memory Database: window|Edit table definition appears, "
                           "2 windows, main title gains '- In-Memory database'")
    def test_shape_new_inmemory_db_opens_table_dialog(self, ax):
        rb_ensure_ui(ax)
        before = kit.rb_showing(ax)
        try:
            assert rb_reach_menu_item(ax, "File", "New In-Memory Database"), \
                "could not press the menu item File > New In-Memory Database"
            after = kit.rb_showing(ax)

            assert kit.rb_reach(before, after, target="window|Edit table definition"), \
                "'New In-Memory Database' did not open the 'Edit table definition' window"

            wins = ax.find(role="window", max_results=10, max_depth=1)
            assert len(wins) == 2, \
                f"expected 2 top-level windows (main + dialog), got {len(wins)}: {names(wins)}"

            mains = [w for w in wins
                     if (w.name or "").strip().lower().startswith(MAIN_WINDOW_PREFIX)]
            assert mains, f"main window vanished; windows: {names(wins)}"
            main_title = (mains[0].name or "").strip().lower()
            assert "in-memory database" in main_title, \
                f"main window title should become 'DB Browser for SQLite - In-Memory database', " \
                f"got {mains[0].name!r}"

            dlg = find_window(ax, "Edit table definition")
            assert dlg is not None, "no window titled 'Edit table definition'"

            fields = role_name_set(ax, "text_field", root_id=dlg.id, limit=40)
            assert "Table" in fields, \
                f"dialog is missing the 'Table' name field; text fields: {sorted(fields)}"
            boxes = role_name_set(ax, "checkbox", root_id=dlg.id, limit=40)
            assert "Advanced" in boxes, \
                f"dialog is missing the 'Advanced' checkbox; checkboxes: {sorted(boxes)}"

            radios = role_name_set(ax, "radio", root_id=dlg.id, limit=20)
            assert radios == TABLE_DIALOG_TABS, \
                f"dialog sub-tabs should be {sorted(TABLE_DIALOG_TABS)}, got {sorted(radios)}"

            btns = role_name_set(ax, "button", root_id=dlg.id, limit=60)
            assert not missing(TABLE_DIALOG_BUTTONS, btns), \
                f"dialog buttons missing: {missing(TABLE_DIALOG_BUTTONS, btns)}"

            cols = role_name_set(ax, "column", root_id=dlg.id, limit=60)
            assert not missing(TABLE_DIALOG_COLUMNS, cols), \
                f"dialog field-grid headers missing: {missing(TABLE_DIALOG_COLUMNS, cols)}; " \
                f"columns: {sorted(cols)}"

            screenshot_assert(
                "structure_test_shape_new_inmemory_db_opens_table_dialog",
                "A modal window titled 'Edit table definition' is open in front of the DB Browser "
                "for SQLite window: it has a 'Table' name field, an 'Advanced' checkbox, a field "
                "grid whose headers read Name, Type, NN, PK, AI, U, Default, Check, Collation, "
                "Foreign Key, Add / Remove / move-up / move-down buttons, a read-only SQL box "
                "showing CREATE TABLE \"\" ( ); , the sub-tabs Fields / Index Constraints / "
                "Foreign Keys / Check Constraints, and OK / Cancel buttons. The main window title "
                "behind it now reads 'DB Browser for SQLite - In-Memory database'.",
                RESULTS_DIR)
        finally:
            close_window_via_cancel(ax, find_window(ax, "Edit table definition"))

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="SQL sub-tab 'SQL 1' created by the New tab button")
    def test_shape_execute_sql_new_tab_creates_sql1(self, ax):
        rb_ensure_ui(ax)
        assert switch_tab(ax, "Execute SQL"), "could not AXPress the radio 'Execute SQL'"

        pre = [n for n in role_name_set(ax, "radio", limit=60) if SQL_SUBTAB_RE.match(n or "")]
        assert not pre, f"a SQL sub-tab already exists before pressing 'New tab': {sorted(pre)}"

        before = kit.rb_showing(ax)
        assert rb_press_button(ax, "New tab", settle=1.4), \
            "could not AXPress the Execute SQL button 'New tab'"
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after, target="radio|SQL 1"), \
            "'New tab' did not create the SQL sub-tab 'SQL 1'"

        bar = find_tab_bar(ax, ["SQL 1"])
        assert bar is not None, "no tab bar owning exactly the radio 'SQL 1' was created"
        assert (bar.name or "").strip() == "SQL 1", \
            f"SQL sub-tab bar AXTitle should be 'SQL 1', got {bar.name!r}"

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="app menu Preferences.../Settings... opens window|Preferences with the "
                           "6 tab radios General..Remote as a new top-level surface")
    def test_shape_preferences_window_is_new_surface(self, ax):
        rb_ensure_ui(ax)
        before = kit.rb_showing(ax)
        win = None
        try:
            assert rb_open_preferences(ax), \
                "could not press Preferences.../Settings... in the application menu"
            after = kit.rb_showing(ax)

            assert kit.rb_reach(before, after, target="window|Preferences"), \
                "no new 'Preferences' window appeared after the app-menu item was pressed"

            win = find_window(ax, "Preferences") or find_window(ax, "Settings")
            assert win is not None, "no top-level window titled Preferences / Settings"

            radios = role_name_set(ax, "radio", root_id=win.id, limit=30)
            assert radios == PREFS_TABS, \
                f"Preferences tab radios should be {sorted(PREFS_TABS)}, got {sorted(radios)}"

            btns = role_name_set(ax, "button", root_id=win.id, limit=80)
            assert not missing(PREFS_BUTTONS, btns), \
                f"Preferences buttons missing: {missing(PREFS_BUTTONS, btns)}"

            screenshot_assert(
                "structure_test_shape_preferences_window_is_new_surface",
                "A separate 'Preferences' window is open with a tab strip reading General, "
                "Database, Data Browser, SQL, Extensions, Remote (General selected). The General "
                "page shows a Language dropdown reading 'English (United States) [System "
                "Language]', Font size 13, Max Recent Files 5, several toolbar-style dropdowns, "
                "and Save / Cancel / Restore Defaults buttons at the bottom.",
                RESULTS_DIR)
        finally:
            close_window_via_cancel(ax, win or find_window(ax, "Preferences"))