Repository navigation
Testing
Checked against v0.6.1 (commit 3b06892) on October 19, 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 and packaging, 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 177 test_*.py modules with about 2,000 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. |
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. 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. - 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. 36 test files use respx, and a few 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_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. |
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. |
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.
A skip is never silent. scripts/check.py prints every skip reason and warns when browser tests did not run, because the UI and PDF checks did not run either. Install Edge, run uv run playwright install chromium, or set KESTREL_BROWSER_PATH before you rely on a local pass. One test that launches whatever the browser ladder finds runs only with KESTREL_LIVE_BROWSER=1.
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.
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 tableRun this before every push:
uv run --extra dev python scripts/check.py # lint, then the full suite (about 3 minutes)
uv run --extra dev python scripts/check.py --quick # lint, then only the packaging and notices guardsIt runs ruff check ., then pytest -q -rs -p no:cacheprovider, with KESTREL_HEADLESS=1 set as CI sets it, so a desktop session does not take the tray and browser paths. It 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. --quick is for iterating and ends with "Quick checks passed; run the full check before pushing."
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.
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.
- 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.
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