File size: 28,004 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
"""AX COMPUTATION tests — DB Browser for SQLite (Qt6).

Four computation engines, all driven purely through the AX API + System Events
keystrokes, every expected value taken verbatim from what was OBSERVED on the
reference app (recon.md ## COMPUTATION):

  1. Execute SQL          type SQL -> press `Execute SQL` -> results grid + message pane
  2. DDL preview          `Edit table definition` / `Edit Index Schema` live CREATE preview
  3. Browse Data          record counter `N - M of T` + "Filter in any column"
  4. Database Structure   tree object counts `Tables (N) / Indices (N) / ...`

A fresh app has NO database open, so every engine test first opens the in-memory
database (`File > New In-Memory Database`) and dismisses the auto-opened
`Edit table definition` modal with that window's OWN scoped `Cancel`.

Deliberate omissions (recon says these reads are unreliable / non-deterministic):
  * the SQL editor's own AXValue is truncated by QScintilla -> never asserted
  * the `in Nms` / `Took 0ms` timing digits in the message pane -> never asserted
Never pressed: Write/Revert Changes, New/Open Database, any Save…, dock Close,
Delete Table…, or any native file-dialog button.
"""

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 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):
    """(column headers, cell values) of the SQL results grid. Skips the 'search result' decoy."""
    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):
    """Browse Data counter, 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 dialog_preview(ax, window):
    """The read-only DDL preview text_area inside a dialog (its AXValue contains CREATE)."""
    for t in ax.find(role="text_area", root_id=window.id, max_results=8):
        v = str(ax.get(t.id, ["AXValue"]).get("AXValue") or "")
        if "CREATE" in v:
            return v
    return None


def structure_group_names(ax):
    out = []
    for g in ax.find(role="group", max_results=250):
        n = g.name or ""
        if n.startswith(("Tables (", "Indices (", "Views (", "Triggers (")):
            out.append(n)
    return sorted(set(out))


# ── extra locators / navigation (semantic: role + visible AXTitle only) ─────────

def wait_ready(ax, timeout=6.0):
    """Settle after the per-test relaunch: wait until the app exposes a window."""
    deadline = time.time() + timeout
    while time.time() < deadline:
        if ax.find(role="window", max_results=1, max_depth=1):
            return True
        time.sleep(0.4)
    return False


def dialog_button(ax, window, name):
    """A button scoped INSIDE a dialog window (never a global 'Cancel'/'Add' match)."""
    if window is None:
        return None
    for b in ax.find(role="button", root_id=window.id, max_results=40):
        if (b.name or "") == name:
            return b
    return None


def dialog_field(ax, window, name):
    if window is None:
        return None
    for t in ax.find(role="text_field", root_id=window.id, max_results=25):
        if (t.name or "") == name:
            return t
    return None


def dialog_checkbox(ax, window, name):
    if window is None:
        return None
    for c in ax.find(role="checkbox", root_id=window.id, max_results=25):
        n = c.name or ""
        if n == name or name in n:
            return c
    return None


def rb_enter_create_table_dialog(ax):
    """SURFACE: Database Structure tab -> AXPress `Create Table` -> window
    'Edit table definition' (the second time this modal is crossed in a test)."""
    switch_tab(ax, "Database Structure")
    b = find_button(ax, "Create Table")
    assert b is not None, "toolbar button 'Create Table' not found"
    assert enabled(ax, b), "'Create Table' is disabled — no database open"
    ax.action(b.id, "AXPress")
    time.sleep(1.3)
    return find_window(ax, "Edit table definition")


def rb_enter_create_index_dialog(ax):
    """SURFACE: Database Structure tab -> AXPress `Create Index` -> window
    'Edit Index Schema' (needs a database AND at least one table)."""
    switch_tab(ax, "Database Structure")
    b = find_button(ax, "Create Index")
    assert b is not None, "toolbar button 'Create Index' not found"
    assert enabled(ax, b), "'Create Index' is disabled — no database open"
    ax.action(b.id, "AXPress")
    time.sleep(1.3)
    return find_window(ax, "Edit Index Schema")


def rb_back_cancel(ax, window):
    """Close a dialog with its OWN scoped Cancel button."""
    b = dialog_button(ax, window, "Cancel")
    if b is None:
        return False
    ok = ax.action(b.id, "AXPress")
    time.sleep(0.8)
    return bool(ok)


def group_named(ax, name):
    for g in ax.find(role="group", max_results=250):
        if (g.name or "") == name:
            return g
    return None


# ── Engine 1 — Execute SQL ─────────────────────────────────────────────────────

class TestExecuteSQLComputation:
    """SQL evaluated by the app: results grid columns/cells + message pane."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="results column 'answer' with cell '42' for SELECT 7*6")
    def test_sql_multiplication(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "SELECT 7*6 AS answer;")
        cols, cells = result_cells(ax)
        screenshot_assert(
            "computation_test_sql_multiplication",
            "DB Browser for SQLite with the Execute SQL tab active. The SQL editor holds "
            "'SELECT 7*6 AS answer;' and the results grid below it shows one column headed "
            "'answer' containing the value 42 (7*6). The message pane under the grid reads "
            "'Execution finished without errors. Result: 1 rows returned ...'.",
            RESULTS_DIR)
        assert cols == ["answer"], f"columns={cols!r} cells={cells!r}"
        assert kit.rb_value(cells, "42"), f"expected cell '42', got cells={cells!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="results column 'total' with cell '5' for SELECT 2+3")
    def test_sql_addition(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "SELECT 2+3 AS total;")
        cols, cells = result_cells(ax)
        assert cols == ["total"], f"columns={cols!r} cells={cells!r}"
        assert kit.rb_value(cells, "5"), f"expected cell '5', got cells={cells!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="columns ['d','m'] and cells ['2','2'] for 10/4 and 10%4")
    def test_sql_integer_division_and_modulo(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "SELECT 10/4 AS d, 10%4 AS m;")
        cols, cells = result_cells(ax)
        assert cols == ["d", "m"], f"columns={cols!r} cells={cells!r}"
        assert cells == ["2", "2"], f"cells={cells!r}"
        assert kit.rb_value(cells, ["2", "2"]), f"cells={cells!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="results column 'u' with cell 'DB4S' for upper('db4s')")
    def test_sql_string_upper(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "SELECT upper('db4s') AS u;")
        cols, cells = result_cells(ax)
        assert cols == ["u"], f"columns={cols!r} cells={cells!r}"
        assert kit.rb_value(cells, "DB4S"), f"expected cell 'DB4S', got cells={cells!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="results column 'n' with cell '5' for length('hello')")
    def test_sql_string_length(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "SELECT length('hello') AS n;")
        cols, cells = result_cells(ax)
        assert cols == ["n"], f"columns={cols!r} cells={cells!r}"
        assert kit.rb_value(cells, "5"), f"expected cell '5', got cells={cells!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="count(*)=3 and sum(a)=6 over 3 inserted rows -> cells ['3','6']")
    def test_sql_aggregate_count_and_sum(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT); "
                    "INSERT INTO t1 VALUES(1,'x'),(2,'y'),(3,'z'); "
                    "SELECT count(*) AS c, sum(a) AS s FROM t1;")
        cols, cells = result_cells(ax)
        assert cols == ["c", "s"], f"columns={cols!r} cells={cells!r}"
        assert cells == ["3", "6"], f"cells={cells!r}"
        assert kit.rb_value(cells, ["3", "6"]), f"cells={cells!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="message pane: 'Execution finished without errors.' and "
                           "'query executed successfully' with '3 rows affected'")
    def test_sql_dml_reports_rows_affected(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); "
                    "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');")
        msg = exec_msg(ax)
        assert msg.startswith("Execution finished without errors."), f"message={msg!r}"
        assert kit.rb_value(msg, "query executed successfully"), f"message={msg!r}"
        assert kit.rb_value(msg, "3 rows affected"), f"message={msg!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="message pane 'Execution finished with errors.' + "
                           "'no such table: no_such_table_xyz' and an EMPTY results grid")
    def test_sql_error_reports_no_such_table(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "SELECT * FROM no_such_table_xyz;")
        msg = exec_msg(ax)
        cols, cells = result_cells(ax)
        screenshot_assert(
            "computation_test_sql_error_no_such_table",
            "DB Browser for SQLite, Execute SQL tab active. The editor holds "
            "'SELECT * FROM no_such_table_xyz;'. The results grid is EMPTY (no columns, no "
            "rows) and the message pane reports the SQLite error: 'Execution finished with "
            "errors. Result: no such table: no_such_table_xyz'.",
            RESULTS_DIR)
        assert msg.startswith("Execution finished with errors."), f"message={msg!r}"
        assert kit.rb_value(msg, "no such table: no_such_table_xyz"), f"message={msg!r}"
        assert cols == [], f"results grid should be empty, got columns={cols!r} cells={cells!r}"

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="button 'Execute SQL' AXEnabled False->True once the in-memory "
                           "database exists")
    def test_sql_execute_button_disabled_until_database_open(self, ax):
        wait_ready(ax)
        assert switch_tab(ax, "Execute SQL"), "could not activate the Execute SQL tab"
        b = find_button(ax, "Execute SQL")
        assert b is not None, "button 'Execute SQL' not found on the Execute SQL tab"
        before = enabled(ax, b)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        b2 = find_button(ax, "Execute SQL")
        assert b2 is not None, "button 'Execute SQL' vanished after opening the database"
        after = enabled(ax, b2)
        assert before is False, f"with no database open the button should be disabled, got {before!r}"
        assert after is True, f"with the in-memory database open it should be enabled, got {after!r}"
        assert kit.rb_flip(before, after), f"no enabled flip: {before!r} -> {after!r}"


