File size: 34,713 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
"""AX button-interaction tests for DB Browser for SQLite (Qt6).

Every assertion below encodes an OBSERVED CONSEQUENCE recorded in recon.md
(`## BUTTONS` B-groups 1..5, `## STATE` ST8/ST9/ST10, `## COMPUTATION`, `## TEXT` T4/T5):
an AXEnabled flip, a new surface, or a changed value / label / counter.

Safety contract honoured here: no press of New Database / Open Database / Open Project /
Save Project / Save Table As / New Data Browser / Save results / Open SQL file(s) /
Save SQL file / Attach Database / Write Changes / Revert Changes / Upload / Refresh /
Clone from Link / Import / Export / Print / Set as NULL / any dock Close or Float /
any window-chrome button.  Dialogs are always closed with their OWN scoped `Cancel`.
"""

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__)))
COUNTER_RE = re.compile(r"^\s*\d+\s*-\s*\d+\s+of\s+\d+\s*$")


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 _keystroke(text):
    subprocess.run(["osascript", "-e",
                    'tell application "System Events" to keystroke ' + json.dumps(text)],
                   capture_output=True)


def open_menu(ax, top):
    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):
    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 find_button(ax, name, root_id=None):
    for b in ax.find(role="button", max_results=90, root_id=root_id):
        if (b.name or "") == name:
            return b
    return None


def enabled(ax, el):
    return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled"))


def btn_enabled(ax, name):
    b = find_button(ax, name)
    return None if b is None else enabled(ax, b)


def sql_editor(ax):
    """The QScintilla SQL editor: the only settable text_area that is not the SQL log."""
    for t in ax.find(role="text_area", max_results=15):
        if not ax.is_attribute_settable(t.id, "AXValue"):
            continue
        v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "")
        if "PRAGMA" in v or "EXECUTING" in v:
            continue
        return t
    return None


def run_sql(ax, sql):
    """Type + execute SQL. set_value is IGNORED by QScintilla -> click + keystroke."""
    switch_tab(ax, "Execute SQL")
    e = sql_editor(ax)
    assert e is not None, "SQL editor not found"
    ax.click_element_cg(e.id)
    time.sleep(0.35)
    subprocess.run(["osascript", "-e",
                    'tell application "System Events" to keystroke "a" using command down'],
                   capture_output=True)
    time.sleep(0.25)
    _keystroke(sql)
    time.sleep(0.5)
    b = find_button(ax, "Execute SQL")
    assert b is not None and enabled(ax, b), "Execute SQL button not enabled"
    ax.action(b.id, "AXPress")
    time.sleep(1.9)


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


def record_counter(ax):
    """Browse Data counter label, e.g. '1 - 3 of 3'. MUST use the regex — a plain
    ' of ' test also matches 'Identification of the cell currently in the editor'."""
    for l in ax.find(role="label", max_results=350):
        v = str(ax.get(l.id, ["AXValue"]).get("AXValue") or "")
        if COUNTER_RE.match(v):
            return v.strip()
    return None


def label_value(ax, needle):
    for l in ax.find(role="label", max_results=350):
        v = str(ax.get(l.id, ["AXValue"]).get("AXValue") or "")
        if needle in v:
            return v
    return None


# ---------------------------------------------------------------------------
# extra locators built on the skeleton (semantic: AXTitle/AXDescription + AXRole,
# scoped by named parent container — never by child index or tree path)
# ---------------------------------------------------------------------------

SQL_SUBTAB_RE = re.compile(r"^SQL\s+\d+$")


def main_window(ax):
    """The main app window, matched on its visible title (never by index)."""
    for w in ax.find(role="window", max_results=10, max_depth=1):
        if (w.name or "").startswith("DB Browser for SQLite"):
            return w
    return None


def reveal_main_window(ax):
    """The app is a regular windowed app (recon REVEAL_STEPS): the main window is already
    on screen at launch. Raise it so window-dependent checks + screenshots see it."""
    w = main_window(ax)
    if w is not None:
        try:
            ax.action(w.id, "AXRaise")
            time.sleep(0.3)
        except Exception:
            pass
    return w


def find_text_field(ax, name, root_id=None, contains=False):
    for t in ax.find(role="text_field", max_results=60, root_id=root_id):
        n = t.name or ""
        if (name in n) if contains else (n == name):
            return t
    return None


