Testing and Cross-Platform QA
[[[appendices.testing]]]
Overview
[[[appendices.testing#overview]]]
Test-writing conventions (docstring format, etc.) live in [[appendices.code-conventions#testing]]; this page
is about how rehuco's tests and static checks are structured and run, and the cross-platform gotchas that
took real time to work through — most of them surfaced by the first full make qa run on
macOS (issue #15); several also gate the planned
cross-platform CI (#14).
The guiding model (stated in the repo-root conftest.py): each platform's test set runs on that
platform's own runner. A test that can't apply on the current OS is skipped, not failed; code
that can't execute on the current OS is excluded from coverage there and measured on the runner
where it does execute.
1. The QA gate
[[[appendices.testing#qa-gate]]]
make qa runs, in order: ruff format + ruff check --fix, then pytest with coverage
(make cov-parallel, which CI runs too, #545), bandit, pyright, pylint. The test stack is pytest plus
pytest-mock, pytest-qt, pytest-cov, pytest-benchmark, pytest-freezer, and pytest-explicit. Tests live
beside their packages under packages/*/tests (testpaths in pyproject.toml);
--strict-markers is on, so every marker must be declared.
2. Qt tests must run headless
[[[appendices.testing#headless-qt]]]
Symptom: running the Qt-touching tests (ApplicationSingleton, the agent app/viewer tests)
without an active window server — a CI runner, or macOS over SSH — segfaults (exit 139) during
QLocalServer/QLocalSocket teardown across tests. Each test passes in isolation; the crash is
an ordering/teardown interaction. The C stack shows libqcocoa / NSApplication run: Qt is
driving a real native event loop.
Fix: force Qt's headless platform. The repo-root conftest.py does, before any test module
builds a QApplication:
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
setdefault so a developer on a real desktop session can still QT_QPA_PLATFORM=cocoa pytest ...
to watch windows during GUI debugging. None of conftest's own imports pull in Qt, so setting it at
conftest import time is early enough.
Linux needs more than offscreen (surfaced by the cross-platform CI in #14; the fix above was only ever
exercised on macOS, where it sufficed). On the ubuntu-latest leg the same test_application_singleton.py
still segfaulted (exit 139) with offscreen set — this time the C stack ran through
QEventDispatcherGlib::processEvents → QCoreApplicationPrivate::sendPostedEvents into a
~QLocalServer → deleteChildren → ~QLocalSocket chain, i.e. a deferred deleteLater() firing
during teardown. Root cause: ApplicationSingleton.shutdown() disposes of its QLocalServer (and
the sockets it accepted) via deleteLater(), but qtbot.wait() runs a nested event loop, and
DeferredDelete events posted at a different loop level are not reliably reaped there. On Linux's
glib dispatcher they instead accumulate across tests and eventually crash when a server is destroyed
after one of its child sockets was already freed. (macOS's cocoa dispatcher happened to reap them in
an order that didn't crash, which is why offscreen alone looked sufficient there.)
Fix: the make_singleton fixture's teardown flushes the deferred deletions explicitly, so each
test disposes of its own Qt objects instead of leaving them for a later test's event loop:
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete.value)
qtbot.wait(10)
Every ApplicationSingleton this fixture builds is shutdown()- then-flushed, so no queued
deleteLater() crosses a test boundary. This is a test-harness concern only: a real app runs
app.exec() to completion, whose event loop (and the QApplication destructor on exit) reap
DeferredDelete continuously, so nothing accumulates.
3. Platform-conditional tests
[[[appendices.testing#platform-tests]]]
Two distinct mechanisms, for two distinct needs:
-
Per-test platform markers.
pyproject.tomldeclareswindows/macos/linuxmarkers; the repo-rootconftest.py'spytest_collection_modifyitemsskips any test whose marker doesn't match the runningsys.platform. Use this for a test that only makes sense on one OS but lives in a normally-importable module. -
Whole-file skip via
importorskip. A test file that imports a module absent on other platforms guards it at the top so the entire file is skipped where the import would fail:
winreg = pytest.importorskip("winreg") # module doesn't exist off Windows
(Subsequent imports then need # noqa: E402 / pylint: disable=wrong-import-position, since they
legitimately follow the guard.)
Simulating another platform in a cross-platform test. A test that asserts the non-Windows
code path can force it anywhere with monkeypatch.setattr("sys.platform", "linux"). But mocking a
Windows-only API from such a test is a trap: ctypes.windll doesn't exist off Windows, and
mocker.patch("ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID", create=True) # WRONG
raises AttributeError — create=True only creates the leaf attribute, but mock still
traverses ctypes.windll first. Patch the whole attribute instead (its parent ctypes exists, so
create=True can add it) and assert on the nested mock:
windll = mocker.patch("ctypes.windll", create=True)
...
windll.shell32.SetCurrentProcessExplicitAppUserModelID.assert_not_called()
This works identically on all platforms (on Windows windll already exists; create=True is then
a harmless no-op).
4. Static analysis across platforms
[[[appendices.testing#static-analysis]]]
win_registration.py uses Windows-only stdlib (winreg, ctypes.windll), which the linters flag
when qa runs on macOS/Linux:
-
pyright raised 14
reportAttributeAccessIssueerrors, because those symbols aresys.platform == "win32"-gated in typeshed. Fixed withpythonPlatform = "All"in[tool.pyright], which makes platform-gated stdlib resolvable regardless of host — the right setting for a project with per-platform modules. -
pylint raised
E0401(import-error) onwinreg. Fixed withignored-modules = ["winreg"]in[tool.pylint.typecheck]. A per-linedisable=import-errorcan't be used:useless-suppressionis enabled, so it would itself be flagged on Windows, where the import resolves fine. A module-level ignore is platform-safe.
4.1 pylint and pyright traps
[[[appendices.testing#lint-traps]]]
- A pragma goes stale when the code under it changes (#470, #404): delete it.
make pylinthidesuseless-suppression; check withuv run pylint --enable=useless-suppression <paths>. Messages can also flicker between identical runs (#343); a pragma for one of those namesuseless-suppressiontoo. pylint_qtreads anyobj.attr[i]as a subscripted signal in a module importing PySide (#376, #457, #485): bind to a local or unpack ((mime,) = call.args, nevercall.args[0].urls()). The same misreading makes item assignment on a dict attribute E1137 — build a local dict and rebind (#568, #505) — and a widget read out of one memberless, whichcastdoes not cure: read its state through a typed helper instead (#505).duplicate-codetrips on a contiguous re-export run, two identical tests (#413, #506) and a second copy of a ctypes binding — import the first (#505).- Pyright's PySide stubs lack some members:
QKeySequence.__getitem__,QObject.staticMetaObject,CDockAreaWidget.currentDockWidget(usedockWidget(currentIndex())). The QtAds stub is hand-kept: add a member the code or a test newly uses (#491:createAndSetupAutoHideContainer,AutoHideFeatureEnabled). - A module-level annotation's name can be undefined and the import still succeed (#459): only ruff and pyright catch it.
- Import what a test patches from where it is defined (#464). pylint cannot infer a mock's recorded argument
(
not-callable): call it in a helper with one reasoned pragma. Patching through the module under test (mocker.patch.object(job_module.CatalogCache, ...),job_module.time) fails pyright'sreportPrivateImportUsage(#682): patch the class where it lives, a standard-library module by its string target (mocker.patch("pkg.mod.time.sleep")). - A
Protocolmethod that returns a value has a docstring-only body under# pyright: ignore[reportReturnType](#682):...after the docstring is pylint'sunnecessary-ellipsis, andraise NotImplementedErroris a line coverage counts as missed. When the signature with its pragma passes 120 columns, a magic trailing comma keeps ruff from joining it, so the pragma sits on the short) -> …:line. - pylint refuses
baras a name (#392, #376), and a name-mangled call through another instance reads as unused (#400). - Astroid cannot type some values (#649):
E1101,E1102orW0632on aMock's recorded call, a signal blocker's or a dict of docks' value, a property read as its signal, an unpacked tuple, aQLabel.pixmap()read off a mangled attribute. Takenext(iter(...)), an index or an annotated local; else a per-line disable. - Pyright drops an
is not Nonenarrowing inside a nested function (#620): bind locals first. A test's**statesplat into a dataclass wantsdict[str, Any](#649).
5. Coverage of platform-specific code
[[[appendices.testing#platform-coverage]]]
Windows-only code can't run on a macOS/Linux qa pass, so it would count as missed: the whole
platforms/windows/ package, and __main__.py's two if sys.platform == "win32": branches. It
must be dropped from coverage there, but still measured on the Windows runner — and coverage
config can't branch by platform.
The wrong way (tried first): gate it with env vars (${COV_EXCLUDE_WIN-…} in exclude_also,
${COV_OMIT_WIN-…} in omit) set from the Makefile and conftest. This fails, because when
coverage reads its config depends on how pytest was launched:
make cov/make cov-parallel/ CI (plainpytest --cov): pytest-cov reads the coverage config before the root conftest runs — so a conftest-set var is too late; only a Makefile-exported one works.- The VSCode test runner invokes
pytest --cov=. --cov-branchdirectly (nomake), and reads config at yet another moment — so neither the Makefile env nor a timely conftest value is reliably present.
No single env-setting site covers all three runners.
The right way: a coverage configurer plugin (coverage_platform.py, registered via
[tool.coverage.run] plugins). Coverage calls it at its own initialization regardless of how
pytest was launched, so one mechanism covers make cov, a bare pytest --cov, and VSCode alike.
On non-Windows it appends */platforms/windows/* to run:omit and the if sys.platform ==
"win32": regex to report:exclude_lines; on Windows it does nothing, so that code is measured by
the Windows test set. Net effect on macOS/Linux: __main__.py goes 42% → 100% and
platforms/windows/ drops out of the report.
Two implementation notes worth keeping:
- Append to
report:exclude_lines, notreport:exclude_also. By the time the configurer runs, coverage has already foldedexclude_alsointoexclude_lines(the list actually matched against source); appending toexclude_alsothen has no effect. - The plugin module must be importable when coverage starts — very early, in pytest-cov's
pytest_load_initial_conftests.[tool.pytest.ini_options] pythonpath = ["."]puts the repo root onsys.pathin time; without it the plugin fails withModuleNotFoundError.
6. A build step that broke test collection
[[[appendices.testing#qualified-rc-imports]]]
Not a test issue per se, but it first showed up as one: pyside6-uic --python-paths expects the
OS-native path separator (; on Windows, : elsewhere). The Makefile hardcoded ;, so on
macOS/Linux uic couldn't resolve a .ui's .qrc to its package and emitted a bare, unimportable
import main_rc — and every rehuco-agent test then errored at collection right after
make uis (ModuleNotFoundError: No module named 'main_rc'). Fixed by deriving the separator from
$(OS). The lesson: a green pytest depends on make uis having generated correct, importable
_ui.py/_rc.py first (both are gitignored and rebuilt, never hand-edited).
7. Reading a QA run
[[[appendices.testing#reading-a-run]]]
- A green summary line is not a green check (#402).
make qastops at the first red step, pylint prints10.00/10even when failing, and anechoafter a backgroundmakereports the wrong code. Runmake qa > log; echo $?from the repo root, then grep the log for: [CRWE]NNNN:,^FAILED,error:andError N.make pyright's summary goes to stderr: read*>&1in PowerShell. - Run
makefrom Git Bash on Windows (#343): PowerShell breaksuname, somake uissilently does nothing. - A hung
makeor pytest keeps running after it is stopped (#459). Find itsuv/pytest/pythonchildren by command line (Get-CimInstance Win32_Process) and stop only those; nevertaskkill /IM python.exe(#102), and nevergit stashacross such a run. A clean second worktree, detached at master, runs master's suite beside a branch. Match onName -eq 'python.exe'as well as the command line: the shell running the query carries the same words in its own, and stopping it stops whatever was to run next — the step restoring a file a break script had changed (#522). - A test's own thread is a daemon (#522):
threading.Thread(daemon=True, …). One left waiting on an answer that never comes keeps pytest alive after the test has failed, so the run hangs instead of reporting it. - A silent parallel run at 0 CPU may be a deadlock (#529):
uvx py-spy dump --pid N --native, thentaskkill /T /F. Repo-wide pylint is silent for minutes, and runs from the repo root (#498). An xdist "node down":-p no:xdist --timeout=20(#512). - A parallel
covfailure is rarely the newest diff. Re-run on master, reproduce deterministically, and fix a race with a gate job occupying the worker ([[appendices.testing#races]]), never a longer wait. ruff checkfirst (#613, #577): the gate stops at its first red step.make qaruns past ten minutes, so run it in the background and wait on its log forrated at(pylint's last line) orError [0-9](#638); Git Bash has nopgrep. Two runs at once void each other's coverage (#319).- Run the gate from a
C:\working directory (#647): from VS Code's lowercasec:\, fourtest_app.pytest_run_*tests fail. PowerShell's*>writes the log as UTF-16, where agrepforrated atfinds nothing; its2>&1makes a clean run exit 1 on pytest-benchmark's stderr warning, so the log decides (#674).
8. Probing the real app
[[[appendices.testing#probing]]]
- Probe a stated premise before building on it (#393, #345, #373, #407, #454, #457, #485): ten lines on a scratch
tree. Every one of these turned out false: "a sub-dock can float", "
Nonevs0separates unmeasured from empty", "QLabel.pixmap()drops the device-pixel ratio" (it follows the label's). Query the real cache read-only before trusting a total. - Headless, a bare
MainWindow()writes the real config on teardown (#400, #461, #491). Before any app import, callset_settings_dir(scratch)(#494; it moves the.ini,config_folder()andcache_folder()intoscratch). Copy the user's config files in, runApplication(argv).show_main_window(), and end withos._exit(0)so nothing saves back. A realRootsPanel(#457) needsRootCatalog(queue, resource_events=events),RehuDocument.newrecords and a poll onqueue.jobs(). A bare-QtAds probe needs the auto-hide flags ([[appendices.qt-ads#auto-hide-flags]]). - Launch a development build with
--settings-dir(#494), from therehuco-agent (local settings)configuration (.local_settings). Without it a second launch forwards to whichever agent is already running and exits ([[nodes#single-instance]], #460), so the window on screen can be another checkout's: "primary already running … forwarded argv" in the run log says so, and each run'sargvthere says which build it was. - A flash is invisible to the suite (#306): probe with a watchdog thread that writes its findings and calls
os._exit. A probe that hangs takes the same watchdog printing the step it is stuck in, run unbuffered (-u, #505). - Measure before guessing (#455, #500, #498, #546): the GUI half of a speed-up (a 10 ms
QTimerheartbeat),gc.get_objects(), a per-directorystaton the share (+32 %), a Windows file fact (aFILE_SHARE_DELETEreader still blocks a replace). A machine-dependent test asks the system's own list (#501:GetLogicalDrives,HKCU\Network). - What the screen and the speakers got (#574):
uv run --with dxcamreads every composed frame (output_color="BGRA"; its RGB path wants OpenCV), but Windows will not raise a background process's window, so check the captured reference level before trusting a run. A static clip (smptehdbars) makes a frame-to-frame pixel difference mean something.soundcardloopback records what reaches the speakers, in a process of its own: with python-vlc in the same one it segfaults. - A bug the tests do not show, drive the real window (#514): a scratchpad script outside pytest (the suite's
conftest mocks
Path.stat) buildsMainWindowover temporary settings folders,toggleView(True)on the dock,QTestclicks, andpanel.grab().save(...)for the owner to see. A new dialog gets a scratchpad demo before it is wired (#416, #498). - Probe recipes: a restart is
set_settings_dir(<scratch>)before any app import, one process to quit and another to check (#576); a catalog goes throughRootCatalogalone, its cache byCatalogCache.open(rehudb_path(cache_folder(), id))(#577); a player is found byQApplication.allWidgets(), and maximized its stage has left the view (#613). Close a probe window byWM_CLOSE; never kill VLC or the agent by name. A native surface needs a screen grab; offscreen draws no video. - A crash from a real session (#630): copy its records and
document-session.jsoninto a scratch folder, repoint the paths and drop the catalog; aQObjectevent filter on the application names the event a change happened in. Is a crash new? Run master from a detached worktree over a copy of.local_settingsand repeat the clicks (#631). - Check what is shown: a label against real data (#592); a drawn thing rendered and looked at, at
QT_SCALE_FACTOR=1.25too, and on a dark theme (an authored SVG is#1f1f1f: recolor it, #649); a new bar widget interactive like its neighbors (#618); a picture's frame read off the picture, not the log (testsrc2's burned-in time, #613); a load probed with saved progress, not at 0; a patched binary read back whole (#628). - A theory is measured before it is built on (#574), in the app's own setup (#618); three fixes on one symptom
mean stop and measure. A mocked
Cataloghid thatrecord_pathsskips a root's own folder: run a new cache lookup once against a copy of a real.rehudb(#645). Both watch backends report a rename out of the root as a delete (#645). A layout question is settled by an offscreen probe of each variant's geometry (#649: a width-capped widget in aQHBoxLayoutis centered in its share; a heavy stretch on it plus a trailing spacer left-aligns it). - Where a run went:
.local_settings\rehuco-agent.logfor a VS Code run,%LOCALAPPDATA%\rehuco\otherwise. Every run logsstartingandexited with code; Windows' Application log (ids 1000–1002) holds crashes and hangs.
9. Races and background work
[[[appendices.testing#races]]]
- A state a fast background job passes through is held with a gate (#484): patch the job's reader to
release.wait(), assert the intermediate state, then set the event (also at teardown). Without the gate the test passes by timing alone. - A stale-answer guard runs on the GUI thread, not the worker (#470): emit
(serial, result)and judge it in a slot; prove it withQThreadPool.waitForDone()between the answer and the switch. TaskQueue.wait_until_idleis true before a just-enqueued job starts (#457): poll the job's state.- A server that never answers is a real listener with a full queue (#482):
listen(0), thencreate_connection(timeout=0.05)until one raisesTimeoutError(assert that, not justOSError); proven on Windows and Linux. - A fake clock replaces the module's own
timename (mocker.patch("pkg.mod.time", SimpleNamespace(monotonic=clock))), nevertime.monotonic, which Qt and pytest-qt read. - An unclosed SQLite connection warns under whichever test the GC runs in (#372). A shared-cache memory database
takes table locks WAL never does: "table is locked" in parallel runs only (
PRAGMA read_uncommitted, #377). - A worker crash with no assertion is often a
QThreaddestroyed while running (3324cf1): reproduce it with a worker that lingers aftersuper().run(). - A native crash in pytest-qt's
_process_eventsis an earlier test's deferred work (#102): run the file 8–12 times, narrow it with targetedsendPostedEvents(obj, DeferredDelete), and fix the source. - Reading a native crash (#491, #529):
primary.runhas faulthandler's stacks,crashdumps\the minidump (uvx --with pefile --from minidump);0xc0000374is page heap (GlobalFlag=0x02000000,PageHeapFlags=3, IFEOrehuco-agent-dev.exe). cdb on pytest: the base interpreter, a script adding the venv'ssite-packages,-cfwithsxe -c "kn 40; q" av. - Two processes in a test act in an order the test fixes (#547): a
spawnworker pauses on flag files; the test sees its own side reach a point (a patchedtime.sleep= the lock's back-off) before releasing it, and releases it in afinallyso a failure reports at once. Never two workers raced from one start instant. A child's pid is the launcher's (#505): a venv's or uv'spython.exestarts the real interpreter, so a child printsos.getpid()itself. - Stale connections are countable (#380):
obj.receivers("2" + signature)around a build and teardown, plussendPostedEvents(None, DeferredDelete). - Gating a lightbox decode (#479): gate
ArchiveImageSource.loadonly whenmax_height is not None(the main image loads on the GUI thread); clearQPixmapCacheper test; monkeypatchroots_lightbox.ThumbnailLoader. - A test handing answers out in call order races a pool of two threads (#573): wait for the held answer to have
started, and prove it by forcing the bad order in a throwaway test. A partial branch only some test order reaches is
covered directly (#618). A race may not show outside the running app (#613). A parametrize id printing a set differs
between xdist workers (hash seed): sort it (#647). A test posting through
PoolRelaytakesqapp: new test files reshuffle the workers and expose one leaning on a neighbor's (#634). - A hang is read with stacks, before anyone ends it:
uv run --with py-spy py-spy dump --pid <pid> [--locals], thencdb -p <pid> -pvr -c "~*k 30; qd"(C:\Program Files\Windows Kits\10\Debuggers\x64):QBasicMutex::lockInternalon one side,PyGILState_Ensureon another. A worker's collection freeing a liveQObjectdeadlocks ([[appendices.testing#cycle-diagnostic]]);gc.DEBUG_SAVEALLandgc.callbacksin a plugin name the objects. A stall is not a deadlock; the mechanisms found so far are in [[appendices.qt#proving]]. - A crash with no Python frame (#631): faulthandler writes into
.local_settings\primary.run; the native stack comes fromcdb -hd -o -G -c "sxn ibp; sxd eh; sxe -c \"~.kn 50; q\" av; g" <venv python> <probe>with Windows paths. Without-hdthe debug heap hid the use-after-free in every run. Retry a crash's variants until one is deterministic (6 of 8, then 6 of 6 with the next document already read).shiboken6.dumpon 6.11.1 faults beside an invalid wrapper, not on a freed one (#657).
10. Driving Qt offscreen
[[[appendices.testing#offscreen-qt]]]
- Synthetic input goes to the widget under the point (#485):
viewer.childAt(p) or viewer, mapped withmapFrom, then moves to the widget that took the press. Sending straight to a container skips its children's hit-testing, so a test of "the band takes the press" passes vacuously. qtbot.mouseMovecan be dropped under load (#321, #378, #462, #457):QApplication.sendEventaQMouseEvent. Text can draw no ink once an icon font has loaded: assert ondrawTextcalls through aQPaintersubclass (keep theQImage).QIcon.paintnever reaches a PythondrawPixmap: read pixels. Skip ink-dependent tests where text draws nothing (#465).- Text does not scale linearly (#462): enlarge until the part overflows, and assert that.
- Key presses (#344, #345): a
MainWindowtest window never activates, so assert onshortcuts(); a bare hostQMainWindowthat is shown, activated and waited on takes a realApplicationShortcutpress. - A PySide signal is cached on the instance after first access (#462): patch the instance, not the class. Make
emitraiseRuntimeErrorrather thanshiboken6.deletea widget. An unshown widget gets noresizeEvent. startDragDistance()is 0 without an application (#395): takeqtbot.- A disabled
QAction.trigger()does nothing, and the settings dialog refreshes enablement on a timer (#457): call__refresh_dirty_uibetween staging and triggering. - An empty-area menu is testable offscreen (#469): show, resize,
waitExposed, pick a point below a column'sviewport(), and patch the module'sQMenuwith a recordingexec. - A modal question lives behind a public method of its owner (#344), which the fixture replaces per instance.
- A Scintilla autocomplete popup on a shown editor corrupts the heap offscreen (#343):
autoCCancel()first, and useQWidget.setFocus(editor). - A test's shown window must be held (#491): a window built in a helper and dropped dies with its wrapper, taking
its dock managers along ("already deleted" at the first call); a generator fixture yields while holding it, since
qtbot.addWidgetkeeps only a weak reference (#574). A.show()withoutqtbot.addWidgetleaks a window (#383). - A press gives the focus in the window, not in
notify(Qt 6, #574):QApplication.sendEventof a press to a widget moves no focus, whileqtbot.mousePressgoes through the window and does. A test of a visibility trigger shows its window (#574): the tests of a document restored after the window was up never did, so a background tab read at start, when QtAds shows each tab it adds into a visible window, went unseen. - A mock widget handed to a
MainWindowis saved and closed at teardown (#464): setdirty = Falseandsave_state.return_value = b"", or the real modal pops orQByteArrayfails. - A test that loads a model in place keeps every tab and the form alive (#470): build all tabs, and hang the form
on the returned surface (
all_editors). - The clipboard is the shared
clipboardfixture inconftest.py, which restores what the developer had in afinally(#485). AQDragis replaced and the staged name asserted through a realImageExporter, never aMock(spec=…). - Drags in tests (#387, #461, #485): send
DragEnterbeforeDropand keep theQMimeDataalive; only events towindow.windowHandle()exercise parent routing. A syntheticDragMoveafter an ignored enter never reaches any event filter (dropped inQApplication.notify, the application's included): hand it to the installed filter'seventFilterdirectly.
11. The suite's own fixtures and patches
[[[appendices.testing#suite-fixtures]]]
- A real folder is pytest's
tmp_path, nothing hand-rolled (#475); never mockPath.mkdir. A/fake/…path is a realC:\fakeon Windows, and aC:/xliteral is absolute only there — a key needs an absolute path, so root a fake one atPath(Path.cwd().anchor)(#414's tests passed on Windows and failed on macOS and Linux). - What is tested elsewhere is mocked here (#545): a class's own tests prove it; every other test assumes it works,
and a break gets a test of that class. The Root Catalog docks tests run
RootCatalogover aMock(spec=Catalog)(catalog) and patchCatalogCache.openwith aMagicMock(cache) for the jobs and notifiers;cached_rowsis what both answer from, as far as their contracts say (hold), and no agent test opens SQLite. The window tests buildMainWindowover stub settings pages and every document they open over stub sub-docks, the Documents dock's tests their documents over the same stub (stub_settings_pages,stub_sub_docks, module-wide); a test of the real ones asks forreal_settings_pagesorreal_sub_docks. Only a class's own tests, and core's contract tests (test_catalog_snapshot), run the real cache. - The agent suite's
Path.statanswers a missing file with aMock(#458):touch()first, or usereal_path_stat(#395). The session's settings, data and cache folders are temporary (isolate_app_folders, #412). - The
servedfixture patchesPath.read_textfor every file (#469): re-patch it to serve.rehucoonly (REAL_READ_TEXT). A checksum record is{"version": 1, "files": [{name, xxh3, verified, status}]}. - The suite swaps
persistent_settingsin its own module for an in-memory fake (#494): a test of the real override patches the real function back;reset_settings_dir(autouse) clears the override. Native window titles can be read withGetWindowTextW; a top-level title lacking the application display name gets it appended. mocker.patch.object(instance, "method")misses a collaborator built with the bound method (#456): hand it the object.- Fixtures are imported by name from a sibling module (
test_catalog_docks'fixture_catalog/served/saves, a card list's page; #487, #493) and keep their name (@fixture(name=…), asfixture_dock). Past the size cap a test module splits the same way ([[appendices.code-conventions#python]]). - Test helpers' id counters start far above explicit ids (#379). Never build expected text from the checkout's path (#398): a never-shown menu elides it.
- A platform branch is a module constant so a test can flip it (#402).
- A "defaults when nothing was saved" test seeds the instance first (#483): loading into a fresh object whose
defaults are already empty passes whatever
load()does. Prove such a test by makingload()a barereturn. - Test each half of a split toggle against the other (#408).
- Assert a query plan one clause at a time (#454):
set_trace_callback+EXPLAIN QUERY PLAN, noSCAN r. AnORuses an index only when every term is on the table's indexed columns; prove the test by restoring the old clause. - A coverage gap in an untouched file is real (#462, #344, #457): reach a defensive branch with a test, or delete a
guard no caller can reach. An
elifloop that can skip is a partial branch: filter in a comprehension. - A bad zip by patching bytes (#480, #484):
writestr(ZipInfo)resetsflag_bits, so set it in the central directory entry afterward (PK\x01\x02+ 8 is the flag byte; encrypted is bit 0); swap a UTF-8 name's bytes for invalid ones of the same length; blank thePK\x01\x02signature to leave the end record intact over a corrupt directory. Both packages keep a copy ofcrafted_zips.py. make check-slugsreads[[x.y]]in test code (#485):== [[widget.action]], a list of lists, trips it.- No
clock=/sleep=seams only tests pass (#546): patchtime.time/time.sleep. One helper per mechanism — grep first (borco_core.retry_refused,shared_read_open); time-dependent data per test, not at import. - A class patched in its own module is
self.Nested(#512); a module overrides an autouse fixture by defining one of its name (#564). - Real links come from
tests/rehuco_core_tests/real_links.py;FakeDirEntrytakesjunction=/link=. - A record's save also reads and writes its
.rehusersidecars (#513): a mockedPath.read_textanswers per path, and an agent test that saves for real takesreal_path_stat. - Coverage globs:
*stops at/, use**; check one withcoverage.files.globs_to_regex(#508). - Parallel
--covruns need aCOVERAGE_FILEeach (#414), and one per agent working at once. - Fakes follow the real thing: a signal added to
DocumentSubDocksgoes onsub_docks_stub.py(#580, #576); one added toRehuDocumentModelbreaks autospecced fakes that connect to it (#573); a second external tool breaks tests assuming one (#318); a shared descriptor's tests use an instance of their own (#319); a fake library answers what the real one does (#618); aCatalogmethod or parameter goes ontest_catalog_docks.py'sholdandmock_catalog(#577); a newPathcall in the renamer needs its mock intest_rehu_rename.py(#629); a patched job class cannot be enqueued:wraps=the real one. conftest.pyis near its size cap: a new fixture goes in a sibling module imported by name (tool_isolation.py,root_layout_templates_isolation.py, #620, #637). A callable handed over at construction misses a test's later patch: defer the lookup with a lambda (#579).- Roots tests (#638): one whose edit commits takes the
savesfixture, or the unsaved warning'sQMessageBoxblocks the run; an editor's.modelis aQAbstractItemModelto pyright, so narrow it byisinstance; a reader split off a shared helper leaves the other's failure branches untested. A cache schema step breaks old-version tests that reconcile before it: they write the version-1 root columns throughMemoryDatabase.insert_roots(#577). - A widget a row used to be leaves tests reading its private attributes (#649:
ElidedLabel, now insideMarkedLabel): grep_Class__attrfirst. - A dock test builds its model already read; the app opens a placeholder first (#316): test what is keyed on the
record's type through
create_pending→load_pending, and check the running app (#576). A shown dock gets no toggle when a record loads: react toreloaded(#317). - Paths across platforms: a posix check does not guard a Windows join (
..\xhas no..in itsPurePosixPathparts, #576).Path ==folds case on Windows: compare spellings withstr()(#629). A test passing only where the disk folds case is caught by CI's macOS and Ubuntu legs. A local-time test gives the code a zone and expects a literal: expectingastimezone()'s own answer passes on a UTC runner with the conversion gone (#623). - A fresh worktree needs
make uis qrcsbefore its tests import (#529).
13. Proving a test
[[[appendices.testing#proving]]]
A test is proven by watching it fail on the break it guards ([[appendices.code-conventions#testing]] has its format).
- Each new test goes red on its break, the file restored from a copy afterward (#500, #512, #546, #547). Many at
once by a script over a list of breaks (#564): a break nothing catches is dead code or a missing test (#505: a
redundant
rstrip). - A flake's cause is found with a scratch
-pplugin (#511, #545), then made red every run by holding the step it races (#565, [[appendices.testing#races]]). A crash is bisected by a scratch module parametrized on the steps run (#529). - Agents proving in parallel see each other's breaks for a second: rerun the whole gate after (#497).
pytest-randomlyis not installed:uv run --with pytest-randomly.
12. Finding what only the cyclic collector frees
[[[appendices.testing#cycle-diagnostic]]]
A Python-owned QObject whose wrapper sits in a reference cycle is destroyed whenever the cyclic collector next runs,
on whichever thread allocated — a pool thread included, where ~QObject takes a signal-slot mutex and then waits for
the GIL the GUI thread may hold (#529). qtbot does not prevent it: its teardown closes and deleteLater()s only the
widgets registered with addWidget.
To list what each test leaves for the collector, run the suites with this throwaway plugin. It switches automatic
collection off for the whole run, so nothing is collected on a pool thread, and after each test's teardown runs one
collection on the main thread with DEBUG_SAVEALL: everything found is kept alive (no PySide finalizer runs, so the
segfault a blanket gc.collect() once caused cannot happen) and recorded against that test, one JSON line per test
with garbage, a file per xdist worker.
"""Throwaway pytest plugin: which tests leave Qt wrappers that only the cyclic collector would free (#529)."""
import gc
import json
import os
from collections import Counter
from pathlib import Path
import pytest
from shiboken6 import Shiboken
OUT = Path(os.environ["GC_CYCLES_OUT"])
KEEP: list[object] = []
def _write(entry: dict) -> None:
with (OUT / f"cycles-{os.getpid()}.jsonl").open("a", encoding="utf-8") as stream:
stream.write(json.dumps(entry) + "\n")
def _type_name(obj: object) -> str:
kind = type(obj)
return f"{kind.__module__}.{kind.__qualname__}"
def _live_and_python_owned(obj: object) -> bool:
try:
return Shiboken.isValid(obj) and Shiboken.ownedByPython(obj)
except TypeError: # a mock with a Qt spec passes the isinstance check
return False
def _collect(nodeid: str) -> None:
gc.disable()
gc.collect()
garbage = list(gc.garbage)
gc.garbage.clear()
KEEP.extend(garbage) # never destroyed: no finalizer runs
wrappers = [obj for obj in garbage if isinstance(obj, Shiboken.Object)]
if wrappers:
others = Counter(_type_name(obj) for obj in garbage if not isinstance(obj, Shiboken.Object))
_write(
{
"test": nodeid,
"wrappers": dict(Counter(_type_name(obj) for obj in wrappers)),
# only these run a C++ destructor when collected
"live_owned": dict(Counter(_type_name(obj) for obj in wrappers if _live_and_python_owned(obj))),
"others": dict(others.most_common(8)),
}
)
def pytest_sessionstart(session: pytest.Session) -> None:
del session
OUT.mkdir(parents=True, exist_ok=True)
gc.disable()
gc.set_debug(gc.DEBUG_SAVEALL)
_collect("<session start>")
def pytest_runtest_setup(item: pytest.Item) -> None:
del item
gc.disable() # a test may have switched it back on
@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_runtest_teardown(item: pytest.Item, nextitem: pytest.Item | None):
del nextitem
yield
_collect(item.nodeid)
Save it as gc_cycles.py in a scratch folder (never in the repo), then from the repo root, in Git Bash:
GC_CYCLES_OUT=<scratch>/out PYTHONPATH=<scratch> uv run pytest packages/rehuco-agent/tests \
packages/borco-pyside/tests -n auto -p gc_cycles -p no:cacheprovider -q --timeout=600
About 16 minutes on the development machine; memory grows, since nothing found is ever freed. Reading the output:
live_ownedis what matters: a wrapper whose C++ object is still alive and owned by Python. The rest are empty shells or children their parent owns, harmless to collect.- Of those, only
QObjectsubclasses take a signal-slot mutex when destroyed. Value types (QPersistentModelIndex,QPixmap,QColor,QKeySequence,QRect) cannot deadlock this way. - Fix at the source, plainly: a
QObjectthe app builds gets a parent (usuallyself); a fixture gives what it builds a parent the test tears down, or deletes it explicitly (deleteLater(), thenQCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete.value), asmake_actiondoes). A test hands what it builds bare to thedelete_at_teardownfixture (the repository conftest). Re-run until noQObjectwith connections is left underlive_owned. - Left on purpose (#529): a
QObjectwith no signal connections — a mockedQDrag's recordedQMimeData, aQBuffer, aQCheckBox— whose~QObjectnever takes a signal-slot mutex; and pytest-qt's ownQEventLoop, built insidewaitSignal, which is a third party's.