agentleFS
zenml-iozenml-io/kitaru/tests/AGENTS.md

kitaru / tests

AGENTS.md324 starsChanged 2 days agoApache-2.0View on GitHub

Ordinary async tests and fixtures are plain async def. pytest-asyncio runs in auto mode, so they need no decorators or asyncio.run wrappers. Synchronous Hypothesis @given tests are the exception: call async code with asyncio.run inside the test body. Cover all four surfaces below for a new persistent public API resource. For changes to an existing resource, select the surfaces that prove the affected behavior. Transaction, locking, migration, and cross-request changes need PostgreSQL coverage; an in-memory fake cannot prove those contracts.

The file

Files
AGENTS.md

Test rules

Ordinary async tests and fixtures are plain async def. pytest-asyncio runs in auto mode, so they need no decorators or asyncio.run wrappers. Synchronous Hypothesis @given tests are the exception: call async code with asyncio.run inside the test body.

Test surfaces per server resource

Cover all four surfaces below for a new persistent public API resource. For changes to an existing resource, select the surfaces that prove the affected behavior. Transaction, locking, migration, and cross-request changes need PostgreSQL coverage; an in-memory fake cannot prove those contracts.

  1. Service tests against the in-memory fake repository (tests/server/test_<x>_service.py).
  2. REST tests over httpx.ASGITransport with the service dependency overridden to the fake (tests/server/test_<x>s_api.py).
  3. Repository contract tests parametrized over the in-memory fake and the SQL implementation (tests/server/test_<x>_repository.py). One shared suite runs against both backends so the fake cannot drift from the real repository. The postgres parameter skips when the local database is unreachable.
  4. An end-to-end PostgreSQL test that runs the app through its lifespan, which also executes the Alembic migrations (tests/server/test_<x>s_api_pg.py). Cross-request visibility proves the per-request commit.

The SDK gets a round-trip test in tests/client/ routing the client through httpx.ASGITransport.

Fakes

Fake repositories live in the tests/kitaru_test_support/ package, one module per group of related resources, and implement the full repository Protocol, including domain error behavior and updated timestamp renewal on update. Tests import them from the package, for example from kitaru_test_support import FakeSessionRepository; add a new public helper to the package __all__. tests/conftest.py keeps the pytest hooks, the fixtures, and the PostgreSQL, settings, and ASGI client helpers, which tests still import with from conftest import .... Keep every file under the 1,000-line limit enforced by just file-size-check.

PostgreSQL

Tests point at localhost:5433 (override with KITARU_TEST_DB_HOST and KITARU_TEST_DB_PORT) and expect docker compose up -d db. Each pg test creates a uniquely named database and drops it on teardown, so tests stay independent and concurrent runs never share state. A session-scoped fixture reaps databases left behind by a killed run, age-gated on the timestamp in the database name so it never drops a concurrent run's live databases.

Set KITARU_TEST_REQUIRE_POSTGRES=1 to fail before collection if PostgreSQL is unavailable. CI enables this for both Python 3.14 base jobs; local runs and the other Python versions keep optional database skips.

Repository sessions copy a session-scoped empty schema into each unique database instead of recreating every table for every test. The template has no open connections while it is copied and is dropped at session teardown. API lifespan and historical migration tests still initialize their own databases. CI stores the disposable PostgreSQL data directory in memory; it retains the normal PostgreSQL transaction and durability settings.

CI test distribution

The Python 3.14 base suite runs on two independent runners, each with its own PostgreSQL service. Set both KITARU_TEST_SHARD_INDEX (zero-based) and KITARU_TEST_SHARD_COUNT to select a partition. Pytest assigns whole files using SHA-256 of their repository-relative POSIX paths modulo the count, preserving test order within each file and automatically including new files. With both variables unset or empty, pytest runs the full selection as usual. Invalid or incomplete settings fail instead of silently dropping tests.

For local reproduction, prefix the normal base pytest command with KITARU_TEST_SHARD_INDEX=0 KITARU_TEST_SHARD_COUNT=2, then repeat with index 1. Both partitions together must contain exactly the unpartitioned collection, with no overlap. Database-required behavior is independent of the partition settings.

