Repository navigation
Testing
Checked against v0.7.6 on November 13, 2026.
Kestrel's tests run offline, against a fresh database, with fake model replies. Nothing in the suite calls a live job board, an applicant tracking system, an SEC endpoint or a language model. This page covers how the tests are laid out, how fixtures and fakes work, the guard tests that protect the shipped config, packaging and outbound calls, the order of the gates a change passes, and how to run the checks before you push. For commit and pull request rules, see Contributing.
The rules come from CLAUDE.md: tests are written alongside the code, never after, and "never call a live job board, ATS, or SEC endpoint from a test."
The suite is flat. tests/ holds 474 test_*.py modules with about 6,700 test functions, plus a few helpers:
| File | Purpose |
|---|---|
tests/conftest.py |
Autouse isolation fixtures and the sm database fixture. |
tests/pipeline_fakes.py |
FakeLLM, a canned stand-in for the model client in pipeline tests. |
tests/learning_fakes.py |
Synthetic label sets with a known relationship to the features, for calibration and reranker tests. |
tests/trigger_fakes.py |
Fakes for consulting trigger classification. |
tests/browser.py |
Shared browser launch for tests that need a real Chromium, and the page leak test (see Browser tests). |
tests/*_seed.py |
Fictional rows written straight into a test's throwaway database for one screen: apps_seed.py, offers_seed.py, prep_seed.py, profile_seed.py, retry_seed.py, role_seed.py, runs_seed.py, tailor_seed.py, today_seed.py and model_check_seed.py. Each states in its docstring which screen it serves and that it touches no network or model. |
tests/throwaway.py |
The mark that says a data folder is a throwaway one. The isolation fixture writes it into every per-test data home, and a seed that deletes data (retry_seed.py) refuses a folder without it. |
tests/js/ |
scene_smoke.js, a Node script that loads the scene art files the way the browser does and draws every scene (tests/test_ui_components.py runs it, and skips when node is missing). |
tests/fixtures/ |
Captured payloads and sample files. |
Modules are named for the feature they cover: test_queue.py, test_greenhouse_adapter.py, test_pipeline_scoring.py, test_backup_restore.py. A handful are named for the review round that found the bugs (test_review_fixes.py, test_release_round_review.py, test_initial_testing_fixes.py). Those collect regression tests, and the docstring in each says which finding a test pins.
pyproject.toml sets testpaths = ["tests"] and asyncio_mode = "auto", so an async def test_... runs without a decorator. It also turns PytestUnhandledThreadExceptionWarning into an error. A database worker thread calling into a closed event loop means a connection leaked, and the suite fails the test rather than let CI annotate it.
tests/conftest.py runs several autouse fixtures for every test, so no test needs to remember to be careful:
-
A private data home.
KESTREL_DATA_HOMEpoints at a new temporary folder per test, marked as a throwaway (tests/throwaway.py). The per-test scope matters on Windows: a leaked database handle in one test used to block another test from deleting a shared file. - NullPool for the database engine. Production uses one event loop for the life of the process. Tests start many short loops, and a pooled aiosqlite connection that outlives its loop breaks the next test. See Database schema.
-
No provider keys from the host. Hosted-provider key variables are removed from the environment, and the
.envkey store is cleared, so a developer's real key cannot change what a page renders. -
A loopback test client. The app validates the
Hostheader and treats non-loopback peers as unauthenticated.TestClientis patched to present itself as127.0.0.1. The comment inconftest.pycalls this a harness fix, not a relaxed assertion: tests of the guards pass an explicit host orclient=and still override it. -
Free ports, never the ladder. The app's own server prefers the ports 8765 to 8774 (
PORT_LADDERinkestrel/web/serve.py) so the browser extension can find it. A test that needs a server callsbind_free_port(ladder=False), which goes straight to an ephemeral port, so concurrent test servers never contend for a rung and a Kestrel running on the developer's machine is never in the way. The one test that checks the ladder behavior reserves a synthetic ladder of its own. - No first-run redirect, reset status caches, worker unpaused. Each undoes process-global state a test might have changed.
Most database tests take sm, an async sessionmaker over a new SQLite file in tmp_path:
async def test_enqueue_and_lease(sm):
q = TaskQueue(sm)
tid = await q.enqueue("t1", {"x": 1}, priority=5)
task = await q.lease("w1")
assert task is not None and task.id == tid
assert task.status == "leased" and task.attempts == 1The fixture builds the database by running the real Alembic chain (migrate.run_migrations) and opens it with make_async_engine, so the connection has WAL and the five second busy timeout like production. Every database test therefore exercises the migrations too.
HTTP is mocked at the transport. 75 test files import respx, and a couple use httpx.MockTransport. respx.mock raises when a request matches no registered route, so a test that accidentally reaches for the network fails instead of passing quietly. Nothing blocks sockets globally; the protection is that tests are written with mocks and reviewed for it.
An adapter test looks like this:
import json
from pathlib import Path
import respx
from httpx import Response
from kestrel.config import get_settings
from kestrel.ingest.adapters.greenhouse import GreenhouseAdapter
from kestrel.ingest.http import HttpClient
_FIXTURE = json.loads((Path(__file__).parent / "fixtures" / "greenhouse.json").read_text())
@respx.mock
async def test_adapter_maps_fields():
respx.get("https://boards-api.greenhouse.io/v1/boards/acme/jobs").mock(
return_value=Response(200, json=_FIXTURE)
)
s = get_settings().ingest
async with HttpClient(user_agent=s.user_agent, respect_robots=False) as client:
postings = await GreenhouseAdapter().fetch({"token": "acme"}, client)
assert len(postings) == 2tests/fixtures/ holds the response shapes the adapters parse: greenhouse.json, lever.json, ashby.json, smartrecruiters_list.json, smartrecruiters_detail.json, workday_list.json, workday_detail.json, and a model-list response for the hosted provider (openrouter_models.json). CLAUDE.md says they are captured from real payloads with identifying data replaced. That is what keeps the field-mapping tests honest. The ATS shapes have quirks that a hand-written fixture would miss, such as Lever's title field being text, Greenhouse's location being an object and its content being HTML-escaped HTML, and Workday's job list being a POST. The adapter tests assert exactly those. SPEC.md Appendix A records the verified shapes.
When you add a fixture:
- Capture one real response and trim it to a few postings.
- Replace company names, people, URLs and ids with fictional ones such as Acme Robotics and
example.com. - Keep every field the real payload has, including the awkward ones. Do not tidy the shape.
- Mock the URL with
respxand assert on the quirks.
Other fixtures: tests/fixtures/docs/ has sample .docx, .md and .pdf files for the resume importer, tests/fixtures/release/ has a changelog, checksums and signing file for the feed builder, and tests/fixtures/updates/ has valid, malformed and wrong-schema latest.json files.
Pipeline tests use FakeLLM from tests/pipeline_fakes.py. It has the same .settings and .complete() shape as LLMClient, reads a marker such as [KILL] or [QUAR1] out of the prompt, and returns a canned reply. Fixture opportunities carry the marker in their text, so a test steers each one down a specific path:
| Marker | Path it exercises |
|---|---|
KILL |
Tier 1 rejects the role. |
LOWCONF |
Tier 1 answers with low confidence, so the role is kept. |
QUAR1, QUAR2
|
Invalid JSON, so the call is quarantined and promoted (Tier 1) or recorded (Tier 2). |
BLOCK, SUSPECT, DIVERGE, REJECT
|
A Tier 2 blocker, a legitimacy concern, a gap between holistic and weighted scores, or a reject verdict. |
The gate test tests/test_pipeline_integration.py pushes 30 fixture opportunities per track through Tiers 0, 1 and 2 this way and asserts stage transitions, rule attribution, weighted scores and quarantine handling. The fake also provides a deterministic embed() derived from a hash of the text, so cosine comparisons are stable.
For the client itself, tests/test_llm_client.py mocks the local chat and embeddings endpoints with respx, and tests/test_llm_loop_guard.py and tests/test_llm_loop_repair.py exercise the repair and loop-guard logic against scripted replies.
What this suite does not do is measure model quality. That is the benchmark harness's job (kestrel bench, with gold sets in evals/), which needs a real model and is not part of pytest. tests/test_bench_guard.py checks the harness's presentation rules offline.
These tests each stop a specific mistake from shipping:
| Test | Guards against |
|---|---|
tests/test_filters_load.py |
A Tier 0 rule that the expression engine cannot evaluate. The AST guard in kestrel/rules/helpers.py rejects a generator expression, so one in filters.yml would make the shipped config fail on a user's first run. |
tests/test_db_schema.py |
A missing table or index, and a connection without WAL, the busy timeout or foreign keys. |
tests/test_prompts.py, tests/test_prompt_budgets.py
|
A prompt that does not load, or one that no longer fits its tier's context window with room for output. |
tests/test_outbound_inventory.py |
A web address in the shipped code that docs/OUTBOUND-CALLS.md does not list, or a listed host the code no longer has. See The outbound guard. |
tests/test_about_sources.py |
A source kind that is registered but missing from the catalog or docs/SOURCES.md, a description left for a kind that is gone, and an example config the Sources page's own validator would refuse. |
tests/test_static_cache.py |
A template that links a static file without its build version (?v=), versioned files not served as immutable, and an offline cache not named for the build. |
tests/test_page_lifecycle_g1.py |
For About, Analytics, Help, Calibrate, Models and Model check: a page that does not name itself, loads its script before the shared UI script, or whose script calls addEventListener, a timer, an observer or history methods directly instead of through the page lifecycle. It reads the rendered pages and the scripts as text, so it needs no browser. The live leak test is in each page's *_browser.py file. See Adding a page. |
tests/test_packaging.py, tests/test_notices.py
|
A broken spec, installer script, workflow or license notice. See Packaging and releases. |
tests/test_test_hygiene.py |
A test module that reads the clock at import time (the value freezes at collection and goes stale after midnight), and a test that seeds a row at "now minus a few minutes" outside tests/clock_seed.py, which fails for the first minutes of every day or month. |
tests/test_clock_boundaries.py |
Opt-in with KESTREL_BOUNDARY=1, which the full check sets and --quick, --fast and CI leave off. Re-runs the "today" and "this month" modules in a child pytest with the clock frozen a few minutes past local midnight and past midnight UTC on the 1st (tests/boundary_clock.py). |
tests/test_queue.py, tests/test_queue_lock_retry.py
|
Double leases, stale workers overwriting a re-leased task, and lock errors that should be retried. |
tests/test_contracts.py |
A consent form that pre-ticks its confirmed field, an online POST route that does not refuse an unconfirmed post, or a route that serves or deletes a stored file path outside the documents folder. It scans every form and route in the repo, so a new one is covered as soon as it exists. |
tests/test_browser_map.py |
A UI file under kestrel/web that no rule in tests/browser_map.toml maps to a browser test file, so the full check would select no browser test for it. |
tests/test_outbound_inventory.py stops a hidden outbound call from shipping. It reads files only and never touches the network. It reads every file under kestrel/ with a text suffix (.py, .js, .html, .css, .yml, .yaml, .json, .toml, .txt, .md, .webmanifest, .svg) and collects each http, https, ws or wss address, with any {placeholder} in an f-string or template read as one part ({*}). Then it compares the hosts with the host index at the end of docs/OUTBOUND-CALLS.md:
- Every host in the code must be in the index. A new address fails the test, and the message names the files that carry it.
- Every host in the index must still be in the code, and its kind must be one of
call,link,local,referenceorbuild. - A third test checks the scanner on a sample, so a change to the pattern cannot quietly stop it from finding addresses.
What it cannot see: an address built at run time from pieces, an address a person types or a posting supplies (the index covers those under {*} in prose), and what a library such as JobSpy requests internally. When you add a network call, the test is the minimum. The prose tables above the index in docs/OUTBOUND-CALLS.md are for you to keep accurate. See Security and privacy model and Outbound calls.
Time-dependent tests compute dates inside the test function. One pipeline gate once went red because of a hard-coded posting date that aged out of max_posting_age_days.
A few tests render PDFs or drive the web UI through a real browser. In production Kestrel uses the Edge already on the machine (it does not bundle Chromium), so the tests try Edge first. If Edge is absent they fall back to a Chromium named by KESTREL_BROWSER_PATH or found in Playwright's browser folder (tests/browser.py). If there is none, they skip with a reason that starts "Browser unavailable".
The UI tests, the tests/test_*_browser.py files and a few others that drive a page, are opt-in. Each skips unless KESTREL_LIVE_BROWSER=1 is set. The main run of scripts/check.py does not set it, so those tests skip there. The full check sets it only for the browser files that map to the pages the branch touches. Its skip summary lists the rest, and its browser warning leaves out the skips whose reason names KESTREL_LIVE_BROWSER. A passing --quick or --fast run therefore says nothing about script, layout or motion, and a full check covers only the pages it touched. See the gates below.
Other skips are environmental: POSIX-only tests skip on Windows, the Windows-only native load-order test skips elsewhere, and a few tests skip when node is not installed.
-
launch_syncandlaunch_asyncstart Edge, then the fallback Chromium, and skip with the "Browser unavailable" reason if neither starts. -
wait_for_layout(page)waits for fonts, finished HTMX swaps and finished layout animations, so a measurement does not catch a page mid-motion. -
art_visible_left,TITLE_RIGHT_JSandLINES_JSmeasure what a screen shows (where the scene art starts drawing, where a title row ends, how many lines an element wraps to) rather than a container's box.
Every page in the desktop window is mounted and unmounted by KUI.page (see Adding a page), and a page's browser test proves it leaves nothing behind. Two pieces in tests/browser.py:
-
TIMER_PROBE_JSis added withpage.add_init_script()before the page loads. It wrapssetTimeout,setIntervaland their clear functions and records the call stack of each timer, so the check can tell which of the page's own scripts left a timer pending or fired one after unmount. A timer that htmx starts for a declarative poll belongs to htmx and goes with its element, so it is not counted. -
assert_page_remounts_clean(page, name, script)unmounts the page throughKUI.page.unmount()and checks that no listener, timer or observer is left, that none of the page script's timers is pending or fires during a quiet period, and that mounting again gives exactly the counts of the first mount. It fails with "add TIMER_PROBE_JS before goto" if the probe is missing.
G4_LISTENER_PROBE_JS does the matching job for partials that an htmx swap brings in: it counts the listeners still live on matching elements, so a script in a swapped-in partial cannot double its handlers.
A change passes these in order. They are the project's QA workflow, and each catches what the one before it cannot.
| Gate | What it proves | When |
|---|---|---|
| 1. Unit and route tests next to the change | The rule the change implements, not just the code it happens to contain | Every change |
2. scripts/check.py ends "Ready to push." |
Lint, static checks, the whole non-browser suite, the repository guards, the browser files for the pages the change touches, diff coverage and a red-first proof for fix commits | Before every push |
3. Live browser tests for each page the change touches, with KESTREL_LIVE_BROWSER=1
|
Script, layout and motion in a real browser | Any template, CSS or JavaScript change. Gate 2 runs these for the pages it maps to the change, so run them by hand only to see the output |
4. The full browser suite, every tests/test_*_browser.py with the same variable |
Nothing elsewhere broke | A change to the shell, shared CSS or JavaScript, or anything every page loads |
Gate 2 runs the browser test files for the pages a change touches, so a page change that breaks its own browser test does not pass it. It runs no other browser files, which is why gate 4 exists. A gate that cannot pass in your environment (a real model, a live key, a browser) is reported as blocked with the exact command to run, never faked.
uv sync --extra dev
uv run pytest -q # everything
uv run pytest -q tests/test_queue.py # one module
uv run pytest -q -k lease # by name
uv run pytest -q -s tests/test_prompt_budgets.py -k table # print the prompt budget table
KESTREL_LIVE_BROWSER=1 uv run pytest -q tests/test_calibrate_browser.py # one page, in a real browserEach test has a 60-second timeout (timeout = 60 in pyproject.toml), and the browser test files have 180 seconds (tests/conftest.py). On Linux and macOS a timeout fails that one test. On Windows, pytest-timeout uses a method that stops the worker the test runs in.
On Windows PowerShell, set the variable first: $env:KESTREL_LIVE_BROWSER = "1". With the variable set, scripts/check.py includes the browser tests in the same run.
Run this before every push. It has three tiers:
uv run --extra dev python scripts/check.py # the full check
uv run --extra dev python scripts/check.py --fast # quick, plus the whole suite (no coverage, no browser stage)
uv run --extra dev python scripts/check.py --quick # lint and static checks, then the packaging and notices guards
uv run --extra dev python scripts/check.py --workers 0 # the full check, serially
uv run --extra dev python scripts/check.py --junitxml out.xml # also write each outcomeEvery tier starts with ruff check ., then the static checks on what the branch changed:
- New pyright errors in the changed files, against the stored baseline (
scripts/pyright_baseline.json). -
BLE001,S110,ASYNCandRUF006lint on the changed lines. - The test floor: a test file may not lose asserts or tests, or gain skips, against the merge base.
- Protected paths: the files that define the gates cannot change unless a commit on the branch carries the justification the gate requires.
- Test quality: changed test lines that would pass without proving anything.
After that:
-
--quickrunstests/test_packaging.pyandtests/test_notices.py. It ends with "Quick checks passed; run the full check before pushing." -
--fastruns the whole pytest suite in parallel, with no coverage and no browser stage. It ends with "Fast checks passed; run the full check before pushing." - The full check runs the whole suite with coverage, and then:
-
Browser files for touched pages. Each changed UI file is mapped to browser test files through
tests/browser_map.toml. Those files run withKESTREL_LIVE_BROWSER=1, one at a time by default (--browser-workers), and each must have at least one passing test. A changed UI file that maps to no browser test file fails the check. -
Diff coverage. At least 80 percent of the lines changed under
kestrel/must be run by a test. -
The midnight run. The "today" and "this month" test modules run again with the clock frozen a few minutes past midnight (
tests/test_clock_boundaries.py). -
Red-first proof. A
fix:commit that adds or changes tests must have those tests fail on the commit's parent.
-
Browser files for touched pages. Each changed UI file is mapped to browser test files through
The full check needs a git base to compare against: the merge base with origin/main, or main. Without one it stops with "Not ready to push" and says why. --quick and --fast run without one and skip the comparisons that need it.
Each failure names the rule, the file and line, and the fix. The script stops at the first failure and prints "Not ready to push: fix the failure above first." On success it prints the skip summary and "Ready to push." If the working tree has uncommitted changes, it lists them and reminds you they are not in the push.
The tests run under pytest-xdist with KESTREL_HEADLESS=1, as CI sets it, so a desktop session does not take the tray and browser paths. The worker count is --workers N, else KESTREL_TEST_WORKERS, else half the CPUs capped at 8 with a minimum of 1, and 0 runs serially. Each worker uses its own per-test data folder and OS-assigned loopback ports. The script prints the time each step took, and the first run on a machine is the way to learn how long it takes there.
To run it automatically, opt in once per clone:
git config core.hooksPath .githooksThe hook (.githooks/pre-push) runs the same script. git push --no-verify skips it.
CI minutes are metered. Windows costs twice what Linux does and macOS ten times. So CI confirms what you already ran; it does not discover. .github/workflows/ci.yml runs ruff check . and pytest -q on Ubuntu and Windows for pull requests, and adds macOS only for pushes to main. On Windows it also compiles the real installer script against a stub folder. Changes that touch only README.md, CLAUDE.md, AGENTS.md or docs/images/** skip CI; the list is explicit, because prompts are .md files and tests read docs/SOURCES.md. CI does not set KESTREL_LIVE_BROWSER, so it does not run the gated browser tests either.
Three working rules follow from this:
- Finish a coherent unit locally, then push once. Do not push work in progress to see what CI says.
- A warning in any CI or release log becomes a failing local test in the same pull request.
- Behavior only the Windows runner can prove (native DLL loading, the installer) is the one thing a local Linux or macOS pass cannot cover. Say so in the pull request.
- Put it in the module for the feature, or add a
test_<feature>.py. - Use
smfor anything that touches the database, andrespxfor anything that touches HTTP. - Use
FakeLLM, or a stub with the same.complete()signature, for anything that would call a model. - Compute dates inside the test, and never read the clock at module level. Patch a module's own clock alias, not the global clock.
- Seed "minutes ago" rows through
tests/clock_seed.py(ago_withinand its helpers). A row at now minus five minutes, counted as "today", fails in the first five minutes after midnight; the helper keeps the row inside the period the test checks, so the test stays correct just after midnight and on the 1st. - Take a free port from
bind_free_port(ladder=False); never listen on one of 8765 to 8774. - Set every precondition the test asserts on. Never rely on test order, on another test's leftovers or on a shared seed.
- Tests are exported with the public source: use invented text only.
- If a test needs a real browser, use
tests/browser.pyso it skips with a reasoncheck.pyrecognizes. - Test the behavior the spec states, not what the code happens to do.
- A new UI file (a template, stylesheet or page script) needs a rule in
tests/browser_map.toml. The full check fails for a changed UI file that no rule maps. - A
fix:commit that adds or changes tests must have those tests fail on the commit's parent. The full check proves this for every such commit.
Kestrel never submits an application, sends a message or acts on a third-party site for the user, so no test needs a live account or a real recipient, and none should ever add one.
-
Database schema and Task queue and concurrency for the code the
smfixture and queue tests cover. -
Adding a job board adapter for the fixture and
respxpattern in practice. - Contributing for the pull request checklist.
Start here
Interfaces
Extending Kestrel
How it works
- Prompts and context budgets
- Document engine
- Learning loop internals
- Analytics internals
- Task queue and concurrency
- Database schema
Shipping and safety
- Packaging and releases
- Preflight and diagnostics
- Security and privacy model
- Outbound calls
- Benchmarking
Workarounds and Troubleshooting