File size: 32,663 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
"""AX TEXT-CONTENT lane — DB Browser for SQLite (Qt6).

Every string asserted here is taken verbatim from recon.md `## TEXT` (T1..T6), with window titles
from T2, column-header texts from T3 and interaction->text deltas from T4/T5.

Ground rules honoured by this module:
  * Visible text of this app lives in `label` elements whose AXTitle is EMPTY and whose AXValue
    carries the string -> always read via `ax.get(el.id, ["AXValue"])`.
  * Column headers are `column`-role elements read via `el.name`.
  * A fresh app has NO DATABASE open; the deterministic, dialog-free way to get one is
    `File > New In-Memory Database` + dismissing the auto-opened "Edit table definition" modal
    with that window's OWN scoped Cancel button (recon REVEAL_STEPS).
  * Build-specific text is NEVER asserted: the About version number
    ("... Version 3.13.99 (Aug 11 2026) ... Last commit hash ...") and the `in Nms` / `Took 0ms`
    timing digits are forbidden. Only the stable prefixes/sentences are asserted.
"""

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 label_values(ax, root_id=None, limit=350):
    """All non-empty AXValue strings of `label` elements."""
    out = []
    for l in ax.find(role="label", max_results=limit, root_id=root_id):
        v = ax.get(l.id, ["AXValue"]).get("AXValue")
        if isinstance(v, str) and v.strip():
            out.append(v)
    return out


def label_with(ax, needle, root_id=None):
    for v in label_values(ax, root_id=root_id):
        if needle in v:
            return v
    return None


def column_names(ax, root_id=None):
    return [c.name for c in ax.find(role="column", max_results=120, root_id=root_id) if c.name]


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 main_window(ax):
    wid = ax.get_main_window()
    return None if wid is None else ax.get(wid, ["AXTitle"]).get("AXTitle")


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, root_id=None):
    r = ax.find(role="radio", name=name, max_results=1, root_id=root_id)
    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 sql_editor(ax):
    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):
    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 exec_msg(ax):
    for t in ax.find(role="text_area", max_results=15):
        v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "")
        if v.startswith("Execution finished"):
            return v
    return ""


def record_counter(ax):
    """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 grid_cell_named(ax, name):
    for t in ax.find(role="table", max_results=10):
        if (t.name or "") == "search result":
            continue
        for c in ax.find(role="label", root_id=t.id, max_results=40, max_depth=1):
            if (c.name or "") == name:
                return c
    return None


# --------------------------------------------------------------------------------------------
# extra text-lane helpers (built on the primitives above)
# --------------------------------------------------------------------------------------------

def ensure_ui(ax):
    """Reveal the app's UI before any window/text inspection.

    recon REVEAL_STEPS: this is a REGULAR windowed app — the main window is already on screen at
    launch (no status item / LSUIElement path). So the only reveal needed is to raise it; a
    recreation that hides the window behind another surface still reports truthfully because the
    assertions below run against whatever `get_main_window()` yields.
    """
    wid = ax.get_main_window()
    if wid is not None:
        try:
            ax.action(wid, "AXRaise")
        except Exception:
            pass
        time.sleep(0.2)
    return wid


def label_strings(ax, root_id=None, limit=350):
    """AXValue *and* AXTitle strings of `label` elements.

    The reference puts dialog prose in AXValue; a differently-built recreation may legitimately
    expose the same visible text as the label's AXTitle, so dialog scans consider both.
    """
    out = []
    for l in ax.find(role="label", max_results=limit, root_id=root_id):
        v = ax.get(l.id, ["AXValue"]).get("AXValue")
        if isinstance(v, str) and v.strip():
            out.append(v)
        if l.name and l.name.strip():
            out.append(l.name)
    return out


def text_area_values(ax, root_id=None):
    out = []
    for t in ax.find(role="text_area", max_results=15, root_id=root_id):
        v = ax.get(t.id, ["AXValue"]).get("AXValue")
        out.append(v if isinstance(v, str) else "")
    return out


def text_area_containing(ax, needle):
    for v in text_area_values(ax):
        if needle in v:
            return v
    return ""


def press_menu_item_startswith(ax, top, prefix):
    """Same scoping discipline as rb_reach_menu_item, but matches on a title PREFIX.

    Needed for the app menu's About item (recon MENUS: 'About DB Browser for SQLite')."""
    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 "").startswith(prefix):
            ok = ax.action(it.id, "AXPress")
            time.sleep(1.4)
            return bool(ok)
    _esc(2)
    return False