Regular push and pull-request CI runs the Python base and plugin suites with two workers and --dist loadfile to keep each file together. CLI and MCP suites remain serial, and both existing Python 3.14 partitions remain intact. Manual CI dispatches retain a test-processes choice of 1 or 2 for comparison and export JUnit outcomes and combined core/plugin coverage JSON as one-day artifacts. Run each mode sequentially on the same commit and runner types; repeat the comparison to distinguish an improvement from runner noise.

TypeScript CI is split into two workflows that both run unconditionally on develop pushes and workflow_dispatch: .github/workflows/ci-typescript.yml (pull requests touching TypeScript, OpenAPI, or TypeScript CI files) and .github/workflows/ci-typescript-bridge.yml (pull requests touching those paths or the Python server, Worker, client, API models, task, or lockfile inputs for tests/typescript and the ticket-resolver example). In ci-typescript.yml, the primary typescript job runs each published package suite once with coverage and PostgreSQL enabled, followed by both Mastra example suites; pull requests run the oldest (packages/mastra) and newest (--mastra-compat=boundary) Mastra releases while develop pushes and dispatches run all intermediate Mastra compatibility packages (skipping four heavy payload-budget/blob/API-hang suites on intermediate releases while retaining version-branching suites, and release-typescript.yml sets KITARU_MASTRA_COMPAT_FULL=1 to run every file on every release). The Node 24 and Node 26 jobs run build:packages, test:core:built, and pack:check:built (24.x/26.x on pull requests; 24.0.0/24.x and 26.0.0/26.x on develop pushes and dispatches). For manual comparisons, compare typescript-tests=repeated against typescript-tests=coverage-once in ci-typescript.yml. Both modes retain the three TypeScript package suites, both Mastra example suites, and the PostgreSQL memory cases. The benchmark-typescript artifact contains canonical test outcomes and per-file coverage JSON; compare test identities and outcomes plus covered lines, statements, functions, and branch arms by source location. The repeated mode retains the original separate coverage pass without PostgreSQL, while the single-pass mode includes PostgreSQL in coverage. Packed-package, compiled-worker, example end-to-end, and supported Node-version checks remain required.

Require repeated same-commit comparisons for further CI performance optimizations, showing at least a 20% improvement in median queue-free CI critical-path execution time, without worsening slower runs or introducing intermittent failures. Reconstruct this metric from job execution durations and the workflow's needs graph, and report observed workflow elapsed time separately. Compare test identities and outcomes, unexpected skips, and per-file covered lines and branch arcs, including child processes. Retain the current Hypothesis settings, database-required failures, supported-version matrix, and package checks.

Property-based tests