def find_checkbox(ax, name, root_id=None, contains=False):
    for c in ax.find(role="checkbox", max_results=60, root_id=root_id):
        n = c.name or ""
        if (name in n) if contains else (n == name):
            return c
    return None


def dialog_ddl_preview(ax, win):
    """The dialog's read-only SQL box: its text_area whose AXValue contains CREATE."""
    for t in ax.find(role="text_area", max_results=10, root_id=win.id):
        v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "")
        if "CREATE" in v:
            return v
    return None


def sql_log_pane(ax):
    """(element, value) of the SQL Log dock text_area — it holds the PRAGMA trace."""
    for t in ax.find(role="text_area", max_results=15):
        v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "")
        if "PRAGMA" in v:
            return t, v
    return None, ""


def enabled_map(ax, names):
    return {n: btn_enabled(ax, n) for n in names}


def prove_value(observed, expected):
    """kit.rb_value proof that tolerates dict/str shapes for map-valued observations."""
    try:
        if kit.rb_value(observed, expected):
            return True
    except Exception:
        pass
    return bool(kit.rb_value(json.dumps(observed, sort_keys=True, default=str),
                             json.dumps(expected, sort_keys=True, default=str)))


def close_dialog_with_cancel(ax, win):
    c = ax.find(role="button", name="Cancel", root_id=win.id, max_results=2)
    assert c, "dialog exposes no scoped Cancel button"
    ax.action(c[0].id, "AXPress")
    time.sleep(1.0)


# ---------------------------------------------------------------------------


class TestToolbarButtonStates:
    """B-group 1 — DB toolbar / project toolbar / Database-Structure toolbar buttons."""

    @pytest.mark.rb(
        depth=0, jump_kind="value",
        expect="Write Changes/Revert Changes/Undo/Save Project/Attach Database/Create Table/"
               "Create Index/Modify Table all AXEnabled False on a fresh app while "
               "New Database/Open Database/Open Project are True",
    )
    def test_toolbar_disabled_state_without_database(self, ax):
        w = reveal_main_window(ax)
        assert w is not None, "no main window named 'DB Browser for SQLite' in the AX tree"
        assert (w.name or "") == "DB Browser for SQLite", (
            "a fresh app must have NO database open (recon T2), got title %r" % (w.name,))

        expected = {
            "New Database": True,
            "Open Database": True,
            "Open Project": True,
            "Write Changes": False,
            "Revert Changes": False,
            "Undo": False,
            "Save Project": False,
            "Attach Database": False,
            "Create Table": False,
            "Create Index": False,
            "Modify Table": False,
        }
        observed = enabled_map(ax, list(expected))

        missing = [n for n, v in observed.items() if v is None]
        assert not missing, "toolbar buttons absent from the AX tree: %r" % (missing,)
        assert observed == expected, (
            "fresh-app toolbar AXEnabled map mismatch:\n observed=%r\n expected=%r"
            % (observed, expected))
        assert prove_value(observed, expected)

        screenshot_assert(
            "buttons_toolbar_fresh_state",
            "DB Browser for SQLite main window, no database open. Top toolbar row shows "
            "New Database and Open Database (Open Database has a dropdown chevron) as active "
            "icons, while Write Changes, Revert Changes, Undo, Open Project (active), "
            "Save Project and Attach Database follow — Write Changes, Revert Changes, Undo, "
            "Save Project and Attach Database are greyed out/disabled. Below the toolbar a "
            "4-tab bar reads Database Structure (selected), Browse Data, Edit Pragmas, "
            "Execute SQL, and above the empty schema tree the Create Table, Create Index and "
            "Modify Table buttons are also greyed out. Right side shows the Edit Database Cell "
            "dock with a Mode: dropdown reading Text and the Remote dock; bottom dock tab strip "
            "reads SQL Log, Plot, DB Schema, Remote; status bar bottom-right reads UTF-8.",
            RESULTS_DIR)

    @pytest.mark.rb(
        depth=1, jump_kind="transition",
        expect="button 'Create Table' AXEnabled False->True after File>New In-Memory Database",
    )
    def test_create_table_button_enables_with_database(self, ax):
        reveal_main_window(ax)
        before = btn_enabled(ax, "Create Table")
        assert before is False, "Create Table must start disabled with no DB, got %r" % (before,)

        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"

        after = btn_enabled(ax, "Create Table")
        assert after is True, "Create Table must become enabled once a DB exists, got %r" % (after,)
        assert kit.rb_flip(before, after)

        w = main_window(ax)
        assert w is not None and "In-Memory database" in (w.name or ""), (
            "main window title must gain '- In-Memory database', got %r"
            % (None if w is None else w.name,))

    @pytest.mark.rb(
        depth=1, jump_kind="transition",
        expect="'Create Index' and 'Attach Database' AXEnabled False->True after opening the "
               "in-memory database",
    )
    def test_create_index_and_attach_buttons_enable_with_database(self, ax):
        reveal_main_window(ax)
        before = (btn_enabled(ax, "Create Index"), btn_enabled(ax, "Attach Database"))
        assert before == (False, False), (
            "Create Index / Attach Database must both start disabled, got %r" % (before,))

        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"

        after = (btn_enabled(ax, "Create Index"), btn_enabled(ax, "Attach Database"))
        assert after == (True, True), (
            "Create Index / Attach Database must both be enabled with a DB, got %r" % (after,))
        assert kit.rb_flip(before, after)

    @pytest.mark.rb(
        depth=1, jump_kind="transition",
        expect="Write Changes / Revert Changes AXEnabled False->True after CREATE TABLE via "
               "Execute SQL",
    )
    def test_write_changes_button_enables_after_ddl(self, ax):
        reveal_main_window(ax)
        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"

        before = (btn_enabled(ax, "Write Changes"), btn_enabled(ax, "Revert Changes"))
        assert before == (False, False), (
            "a freshly created DB has no pending changes, so Write/Revert Changes must be "
            "disabled, got %r" % (before,))

        run_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT);")

        after = (btn_enabled(ax, "Write Changes"), btn_enabled(ax, "Revert Changes"))
        assert after == (True, True), (
            "DDL opens a transaction, so Write/Revert Changes must be enabled, got %r" % (after,))
        assert kit.rb_flip(before, after)
        # never pressed: committing / rolling back destabilises the shared session


