Skip to content

Testing

Claude edited this page Oct 30, 2026 · 5 revisions

Checked against v0.7.0 on October 30, 2026.

Testing

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."

Layout

The suite is flat. tests/ holds 301 test_*.py modules with about 4,100 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.

Isolation

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_HOME points 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 .env key store is cleared, so a developer's real key cannot change what a page renders.
  • A loopback test client. The app validates the Host header and treats non-loopback peers as unauthenticated. TestClient is patched to present itself as 127.0.0.1. The comment in conftest.py calls this a harness fix, not a relaxed assertion: tests of the guards pass an explicit host or client= and still override it.
  • No first-run redirect, reset status caches, worker unpaused. Each undoes process-global state a test might have changed.

The sm fixture

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 == 1

The 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.

No live endpoints

HTTP is mocked at the transport. 58 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) == 2

Fixtures from real payloads

tests/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:

  1. Capture one real response and trim it to a few postings.
  2. Replace company names, people, URLs and ids with fictional ones such as Acme Robotics and example.com.
  3. Keep every field the real payload has, including the awkward ones. Do not tidy the shape.
  4. Mock the URL with respx and 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.

Faking the model

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.

Guard tests

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.
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.

The outbound guard

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:

  1. 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.
  2. Every host in the index must still be in the code, and its kind must be one of call, link, local, reference or build.
  3. 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.

Browser tests

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. scripts/check.py does not set it, so a plain check.py run does not run them. Its skip summary lists them, and its browser warning leaves out the skips whose reason names KESTREL_LIVE_BROWSER. A passing check.py therefore says nothing about script, layout or motion. 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.

tests/browser.py helpers

  • launch_sync and launch_async start 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_JS and LINES_JS measure 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.

The page leak test

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_JS is added with page.add_init_script() before the page loads. It wraps setTimeout, setInterval and 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 through KUI.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.

The gates, in order

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, the whole non-browser suite and the repository guards 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
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 does not run the browser tests, which is why gate 3 exists: a page change can pass check.py and still break that page's own browser test. 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.

Running the tests

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 browser

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.

scripts/check.py

Run this before every push:

uv run --extra dev python scripts/check.py                 # lint, then the full suite
uv run --extra dev python scripts/check.py --quick         # lint, then only the packaging and notices guards
uv run --extra dev python scripts/check.py --workers 0     # the same suite, serially
uv run --extra dev python scripts/check.py --junitxml out.xml   # also write each outcome

It runs ruff check ., then pytest -q -rs -p no:cacheprovider -n <workers> --dist worksteal --max-worker-restart 0, with KESTREL_HEADLESS=1 set as CI sets it, so a desktop session does not take the tray and browser paths. The suite runs in parallel with pytest-xdist. 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.

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 .githooks

The hook (.githooks/pre-push) runs the same script. git push --no-verify skips it.

Why the local check matters

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.

Writing a new test

  • Put it in the module for the feature, or add a test_<feature>.py.
  • Use sm for anything that touches the database, and respx for 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.py so it skips with a reason check.py recognizes.
  • 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.

Related

Clone this wiki locally