Hypothesis tests live next to the surface they cover: plugins/tests/importers/test_fuzz_parse.py and test_normalization_properties.py (importer parsing and normalization contracts), property modules under plugins/tests/evaluators/, tests/api_models/test_wire_properties.py, tests/mcp/test_fuzz_tools.py (MCP tool boundary, requests generated from each tool's JSON schema), tests/cli/test_redaction_properties.py, tests/server/test_fuzz_filters.py (recursive JSON list filters), tests/server/test_fuzz_api_sequences.py (isolated successful agent/version API sequences), and codec, capture, and record/replay property modules under plugins/tests/adapters/.

Three profiles are registered in each root's conftest.py and selected with HYPOTHESIS_PROFILE: dev (100 examples, default locally), ci (50 examples, fixed seed; default when CI is set, so PR runs are deterministic), and nightly (2000 examples, random; used by just fuzz and the fuzz-nightly workflow). The just fuzz aggregate runs fuzz-importers, fuzz-evaluators, fuzz-api-models, fuzz-mcp, fuzz-adapters, fuzz-filters, and fuzz-api. The nightly workflow also runs fuzz-filters-pg, fuzz-api-sequences, and fuzz-task-lifecycle as separate PostgreSQL-backed jobs with fresh random samples and their bounded recipe defaults instead of the 2000-example profile. @given tests are sync; call async code with asyncio.run inside the body.

Known bugs are pinned with @pytest.mark.xfail(raises=..., reason="<issue>") example tests, where raises= names the specific failure (a pytest.RaisesExc matcher when the exception type alone cannot tell it apart) so that a different failure still fails the run, and the generators exclude the matching input class with a comment naming the same issue. Fixing the bug makes the xfail fail because xfail_strict is on; remove the marker and the generator exclusion in the same PR. Failing examples are saved under .hypothesis/examples and replayed first on the next run.

Mark generated-input MCP tests with mcp_fuzz. PR CI runs those properties on Python 3.14 only; fixed MCP regression tests continue on every supported Python version. Nightly MCP boundary and redaction jobs run separately on Python 3.12, retaining 2,000 examples per property. just fuzz-mcp runs their combined selection locally; just fuzz-mcp-boundary and just fuzz-mcp-redaction reproduce each job. The recipes print test names and durations. The nightly workflow runs each MCP job with four pytest workers through PYTEST_ADDOPTS, because serial runs exceed the process limit; local recipe runs stay serial. Do not add faulthandler_timeout: its watchdog stack dump segfaulted the nightly MCP jobs. Nightly processes stop before the job deadline so logs and saved examples can be uploaded; a separate reporting job includes failed and cancelled matrix jobs. Cancelling the entire workflow or losing a runner can still prevent diagnostics and reporting.

The CI and nightly profiles omit Hypothesis's explanation phase only for the known-failing invalid-input MCP property. They still generate and shrink examples; the local development profile retains explanation.

API fuzzing

tests/server/test_fuzz_api.py generates requests from openapi/openapi.json with Schemathesis and sends them to the real app. Opt in with KITARU_FUZZ=1 (the module skips at import otherwise; keep that skip above the schema setup rather than in a pytestmark, for the reason in its comment) and start the database first with docker compose up -d db; just fuzz-api runs the deep nightly configuration. The fuzz dependency group carries schemathesis, so run under uv run --extra server --group fuzz.

tests/server/fuzz_server.py boots one real server per session on its own disposable database, with real Alembic migrations and a real bearer token from POST /api/v1/login. It runs under uvicorn in a background thread rather than an in-process ASGI transport, because those transports rerun the lifespan — migrations included — for every generated example. An ASGI wrapper records unhandled exceptions so a failure names the exception and not just the endpoint; a 500 body carries no detail on its own.

The only assertion is that the server never answers 5xx. One database is shared for the whole session, so an earlier operation's rows are visible to a later one, which makes "was this input rejected?" depend on run order while leaving "did the server crash?" well-posed. Schemathesis's negative_data_rejection is therefore deliberately not run. Negative generation is still on, so schema-violating input is still sent; only the rejection assertion is dropped.

Known defects are listed in KNOWN_FAILURES keyed by method and path, with the issue number as the reason, and skip rather than mask everything behind them in the same operation. Delete an entry as part of closing its issue.

KITARU_FUZZ_MAX_EXAMPLES sets depth (default 25) and KITARU_FUZZ_RANDOM=1 turns off derandomize so a nightly explores fresh inputs; the default stays derandomized so a failure reproduces. KITARU_FUZZ_CAPTURE writes captured tracebacks to a JSONL file. Findings scale steeply with depth, so prefer nightly depth over a shallow gate.

tests/server/test_fuzz_api_sequences.py gives each complete generated action list a fresh PostgreSQL database, application lifespan, and authenticated client. It records symbolic resource IDs and credential roles so a shrunk failure can be replayed without retaining database IDs or tokens. Schemathesis validates observed responses against the committed OpenAPI schema; ordinary Hypothesis action lists keep prerequisites valid and isolation explicit. Opt in with just fuzz-api-sequences, or pass smaller bounds such as just fuzz-api-sequences 5 5 for a smoke run. The explicit suite fails rather than skips when PostgreSQL is unavailable.

tests/server/test_fuzz_task_lifecycle.py generates authenticated task-attempt sequences in a fresh PostgreSQL database. It models legal transitions separately from deliberate stale-attempt and foreign-task credential checks, and drives recovery with the production task service at a synthetic future time. Opt in with just fuzz-task-lifecycle, or pass smaller bounds such as just fuzz-task-lifecycle 5 5 for a smoke run. The explicit suite fails rather than skips when PostgreSQL is unavailable.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.