File size: 16,537 Bytes
e5a3ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""TEXT lane — DB Browser for SQLite (Qt5).

CONTENT / OUTPUT text that an INTERACTION produces, read off the running
reference and asserted as a substring of the observed value (never read from
source / a version constant — a recreation cannot know those, so the expected
string is always something observed live). Surfaces owned here:

  * Window TITLE reflecting the opened DB (File>Open consequence).
  * Database-Structure tree SCHEMA text — the app-rendered CREATE TABLE / CREATE
    VIEW SQL + the category summary rows (Tables (2) / Indices (1) / Views (1)).
  * Execute-SQL editor content ROUND-TRIP (type -> read back == real text control).
  * Execute-SQL STATUS message text ("Execution finished without/with errors.").
  * About-dialog rendered VERSION text (programmatic label read + VLM screenshot).

LANE BOUNDARY (NOT asserted here, owned elsewhere):
  * The numeric query RESULT in the grid / the "1 - N of N" row counter as a
    computed value -> computation lane.
  * CHECKED toggles -> state lane.
  * Whether a menu/dialog merely opens -> menu lane (we read the TEXT it renders).

Every value test declares jump_kind="value" with the exact expected TEXT in
expect=, and calls rb.enter() on the tab/dialog crossing (measured depth 1).
Screenshots are ADDITIVE on tree-readable text and the SOLE assertion for the
About version (rendered) — one shot per DISTINCT rendered state.
"""

import time

import pytest, pytest_check as check
import rb_atspi

from gi.repository import Atspi

DB = "/workspace/output/fixtures/sample.db"


# --------------------------------------------------------------------------- #
# Module fixture — ensure sample.db is open (cold baseline starts with no DB).
# --------------------------------------------------------------------------- #
@pytest.fixture(scope="module", autouse=True)
def _load_db(app):
    rb_atspi.focus_app_window(app)
    frame = rb_atspi.get_main_frame(app)
    for _ in range(4):
        rb_atspi.press_escape(); time.sleep(0.15)
    if "sample.db" not in (frame.get_name() or ""):
        fm = rb_atspi.find_first(frame, role="menu item", name="File")
        if fm:
            rb_atspi.click_node(fm); time.sleep(0.4)
        op = rb_atspi.find_first(frame, role="menu item", name="Open Database...")
        if op:
            rb_atspi.open_modal(op); time.sleep(1.2)
            rb_atspi.type_text(DB); time.sleep(0.4)
            rb_atspi.key("Return"); time.sleep(1.5)
    yield


# --------------------------------------------------------------------------- #
# Locators / helpers (all verified live on the running reference).
# --------------------------------------------------------------------------- #
def _extents(n):
    try:
        return n.get_extents(Atspi.CoordType.SCREEN)
    except Exception:
        return None


def _forigin(frame):
    """Frame's top-left in SCREEN coords; locators below are frame-RELATIVE so they
    hold wherever the WM places the window (a cold relaunch does not reuse the warm
    testgen instance's absolute position)."""
    e = _extents(frame)
    return (e.x, e.y) if e else (0, 0)


def _select_tab(frame, name, settle=0.8):
    """Switch a main page tab via its AT-SPI Press action (falls back to a real
    click). Verified: do_action(tab,'Press') activates the tab."""
    rb_atspi.focus_app_window(rb_atspi.get_app())
    t = rb_atspi.find_first(frame, role="page tab", name=name)
    if t is not None:
        if not rb_atspi.do_action(t, "Press"):
            rb_atspi.click_node(t)
        time.sleep(settle)
    return t


def _all_names(frame):
    """Every node's a11y name in the frame (any role). The structure-tree schema
    cells are role='tree item' whose NAME carries the full CREATE SQL; searching
    across roles keeps the match tolerant to the exact role the toolkit uses."""
    out = []
    rb_atspi.walk(frame, lambda n, _d: out.append(n.get_name() or ""))
    return out


def _find_name_containing(frame, needle):
    """First a11y name in the frame that contains `needle` (case-sensitive)."""
    for nm in _all_names(frame):
        if needle in nm:
            return nm
    return None


def _sql_editor(frame):
    """The Scintilla SQL editor: the showing role=text at the TOP-LEFT of the
    Execute SQL tab (frame-relative x<400, tall, wide, smallest y)."""
    fx, fy = _forigin(frame)
    best = None
    for t in rb_atspi.find_all(frame, role="text"):
        if not rb_atspi.is_showing(t):
            continue
        e = _extents(t)
        if e is None:
            continue
        rx, ry = e.x - fx, e.y - fy
        if rx < 400 and e.height > 80 and e.width > 200 and ry < 420:
            if best is None or e.y < best[1]:
                best = (t, e.y)
    return best[0] if best else None


def _status_text(frame):
    """editErrors QTextEdit: the showing role=text at the BOTTOM-LEFT (largest y,
    frame-relative x<400) of the Execute SQL tab. Returns its plain text."""
    fx, fy = _forigin(frame)
    cand = None
    for t in rb_atspi.find_all(frame, role="text"):
        if not rb_atspi.is_showing(t):
            continue
        e = _extents(t)
        if e is None:
            continue
        rx, ry = e.x - fx, e.y - fy
        if rx < 400 and e.width > 200 and ry > 420:
            if cand is None or e.y > cand[1]:
                cand = (t, e.y)
    return rb_atspi.get_text(cand[0]) if cand else ""


def _run_sql(frame, sql):
    """Clear the SQL editor, type `sql`, press F5, poll for completion, and return
    the editErrors STATUS text. (This lane reads the STATUS MESSAGE, not the grid
    numbers — those belong to the computation lane.)"""
    _select_tab(frame, "Execute SQL")
    ed = _sql_editor(frame)
    assert ed is not None, "SQL editor not found on Execute SQL tab"
    rb_atspi.click_node(ed); time.sleep(0.25)
    rb_atspi.key("ctrl+a"); rb_atspi.key("Delete"); time.sleep(0.15)
    rb_atspi.type_text(sql); time.sleep(0.3)
    rb_atspi.key("F5")
    rb_atspi.wait_for(
        lambda: "Execution finished" in _status_text(frame), timeout=6.0, interval=0.25
    )
    time.sleep(0.3)
    return _status_text(frame)


# =========================================================================== #
# 1. Window title reflects the opened DB (File>Open consequence).
# =========================================================================== #
@pytest.mark.rb(jump_kind="value", expect="title contains 'sample.db' and 'DB Browser for SQLite'")
def test_window_title_reflects_open_db(app, frame, rb, results_dir):
    # The title is app-authored output of the open action: a dead shell with a
    # fixed/blank title fails. Read it straight off the live frame.
    title = frame.get_name() or ""
    check.is_in("sample.db", title,
                f"window title should contain the opened DB filename 'sample.db', got {title!r}")
    check.is_in("DB Browser for SQLite", title,
                f"window title should name the app 'DB Browser for SQLite', got {title!r}")
    rb_atspi.screenshot_assert(
        "test_window_title_reflects_open_db",
        "The DB Browser for SQLite application window's title bar reads "
        "'DB Browser for SQLite - /workspace/output/fixtures/sample.db' "
        "(the app name followed by the full path to the opened sample.db file).",
        results_dir,
    )


# =========================================================================== #
# 2. Structure tree renders the employees CREATE TABLE SQL.
# =========================================================================== #
@pytest.mark.rb(jump_kind="value",
                expect="employees CREATE TABLE SQL with 'name TEXT' and 'salary INTEGER'")
def test_structure_shows_create_table_employees(app, frame, rb, results_dir):
    rb.enter("structure")
    _select_tab(frame, "Database Structure")
    cell = _find_name_containing(frame, "CREATE TABLE employees")
    check.is_true(cell is not None,
                  "no structure cell renders 'CREATE TABLE employees'")
    if cell:
        # The app renders the actual column definitions (read from the DB schema).
        check.is_in("name TEXT", cell,
                    f"employees CREATE SQL should show 'name TEXT', got {cell!r}")
        check.is_in("salary INTEGER", cell,
                    f"employees CREATE SQL should show 'salary INTEGER', got {cell!r}")
    rb_atspi.screenshot_assert(
        "test_structure_shows_create_table_employees",
        "The Database Structure tab is active, showing a schema tree with a "
        "'Tables (2)' group listing 'departments' and 'employees', an 'Indices "
        "(1)' group with 'idx_emp_dept', a 'Views (1)' group with 'high_earners', "
        "and a 'Triggers (0)' group; the Schema column shows 'CREATE TABLE ...' "
        "text beside the departments and employees rows.",
        results_dir, window=frame,
    )


# =========================================================================== #
# 3. Structure tree renders the high_earners CREATE VIEW SQL (same tab state).
# =========================================================================== #
@pytest.mark.rb(jump_kind="value",
                expect="CREATE VIEW high_earners AS SELECT name, salary FROM employees WHERE salary > 60000")
def test_structure_shows_create_view(app, frame, rb):
    rb.enter("structure")
    _select_tab(frame, "Database Structure")
    cell = _find_name_containing(frame, "CREATE VIEW high_earners")
    check.is_true(cell is not None,
                  "no structure cell renders 'CREATE VIEW high_earners'")
    if cell:
        for frag in ("SELECT name, salary", "FROM employees", "WHERE salary > 60000"):
            check.is_in(frag, cell,
                        f"high_earners CREATE VIEW SQL missing {frag!r}, got {cell!r}")
    # No separate screenshot: identical tree state as test #2 (one shot per state).


# =========================================================================== #
# 4. Structure tree category summary rows (app-rendered object counts as text).
# =========================================================================== #
@pytest.mark.rb(jump_kind="value",
                expect="category rows 'Tables (2)', 'Indices (1)', 'Views (1)'")
def test_structure_category_labels(app, frame, rb):
    rb.enter("structure")
    _select_tab(frame, "Database Structure")
    names = _all_names(frame)
    for want in ("Tables (2)", "Indices (1)", "Views (1)"):
        check.is_true(any(want == n or want in n for n in names),
                      f"structure tree should show category row {want!r}")
    # No screenshot: same structure-tree state as test #2.


# =========================================================================== #
# 5. Execute-SQL editor stores typed content (round-trip == real text control).
# =========================================================================== #
@pytest.mark.rb(jump_kind="value", expect="editor content echoes 'hello_world'")
def test_sql_editor_text_roundtrip(app, frame, rb, results_dir):
    rb.enter("execute")
    _select_tab(frame, "Execute SQL")
    ed = _sql_editor(frame)
    assert ed is not None, "SQL editor not found on Execute SQL tab"
    rb_atspi.click_node(ed); time.sleep(0.25)
    rb_atspi.key("ctrl+a"); rb_atspi.key("Delete"); time.sleep(0.15)
    typed = "SELECT 'hello_world' AS greeting;"
    rb_atspi.type_text(typed); time.sleep(0.4)
    got = rb_atspi.get_text(ed)
    check.is_in("hello_world", got,
                f"editor should echo the typed 'hello_world', got {got!r}")
    check.is_in("greeting", got,
                f"editor should echo the typed alias 'greeting', got {got!r}")
    rb_atspi.screenshot_assert(
        "test_sql_editor_text_roundtrip",
        "The Execute SQL tab's SQL editor pane contains the typed query text "
        "\"SELECT 'hello_world' AS greeting;\".",
        results_dir, window=frame,
    )
    # Leave the editor clean for order-independence.
    rb_atspi.click_node(ed); time.sleep(0.15)
    rb_atspi.key("ctrl+a"); rb_atspi.key("Delete"); time.sleep(0.15)


# =========================================================================== #
# 6. Execute-SQL STATUS message on a valid query.
# =========================================================================== #
@pytest.mark.rb(jump_kind="value",
                expect="status: 'Execution finished without errors.' + 'rows returned'")
def test_sql_status_message_success(app, frame, rb, results_dir):
    rb.enter("execute")
    status = _run_sql(frame, "SELECT 1;")
    check.is_in("Execution finished without errors.", status,
                f"valid query status should read success, got {status!r}")
    check.is_in("rows returned", status,
                f"valid query status should report 'rows returned', got {status!r}")
    rb_atspi.screenshot_assert(
        "test_sql_status_message_success",
        "The Execute SQL status panel (below the editor) reads "
        "'Execution finished without errors.' followed by 'Result: 1 rows "
        "returned in ...ms' for the query SELECT 1.",
        results_dir, window=frame,
    )


# =========================================================================== #
# 7. Execute-SQL STATUS message on an invalid query.
# =========================================================================== #
@pytest.mark.rb(jump_kind="value", expect="status: 'Execution finished with errors.'")
def test_sql_status_message_error(app, frame, rb, results_dir):
    rb.enter("execute")
    status = _run_sql(frame, "SELECT * FROM nonexistent_zzz;")
    # This lane asserts the generic STATUS-MESSAGE content (the error identity
    # 'no such table' is the computation lane's; the status line is text-content).
    check.is_in("Execution finished with errors.", status,
                f"invalid query status should read failure, got {status!r}")
    rb_atspi.screenshot_assert(
        "test_sql_status_message_error",
        "The Execute SQL status panel shows an error state reading 'Execution "
        "finished with errors.' (with a red-tinted background) after running a "
        "query against a table that does not exist.",
        results_dir, window=frame,
    )
    # Restore a clean, successful state so later ordering isn't left on an error.
    _run_sql(frame, "SELECT 1;")


# =========================================================================== #
# 8. Help > About renders the app version text (rendered/opaque -> VLM + label).
# =========================================================================== #
@pytest.mark.rb(jump_kind="value", expect="About dialog shows a 'Version' string for DB Browser for SQLite")
def test_about_version_text(app, frame, rb, results_dir):
    for _ in range(3):
        rb_atspi.press_escape(); time.sleep(0.15)
    # Help menu -> About (dialog-opener: open_modal so the modal loop can't hang).
    # Two real surface crossings: opening the menu (depth 1) then the dialog (depth 2).
    helpm = rb_atspi.find_first(frame, role="menu item", name="Help")
    assert helpm is not None, "Help menu not found"
    rb.enter("help_menu")
    rb_atspi.click_node(helpm); time.sleep(0.5)
    about = rb_atspi.find_first(frame, role="menu item", name="About")
    assert about is not None, "Help > About item not found"
    rb.enter("about_dialog")
    rb_atspi.open_modal(about)
    dlg = rb_atspi.wait_node(
        lambda: app, timeout=5.0, role="dialog", name="About DB Browser for SQLite"
    )
    check.is_true(dlg is not None and rb_atspi.is_showing(dlg),
                  "About dialog did not appear")
    # (a) programmatic: a label in the dialog renders the app name + a Version string.
    if dlg is not None:
        blob = " ".join(rb_atspi.get_text(l) for l in rb_atspi.find_all(dlg, role="label"))
        check.is_in("DB Browser for SQLite", blob,
                    f"About dialog should name the app, got {blob[:120]!r}")
        check.is_in("Version", blob,
                    f"About dialog should render a 'Version' string, got {blob[:120]!r}")
    # (b) VLM: the rendered version text (full screen — the dialog is its own window).
    rb_atspi.screenshot_assert(
        "test_about_version_text",
        "The 'About DB Browser for SQLite' dialog is open and shows a version "
        "line reading 'DB Browser for SQLite Version 3.13...' together with the "
        "program description ('an open source, freeware visual tool ...').",
        results_dir,
    )
    rb_atspi.press_escape(); time.sleep(0.3)
    rb_atspi.press_escape(); time.sleep(0.3)