Datasets:
Download windows/couchcoding-logbert/tests/logbert_ui.py from Qwen/RecreationBench: direct link, hf CLI and curl.
- Browser
- Download file 23.7 kB
-
https://huggingface.co/datasets/Qwen/RecreationBench/resolve/main/windows/couchcoding-logbert/tests/logbert_ui.py
- Command line
-
hf download hf://datasets/Qwen/RecreationBench/windows/couchcoding-logbert/tests/logbert_ui.py
-
curl -L -o logbert_ui.py https://huggingface.co/datasets/Qwen/RecreationBench/resolve/main/windows/couchcoding-logbert/tests/logbert_ui.py
23.7 kB
| """logbert_ui — vetted UIA primitives for the Logbert test suite. | |
| Every function here was validated against the running reference build during recon. | |
| Import it from a test module:: | |
| import logbert_ui as L | |
| from rb_uia import rb_showing, rb_reach, rb_flip, rb_value | |
| WHY THIS MODULE EXISTS (pitfalls it solves — do not re-invent these): | |
| 1. ``rb_uia.find_first(app, ...)`` ALWAYS returns ``None``. The ``app`` fixture | |
| yields a pywinauto ``UIAWrapper``, which has no ``child_window()``. Use | |
| ``L.one()`` / ``L.alld()`` (they go through ``.descendants()``) instead. | |
| 2. Logbert's modal dialogs (New Logger, Options, About, Edit Filter, message | |
| boxes, and even the native "Open" file dialog) are NOT desktop top-level | |
| windows — they appear as ``control_type="Window"`` DESCENDANTS of the main | |
| window. Use ``L.dialog(app, "New Logger")``. | |
| 3. Menu dropdown items are only present in the tree while the dropdown is open, | |
| and the tree lists each item twice. Use ``L.open_menu`` + ``L.pick_menu``. | |
| 4. Toolbar toggle buttons expose NO TogglePattern. Read CHECKED with | |
| ``L.is_checked(button)`` (LegacyIAccessible STATE_SYSTEM_CHECKED bit). | |
| 5. The app opens on a Welcome page with no log data. Call | |
| ``L.rb_enter_document(app, rb)`` first to reach the core working state. | |
| """ | |
| from __future__ import annotations | |
| import ctypes | |
| import os | |
| import time | |
| # ── fixtures ───────────────────────────────────────────────────────────────── | |
| DEFAULT_LOG = "sample_log4net.log" | |
| MIXED_LOG = "sample_log4net_mixed.log" | |
| def fixtures_dir() -> str: | |
| """FIXTURES_DIR when the eval harness sets it, else ``fixtures/`` next to the | |
| results dir (warm ``run_live.ps1`` runs). | |
| Always returned as a NATIVE path: the Windows file chooser silently refuses a | |
| path typed with forward slashes, so `/` separators must be normalised away. | |
| """ | |
| fd = os.environ.get("FIXTURES_DIR", "") | |
| if fd and os.path.isdir(fd): | |
| return os.path.normpath(fd) | |
| rd = os.environ.get("RB_RESULTS_DIR") or os.environ.get("RESULTS_DIR") or "." | |
| cand = os.path.join(os.path.dirname(os.path.abspath(rd)), "fixtures") | |
| if os.path.isdir(cand): | |
| return os.path.normpath(cand) | |
| return os.path.normpath(os.path.join(os.path.abspath(rd), "fixtures")) | |
| def fixture(name: str = DEFAULT_LOG) -> str: | |
| return os.path.normpath(os.path.join(fixtures_dir(), name)) | |
| # ── locators (never use rb_uia.find_first — see module docstring) ──────────── | |
| def alld(root, ct: str | None = None, title: str | None = None, **kw) -> list: | |
| """All descendants of ``root`` matching control_type / visible title.""" | |
| root = _healed(root) | |
| if root is None: | |
| return [] | |
| crit = {} | |
| if ct: | |
| crit["control_type"] = ct | |
| if title: | |
| crit["title"] = title | |
| crit.update(kw) | |
| try: | |
| return root.descendants(**crit) if crit else root.descendants() | |
| except Exception: | |
| return [] | |
| def one(root, ct: str | None = None, title: str | None = None, **kw): | |
| r = alld(root, ct, title, **kw) | |
| return r[0] if r else None | |
| def named(root, ct: str, name: str): | |
| """First descendant of ``ct`` whose visible name is EXACTLY ``name``.""" | |
| for e in alld(root, ct): | |
| try: | |
| if (e.window_text() or "") == name: | |
| return e | |
| except Exception: | |
| continue | |
| return None | |
| def btn(root, name: str): | |
| """Button (incl. toolbar button) by exact visible name.""" | |
| return named(root, "Button", name) | |
| def tab(root, name: str): | |
| return named(root, "TabItem", name) | |
| def pane(root, name: str): | |
| return named(root, "Pane", name) | |
| def pane_names(root) -> set: | |
| out = set() | |
| for p in alld(root, "Pane"): | |
| try: | |
| t = p.window_text() or "" | |
| except Exception: | |
| continue | |
| if t: | |
| out.add(t) | |
| return out | |
| def button_names(root) -> set: | |
| out = set() | |
| for b in alld(root, "Button"): | |
| try: | |
| t = b.window_text() or "" | |
| except Exception: | |
| continue | |
| if t: | |
| out.add(t) | |
| return out | |
| def wait_until(fn, timeout: float = 10.0, interval: float = 0.25): | |
| """Poll ``fn`` until it returns something truthy; return last value.""" | |
| deadline = time.time() + timeout | |
| val = None | |
| while time.time() < deadline: | |
| try: | |
| val = fn() | |
| if val: | |
| return val | |
| except Exception: | |
| pass | |
| time.sleep(interval) | |
| return val | |
| # ── stray-window defence ───────────────────────────────────────────────────── | |
| # | |
| # Once a log file lands in Logbert's MRU, the Welcome page renders it as a link. | |
| # A pointer resting over that link makes Logbert pop a ToolTip, which on Windows | |
| # is a *top-level window owned by the same process* and carries the file path as | |
| # its title. The harness picks "the first titled window of this PID", so it can | |
| # latch onto the ToolTip instead of the main window — after which every locator | |
| # comes back empty and the whole module fails. Two defences: | |
| # park_cursor() — keep the pointer off the app so the ToolTip never appears | |
| # main_window() — if we were handed a childless stray, swap in the real window | |
| def park_cursor() -> None: | |
| """Move the physical pointer to the right edge of the screen, away from the app.""" | |
| try: | |
| u = ctypes.windll.user32 | |
| w = u.GetSystemMetrics(0) | |
| h = u.GetSystemMetrics(1) | |
| u.SetCursorPos(max(0, int(w) - 3), max(0, int(h) // 2)) | |
| except Exception: | |
| pass | |
| def main_window(root): | |
| """The app's real main window — repairs a childless stray (ToolTip) root.""" | |
| if root is None: | |
| return None | |
| try: | |
| if len(root.children()) > 0: | |
| return root | |
| except Exception: | |
| pass | |
| try: | |
| from pywinauto import Desktop | |
| pid = root.process_id() | |
| for w in Desktop(backend="uia").windows(): | |
| try: | |
| if w.process_id() != pid: | |
| continue | |
| if (w.window_text() or "") and len(w.children()) > 0: | |
| return w | |
| except Exception: | |
| continue | |
| except Exception: | |
| pass | |
| return root | |
| def _healed(root): | |
| """Cheap guard used by every locator: only pays for a repair when the root is | |
| a childless top-level Window (never true of a real dialog or pane).""" | |
| if root is None: | |
| return None | |
| try: | |
| if root.element_info.control_type != "Window": | |
| return root | |
| if len(root.children()) > 0: | |
| return root | |
| except Exception: | |
| return root | |
| return main_window(root) | |
| # ── dialogs (descendants, NOT desktop windows) ─────────────────────────────── | |
| def dialog(app, title: str, timeout: float = 10.0): | |
| """Wait for and return the modal dialog whose title is exactly ``title``.""" | |
| return wait_until(lambda: named(app, "Window", title), timeout=timeout) | |
| def dialog_titles(app) -> list: | |
| out = [] | |
| for w in alld(app, "Window"): | |
| try: | |
| t = w.window_text() or "" | |
| except Exception: | |
| continue | |
| if t: | |
| out.append(t) | |
| return out | |
| def close_dialog(app, title: str | None = None) -> None: | |
| """Dismiss a dialog non-destructively: Cancel button if present, else Escape. | |
| NEVER commits changes (no OK) — Logbert persists Options to user settings and | |
| a committed change would leak into later tests. | |
| """ | |
| dlg = named(app, "Window", title) if title else None | |
| target = dlg if dlg is not None else app | |
| b = btn(target, "Cancel") or btn(target, "Close") | |
| if b is not None and (b.window_text() or "") == "Cancel": | |
| try: | |
| b.click_input() | |
| time.sleep(0.4) | |
| return | |
| except Exception: | |
| pass | |
| press("{ESC}") | |
| time.sleep(0.4) | |
| # ── keyboard / mouse ───────────────────────────────────────────────────────── | |
| def press(keys: str) -> None: | |
| from pywinauto.keyboard import send_keys | |
| send_keys(keys) | |
| def type_text(text: str) -> None: | |
| from pywinauto.keyboard import send_keys | |
| send_keys(text, with_spaces=True) | |
| def click_at(x: int, y: int) -> None: | |
| import pywinauto.mouse as mouse | |
| mouse.click(coords=(int(x), int(y))) | |
| # ── menus ──────────────────────────────────────────────────────────────────── | |
| def open_menu(app, top: str) -> bool: | |
| """Click a top-level menu ("File" / "Edit" / "Extras" / "Help").""" | |
| m = named(app, "MenuItem", top) | |
| if m is None: | |
| return False | |
| m.click_input() | |
| time.sleep(0.5) | |
| return True | |
| def pick_menu(app, prefix: str) -> bool: | |
| """Click the open dropdown item whose visible text starts with ``prefix``.""" | |
| for mi in alld(app, "MenuItem"): | |
| try: | |
| if (mi.window_text() or "").startswith(prefix): | |
| mi.click_input() | |
| time.sleep(0.7) | |
| return True | |
| except Exception: | |
| continue | |
| return False | |
| def menu_item_names(app) -> set: | |
| out = set() | |
| for mi in alld(app, "MenuItem"): | |
| try: | |
| t = mi.window_text() or "" | |
| except Exception: | |
| continue | |
| if t: | |
| out.add(t) | |
| return out | |
| def use_menu(app, top: str, prefix: str) -> bool: | |
| """open_menu + pick_menu in one call.""" | |
| return open_menu(app, top) and pick_menu(app, prefix) | |
| # ── reaching the core working state ────────────────────────────────────────── | |
| def select_tab(root, name: str, pause: float = 0.4) -> bool: | |
| """Click a TabItem by its visible name.""" | |
| t = tab(root, name) | |
| if t is None: | |
| return False | |
| try: | |
| t.click_input() | |
| time.sleep(pause) | |
| return True | |
| except Exception: | |
| return False | |
| def normalize_document(app) -> None: | |
| """Put a freshly opened document into its canonical layout. | |
| Logbert PERSISTS the docking layout per receiver, so whichever document tab and | |
| bottom-dock tab a previous run left active come back on the next launch — and a | |
| panel that is not the active one contributes nothing to the UIA tree. Without | |
| this, a run in which some earlier test selected `Filter` would leave every later | |
| test unable to read the Message Details fields. | |
| """ | |
| select_tab(app, "Messages") | |
| select_tab(app, "Message Details") | |
| try: | |
| if pane(app, "Logger Tree") is None: | |
| b = btn(app, "Logger Tree") | |
| if b is not None: | |
| b.click_input() | |
| time.sleep(0.5) | |
| except Exception: | |
| pass | |
| def rb_enter_document(app, rb=None, log_name: str = DEFAULT_LOG, | |
| receiver: str = "Log4Net File Receiver"): | |
| """Welcome page -> File > New Logger... -> pick receiver -> set file -> OK. | |
| A REAL surface crossing (Welcome -> log document), so it bumps ``rb`` by one | |
| when a tracker is passed. Leaves the app showing a loaded log document in its | |
| canonical layout: 6 messages (one per level) for DEFAULT_LOG, 10 for MIXED_LOG. | |
| """ | |
| park_cursor() | |
| use_menu(app, "File", "New Logger") | |
| dlg = dialog(app, "New Logger", 12) | |
| if dlg is None: | |
| raise AssertionError("New Logger dialog did not open") | |
| item = named(dlg, "ListItem", receiver) | |
| if item is None: | |
| raise AssertionError("receiver not in list: %s" % receiver) | |
| item.click_input() | |
| time.sleep(0.6) | |
| ed = named(dlg, "Edit", "File to observe:") | |
| if ed is None: | |
| raise AssertionError("'File to observe:' edit not found") | |
| ed.set_edit_text(fixture(log_name)) | |
| time.sleep(0.3) | |
| ok = btn(dlg, "OK") | |
| if ok is None: | |
| raise AssertionError("OK button not found in New Logger dialog") | |
| ok.click_input() | |
| if wait_until(lambda: len(column_values(app, "Number")) > 0, timeout=15) is None: | |
| raise AssertionError("log document did not load any messages") | |
| time.sleep(0.5) | |
| normalize_document(app) | |
| park_cursor() | |
| if rb is not None: | |
| rb.enter("document") | |
| return app | |
| # ── status bar ─────────────────────────────────────────────────────────────── | |
| def status_texts(app) -> list: | |
| out = [] | |
| for t in alld(app, "Text"): | |
| try: | |
| s = t.window_text() or "" | |
| except Exception: | |
| continue | |
| if s.startswith("Status:") or "Messages (" in s: | |
| out.append(s) | |
| return out | |
| def message_count_text(app) -> str: | |
| """e.g. '6 Messages (all displayed)' or '6 Messages (2 displayed)'.""" | |
| for s in status_texts(app): | |
| if "Messages (" in s: | |
| return s | |
| return "" | |
| def run_state_text(app) -> str: | |
| """'Status: Running' or 'Status: Stopped'.""" | |
| for s in status_texts(app): | |
| if s.startswith("Status:"): | |
| return s | |
| return "" | |
| # ── message grid ───────────────────────────────────────────────────────────── | |
| _GRID_COLS = ("Number", "Level", "Timestamp", "Logger", "Thread", "Message") | |
| def _cell_edits(root): | |
| """Grid cells are Edits named '<Column> Row <n>, <sort state>.'.""" | |
| out = [] | |
| for e in alld(root, "Edit"): | |
| try: | |
| n = e.window_text() or "" | |
| except Exception: | |
| continue | |
| if " Row " in n and n.split(" Row ")[0].strip() in _GRID_COLS: | |
| out.append((n, e)) | |
| return out | |
| def _messages_root(app): | |
| """Scope grid reads to the Messages pane so the Bookmarks / Statistic grids | |
| can never bleed in.""" | |
| return pane(app, "Messages") or app | |
| def grid_rows(app) -> list: | |
| """Visible message rows as a list of dicts keyed by column name.""" | |
| rows: dict[int, dict] = {} | |
| for n, e in _cell_edits(_messages_root(app)): | |
| col = n.split(" Row ")[0].strip() | |
| try: | |
| idx = int(n.split(" Row ")[1].split(",")[0].strip()) | |
| except Exception: | |
| continue | |
| try: | |
| rows.setdefault(idx, {})[col] = e.get_value() | |
| except Exception: | |
| rows.setdefault(idx, {})[col] = None | |
| return [rows[k] for k in sorted(rows)] | |
| def column_values(app, col: str) -> list: | |
| return [r.get(col) for r in grid_rows(app) if col in r] | |
| def row_count(app) -> int: | |
| return len(column_values(app, "Number")) | |
| def cell(app, row: int, col: str): | |
| for n, e in _cell_edits(_messages_root(app)): | |
| if n.startswith("%s Row %d," % (col, row)): | |
| return e | |
| return None | |
| # ── message details pane ───────────────────────────────────────────────────── | |
| _DETAIL_FIELDS = ("Logger", "Level", "Date and Time", "Thread", "Message", | |
| "Location", "Properties") | |
| def details_fields(app) -> dict: | |
| """Message Details pane field values (the selected message). | |
| Self-activating: the bottom dock shares one slot between Message Details / | |
| Bookmarks / Filter / Statistic and the active one is persisted, so bring the | |
| Message Details tab forward if some other panel currently owns the slot. | |
| """ | |
| root = pane(app, "Message Details") | |
| if root is None: | |
| select_tab(app, "Message Details") | |
| root = pane(app, "Message Details") | |
| if root is None: | |
| root = app | |
| out = {} | |
| for e in alld(root, "Edit"): | |
| try: | |
| n = e.window_text() or "" | |
| except Exception: | |
| continue | |
| if n in _DETAIL_FIELDS and n not in out: | |
| try: | |
| out[n] = e.get_value() | |
| except Exception: | |
| out[n] = None | |
| return out | |
| # ── other panes ────────────────────────────────────────────────────────────── | |
| def bookmark_rows(app) -> list: | |
| """Rows of the Bookmarks pane grid: [{'Number': .., 'Message': ..}, ...]. | |
| Self-activating (the bottom dock shares one slot — see details_fields).""" | |
| root = pane(app, "Bookmarks") | |
| if root is None: | |
| select_tab(app, "Bookmarks") | |
| root = pane(app, "Bookmarks") | |
| if root is None: | |
| return [] | |
| rows: dict[int, dict] = {} | |
| for n, e in _cell_edits(root): | |
| col = n.split(" Row ")[0].strip() | |
| try: | |
| idx = int(n.split(" Row ")[1].split(",")[0].strip()) | |
| except Exception: | |
| continue | |
| try: | |
| rows.setdefault(idx, {})[col] = e.get_value() | |
| except Exception: | |
| rows.setdefault(idx, {})[col] = None | |
| return [rows[k] for k in sorted(rows)] | |
| def statistic_labels(app) -> list: | |
| """Percentage labels of the Statistic pie chart, e.g. ['20%','50%','30%']. | |
| Self-activating (the bottom dock shares one slot — see details_fields).""" | |
| if pane(app, "Statistic") is None: | |
| select_tab(app, "Statistic", pause=0.8) | |
| out = [] | |
| for e in alld(app, "Edit"): | |
| try: | |
| if (e.window_text() or "").startswith("Data Point Label"): | |
| out.append(e.get_value()) | |
| except Exception: | |
| continue | |
| return out | |
| def logger_tree_items(app) -> list: | |
| out = [] | |
| for t in alld(app, "TreeItem"): | |
| try: | |
| out.append(t.window_text() or "") | |
| except Exception: | |
| continue | |
| return out | |
| def logger_node(app, name: str): | |
| return named(app, "TreeItem", name) | |
| # ── script (Lua) tab ───────────────────────────────────────────────────────── | |
| def script_output(app) -> str: | |
| """Value of the Lua output box at the bottom of the Script tab.""" | |
| sp = pane(app, "Script") | |
| if sp is None: | |
| return "" | |
| for e in alld(sp, "Edit"): | |
| try: | |
| if not (e.window_text() or ""): | |
| return e.get_value() or "" | |
| except Exception: | |
| continue | |
| return "" | |
| def put_script(app, code: str) -> bool: | |
| """Replace the Scintilla editor content with ``code``. | |
| Uses the clipboard: Scintilla auto-closes brackets, so typing Lua source | |
| character-by-character corrupts it. The Script tab must already be open. | |
| """ | |
| sp = pane(app, "Script") | |
| if sp is None: | |
| return False | |
| r = sp.rectangle() | |
| click_at(r.left + min(240, (r.right - r.left) // 3), r.top + 120) | |
| time.sleep(0.4) | |
| set_clipboard(code) | |
| press("^a") | |
| time.sleep(0.2) | |
| press("^v") | |
| time.sleep(0.6) | |
| return True | |
| # ── checked state (toolbar buttons expose no TogglePattern) ────────────────── | |
| _STATE_CHECKED = 0x10 | |
| def is_checked(el): | |
| """CHECKED for toolbar toggle buttons via LegacyIAccessible state bit. | |
| Returns True/False, or None when the element exposes no state at all.""" | |
| if el is None: | |
| return None | |
| try: | |
| return bool(int(el.legacy_properties().get("State", 0)) & _STATE_CHECKED) | |
| except Exception: | |
| pass | |
| try: | |
| return el.get_toggle_state() == 1 | |
| except Exception: | |
| return None | |
| def toggle_state(el): | |
| """CHECKED for real CheckBox controls (TogglePattern): True/False/None.""" | |
| if el is None: | |
| return None | |
| try: | |
| return el.get_toggle_state() == 1 | |
| except Exception: | |
| return is_checked(el) | |
| def checkbox(root, name_startswith: str): | |
| for c in alld(root, "CheckBox"): | |
| try: | |
| if (c.window_text() or "").startswith(name_startswith): | |
| return c | |
| except Exception: | |
| continue | |
| return None | |
| def focused_name(app=None) -> str: | |
| """Name of the element that currently owns keyboard focus ('' if unknown).""" | |
| try: | |
| from pywinauto.uia_defines import IUIA | |
| el = IUIA().iuia.GetFocusedElement() | |
| if el is None: | |
| return "" | |
| return el.CurrentName or "" | |
| except Exception: | |
| return "" | |
| def has_focus(el) -> bool: | |
| try: | |
| return bool(el.has_keyboard_focus()) | |
| except Exception: | |
| return False | |
| # ── clipboard ──────────────────────────────────────────────────────────────── | |
| _CF_UNICODETEXT = 13 | |
| def set_clipboard(text: str) -> bool: | |
| try: | |
| u = ctypes.windll.user32 | |
| k = ctypes.windll.kernel32 | |
| k.GlobalAlloc.restype = ctypes.c_void_p | |
| k.GlobalLock.restype = ctypes.c_void_p | |
| k.GlobalLock.argtypes = [ctypes.c_void_p] | |
| k.GlobalUnlock.argtypes = [ctypes.c_void_p] | |
| u.SetClipboardData.argtypes = [ctypes.c_uint, ctypes.c_void_p] | |
| if not u.OpenClipboard(None): | |
| return False | |
| try: | |
| u.EmptyClipboard() | |
| data = text.encode("utf-16-le") + b"\x00\x00" | |
| h = k.GlobalAlloc(0x2042, len(data)) | |
| p = k.GlobalLock(h) | |
| ctypes.memmove(p, data, len(data)) | |
| k.GlobalUnlock(h) | |
| u.SetClipboardData(_CF_UNICODETEXT, h) | |
| finally: | |
| u.CloseClipboard() | |
| return True | |
| except Exception: | |
| return False | |
| def get_clipboard() -> str: | |
| try: | |
| u = ctypes.windll.user32 | |
| k = ctypes.windll.kernel32 | |
| k.GlobalLock.restype = ctypes.c_void_p | |
| k.GlobalLock.argtypes = [ctypes.c_void_p] | |
| k.GlobalUnlock.argtypes = [ctypes.c_void_p] | |
| u.GetClipboardData.restype = ctypes.c_void_p | |
| if not u.OpenClipboard(None): | |
| return "" | |
| try: | |
| h = u.GetClipboardData(_CF_UNICODETEXT) | |
| if not h: | |
| return "" | |
| p = k.GlobalLock(h) | |
| s = ctypes.wstring_at(p) | |
| k.GlobalUnlock(h) | |
| return s | |
| finally: | |
| u.CloseClipboard() | |
| except Exception: | |
| return "" | |
| # ── geometry (style / layout assertions) ───────────────────────────────────── | |
| def rect(el): | |
| """(left, top, right, bottom) or None.""" | |
| try: | |
| r = el.rectangle() | |
| return (r.left, r.top, r.right, r.bottom) | |
| except Exception: | |
| return None | |
| def size(el): | |
| r = rect(el) | |
| return None if r is None else (r[2] - r[0], r[3] - r[1]) | |
| def center(el): | |
| r = rect(el) | |
| return None if r is None else ((r[0] + r[2]) // 2, (r[1] + r[3]) // 2) | |
| def is_right_of(a, b) -> bool: | |
| ra, rb = rect(a), rect(b) | |
| return bool(ra and rb and ra[0] >= rb[2] - 2) | |
| def is_below(a, b) -> bool: | |
| ra, rb = rect(a), rect(b) | |
| return bool(ra and rb and ra[1] >= rb[3] - 2) | |
| def in_row(elements, tol: int = 6) -> bool: | |
| """True when all elements share a horizontal band (toolbar-style row).""" | |
| tops = [rect(e)[1] for e in elements if rect(e)] | |
| return bool(tops) and (max(tops) - min(tops)) <= tol | |