def dialog_containing_text(ax, needle):
    """Locate a secondary surface by its VISIBLE TEXT (never by index/path).

    Returns (window_element, matching_text) or (None, None)."""
    for w in ax.find(role="window", max_results=10, max_depth=1):
        if (w.name or "").startswith("DB Browser for SQLite"):
            continue  # the main window (fresh or '... - In-Memory database')
        for v in label_strings(ax, root_id=w.id, limit=80):
            if needle in v:
                return w, v
    return None, None


def close_dialog(ax, win, button_name="Cancel"):
    """Always dismiss with the dialog's OWN scoped button (recon: never a global Cancel)."""
    if win is None:
        return False
    b = find_button(ax, button_name, root_id=win.id)
    if b is None:
        _esc(1)
        return False
    ok = ax.action(b.id, "AXPress")
    time.sleep(1.0)
    return bool(ok)


def table_grid(ax, want_col=None):
    """result_cells() but able to prefer the grid that owns a given column header."""
    best = ([], [])
    for t in ax.find(role="table", max_results=10):
        if (t.name or "") == "search result":
            continue  # 1x5px decoy table (recon COMPUTATION)
        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 want_col is not None and want_col in c:
            return c, v
        if c or v:
            best = (c, v)
    return best


# ---- exact texts from recon ## TEXT ---------------------------------------------------------

T1_STATIC_LABELS = [
    "Mode:",
    "Show SQL submitted by",
    "Line type:",
    "Point shape:",
    "Identity",
    "Identification of the cell currently in the editor",
    "Type and size of data currently in table",
]

STRUCTURE_HEADERS = ["Name", "Object", "Type", "Schema", "Database"]
REMOTE_HEADERS = ["Name", "Last modified", "Size", "Commit"]
PLOT_HEADERS = ["Columns", "X", "Y1", "Y2", "Axis Type"]
TABLE_DIALOG_HEADERS = ["Name", "Type", "NN", "PK", "AI", "U",
                        "Default", "Check", "Collation", "Foreign Key"]

INTEGRITY_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_DESC = ("DB Browser for SQLite is an open source, freeware visual tool used to create, "
              "design and edit SQLite")

RESULTS_HELP = "Results of the last executed statements."

SQL_LOG_HEAD = "PRAGMA foreign_keys = '1';"

PRAGMA_DISPLAY_LABELS = [
    "Auto Vacuum", "Automatic Index", "Case Sensitive Like", "Checkpoint Full FSYNC",
    "Foreign Keys", "Full FSYNC", "Ignore Check Constraints", "Journal Mode",
    "Journal Size Limit", "Locking Mode", "Max Page Count", "Page Size",
    "Recursive Triggers", "Secure Delete", "Synchronous", "Temp Store",
    "User Version", "WAL Auto Checkpoint",
]

MAKE_NUMS = ("CREATE TABLE nums(n INTEGER, label TEXT); "
             "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');")