class TestStructureToolbarDialogButtons:
    """B-group 1 press effects + B-group 5 dialog buttons."""

    @pytest.mark.rb(
        depth=1, jump_kind="reach",
        expect="window 'Edit table definition' opens with preview CREATE TABLE \"\" ( );",
    )
    def test_create_table_button_opens_edit_table_definition_dialog(self, ax):
        reveal_main_window(ax)
        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"

        before = kit.rb_showing(ax)
        b = find_button(ax, "Create Table")
        assert b is not None and enabled(ax, b), "Create Table button missing or disabled"
        ax.action(b.id, "AXPress")
        time.sleep(1.4)
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after, target="window|Edit table definition")

        w = find_window(ax, "Edit table definition")
        assert w is not None, "no window titled 'Edit table definition' after the press"

        preview = dialog_ddl_preview(ax, w)
        assert preview == 'CREATE TABLE "" (\n\n);', (
            "freshly opened dialog DDL preview mismatch: %r" % (preview,))

        dialog_buttons = {
            "Add": True,     # a new field can always be appended
            "Remove": False,  # nothing to remove yet
            "OK": False,      # table has no name yet
            "Cancel": True,
        }
        observed = {}
        for name, _ in dialog_buttons.items():
            el = find_button(ax, name, root_id=w.id)
            observed[name] = None if el is None else enabled(ax, el)
        assert observed == dialog_buttons, (
            "Edit-table-definition button enabled map mismatch:\n observed=%r\n expected=%r"
            % (observed, dialog_buttons))

        screenshot_assert(
            "buttons_create_table_dialog",
            "A modal window titled 'Edit table definition' is open in front of the DB Browser "
            "for SQLite main window. It shows a 'Table' name field (empty), an 'Advanced' "
            "checkbox, an empty field grid whose column headers read Name, Type, NN, PK, AI, U, "
            "Default, Check, Collation, Foreign Key, a column of Add / Remove / Move up / "
            "Move down / Move to top / Move to bottom buttons (only Add is enabled), the tab row "
            "Fields / Index Constraints / Foreign Keys / Check Constraints with Fields selected, "
            "a read-only SQL box showing CREATE TABLE \"\" ( ); and OK (greyed out) plus Cancel "
            "buttons at the bottom.",
            RESULTS_DIR)

        close_dialog_with_cancel(ax, w)
        assert find_window(ax, "Edit table definition") is None, (
            "the dialog's own Cancel button must close 'Edit table definition'")

    @pytest.mark.rb(
        depth=1, jump_kind="reach",
        expect="window 'Edit Index Schema' opens from the Create Index toolbar button",
    )
    def test_create_index_button_opens_edit_index_schema_dialog(self, ax):
        reveal_main_window(ax)
        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"

        before = kit.rb_showing(ax)
        b = find_button(ax, "Create Index")
        assert b is not None and enabled(ax, b), "Create Index button missing or disabled"
        ax.action(b.id, "AXPress")
        time.sleep(1.4)
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after, target="window|Edit Index Schema")

        w = find_window(ax, "Edit Index Schema")
        assert w is not None, "no window titled 'Edit Index Schema' after the press"

        name_field = find_text_field(ax, "Name", root_id=w.id)
        unique_box = find_checkbox(ax, "Unique", root_id=w.id)
        partial = find_text_field(ax, "Partial", root_id=w.id, contains=True)
        cancel = ax.find(role="button", name="Cancel", root_id=w.id, max_results=2)
        ok_btn = find_button(ax, "OK", root_id=w.id)

        assert name_field is not None, "Edit Index Schema exposes no text_field 'Name'"
        assert unique_box is not None, "Edit Index Schema exposes no checkbox 'Unique'"
        assert partial is not None, (
            "Edit Index Schema exposes no partial-index-clause text_field")
        assert cancel, "Edit Index Schema exposes no scoped Cancel button"
        assert ok_btn is not None and enabled(ax, ok_btn) is False, (
            "OK must stay disabled while the index is unnamed")

        close_dialog_with_cancel(ax, w)
        assert find_window(ax, "Edit Index Schema") is None, (
            "the dialog's own Cancel button must close 'Edit Index Schema'")

    @pytest.mark.rb(
        depth=2, jump_kind="value",
        expect='preview goes CREATE TABLE "people" ( ) -> adds "Field1" INTEGER -> '
               'adds "Field2" INTEGER',
    )
    def test_dialog_add_button_grows_create_table_preview(self, ax):
        reveal_main_window(ax)
        # surface 1: the in-memory DB (its auto-opened dialog is dismissed by the helper)
        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"

        # surface 2: re-open the table designer through the toolbar button
        b = find_button(ax, "Create Table")
        assert b is not None and enabled(ax, b), "Create Table button missing or disabled"
        ax.action(b.id, "AXPress")
        time.sleep(1.4)
        w = find_window(ax, "Edit table definition")
        assert w is not None, "'Edit table definition' did not re-open"

        table_field = find_text_field(ax, "Table", root_id=w.id)
        assert table_field is not None, "dialog exposes no text_field 'Table'"
        ax.set_value(table_field.id, "people")
        time.sleep(0.5)
        named = dialog_ddl_preview(ax, w)
        assert named == 'CREATE TABLE "people" (\n\n);', (
            "preview after naming the table mismatch: %r" % (named,))

        add = find_button(ax, "Add", root_id=w.id)
        assert add is not None and enabled(ax, add), "dialog 'Add' button missing or disabled"

        ax.action(add.id, "AXPress")
        time.sleep(0.6)
        one_field = dialog_ddl_preview(ax, w)
        assert one_field == 'CREATE TABLE "people" (\n\t"Field1"\tINTEGER\n);', (
            "preview after the first Add mismatch: %r" % (one_field,))

        add = find_button(ax, "Add", root_id=w.id) or add
        ax.action(add.id, "AXPress")
        time.sleep(0.6)
        two_fields = dialog_ddl_preview(ax, w)
        expected = ('CREATE TABLE "people" (\n\t"Field1"\tINTEGER,'
                    '\n\t"Field2"\tINTEGER\n);')
        assert two_fields == expected, (
            "preview after the second Add mismatch: %r" % (two_fields,))
        assert kit.rb_value(two_fields, expected)

        close_dialog_with_cancel(ax, w)
        assert find_window(ax, "Edit table definition") is None, (
            "the dialog's own Cancel button must close 'Edit table definition'")


