Datasets:
File size: 42,096 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 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 | """AX STATE verification suite — DB Browser for SQLite (Qt6).
Sole owner of AXMenuItemMarkChar (CHECKED), AXEnabled flips, AXFocused and the
mode/selection indicators.
KEY MECHANISM (recon ST1/ST2): Qt tab-bar radios expose AXValue == None and
AXSelected == None, so selection CANNOT be read from the radio. The tab-bar
`group`'s AXTitle equals the currently selected tab name; a tab bar is located by
its exact list of direct radio children (never by index / tree path).
Every test declares depth + jump rigor via @pytest.mark.rb(...) and backs a
transition with kit.rb_flip / a value with kit.rb_value.
"""
import json
import os
import subprocess
import time
import pytest
import rb_testgen_kit as kit
RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__)))
MAIN_TABS = ["Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL"]
DOCK_TABS = ["SQL Log", "Plot", "DB Schema", "Remote"]
REMOTE_TABS = ["DBHub.io", "Local", "Current Database"]
DIALOG_TABS = ["Fields", "Index Constraints", "Foreign Keys", "Check Constraints"]
PREFS_TABS = ["General", "Database", "Data Browser", "SQL", "Extensions", "Remote"]
PRAGMA_CHECKBOXES = ["Automatic Index", "Case Sensitive Like", "Checkpoint Full FSYNC",
"Foreign Keys", "Full FSYNC", "Ignore Check Constraints",
"Recursive Triggers", "Secure Delete"]
VIEW_TOGGLES = ["SQL Log", "Plot", "DB Schema", "Edit Database Cell", "Remote",
"DB Toolbar", "Extra DB Toolbar", "Project Toolbar",
"Database Structure", "Browse Data", "Edit Pragmas", "Execute SQL"]
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 _key(code):
subprocess.run(["osascript", "-e",
'tell application "System Events" to key code %d' % code],
capture_output=True)
time.sleep(0.35)
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 menu_item_map(ax, top, attrs=("AXEnabled", "AXMenuItemMarkChar")):
"""Open `top`, read {name: {attr: value}} for its named items, then close the menu."""
m = open_menu(ax, top)
out = {}
if m is not None:
for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1):
if it.name:
out[it.name] = ax.get(it.id, list(attrs))
_esc(2)
return out
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, 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 tabbar(ax, kids, root_id=None):
"""The tab-bar `group` whose direct radio children == kids. AXTitle == selected tab."""
for g in ax.find(role="group", max_results=250, root_id=root_id):
ks = [k.name for k in ax.find(role="radio", root_id=g.id, max_results=10, max_depth=1)]
if ks == kids:
return g
return None
def selected_tab(ax, kids, root_id=None):
g = tabbar(ax, kids, root_id=root_id)
return None if g is None else g.name
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 checkbox_containing(ax, needle, root_id=None):
"""Pragma checkbox AXTitles are literal HTML -> match by substring."""
for c in ax.find(role="checkbox", max_results=60, root_id=root_id):
if needle in (c.name or ""):
return c
return None
def incrementor_containing(ax, needle, root_id=None):
for c in ax.find(role="incrementor", max_results=30, root_id=root_id):
if needle in (c.name or ""):
return c
return None
def cb_value(ax, el):
return ax.get(el.id, ["AXValue"]).get("AXValue")
def combo_named(ax, names, root_id=None):
for c in ax.find(role="combobox", max_results=30, root_id=root_id):
if (c.name or "") in names:
return c
return None
def combo_change(ax, combo, direction_code):
"""Qt combobox: AXPress opens the popup, then arrow + Return commits.
direction_code: 125 = Down, 126 = Up."""
ax.action(combo.id, "AXPress")
time.sleep(0.9)
_key(direction_code)
_key(36)
time.sleep(0.9)
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
# ─────────────────────────── extra local helpers ───────────────────────────
# All batched: ONE tree walk per role (12 separate full-tree walks blow the
# 30 s per-test budget on a ~325-node tree).
PRAGMA_INCREMENTORS = ["Journal Size Limit", "Max Page Count",
"User Version", "WAL Auto Checkpoint"]
TOOLS_ITEMS = ["Compact Database...", "Load Extension...", "Integrity Check",
"Quick Integrity Check", "Foreign-Key Check", "Optimize",
"Show Row Counts"]
EDIT_DDL_ITEMS = ["Create Table...", "Create Index...",
"Modify Table...", "Delete Table..."]
# The app-menu Preferences item AXTitle is NOT stable ('Preferences...' vs
# 'Settings…') — always match by keyword (EN + ZH fallbacks).
PREF_KEYS = ("prefer", "etting", "偏好", "设置")
def _i(v):
"""Normalize a checkbox AXValue (0/1, '0'/'1', bool) to an int."""
if isinstance(v, bool):
return int(v)
try:
return int(v)
except (TypeError, ValueError):
return v
def _numstr(v):
"""Normalize a spin-box AXValue to its plain string form ('1000', '-1')."""
if v is None:
return None
if isinstance(v, bool):
return str(int(v))
if isinstance(v, float) and v.is_integer():
return str(int(v))
return str(v)
def buttons_by_name(ax, names, root_id=None):
"""{name: element} for the wanted button AXTitles — one tree walk."""
out = {}
for b in ax.find(role="button", max_results=120, root_id=root_id):
n = b.name or ""
if n in names and n not in out:
out[n] = b
return out
def button_names(ax, root_id=None):
return [b.name or "" for b in ax.find(role="button", max_results=120, root_id=root_id)]
def radio_names(ax, root_id=None):
return [r.name or "" for r in ax.find(role="radio", max_results=30, root_id=root_id)]
def combo_names(ax, root_id=None):
return [c.name or "" for c in ax.find(role="combobox", max_results=30, root_id=root_id)]
def label_texts(ax, root_id=None):
"""Visible label text (AXValue and AXTitle both count — a recreation may use
either) for every `label` in the tree."""
out = set()
for el in ax.find(role="label", max_results=150, root_id=root_id):
if el.value:
out.add(str(el.value))
if el.name:
out.add(str(el.name))
return out
def pragma_widgets(ax):
"""({readable name: checkbox}, {readable name: incrementor}) — 2 tree walks.
Pragma AXTitles are literal HTML, so match by substring."""
cbs = ax.find(role="checkbox", max_results=60)
incs = ax.find(role="incrementor", max_results=30)
cmap, imap = {}, {}
for n in PRAGMA_CHECKBOXES:
for c in cbs:
if n in (c.name or ""):
cmap[n] = c
break
for n in PRAGMA_INCREMENTORS:
for el in incs:
if n in (el.name or ""):
imap[n] = el
break
return cmap, imap
def pragma_enabled_list(ax):
"""[AXEnabled] for the 8 pragma checkboxes then the 4 incrementors (None when
the widget is missing, so a gap FAILS instead of silently passing)."""
cmap, imap = pragma_widgets(ax)
out = []
for n in PRAGMA_CHECKBOXES:
out.append(None if n not in cmap else enabled(ax, cmap[n]))
for n in PRAGMA_INCREMENTORS:
out.append(None if n not in imap else enabled(ax, imap[n]))
return out
def pragma_value_maps(ax):
cmap, imap = pragma_widgets(ax)
cvals = {n: (None if n not in cmap else _i(cb_value(ax, cmap[n])))
for n in PRAGMA_CHECKBOXES}
ivals = {n: (None if n not in imap else _numstr(cb_value(ax, imap[n])))
for n in PRAGMA_INCREMENTORS}
return cvals, ivals
def menu_enabled_map(item_map, names):
return {n: (bool(item_map[n].get("AXEnabled")) if n in item_map else None)
for n in names}
def mark_of(item_map, name):
return item_map.get(name, {}).get("AXMenuItemMarkChar")
def option_texts(ax, el):
"""Visible option texts of a Qt combobox (its popup `list` holds one label per
option). Accepts AXTitle or AXValue so framework differences don't matter."""
out = []
for lb in ax.find(role="label", root_id=el.id, max_results=40):
t = lb.name or lb.value or ""
if t:
out.append(str(t))
return out
def type_sql(ax, sql):
"""QScintilla ignores set_value -> CG click + ⌘A + keystroke (recon COMPUTATION)."""
e = sql_editor(ax)
if e is None:
return False
ax.click_element_cg(e.id)
time.sleep(0.4)
subprocess.run(["osascript", "-e",
'tell application "System Events" to keystroke "a" using command down'],
capture_output=True)
time.sleep(0.25)
subprocess.run(["osascript", "-e",
'tell application "System Events" to keystroke ' + json.dumps(sql)],
capture_output=True)
time.sleep(0.5)
return True
def exec_sql(ax):
b = find_button(ax, "Execute SQL")
if b is None:
return False
ok = ax.action(b.id, "AXPress")
time.sleep(1.9)
return bool(ok)
def find_prefs_window(ax):
for w in ax.find(role="window", max_results=10, max_depth=1):
n = (w.name or "").lower()
if any(k in n for k in PREF_KEYS):
return w
return None
def rb_reach_preferences(ax):
"""Open the Preferences/Settings surface by KEYWORD (recon: the menu item's
AXTitle is UNSTABLE — 'Preferences...' on one build, 'Settings…' on another).
Tries the app menu first, then the other menus, then the ⌘, hotkey."""
w = find_prefs_window(ax)
if w is not None:
return w
tops = [t for t in ax.find(role="menu_bar_item", max_results=12, max_depth=3)
if (t.name or "") and (t.name or "").lower() != "apple"]
tops.sort(key=lambda t: 0 if any(k in (t.name or "").lower()
for k in ("sqlite", "browser", "db4s")) else 1)
for t in tops[:4]:
m = open_menu(ax, t.name)
if m is None:
continue
target = None
for it in ax.find(role="menu_item", root_id=m.id, max_results=80, max_depth=1):
nm = (it.name or "").lower()
if not nm or "service" in nm:
continue
if any(k in nm for k in PREF_KEYS):
target = it
break
if target is not None:
ax.action(target.id, "AXPress")
time.sleep(1.5)
w = find_prefs_window(ax)
if w is not None:
return w
_esc(2)
subprocess.run(["osascript", "-e",
'tell application "System Events" to keystroke "," using command down'],
capture_output=True)
time.sleep(1.5)
return find_prefs_window(ax)
def close_scoped(ax, win, name="Cancel"):
"""Close a dialog with ITS OWN scoped button (a global find(name='Cancel')
would also match the Edit-Pragmas / Preferences Cancel)."""
if win is None:
return False
b = ax.find(role="button", name=name, root_id=win.id, max_results=2)
if not b:
return False
ax.action(b[0].id, "AXPress")
time.sleep(0.8)
return True
def ext_widget_counts(ax, root_id):
"""(n_checkboxes, n_buttons) whose visible label mentions "extension" — the
Extensions prefs page signature."""
cbs = [c for c in ax.find(role="checkbox", max_results=60, root_id=root_id)
if "xtension" in (c.name or "").lower()]
bts = [b for b in ax.find(role="button", max_results=90, root_id=root_id)
if "xtension" in (b.name or "").lower()]
return len(cbs), len(bts)
# ══════════════════════════════ TAB-BAR SELECTION ══════════════════════════════
class TestTabBarSelectionState:
"""ST1/ST2/ST3 — the mode/selection indicator is the tab-bar group's AXTitle."""
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="main tab-bar group AXTitle 'Database Structure'->'Execute SQL'"
"->'Browse Data'->'Edit Pragmas'->back to 'Database Structure'")
def test_main_tab_bar_selection_indicator_walks_all_four(self, ax):
fresh = selected_tab(ax, MAIN_TABS)
assert fresh == "Database Structure", (
f"fresh main tab-bar AXTitle should be 'Database Structure', got {fresh!r}")
seq = [fresh]
for name in ["Execute SQL", "Browse Data", "Edit Pragmas", "Database Structure"]:
assert switch_tab(ax, name), f"could not AXPress main tab radio {name!r}"
now = selected_tab(ax, MAIN_TABS)
assert now == name, (
f"after pressing radio {name!r} the tab-bar AXTitle should be {name!r}, "
f"got {now!r}")
seq.append(now)
assert seq == ["Database Structure", "Execute SQL", "Browse Data",
"Edit Pragmas", "Database Structure"], seq
assert kit.rb_flip(seq[:-1], seq[1:]), (
"the selection indicator never changed across the 4 main tabs")
screenshot_assert(
"states_test_main_tab_bar_selection",
"DB Browser for SQLite main window with the 4-tab bar Database Structure / "
"Browse Data / Edit Pragmas / Execute SQL. The walk ended back on "
"Database Structure, so that tab is the highlighted/selected one and the "
"left pane shows the empty object tree with Create Table, Create Index and "
"Modify Table buttons above it (all greyed out, no database open).",
RESULTS_DIR)
@pytest.mark.rb(depth=0, jump_kind="value",
expect="tab radios report AXValue None and AXSelected None; selection is "
"only readable from the tab-bar group AXTitle")
def test_main_tab_radios_expose_no_selection_attribute(self, ax):
g = tabbar(ax, MAIN_TABS)
assert g is not None, "main tab bar (radios == MAIN_TABS) not found"
radios = ax.find(role="radio", root_id=g.id, max_results=10, max_depth=1)
assert [r.name for r in radios] == MAIN_TABS, [r.name for r in radios]
for r in radios:
attrs = ax.get(r.id, ["AXValue", "AXSelected"])
assert attrs.get("AXValue") is None, (
f"radio {r.name!r} AXValue should be None, got {attrs.get('AXValue')!r}")
assert attrs.get("AXSelected") is None, (
f"radio {r.name!r} AXSelected should be None, "
f"got {attrs.get('AXSelected')!r}")
assert kit.rb_value(selected_tab(ax, MAIN_TABS), "Database Structure")
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="dock tab-bar group AXTitle 'Remote'->'DB Schema'->'Plot'->'SQL Log'")
def test_dock_tab_bar_selection_indicator(self, ax):
fresh = selected_tab(ax, DOCK_TABS)
assert fresh == "Remote", (
f"fresh dock tab-bar AXTitle should be 'Remote', got {fresh!r}")
seq = [fresh]
for name in ["DB Schema", "Plot", "SQL Log"]:
assert switch_tab(ax, name), f"could not AXPress dock tab radio {name!r}"
now = selected_tab(ax, DOCK_TABS)
assert now == name, (
f"after pressing dock radio {name!r} the tab-bar AXTitle should be "
f"{name!r}, got {now!r}")
seq.append(now)
assert seq == ["Remote", "DB Schema", "Plot", "SQL Log"], seq
assert kit.rb_flip(seq[:-1], seq[1:]), "the dock selection indicator never changed"
screenshot_assert(
"states_test_dock_tab_selection",
"The bottom-right dock of DB Browser for SQLite. Its tab strip reads "
"SQL Log / Plot / DB Schema / Remote and SQL Log is now the highlighted "
"(selected) tab, so the dock body shows the SQL log text pane with the "
"'Show SQL submitted by' dropdown (Application) and a Clear button — the "
"Remote panel is no longer displayed.",
RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Remote panel sub tab-bar AXTitle 'DBHub.io'->'Local'"
"->'Current Database'")
def test_remote_sub_tab_bar_selection_indicator(self, ax):
g = tabbar(ax, REMOTE_TABS)
assert g is not None, "Remote sub tab bar (radios == REMOTE_TABS) not found"
fresh = g.name
assert fresh == "DBHub.io", (
f"fresh Remote sub tab-bar AXTitle should be 'DBHub.io', got {fresh!r}")
seq = [fresh]
for name in ["Local", "Current Database"]:
bar = tabbar(ax, REMOTE_TABS)
assert bar is not None, "Remote sub tab bar vanished"
assert switch_tab(ax, name, root_id=bar.id), (
f"could not AXPress Remote sub-tab radio {name!r}")
now = selected_tab(ax, REMOTE_TABS)
assert now == name, (
f"after pressing Remote sub-tab {name!r} the sub tab-bar AXTitle should "
f"be {name!r}, got {now!r}")
seq.append(now)
assert seq == ["DBHub.io", "Local", "Current Database"], seq
assert kit.rb_flip(seq[:-1], seq[1:]), "the Remote sub-tab indicator never changed"
# ═════════════════════════ VIEW MENU CHECK STATE (ST6) ═════════════════════════
class TestViewMenuCheckState:
"""AXMenuItemMarkChar on the 12 View toggles + two SAFE round trips."""
@pytest.mark.rb(depth=1, jump_kind="value",
expect="all 12 View toggles have AXMenuItemMarkChar '✓' on a fresh app")
def test_view_menu_all_twelve_toggles_checked_by_default(self, ax_with_reset):
ax = ax_with_reset
items = menu_item_map(ax, "View")
assert items, "View menu exposed no named menu items"
marks = []
for name in VIEW_TOGGLES:
assert name in items, f"View menu item {name!r} missing (got {sorted(items)})"
mark = mark_of(items, name)
assert mark == "✓", (
f"View toggle {name!r} should carry AXMenuItemMarkChar '✓' on a "
f"fresh app, got {mark!r}")
marks.append(mark)
assert len(marks) == 12
assert kit.rb_value(sorted(set(marks)), "✓")
open_menu(ax, "View")
screenshot_assert(
"states_test_view_menu_checkmarks",
"The View menu of DB Browser for SQLite is open in the macOS menu bar. It "
"lists SQL Log, Plot, DB Schema, Edit Database Cell, Remote, DB Toolbar, "
"Extra DB Toolbar, Project Toolbar, Database Structure, Browse Data, "
"Edit Pragmas and Execute SQL — every one of those 12 entries shows a "
"checkmark on its left — plus a 'Window Layout' submenu and "
"'Enter Full Screen' with no checkmark.",
RESULTS_DIR)
_esc(2)
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="View▸SQL Log mark '✓'->None and the dock's Clear button / "
"'Show SQL submitted by' label / source combobox / 'SQL Log' radio "
"disappear, then all return")
def test_view_sql_log_toggle_round_trip(self, ax_with_reset):
ax = ax_with_reset
mark_before = mark_of(menu_item_map(ax, "View"), "SQL Log")
assert mark_before == "✓", (
f"View▸SQL Log should start CHECKED, got {mark_before!r}")
assert find_button(ax, "Clear") is not None, "SQL Log dock 'Clear' button missing"
before = kit.rb_showing(ax)
assert rb_reach_menu_item(ax, "View", "SQL Log"), "could not press View▸SQL Log"
after = kit.rb_showing(ax)
mark_off = mark_of(menu_item_map(ax, "View"), "SQL Log")
assert mark_off is None, (
f"View▸SQL Log mark should be None once the dock is hidden, got {mark_off!r}")
assert find_button(ax, "Clear") is None, "SQL Log dock 'Clear' button still present"
assert combo_named(ax, ("Application",)) is None, (
"SQL log source combobox 'Application' still present")
assert "SQL Log" not in radio_names(ax), "dock tab radio 'SQL Log' still present"
assert "Show SQL submitted by" not in label_texts(ax), (
"label 'Show SQL submitted by' still present")
assert kit.rb_flip(mark_before, mark_off), "the SQL Log checkmark never flipped"
assert len(after) < len(before), (
"hiding the SQL Log dock should REMOVE nodes from the AX tree "
f"(before={len(before)} after={len(after)})")
assert rb_reach_menu_item(ax, "View", "SQL Log"), "could not re-press View▸SQL Log"
mark_back = mark_of(menu_item_map(ax, "View"), "SQL Log")
assert mark_back == "✓", (
f"View▸SQL Log mark should return to '✓', got {mark_back!r}")
assert find_button(ax, "Clear") is not None, "'Clear' button did not come back"
assert combo_named(ax, ("Application",)) is not None, (
"SQL log source combobox did not come back")
assert "SQL Log" in radio_names(ax), "dock tab radio 'SQL Log' did not come back"
assert "Show SQL submitted by" in label_texts(ax), (
"label 'Show SQL submitted by' did not come back")
_esc(2)
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="View▸Plot mark '✓'->None->'✓' and the 'Line type:' / "
"'Point shape:' labels disappear and return")
def test_view_plot_toggle_round_trip(self, ax_with_reset):
ax = ax_with_reset
mark_before = mark_of(menu_item_map(ax, "View"), "Plot")
assert mark_before == "✓", (
f"View▸Plot should start CHECKED, got {mark_before!r}")
texts = label_texts(ax)
assert "Line type:" in texts and "Point shape:" in texts, (
"the Plot dock's 'Line type:' / 'Point shape:' labels are missing on a fresh app")
assert rb_reach_menu_item(ax, "View", "Plot"), "could not press View▸Plot"
mark_off = mark_of(menu_item_map(ax, "View"), "Plot")
assert mark_off is None, (
f"View▸Plot mark should be None once the dock is hidden, got {mark_off!r}")
gone = label_texts(ax)
assert "Line type:" not in gone, "'Line type:' label still present"
assert "Point shape:" not in gone, "'Point shape:' label still present"
assert "Plot" not in radio_names(ax), "dock tab radio 'Plot' still present"
assert kit.rb_flip(mark_before, mark_off), "the Plot checkmark never flipped"
assert rb_reach_menu_item(ax, "View", "Plot"), "could not re-press View▸Plot"
mark_back = mark_of(menu_item_map(ax, "View"), "Plot")
assert mark_back == "✓", (
f"View▸Plot mark should return to '✓', got {mark_back!r}")
back = label_texts(ax)
assert "Line type:" in back and "Point shape:" in back, (
"the Plot dock labels did not come back")
_esc(2)
# ═══════════════════════════ PRAGMA STATE (ST7/ST8) ═══════════════════════════
class TestPragmaState:
@pytest.mark.rb(depth=1, jump_kind="value",
expect="all 8 pragma checkboxes AXValue 0 / AXEnabled False and the 4 "
"incrementors AXValue '0' / disabled with no database open")
def test_pragma_widgets_disabled_without_database(self, ax):
assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab"
assert selected_tab(ax, MAIN_TABS) == "Edit Pragmas"
cvals, ivals = pragma_value_maps(ax)
assert cvals == {n: 0 for n in PRAGMA_CHECKBOXES}, cvals
assert ivals == {n: "0" for n in PRAGMA_INCREMENTORS}, ivals
en = pragma_enabled_list(ax)
assert len(en) == 12 and all(v is False for v in en), (
f"every pragma widget must be DISABLED with no database open, got {en}")
observed = (tuple(sorted(cvals.items())), tuple(sorted(ivals.items())), tuple(en))
expected = (tuple(sorted({n: 0 for n in PRAGMA_CHECKBOXES}.items())),
tuple(sorted({n: "0" for n in PRAGMA_INCREMENTORS}.items())),
tuple([False] * 12))
assert kit.rb_value(observed, expected)
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="pragma checkboxes+incrementors AXEnabled False->True after "
"File▸New In-Memory Database")
def test_pragma_widgets_enable_with_database(self, ax_with_reset):
ax = ax_with_reset
assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab"
before = pragma_enabled_list(ax)
assert len(before) == 12 and all(v is False for v in before), before
assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly"
assert switch_tab(ax, "Database Structure")
assert switch_tab(ax, "Edit Pragmas"), "could not re-activate the Edit Pragmas tab"
after = pragma_enabled_list(ax)
assert len(after) == 12 and all(v is True for v in after), (
f"every pragma widget must be ENABLED once a database is open, got {after}")
assert kit.rb_flip(before, after), "the pragma ENABLED state never flipped"
@pytest.mark.rb(depth=1, jump_kind="value",
expect="Foreign Keys=1, Automatic Index=1, other 6 pragma checkboxes=0, "
"WAL Auto Checkpoint='1000', Journal Size Limit='-1', "
"Max Page Count='0', User Version='0'")
def test_pragma_values_load_for_inmemory_database(self, ax_with_reset):
ax = ax_with_reset
# ORDERING MATTERS: open the DB while ANOTHER tab is active, then activate
# Edit Pragmas — the pragma values only load on tab activation.
assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly"
assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab"
cvals, ivals = pragma_value_maps(ax)
expected_cb = {n: 0 for n in PRAGMA_CHECKBOXES}
expected_cb["Foreign Keys"] = 1
expected_cb["Automatic Index"] = 1
expected_inc = {"WAL Auto Checkpoint": "1000", "Journal Size Limit": "-1",
"Max Page Count": "0", "User Version": "0"}
assert cvals == expected_cb, f"pragma checkbox values {cvals} != {expected_cb}"
assert ivals == expected_inc, f"pragma spin values {ivals} != {expected_inc}"
assert kit.rb_value((tuple(sorted(cvals.items())), tuple(sorted(ivals.items()))),
(tuple(sorted(expected_cb.items())),
tuple(sorted(expected_inc.items()))))
screenshot_assert(
"states_test_pragma_values_inmemory",
"The Edit Pragmas tab of DB Browser for SQLite with the in-memory database "
"open. The pragma form lists 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. Exactly two checkboxes are "
"ticked — Foreign Keys and Automatic Index — every other pragma checkbox is "
"unticked, and the WAL Auto Checkpoint spin box reads 1000 while Journal "
"Size Limit reads -1. Save and Cancel buttons sit at the bottom.",
RESULTS_DIR)
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Foreign Keys checkbox AXValue 1->0->1")
def test_pragma_foreign_keys_checkbox_toggle_round_trip(self, ax_with_reset):
ax = ax_with_reset
assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly"
assert switch_tab(ax, "Edit Pragmas"), "could not activate the Edit Pragmas tab"
cb = checkbox_containing(ax, "Foreign Keys")
assert cb is not None, "pragma checkbox 'Foreign Keys' not found"
assert enabled(ax, cb), "pragma checkbox 'Foreign Keys' should be ENABLED with a DB"
v0 = _i(cb_value(ax, cb))
assert v0 == 1, f"Foreign Keys should start CHECKED (1) for a new DB, got {v0!r}"
assert ax.action(cb.id, "AXPress"), "AXPress on the Foreign Keys checkbox failed"
time.sleep(0.5)
v1 = _i(cb_value(ax, cb))
assert v1 == 0, f"Foreign Keys should be UNCHECKED (0) after one press, got {v1!r}"
assert kit.rb_flip(v0, v1), "the Foreign Keys checkbox value never flipped"
assert ax.action(cb.id, "AXPress"), "second AXPress on Foreign Keys failed"
time.sleep(0.5)
v2 = _i(cb_value(ax, cb))
assert v2 == 1, f"Foreign Keys should be CHECKED (1) again, got {v2!r}"
# ═════════════════════════ ENABLED FLIPS (ST8/ST9/ST10) ════════════════════════
class TestEnabledFlips:
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Write Changes / Revert Changes AXEnabled False->True after a "
"CREATE TABLE executed in the Execute SQL tab")
def test_write_changes_enabled_flip_after_ddl(self, ax_with_reset):
ax = ax_with_reset
assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly"
wanted = ("Write Changes", "Revert Changes")
bm = buttons_by_name(ax, wanted)
assert set(bm) == set(wanted), f"toolbar buttons missing: {sorted(bm)}"
before = (enabled(ax, bm["Write Changes"]), enabled(ax, bm["Revert Changes"]))
assert before == (False, False), (
f"Write/Revert Changes must be DISABLED before any DDL, got {before}")
assert switch_tab(ax, "Execute SQL"), "could not activate the Execute SQL tab"
assert type_sql(ax, "CREATE TABLE t1(a INTEGER, b TEXT);"), "SQL editor not found"
assert exec_sql(ax), "could not press the 'Execute SQL' button"
bm2 = buttons_by_name(ax, wanted)
assert set(bm2) == set(wanted), f"toolbar buttons missing after DDL: {sorted(bm2)}"
after = (enabled(ax, bm2["Write Changes"]), enabled(ax, bm2["Revert Changes"]))
assert after == (True, True), (
f"Write/Revert Changes must be ENABLED after a CREATE TABLE, got {after}")
assert kit.rb_flip(before, after), "the pending-changes ENABLED state never flipped"
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Tools items and Edit▸Create Table.../Create Index... AXEnabled "
"False->True after opening the in-memory database")
def test_tools_and_edit_menu_enabled_flip_with_database(self, ax_with_reset):
ax = ax_with_reset
tools_before = menu_enabled_map(menu_item_map(ax, "Tools"), TOOLS_ITEMS)
edit_before = menu_enabled_map(menu_item_map(ax, "Edit"), EDIT_DDL_ITEMS)
assert tools_before == {n: False for n in TOOLS_ITEMS}, tools_before
assert edit_before == {n: False for n in EDIT_DDL_ITEMS}, edit_before
assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly"
tools_after = menu_enabled_map(menu_item_map(ax, "Tools"), TOOLS_ITEMS)
edit_after = menu_enabled_map(menu_item_map(ax, "Edit"), EDIT_DDL_ITEMS)
assert tools_after == {n: True for n in TOOLS_ITEMS}, (
f"every Tools item must be ENABLED with a database open, got {tools_after}")
assert edit_after == {"Create Table...": True, "Create Index...": True,
"Modify Table...": False, "Delete Table...": False}, edit_after
before = (tuple(sorted(tools_before.items())), tuple(sorted(edit_before.items())))
after = (tuple(sorted(tools_after.items())), tuple(sorted(edit_after.items())))
assert kit.rb_flip(before, after), "no menu-item ENABLED state flipped"
@pytest.mark.rb(depth=1, jump_kind="transition",
expect="Clear Filters AXEnabled False->True when a filter is typed and "
"back to False after pressing it")
def test_clear_filters_enabled_round_trip(self, ax_with_reset):
ax = ax_with_reset
assert rb_enter_inmemory_db(ax), "in-memory database was not opened cleanly"
assert switch_tab(ax, "Execute SQL"), "could not activate the Execute SQL tab"
assert type_sql(ax, "CREATE TABLE nums(n INTEGER, label TEXT); "
"INSERT INTO nums VALUES(10,'ten'),(20,'twenty'),(30,'thirty');")
assert exec_sql(ax), "could not press the 'Execute SQL' button"
assert switch_tab(ax, "Browse Data"), "could not activate the Browse Data tab"
btn = find_button(ax, "Clear Filters")
assert btn is not None, "button 'Clear Filters' not found on the Browse Data tab"
before = enabled(ax, btn)
assert before is False, "'Clear Filters' must be DISABLED with no filter typed"
flt = ax.find(role="text_field", name="Filter in any column", max_results=1)
assert flt, "text_field 'Filter in any column' not found"
assert ax.set_value(flt[0].id, "twenty"), "could not set the filter text"
time.sleep(1.7)
after = enabled(ax, find_button(ax, "Clear Filters"))
assert after is True, "'Clear Filters' must be ENABLED once a filter is typed"
assert kit.rb_flip(before, after), "the Clear Filters ENABLED state never flipped"
btn2 = find_button(ax, "Clear Filters")
assert btn2 is not None
assert ax.action(btn2.id, "AXPress"), "AXPress on 'Clear Filters' failed"
time.sleep(1.7)
assert enabled(ax, find_button(ax, "Clear Filters")) is False, (
"'Clear Filters' must be DISABLED again after clearing")
flt2 = ax.find(role="text_field", name="Filter in any column", max_results=1)
assert flt2, "the filter field disappeared"
assert (ax.get(flt2[0].id, ["AXValue"]).get("AXValue") or "") == "", (
"the filter field should be emptied by 'Clear Filters'")
# ═══════════════════════ MODE COMBOBOX + FOCUS (ST13/ST11) ═══════════════════════
class TestModeAndFocusState:
@pytest.mark.rb(depth=0, jump_kind="transition",
expect="SQL log source combobox AXTitle 'Application'->'User' via popup "
"+ Up + Return")
def test_sql_log_source_combobox_mode_flip(self, ax):
combo = combo_named(ax, ("Application",))
assert combo is not None, "SQL log source combobox 'Application' not found"
assert enabled(ax, combo), "the SQL log source combobox should be ENABLED"
opts = option_texts(ax, combo)
assert opts == ["User", "Application", "Error Log"], (
f"SQL log source options should be User/Application/Error Log, got {opts}")
before = ax.get(combo.id, ["AXTitle"]).get("AXTitle")
assert before == "Application", (
f"the fresh SQL log source should be 'Application', got {before!r}")
combo_change(ax, combo, 126)
after = ax.get(combo.id, ["AXTitle"]).get("AXTitle")
assert after == "User", (
f"after popup + Up + Return the source should read 'User', got {after!r}")
assert kit.rb_flip(before, after), "the SQL log source mode never changed"
# ═════════════════════ DIALOG (ST4) + PREFERENCES (ST5) STATE ═════════════════════
class TestDialogAndPrefsState:
@pytest.mark.rb(depth=2, jump_kind="transition",
expect="Preferences tab-bar AXTitle 'General'->'Extensions' and the "
"Extensions-tab extension checkboxes/buttons appear")
def test_preferences_tab_bar_selection_indicator(self, ax_with_reset):
ax = ax_with_reset
prefs = rb_reach_preferences(ax)
assert prefs is not None, "the Preferences/Settings window did not open"
tab_before = selected_tab(ax, PREFS_TABS, root_id=prefs.id)
assert tab_before == "General", (
f"the Preferences tab bar should open on 'General', got {tab_before!r}")
ext_before = ext_widget_counts(ax, prefs.id)
assert ext_before == (0, 0), (
f"no extension checkbox/button should be showing on the General page, "
f"got {ext_before}")
bar = tabbar(ax, PREFS_TABS, root_id=prefs.id)
assert bar is not None, "the Preferences tab bar was not found"
assert switch_tab(ax, "Extensions", root_id=bar.id), (
"could not AXPress the Preferences 'Extensions' tab")
tab_after = selected_tab(ax, PREFS_TABS, root_id=prefs.id)
assert tab_after == "Extensions", (
f"the Preferences tab-bar AXTitle should be 'Extensions', got {tab_after!r}")
ext_after = ext_widget_counts(ax, prefs.id)
assert ext_after[0] >= 2, (
f"the Extensions page should expose at least 2 extension checkboxes "
f"(e.g. 'Disable Regular Expression extension', 'Allow loading extensions "
f"from SQL code'), got {ext_after[0]}")
assert ext_after[1] >= 2, (
f"the Extensions page should expose add/remove extension buttons, "
f"got {ext_after[1]}")
assert kit.rb_flip((tab_before, ext_before), (tab_after, ext_after)), (
"the Preferences tab selection never changed")
screenshot_assert(
"states_test_preferences_extensions_tab",
"A separate Preferences window of DB Browser for SQLite, in front of the "
"main window. Its tab strip reads General, Database, Data Browser, SQL, "
"Extensions, Remote and 'Extensions' is now the selected tab, so the page "
"shows the SQLite extension list with Add/Remove extension buttons and the "
"checkboxes for disabling the Regular Expression extension and allowing "
"extension loading from SQL code. Save, Cancel and Restore Defaults buttons "
"are at the bottom.",
RESULTS_DIR)
assert close_scoped(ax, prefs, "Cancel"), (
"could not close the Preferences window with its own Cancel button")
|