class TestStaticText:
    """T1/T3 — text that must be readable on a freshly launched app (NO database)."""

    @pytest.mark.rb(depth=0, jump_kind="value",
                    expect="labels 'Mode:', 'Show SQL submitted by', 'Line type:', "
                           "'Point shape:', 'Identity', 'Identification of the cell currently in "
                           "the editor', 'Type and size of data currently in table' all present "
                           "with those exact AXValues")
    def test_static_label_texts_on_fresh_app(self, ax):
        ensure_ui(ax)
        values = label_values(ax)

        # every text-bearing label read must be non-empty by construction
        assert values, "no `label` element on the fresh app exposes a non-empty AXValue"
        assert all(v.strip() for v in values), "collected a blank label value"

        found = set(values)
        missing = [s for s in T1_STATIC_LABELS if s not in found]
        assert not missing, f"missing exact label AXValues {missing}; observed={sorted(found)}"

        # tolerant proof on the SQL-log dock caption (recon T1)
        assert kit.rb_value(values, "Show SQL submitted by"), \
            f"'Show SQL submitted by' not among label values: {sorted(found)}"

        # character count must match the actual text length for each asserted label
        for s in T1_STATIC_LABELS:
            actual = [v for v in values if v == s][0]
            assert len(actual) == len(s), f"length mismatch for {s!r}: {len(actual)} != {len(s)}"

        screenshot_assert(
            "text_test_static_labels_fresh",
            "Dark-themed window titled 'DB Browser for SQLite' on a fresh launch with no database. "
            "The 'Edit Database Cell' dock on the right shows the caption 'Mode:' next to a "
            "dropdown reading Text plus the two placeholder lines 'Identification of the cell "
            "currently in the editor' and 'Type and size of data currently in table'. The SQL Log "
            "dock shows 'Show SQL submitted by' with an 'Application' dropdown and a Clear button; "
            "the Plot dock shows 'Line type:' and 'Point shape:'; the Remote dock shows 'Identity' "
            "with a 'Select an identity to connect' dropdown and DBHub.io / Local / Current "
            "Database tabs. Main tab bar reads Database Structure (selected), Browse Data, Edit "
            "Pragmas, Execute SQL. Status bar bottom-right reads 'UTF-8'.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=0, jump_kind="value",
                    expect="status-bar label named 'Database encoding' has AXValue 'UTF-8'")
    def test_status_bar_database_encoding_utf8(self, ax):
        ensure_ui(ax)
        target = None
        for l in ax.find(role="label", max_results=350):
            if (l.name or "") == "Database encoding":
                target = l
                break
        assert target is not None, "status-bar label named 'Database encoding' not found"

        value = ax.get(target.id, ["AXValue"]).get("AXValue")
        assert isinstance(value, str) and value.strip(), \
            f"status bar text is empty: {value!r}"
        assert value == "UTF-8", f"expected status bar 'UTF-8', got {value!r}"
        assert kit.rb_value(value, "UTF-8"), f"rb_value rejected status bar text {value!r}"

    @pytest.mark.rb(depth=0, jump_kind="value",
                    expect="column headers include the structure-tree set "
                           "{Name,Object,Type,Schema,Database}, the remote set "
                           "{Name,Last modified,Size,Commit} and the plot set "
                           "{Columns,X,Y1,Y2,Axis Type}")
    def test_column_header_texts_on_fresh_app(self, ax):
        ensure_ui(ax)
        headers = column_names(ax)
        assert headers, "no `column` element exposes a header name"
        got = set(headers)

        assert set(STRUCTURE_HEADERS).issubset(got), \
            f"structure-tree headers missing {sorted(set(STRUCTURE_HEADERS) - got)}; got {sorted(got)}"
        assert set(REMOTE_HEADERS).issubset(got), \
            f"remote-list headers missing {sorted(set(REMOTE_HEADERS) - got)}; got {sorted(got)}"
        assert set(PLOT_HEADERS).issubset(got), \
            f"plot-list headers missing {sorted(set(PLOT_HEADERS) - got)}; got {sorted(got)}"

        assert kit.rb_value(headers, "Axis Type"), \
            f"'Axis Type' header not observed; got {sorted(got)}"