class TestExecuteSqlButtons:
    """B-group 2 — Execute SQL tab toolbar buttons."""

    @pytest.mark.rb(
        depth=1, jump_kind="value",
        expect="Execute SQL tab, no DB: New tab/Open SQL file(s)/Save SQL file/Find or replace/"
               "Un/comment block/Stop execution True; Execute SQL/Execute line/Save results False",
    )
    def test_execute_sql_buttons_enabled_map_without_database(self, ax):
        reveal_main_window(ax)
        assert switch_tab(ax, "Execute SQL"), "no radio named 'Execute SQL' in the main tab bar"

        expected = {
            "New tab": True,
            "Open SQL file(s)": True,
            "Save SQL file": True,
            "Find or replace": True,
            "Un/comment block": True,
            "Stop execution": True,
            "Execute SQL": False,
            "Execute line": False,
            "Save results": False,
        }
        observed = enabled_map(ax, list(expected))

        missing = [n for n, v in observed.items() if v is None]
        assert not missing, "Execute-SQL toolbar buttons absent from the AX tree: %r" % (missing,)
        assert observed == expected, (
            "Execute-SQL button AXEnabled map (no DB) mismatch:\n observed=%r\n expected=%r"
            % (observed, expected))
        assert prove_value(observed, expected)
        # no file-dialog button was pressed

    @pytest.mark.rb(
        depth=1, jump_kind="reach",
        expect="SQL sub-tab 'SQL 1' created (radio|SQL 1 appears)",
    )
    def test_new_tab_button_creates_sql_sub_tab(self, ax):
        reveal_main_window(ax)
        assert switch_tab(ax, "Execute SQL"), "no radio named 'Execute SQL' in the main tab bar"

        pre = [r.name for r in ax.find(role="radio", max_results=40)
               if SQL_SUBTAB_RE.match(r.name or "")]
        assert pre == [], "no SQL sub-tab may exist before pressing New tab, found %r" % (pre,)

        before = kit.rb_showing(ax)
        b = find_button(ax, "New tab")
        assert b is not None and enabled(ax, b), "New tab button missing or disabled"
        ax.action(b.id, "AXPress")
        time.sleep(1.0)
        after = kit.rb_showing(ax)

        assert kit.rb_reach(before, after, target="radio|SQL 1")

        post = [r.name for r in ax.find(role="radio", max_results=40)
                if SQL_SUBTAB_RE.match(r.name or "")]
        assert post == ["SQL 1"], "expected exactly one sub-tab 'SQL 1', found %r" % (post,)

    @pytest.mark.rb(
        depth=1, jump_kind="value",
        expect="Execute SQL button False->True, and running SELECT 7*6 AS answer; yields "
               "column 'answer' cell '42'",
    )
    def test_execute_sql_button_enables_with_database_and_computes(self, ax):
        reveal_main_window(ax)
        assert switch_tab(ax, "Execute SQL"), "no radio named 'Execute SQL' in the main tab bar"

        before = btn_enabled(ax, "Execute SQL")
        assert before is False, (
            "Execute SQL must be disabled while no database is open, got %r" % (before,))

        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"

        after = btn_enabled(ax, "Execute SQL")
        assert after is True, (
            "Execute SQL must become enabled once a database is open, got %r" % (after,))

        run_sql(ax, "SELECT 7*6 AS answer;")

        cols, cells = result_cells(ax)
        assert cols == ["answer"], "results grid columns mismatch: %r" % (cols,)
        assert kit.rb_value(cells, "42")
        assert "42" in [str(c) for c in cells], "results grid cells mismatch: %r" % (cells,)

        screenshot_assert(
            "buttons_execute_sql_result",
            "DB Browser for SQLite with the in-memory database open and the Execute SQL tab "
            "active. The SQL editor holds the statement SELECT 7*6 AS answer; the Execute "
            "toolbar (green play icon plus Execute line, Stop, open/save SQL, New tab, find and "
            "comment icons) sits above it with Execute now enabled, the results grid below shows "
            "a single column headed 'answer' containing the value 42, and the message pane reads "
            "'Execution finished without errors. Result: 1 rows returned in ...'.",
            RESULTS_DIR)