# ── Engine 2 — DDL preview generators (dialog surfaces) ───────────────────────

class TestDDLPreviewComputation:
    """The dialogs generate a live CREATE statement from the form contents."""

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect='preview CREATE TABLE "" ( ); -> CREATE TABLE "people" ( );')
    def test_create_table_preview_reflects_table_name(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        w = rb_enter_create_table_dialog(ax)
        assert w is not None, "window 'Edit table definition' did not open"
        before = dialog_preview(ax, w)
        assert before == 'CREATE TABLE "" (\n\n);', f"initial preview={before!r}"
        field = dialog_field(ax, w, "Table")
        assert field is not None, "text_field 'Table' not found in the dialog"
        ax.set_value(field.id, "people")
        time.sleep(0.7)
        after = dialog_preview(ax, w)
        screenshot_assert(
            "computation_test_create_table_preview",
            "The modal window 'Edit table definition' is open in front of the DB Browser for "
            "SQLite main window. Its 'Table' name box contains 'people', the field grid "
            "(headers Name, Type, NN, PK, AI, U, Default, Check, Collation, Foreign Key) is "
            "still empty, and the read-only SQL preview box below shows "
            'CREATE TABLE "people" ( );  Fields / Index Constraints / Foreign Keys / Check '
            "Constraints tabs and OK / Cancel buttons are visible.",
            RESULTS_DIR)
        rb_back_cancel(ax, w)
        assert after == 'CREATE TABLE "people" (\n\n);', f"preview after naming={after!r}"
        assert kit.rb_value(after, 'CREATE TABLE "people" (\n\n);'), f"preview={after!r}"

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect='two Add presses give CREATE TABLE "people" ( "Field1" INTEGER, '
                           '"Field2" INTEGER );')
    def test_create_table_preview_grows_with_add_field(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        w = rb_enter_create_table_dialog(ax)
        assert w is not None, "window 'Edit table definition' did not open"
        field = dialog_field(ax, w, "Table")
        assert field is not None, "text_field 'Table' not found in the dialog"
        ax.set_value(field.id, "people")
        time.sleep(0.7)
        add = dialog_button(ax, w, "Add")
        assert add is not None, "button 'Add' not found in the dialog"
        ax.action(add.id, "AXPress")
        time.sleep(0.8)
        one = dialog_preview(ax, w)
        ax.action(add.id, "AXPress")
        time.sleep(0.8)
        two = dialog_preview(ax, w)
        rb_back_cancel(ax, w)
        assert one == 'CREATE TABLE "people" (\n\t"Field1"\tINTEGER\n);', \
            f"preview after 1 Add={one!r}"
        assert two == 'CREATE TABLE "people" (\n\t"Field1"\tINTEGER,\n\t"Field2"\tINTEGER\n);', \
            f"preview after 2 Adds={two!r}"
        assert kit.rb_value(two, '"Field2"\tINTEGER'), f"preview={two!r}"

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect='CREATE INDEX "" ON "t1" ( ); -> named idx_a -> '
                           'CREATE UNIQUE INDEX "idx_a" ON "t1" ( );')
    def test_create_index_preview_name_and_unique(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT);")
        w = rb_enter_create_index_dialog(ax)
        assert w is not None, "window 'Edit Index Schema' did not open"
        opened = dialog_preview(ax, w)
        assert opened is not None, "no CREATE preview text_area in 'Edit Index Schema'"
        assert 'ON "t1"' in opened, f"initial index preview={opened!r}"
        name = dialog_field(ax, w, "Name")
        assert name is not None, "text_field 'Name' not found in 'Edit Index Schema'"
        ax.set_value(name.id, "idx_a")
        time.sleep(0.7)
        named = dialog_preview(ax, w)
        uniq = dialog_checkbox(ax, w, "Unique")
        assert uniq is not None, "checkbox 'Unique' not found in 'Edit Index Schema'"
        ax.action(uniq.id, "AXPress")
        time.sleep(0.7)
        unique = dialog_preview(ax, w)
        rb_back_cancel(ax, w)
        assert named == 'CREATE INDEX "idx_a" ON "t1" (\n\n);', f"preview after naming={named!r}"
        assert unique == 'CREATE UNIQUE INDEX "idx_a" ON "t1" (\n\n);', \
            f"preview after Unique={unique!r}"
        assert kit.rb_value(unique, 'CREATE UNIQUE INDEX "idx_a" ON "t1" (\n\n);'), \
            f"preview={unique!r}"