class TestWindowTitleText:
    """T2 — window-title text, fresh and after the in-memory database is created."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="window title 'DB Browser for SQLite' -> "
                           "'DB Browser for SQLite - In-Memory database'")
    def test_main_window_title_fresh_and_after_opening_database(self, ax):
        ensure_ui(ax)
        before = main_window(ax)
        assert before == "DB Browser for SQLite", \
            f"fresh main window title should be 'DB Browser for SQLite', got {before!r}"
        assert "DB Browser for SQLite" in (before or ""), "frame title lacks the app name"

        assert rb_enter_inmemory_db(ax), "'Edit table definition' modal was not dismissed"

        after = main_window(ax)
        assert after != before, f"window title did not change after creating a database: {after!r}"
        assert after == "DB Browser for SQLite - In-Memory database", \
            f"expected '<document> - <app>' title format, got {after!r}"
        assert kit.rb_value(after, "DB Browser for SQLite - In-Memory database"), \
            f"rb_value rejected the title {after!r}"


class TestPanelText:
    """T5 — long prose owned by docks / panels (needs a database)."""


    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="SQL Log dock text_area AXValue starts with \"PRAGMA foreign_keys = "
                           "'1';\" and lists PRAGMA database_list and the sqlite_master query")
    def test_sql_log_shows_startup_pragmas(self, ax):
        ensure_ui(ax)
        assert rb_enter_inmemory_db(ax), "could not create the in-memory database"
        assert switch_tab(ax, "SQL Log"), "SQL Log dock tab radio not pressable"

        log = text_area_containing(ax, "PRAGMA")
        assert log, f"no text_area holds the SQL log; panes={text_area_values(ax)!r}"
        assert log.startswith(SQL_LOG_HEAD), \
            f"SQL log should start with {SQL_LOG_HEAD!r}, got {log[:80]!r}"
        assert "PRAGMA database_list;" in log, f"SQL log lacks PRAGMA database_list: {log!r}"
        assert 'SELECT type,name,sql,tbl_name FROM "main".sqlite_master;' in log, \
            f"SQL log lacks the sqlite_master query: {log!r}"
        assert kit.rb_value(log, "PRAGMA database_list;"), f"rb_value rejected the log {log[:80]!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Edit Database Cell shows 'No cell active.' and "
                           "'Type: NULL; Size: 0 bytes' once a database is open")
    def test_cell_editor_status_labels_with_database(self, ax):
        ensure_ui(ax)
        before = label_values(ax)
        assert "Identification of the cell currently in the editor" in before, \
            ("fresh cell-editor panel should carry the placeholder "
             f"'Identification of the cell currently in the editor'; got {sorted(set(before))}")

        assert rb_enter_inmemory_db(ax), "could not create the in-memory database"
        after = label_values(ax)

        assert "No cell active." in after, \
            f"cell editor should read 'No cell active.' with a DB open; got {sorted(set(after))}"
        assert "Type: NULL; Size: 0 bytes" in after, \
            f"cell editor should read 'Type: NULL; Size: 0 bytes'; got {sorted(set(after))}"
        assert set(after) != set(before), "no cell-editor text changed after opening the database"
        assert kit.rb_value(after, "Type: NULL; Size: 0 bytes"), \
            "rb_value rejected the cell-editor type/size line"


class TestDialogText:
    """Text that only exists on a surface this test opened (depth >= 1)."""


    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect='About window shows "DB Browser for SQLite is an open source, freeware '
                           'visual tool used to create, design and edit SQLite" and a label '
                           'containing "DB Browser for SQLite Version"')
    def test_about_dialog_description_text(self, ax):
        ensure_ui(ax)
        assert press_menu_item_startswith(ax, "DB Browser for SQLite", "About"), \
            "app menu > About ... could not be pressed"

        win = find_window(ax, "About DB Browser for SQLite")
        try:
            assert win is not None, "no 'About DB Browser for SQLite' window appeared"
            assert (win.name or "") == "About DB Browser for SQLite", \
                f"About window title should be 'About DB Browser for SQLite', got {win.name!r}"

            texts = label_strings(ax, root_id=win.id, limit=60)
            assert any(ABOUT_DESC in t for t in texts), \
                f"About window lacks the description sentence; observed={texts!r}"
            # version LINE only — the version NUMBER / commit hash are build-specific.
            assert any("DB Browser for SQLite Version" in t for t in texts), \
                f"About window lacks a 'DB Browser for SQLite Version' line; observed={texts!r}"
            assert kit.rb_value(texts, ABOUT_DESC), "rb_value rejected the About description"

            screenshot_assert(
                "text_test_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)
        finally:
            close_dialog(ax, win, "Close")   # the About window's own Close button

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Edit table definition dialog exposes column headers Name,Type,NN,PK,"
                           "AI,U,Default,Check,Collation,Foreign Key")
    def test_dialog_column_header_texts(self, ax):
        ensure_ui(ax)
        # press the menu item directly so the auto-opened modal is still on screen to inspect
        assert rb_reach_menu_item(ax, "File", "New In-Memory Database"), \
            "File > New In-Memory Database could not be pressed"

        dialog = find_window(ax, "Edit table definition")
        try:
            assert dialog is not None, "'Edit table definition' dialog did not appear"
            headers = column_names(ax, root_id=dialog.id)
            assert headers, "the dialog's field grid exposes no column header text"
            got = set(headers)
            assert set(TABLE_DIALOG_HEADERS).issubset(got), \
                (f"dialog headers missing {sorted(set(TABLE_DIALOG_HEADERS) - got)}; "
                 f"got {headers!r}")
            assert kit.rb_value(headers, "Collation"), \
                f"'Collation' header not observed; got {headers!r}"
        finally:
            close_dialog(ax, dialog, "Cancel")   # scoped Cancel, never a global one


class TestComputedText:
    """T4/T5 — text PRODUCED by executing SQL (message pane + results grid)."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect='message pane starts "Execution finished without errors." and contains '
                           '"1 rows returned" and "SELECT 2+3 AS total;"')
    def test_sql_execution_message_text_success(self, ax):
        ensure_ui(ax)
        assert rb_enter_inmemory_db(ax), "could not create the in-memory database"
        run_sql(ax, "SELECT 2+3 AS total;")

        msg = exec_msg(ax)
        assert msg, f"message pane is empty; panes={text_area_values(ax)!r}"
        assert msg.startswith("Execution finished without errors."), \
            f"unexpected message prefix: {msg!r}"
        assert "1 rows returned" in msg, f"message lacks '1 rows returned': {msg!r}"
        assert "At line 1:" in msg, f"message lacks 'At line 1:': {msg!r}"
        assert "SELECT 2+3 AS total;" in msg, f"message does not echo the statement: {msg!r}"
        assert kit.rb_value(msg, "Execution finished without errors."), \
            "rb_value rejected the success message"

        cols, cells = result_cells(ax)
        assert "total" in cols, f"results grid header should read 'total'; got {cols!r}"
        assert kit.rb_value(cells, "5"), f"results grid should show '5'; got {cells!r}"

        screenshot_assert(
            "text_test_sql_message_success",
            "Execute SQL tab active in the 'DB Browser for SQLite - In-Memory database' window. "
            "The SQL editor holds the statement SELECT 2+3 AS total; a results grid below shows a "
            "single column headed 'total' containing the value 5, and the message pane reads "
            "'Execution finished without errors.' followed by 'Result: 1 rows returned in ...' and "
            "'At line 1: SELECT 2+3 AS total;'.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect='message pane starts "Execution finished with errors." and contains '
                           '"no such table: no_such_table_xyz"')
    def test_sql_execution_message_text_error(self, ax):
        ensure_ui(ax)
        assert rb_enter_inmemory_db(ax), "could not create the in-memory database"
        run_sql(ax, "SELECT * FROM no_such_table_xyz;")

        msg = exec_msg(ax)
        assert msg, f"message pane is empty; panes={text_area_values(ax)!r}"
        assert msg.startswith("Execution finished with errors."), \
            f"unexpected message prefix: {msg!r}"
        assert "no such table: no_such_table_xyz" in msg, \
            f"message lacks the sqlite error text: {msg!r}"
        assert kit.rb_value(msg, "no such table: no_such_table_xyz"), \
            "rb_value rejected the error message"

        cols, _cells = result_cells(ax)
        assert cols == [], f"results grid should stay empty on error; got columns {cols!r}"