class TestBrowseDataButtons:
    """B-group 3 — Browse Data tab buttons."""

    def _load_nums(self, ax, rows_sql):
        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"
        run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); "
                    "INSERT INTO nums VALUES" + rows_sql + ";")
        assert switch_tab(ax, "Browse Data"), "no radio named 'Browse Data' in the main tab bar"

    @pytest.mark.rb(
        depth=1, jump_kind="value",
        expect="Browse Data counter '1 - 3 of 3' -> '1 - 4 of 4' after pressing New Record",
    )
    def test_new_record_button_increments_record_counter(self, ax):
        reveal_main_window(ax)
        self._load_nums(ax, "(10,'ten'),(20,'twenty'),(30,'thirty')")

        before = record_counter(ax)
        assert before == "1 - 3 of 3", "record counter before New Record: %r" % (before,)

        b = find_button(ax, "New Record")
        assert b is not None and enabled(ax, b), "New Record button missing or disabled"
        ax.action(b.id, "AXPress")
        time.sleep(1.4)

        after = record_counter(ax)
        assert kit.rb_value(after, "1 - 4 of 4")
        assert after == "1 - 4 of 4", "record counter after New Record: %r" % (after,)

        screenshot_assert(
            "buttons_new_record_counter",
            "DB Browser for SQLite, Browse Data tab active on the in-memory database. A "
            "'Table:' dropdown reads nums, the data grid has columns _rowid_, n, label with the "
            "rows 10/ten, 20/twenty, 30/thirty plus a newly inserted empty row at the bottom, a "
            "'Filter in any column' box sits under the headers, and the record navigation strip "
            "(|< < > >| and Go to:) with the record counter now reads '1 - 4 of 4' after the New "
            "Record button was pressed.",
            RESULTS_DIR)

    @pytest.mark.rb(
        depth=1, jump_kind="transition",
        expect="Clear Filters False->True when a filter is set, and pressing it restores counter "
               "'1 - 3 of 3' and empties the filter",
    )
    def test_clear_filters_button_round_trip(self, ax):
        reveal_main_window(ax)
        self._load_nums(ax, "(10,'ten'),(20,'twenty'),(30,'thirty')")

        assert btn_enabled(ax, "Clear Filters") is False, (
            "Clear Filters must be disabled on a freshly loaded, unfiltered table")
        c0 = record_counter(ax)
        assert c0 == "1 - 3 of 3", "record counter before filtering: %r" % (c0,)

        f = find_text_field(ax, "Filter in any column")
        assert f is not None, "no text_field 'Filter in any column' on the Browse Data tab"
        ax.set_value(f.id, "twenty")
        time.sleep(1.6)

        filtered_enabled = btn_enabled(ax, "Clear Filters")
        c1 = record_counter(ax)
        assert filtered_enabled is True, (
            "Clear Filters must become enabled once a filter is active, got %r"
            % (filtered_enabled,))
        assert c1 == "1 - 1 of 1", "record counter while filtered on 'twenty': %r" % (c1,)
        assert kit.rb_flip((False, c0), (filtered_enabled, c1))

        screenshot_assert(
            "buttons_clear_filters_filtered",
            "DB Browser for SQLite, Browse Data tab on table nums with a filter applied: the "
            "'Filter in any column' box contains the text twenty, the data grid (columns "
            "_rowid_, n, label) shows only ONE visible row 20 / twenty, the record counter reads "
            "'1 - 1 of 1', and the Clear Filters button in the toolbar strip is now enabled "
            "(no longer greyed out).",
            RESULTS_DIR)

        cf = find_button(ax, "Clear Filters")
        assert cf is not None and enabled(ax, cf), "Clear Filters button missing or disabled"
        ax.action(cf.id, "AXPress")
        time.sleep(1.6)

        assert btn_enabled(ax, "Clear Filters") is False, (
            "Clear Filters must disable itself again once no filter remains")
        f2 = find_text_field(ax, "Filter in any column")
        assert f2 is not None, "the filter field disappeared after Clear Filters"
        fv = str(ax.get(f2.id, ["AXValue"]).get("AXValue") or "")
        assert fv == "", "filter field must be emptied by Clear Filters, got %r" % (fv,)
        c2 = record_counter(ax)
        assert c2 == "1 - 3 of 3", "record counter after Clear Filters: %r" % (c2,)

    @pytest.mark.rb(
        depth=1, jump_kind="value",
        expect="|< < > >| Go to: New Record Save Table As New Data Browser enabled and "
               "Clear Filters/Clear Sorting disabled on a freshly loaded table",
    )
    def test_browse_data_navigation_buttons_enabled_with_data(self, ax):
        reveal_main_window(ax)
        self._load_nums(ax, "(10,'ten'),(20,'twenty')")

        expected = {
            "|<": True,
            "<": True,
            ">": True,
            ">|": True,
            "Go to:": True,
            "New Record": True,
            "Save Table As": True,
            "New Data Browser": True,
            "Clear Filters": False,
            "Clear Sorting": False,
        }
        observed = enabled_map(ax, list(expected))

        missing = [n for n, v in observed.items() if v is None]
        assert not missing, "Browse-Data buttons absent from the AX tree: %r" % (missing,)
        assert observed == expected, (
            "Browse-Data button AXEnabled map mismatch:\n observed=%r\n expected=%r"
            % (observed, expected))
        assert prove_value(observed, expected)

        goto = find_text_field(ax, "Enter record number to browse")
        assert goto is not None, "'Go to:' has no paired record-number text_field"
        # Save Table As / New Data Browser were never pressed (they raise dialogs/windows)