# ── Engine 3 — Browse Data record counter + filter ────────────────────────────

class TestBrowseDataCounterComputation:
    """The Browse Data tab computes 'first - last of total' and re-computes it
    from the filter expression."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Browse Data record counter reads '0 - 0 of 0' with no database open")
    def test_record_counter_zero_without_database(self, ax):
        wait_ready(ax)
        assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab"
        counter = record_counter(ax)
        assert counter is not None, "no 'N - M of T' record counter label on the Browse Data tab"
        assert kit.rb_value(counter, "0 - 0 of 0"), f"counter={counter!r}"
        assert counter == "0 - 0 of 0", f"counter={counter!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="counter '1 - 3 of 3' and Table: combobox 'nums' after inserting 3 rows")
    def test_record_counter_matches_inserted_rows(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); "
                    "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');")
        assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab"
        counter = record_counter(ax)
        combo = ax.find(role="combobox", name="nums", max_results=1)
        screenshot_assert(
            "computation_test_record_counter_three_rows",
            "DB Browser for SQLite with the Browse Data tab active. The 'Table:' dropdown "
            "shows 'nums', the data grid has the columns _rowid_, n, label with the three "
            "rows 10/ten, 20/twenty, 30/thirty, a 'Filter in any column' box sits under the "
            "headers, and the record counter reads '1 - 3 of 3'.",
            RESULTS_DIR)
        assert counter is not None, "no 'N - M of T' record counter label found"
        assert kit.rb_value(counter, "1 - 3 of 3"), f"counter={counter!r}"
        assert counter == "1 - 3 of 3", f"counter={counter!r}"
        assert combo, "no combobox titled 'nums' (the browsed table) found"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="filter 'twenty' -> counter '1 - 1 of 1' and grid cells "
                           "['20','twenty'] with columns ['_rowid_','n','label']")
    def test_filter_narrows_grid_and_counter(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); "
                    "INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');")
        assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab"
        flt = ax.find(role="text_field", name="Filter in any column", max_results=1)
        assert flt, "text_field 'Filter in any column' not found on the Browse Data tab"
        ax.set_value(flt[0].id, "twenty")
        time.sleep(1.7)
        counter = record_counter(ax)
        cols, cells = result_cells(ax)
        screenshot_assert(
            "computation_test_filter_narrows_grid",
            "DB Browser for SQLite, Browse Data tab active on table 'nums'. The filter box "
            "under the column headers contains 'twenty', so the grid shows only ONE row "
            "(20 / twenty) out of three, the record counter reads '1 - 1 of 1', and the "
            "'Clear Filters' toolbar button is now enabled.",
            RESULTS_DIR)
        assert counter == "1 - 1 of 1", f"counter={counter!r}"
        assert cols == ["_rowid_", "n", "label"], f"columns={cols!r}"
        assert cells == ["20", "twenty"], f"cells={cells!r}"
        assert kit.rb_value(cells, ["20", "twenty"]), f"cells={cells!r}"


# ── Engine 4 — Database Structure object counts ───────────────────────────────

class TestStructureCountComputation:
    """The structure tree counts schema objects: Tables (N) / Indices (N) / ..."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Tables (0)->Tables (1) with a tree node named 'nums' after "
                           "CREATE TABLE")
    def test_structure_tree_object_counts_reflect_created_table(self, ax):
        wait_ready(ax)
        assert rb_enter_inmemory_db(ax), "in-memory database did not open"
        assert switch_tab(ax, "Database Structure"), "could not activate Database Structure"
        before_names = structure_group_names(ax)
        assert "Tables (0)" in before_names, f"before={before_names!r}"
        assert "Indices (0)" in before_names, f"before={before_names!r}"
        assert "Views (0)" in before_names, f"before={before_names!r}"
        assert "Triggers (0)" in before_names, f"before={before_names!r}"
        run_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT);")
        # re-activating the tab is what refreshes the structure tree
        assert switch_tab(ax, "Database Structure"), "could not re-activate Database Structure"
        after_names = structure_group_names(ax)
        nums_node = group_named(ax, "nums")
        screenshot_assert(
            "computation_test_structure_counts",
            "DB Browser for SQLite with the Database Structure tab active. The schema tree "
            "now lists 'Tables (1)' expanded/containing an entry named 'nums', alongside "
            "'Indices (0)', 'Views (0)' and 'Triggers (0)'; the Create Table / Create Index / "
            "Modify Table buttons sit above the tree.",
            RESULTS_DIR)
        assert kit.rb_value(after_names, "Tables (1)"), f"after={after_names!r}"
        assert "Tables (1)" in after_names, f"after={after_names!r}"
        assert "Tables (0)" not in after_names, f"after={after_names!r}"
        assert nums_node is not None, "no tree node named 'nums' after CREATE TABLE nums"
        assert kit.rb_flip(before_names, after_names), \
            f"object counts did not change: {before_names!r} -> {after_names!r}"