class TestGridText:
    """T3/T4 — Browse Data grid text, record counter, and the cell-editor identification line."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="grid columns ['_rowid_','n','label'], cell texts include "
                           "'ten'/'twenty'/'thirty' and counter '1 - 3 of 3'")
    def test_browse_data_grid_text_and_counter(self, ax):
        ensure_ui(ax)
        assert rb_enter_inmemory_db(ax), "could not create the in-memory database"
        run_sql(ax, MAKE_NUMS)
        assert switch_tab(ax, "Browse Data"), "Browse Data tab radio not pressable"

        cols, cells = table_grid(ax, want_col="_rowid_")
        assert cols == ["_rowid_", "n", "label"], \
            f"expected columns ['_rowid_','n','label']; got {cols!r}"
        for want in ["ten", "twenty", "thirty", "10", "20", "30"]:
            assert want in cells, f"grid cell text {want!r} missing; cells={cells!r}"
        assert kit.rb_value(cells, "twenty"), f"rb_value rejected the cells {cells!r}"

        counter = record_counter(ax)
        assert counter == "1 - 3 of 3", f"record counter should read '1 - 3 of 3'; got {counter!r}"

        screenshot_assert(
            "text_test_browse_data_grid",
            "Browse Data tab active with a 'Table:' dropdown reading nums. The data grid shows "
            "columns _rowid_, n and label with the rows 10/ten, 20/twenty and 30/thirty, a 'Filter "
            "in any column' box under the headers, and the record counter reading '1 - 3 of 3'.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="clicking grid cell 'twenty' changes the cell-editor labels to "
                           "'Editing row=2, column=2' and 'Type: Text / Numeric; Size: 6 "
                           "character(s)' with the editor holding 'twenty'")
    def test_cell_click_updates_editor_identification_text(self, ax):
        ensure_ui(ax)
        assert rb_enter_inmemory_db(ax), "could not create the in-memory database"
        run_sql(ax, MAKE_NUMS)
        assert switch_tab(ax, "Browse Data"), "Browse Data tab radio not pressable"

        before_vals = label_values(ax)
        before = next((v for v in before_vals if "Editing row=" in v), None)

        cell = grid_cell_named(ax, "twenty")
        assert cell is not None, "grid cell with the text 'twenty' not found"
        ax.click_element_cg(cell.id)
        time.sleep(1.2)

        after_vals = label_values(ax)
        ident = next((v for v in after_vals if "Editing row=" in v), None)
        assert ident is not None, \
            f"no cell-editor identification label after the click; labels={sorted(set(after_vals))}"
        assert "Editing row=2" in ident, f"identification text should name row 2; got {ident!r}"
        assert "column=" in ident, f"identification text should name a column; got {ident!r}"
        if before is not None:
            assert ident != before, f"identification text did not change from {before!r}"

        type_line = next((v for v in after_vals if v.startswith("Type: ")), None)
        assert type_line is not None, \
            f"no 'Type: ...' size line after the click; labels={sorted(set(after_vals))}"
        assert "character(s)" in type_line, \
            f"type/size line should report character(s) for a text cell; got {type_line!r}"

        editor_value = next((v for v in text_area_values(ax) if v == "twenty"), None)
        assert editor_value == "twenty", \
            f"cell editor should hold exactly 'twenty'; panes={text_area_values(ax)!r}"
        assert kit.rb_value(editor_value, "twenty"), "rb_value rejected the cell editor text"


class TestPragmaText:
    """T6 — pragma display labels (plain `label`s that end with the object-replacement glyph)."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Edit Pragmas tab shows the 18 pragma display labels (Auto Vacuum, "
                           "Automatic Index, ..., WAL Auto Checkpoint)")
    def test_pragma_display_labels_present(self, ax):
        ensure_ui(ax)
        assert switch_tab(ax, "Edit Pragmas"), "Edit Pragmas tab radio not pressable"

        values = label_values(ax)
        assert values, "Edit Pragmas page exposes no label text"

        found, missing = [], []
        for name in PRAGMA_DISPLAY_LABELS:
            # recon T6: the value carries a trailing 'what's this' glyph -> startswith, never ==
            hit = next((v for v in values if v.startswith(name)), None)
            (found if hit is not None else missing).append(name)
        assert not missing, f"pragma display labels missing {missing}; got {sorted(set(values))}"

        found_count = len(found)
        assert found_count == 18, f"expected 18 pragma labels, found {found_count}"
        assert kit.rb_value(found_count, 18), f"rb_value rejected the pragma label count {found_count}"

        screenshot_assert(
            "text_test_pragma_labels",
            "Edit Pragmas tab active, showing a form of SQLite pragma controls whose visible "
            "labels read Auto Vacuum, Automatic Index, Case Sensitive Like, Checkpoint Full FSYNC, "
            "Foreign Keys, Full FSYNC, Ignore Check Constraints, Journal Mode, Journal Size Limit, "
            "Locking Mode, Max Page Count, Page Size, Recursive Triggers, Secure Delete, "
            "Synchronous, Temp Store, User Version and WAL Auto Checkpoint, with Save and Cancel "
            "buttons at the bottom of the page.",
            RESULTS_DIR)