Writing tests worth keeping
The handbook carries the rationale and the same rules for people: Backend coding conventions › Testing (docs/published/handbook/engineering/conventions/backend-coding.md).
This skill is the gate an agent runs before it writes a test.
It holds the decision procedure and a catalog of the bug shapes we actually ship.
The gate covers added coverage, not only new test functions.
One fixture and one assertion added to an existing block go through the same questions, because that is the shape this skill prefers.
The gate
Answer questions 1 and 2 in one sentence each before you write the test, and question 3 before you commit it.
A question you can't answer stops the test.
1. Does it earn its place?
What realistic regression does this test catch that no existing test already catches?
Name the bug, the code path, and the input that would break it.
"Increases coverage", "good practice", and "the function exists" are not answers.
A good answer sounds like _"if someone makes parse_filters drop the team_id clause, this fails"_ or _"empty-cohort input used to 500; this locks in the 400."_
Aim each test at a failure mode we actually ship.
references/mistakes-we-make.md catalogs those shapes, the test that catches each, and the failure modes no unit test should chase.
A test that maps to none of them is probably not worth keeping.
2. Where does it go?
Passing question 1 buys the coverage, not a new test function.
Find the test that covers the nearest behavior and answer:
Why can't this be a case in that test?
When your case is a variation of that behavior, extend it with a @parameterized case in Python or a test.each row in Jest.
Write a standalone test only when you can name one of three reasons: the setup differs, the behavior belongs to a different unit, or no relevant test exists.
"It's cleaner as its own test" names none of them.
Extend to remove duplication.
A parameterized case is still its own invocation, so setUp and beforeEach run for it as they would for a standalone function, and extending saves no setup time.
Fold in variations of the same behavior, and give assertions about other behavior their own test.
Extending adds your case, not the neighbor's habits.
When the nearest test mocks internal helpers or asserts on mock calls, give your case real input through the public interface and assert an outcome.
When that test's harness can't observe the outcome, the setup differs, so write a standalone test.
Search for the nearest test first; question 2 has no answer without it.
A new test file needs a team owner, because ownership routes its failures and flakes.
Put it next to the code it tests, inside products/<name>/ when one product owns the behavior, so it inherits that owner.
Check with hogli owners:who <path>.
When no team owns the path, name the team responsible for the behavior it checks in the nearest owners.yaml, not the team of a helper it imports.
CI fails a pull request that leaves a test file with no team owner: a new file, a moved file, or a file that an owners.yaml edit left without a team.
The pre-push hook runs the same check and blocks the push.
3. Does it go red?
Break the line the test guards: drop the clause, flip the condition, or return early.
Run the test, and watch it fail for the reason you named in question 1.
Then restore the line.
For a bug fix, the pre-fix code is the broken line.
A test that stays green guards nothing.
Rewrite it to assert an outcome, or delete it.
This check catches tautologies and mock plumbing on every level, so run it on each test you add or change.
Tests that guard nothing
Most low-value tests take one of these shapes.
Recognize them and skip them.
- Framework behavior.
Getters, setters, constants, dataclass field assignment, that Django saved a row, that DRF serialized a field, or that a library does what its docs say.
That tests someone else's code.
- Change-detector tests.
A test that mirrors the implementation by asserting which private methods ran, in what order, with mocks wired to match the current code.
It fails on every refactor and catches no real bug.
Assert an outcome instead.
See Change-Detector Tests Considered Harmful and Prefer Testing Public APIs.
- Redundant coverage.
Ten tests that run the same path with different data are one parameterized test.
AI-generated suites bloat here first, turning a 30-second suite into 3 minutes with hundreds of near-identical cases.
- Coverage-chasing.
An uncovered line is information, not a defect.
When the coverage report is the only reason to test a branch, the branch probably needs no test, or it is dead code to delete.
- Cross-language source scraping.
A test that reads or regex-parses another language's source, such as a Python test that Path(...).read_text()s a .ts file and matches category: '...', or a TypeScript test that greps a .py file.
It couples two trees through a string match that breaks on a rename, a reformat, a moved file, or a comment, and it proves nothing at runtime because the two sides never run together.
When two sides must agree on a set of values, give them one source of truth, a generated artifact or a checked-in data file that both import, and assert against it.
Otherwise let drift surface where the two sides meet: an API contract test, a rendered output, or a round trip.
When the answer is "skip it", extend an existing test or delete the code instead.
Both shrink the suite.
What counts as an outcome
A test gives input through the unit's public interface and asserts an outcome, something a caller can observe:
- the return value of a pure function, through its own signature;
- the HTTP response, or the row the request stored;
- the
valuesa kea logic exposes after its actions run; - the message, email, or request that a boundary fake recorded, meaning the URL, body, and headers the receiving service reads.
The last one matters most for code whose job is to send.
For a destination or a webhook, the request that crossed the boundary is the delivery, so asserting on it tests the outcome.
A call to your own helper, its call count, or its arguments is not an outcome.
If you write it, weight it down the cost ladder
Each level of the cost ladder is slower and flakier than the one below:
pure function → kea logic → Django TestCase / Node service test → ClickHouse-backed test → Node serial lane / Playwright e2e
cheapest most expensive
Aim for a ratio, not a cap: many tests at the bottom, very few at the top.
Add more coverage at the bottom.
Pick the lowest level where the behavior exists and its outcome is visible.
A lower level that sees only an internal call, or a mock standing in for the code under test, is not a cheaper test of the same behavior.
It tests something else.
Take a real dependency only when the behavior reads or writes it.
Logic that never touches Postgres, ClickHouse, or Redis belongs on a level without them.
Logic that does belongs on the real one, because a mock of it agrees with whatever the code assumes.
When something is hard to test cheaply, that's a design signal: extract, don't escalate.
When the only way to run your logic is a database, a request, and a render, the logic is tangled with its dependencies.
Pull it into a pure function or a kea logic and test it through that unit's own interface, its signature or its actions and values.
You get a faster test and better-factored code at once.
Mocking the tangled code's internal helpers also makes the test cheap, but then the test observes the mocks.
When the behavior can't be pulled out, because it lives in a query, a transaction, or the wiring, test it at the level where a caller observes it.
When you extract a decision this way, such as the dedupe, routing, or eligibility rule that .agents/architecture.md keeps pure, put the case matrix on the pure function and keep one database-backed test as a wiring guard.
Without that guard, a refactor that stops calling the decision passes every pure case.
A property is the right shape when a pure unit has a rule that holds for every input: a round trip, an optimized path that must match a slow reference, or a port that must match the original.
Generate the inputs (Hypothesis, proptest, or a loop over a small domain you can enumerate), keep the test at the pure level, and bound the number of examples so it stays fast.
Hypothesis loads its built-in ci profile on a CI runner, which derandomizes the run; proptest picks a new random seed on every run unless PROPTEST_RNG_SEED is set, and writes each failure to a proptest-regressions/ file to commit.
Either way, copy each counterexample it finds into a fixed case.
Reach for ClickHouse, the Node serial lane, or a browser only when the regression lives there.
Python (pytest / Django)
- Use
TestCase, notTransactionTestCase, unless you truly need it.
TransactionTestCase flushes the database between tests instead of rolling back a transaction, which is much slower and a common source of cross-test interference.
The choice is about Postgres isolation, not about which datastore you touch: a ClickHouse-backed test is still a plain TestCase, because ClickhouseTestMixin sets ClickHouse up.
The usual reasons for TransactionTestCase have cheaper answers:
- For
transaction.on_commitside effects, useTestCasewithself.captureOnCommitCallbacks(execute=True). - For a connection visible across a real separate thread (
thread_sensitive), useasync_to_sync(...), notasyncio.run(...).
Use TransactionTestCase only when the regression needs committed transaction boundaries that TestCase hides.
- A test class only takes a database it uses.
BaseTest and APIBaseTest inherit Django TestCase, so a class on either one needs a database: setUpTestData writes an organization, a project, a team, and a user, and every test method runs inside a transaction.
A class of pure assertions pays all of that and reads no row.
Put those cases on django.test.SimpleTestCase, which refuses database access and so proves they never needed one.
The posthog/test/repo_invariants/test_database_free_test_classes.py check holds the frozen list of the classes already here and fails the pull request that adds another.
When it trips, references/database-free-test-classes.md covers what the failure means, the three ways to answer it, and how to regenerate the baseline.
- Dedicated data migration tests are temporary.
Remove one after every supported environment has applied the migration, the rollback window has closed, and no supported upgrade relies on the old data state.
Delete the expired test instead of marking it skipped.
Keep the migration file, and keep tests for migration tooling, safety checks, reusable backfill systems, and backfills people can still run.
Use /django-migrations for the migration safety workflow.
- DRF input validation belongs in a
SimpleTestCase, not anAPIBaseTestround trip.
A test that posts a malformed body and asserts a 400 pays for APIBaseTest to build an organization, a team, and a user in Postgres, only to run validation that happens in memory.
DRF field validators (required, type coercion, choices, min/max, regex) and validate_<field> methods run inside Serializer(data=...).is_valid() with no database and no request.
Field-level validation runs in to_internal_value, before the object-level validate() that usually needs self.context, so an invalid-field case never reaches code that touches the database.
Test the serializer directly and assert on .errors:
```python
class TestTeamValidation(SimpleTestCase): # no DB, not APIBaseTest
def test_sample_rate_too_many_digits(self) -> None:
s = TeamSerializer(data={"session_recording_sample_rate": "30001"}, partial=True)
assert not s.is_valid()
assert s.errors["session_recording_sample_rate"][0].code == "max_digits"
```
When you move the case matrix down to the serializer, keep or add one database-backed endpoint test as a wiring guard, proving the viewset invokes this serializer and rejects a bad request with a 400.
The serializer test proves the validation logic, not the wiring: a refactor that drops serializer_class, skips is_valid(), or stops passing raise_exception=True passes every SimpleTestCase and still ships a broken endpoint.
For a query serializer built inline, such as Serializer(data=request.query_params).is_valid(raise_exception=True), the wiring guard asserts that a bad query parameter returns a 400.
.errors carries DRF's raw code (invalid, max_digits); exceptions-hog renders the {"attr", "code", "detail", "type"} HTTP envelope later and maps invalid to invalid_input.
That rendering is framework behavior, so the wiring guard asserts the envelope once and the cases skip it.
Validation that needs the database stays at the endpoint: uniqueness checks, PrimaryKeyRelatedField queryset lookups, related-object existence, permission and team scoping, and password-hash checks.
- Parameterize repeated assertions with the
parameterizedlibrary rather than copying test bodies. - Use a
parameterizedcase when the cases are known before the test runs, andself.subTestonly when they are not, such as one check per row a query returns.
Our pytest configuration makes self.subTest fail fast so CI can retry the test.
Use self.subTest, not the pytest subtests fixture, which leaves a failure in the junit file after a rerun passes.
- No doc comments in Python tests (house rule).
- Drive your own helpers through the code that calls them.
A mock of an internal helper is how change-detector tests start.
For Postgres, ClickHouse, and Redis, follow the real-dependency rule in the ladder section above.
- Person, group, and cohort data: use the helpers in
posthog/test/persons.py(create_person,create_group,create_group_type_mapping,add_cohort_members, and others), neverPerson.objects.create()or similar ORM calls.