class TestDockPanelButtons:
    """B-group 4 — SQL Log / Plot / Remote / Edit-Database-Cell dock buttons."""

    @pytest.mark.rb(
        depth=1, jump_kind="transition",
        expect="SQL Log dock text_area AXValue starts with PRAGMA foreign_keys = '1'; before "
               "Clear and is '' after",
    )
    def test_sql_log_clear_button_empties_the_log(self, ax):
        reveal_main_window(ax)
        assert rb_enter_inmemory_db(ax), "in-memory DB did not open (modal still present)"
        assert switch_tab(ax, "SQL Log"), "no dock radio named 'SQL Log'"

        pane, before_value = sql_log_pane(ax)
        assert pane is not None, "no SQL-log text_area holding the PRAGMA trace"
        assert before_value.startswith("PRAGMA foreign_keys = '1';"), (
            "SQL log must record the connection PRAGMAs, got %r" % (before_value[:120],))

        b = find_button(ax, "Clear")
        assert b is not None and enabled(ax, b), "SQL Log dock 'Clear' button missing or disabled"
        ax.action(b.id, "AXPress")
        time.sleep(0.6)

        after_value = str(ax.get(pane.id, ["AXValue"]).get("AXValue") or "")
        assert after_value == "", "Clear must empty the SQL log, got %r" % (after_value[:120],)
        assert kit.rb_flip(before_value, after_value)

    @pytest.mark.rb(
        depth=0, jump_kind="value",
        expect="Load all data and redraw plot / Save current plot / Upload / Refresh / "
               "Clone from Link / Import / Export / Set as NULL / Print / Apply all "
               "AXEnabled False on a fresh app",
    )
    def test_plot_and_cell_editor_buttons_disabled_without_database(self, ax):
        w = reveal_main_window(ax)
        assert w is not None, "no main window named 'DB Browser for SQLite' in the AX tree"
        assert (w.name or "") == "DB Browser for SQLite", (
            "a fresh app must have NO database open (recon T2), got title %r" % (w.name,))

        names = [
            "Load all data and redraw plot",   # Plot dock
            "Upload", "Refresh", "Clone from Link",   # Remote dock
            "Import", "Export", "Set as NULL", "Print", "Apply",   # Edit Database Cell dock
            "Open in external application", "Open in application",
        ]
        expected = {n: False for n in names}
        observed = enabled_map(ax, names)

        missing = [n for n, v in observed.items() if v is None]
        assert not missing, "dock buttons absent from the AX tree: %r" % (missing,)
        assert observed == expected, (
            "dock buttons must all be disabled with no database:\n observed=%r" % (observed,))
        assert prove_value(observed, expected)

        # the plot-save button carries a literal HTML AXTitle -> substring match, never equality
        plot_save = [b for b in ax.find(role="button", max_results=90)
                     if "Save current plot" in (b.name or "")]
        assert plot_save, "no button whose AXTitle contains 'Save current plot'"
        assert enabled(ax, plot_save[0]) is False, (
            "'Save current plot' must be disabled while there is nothing plotted")
        # none of these buttons were pressed (network / file-dialog / print side effects)