Write tests
1. Learn the house style
Find existing tests near the code: framework (pytest, unittest, Jest, Vitest, Go testing, JUnit, RSpec…), file naming, fixtures/factories, how the DB and HTTP are handled, how to run one test. Match it. Do not introduce a new test framework.
2. Choose the level
| Level | Use for | Typical speed |
|---|---|---|
| Unit | Pure logic, calculations, parsing, branching | milliseconds |
| Integration | Code + real database, queue, filesystem, framework routing | 10 ms - seconds |
| End-to-end | A few critical user journeys through the real stack | seconds - minutes |
Most tests should be unit or integration. Use end-to-end sparingly for the paths that would cost the most if broken (sign-up, checkout).
3. Pick the cases
For each function or behavior, list cases before writing code:
- Happy path: one typical input.
- Equivalence classes: one representative per class of input that should behave the same.
- Boundaries: 0, 1, many; empty string/list; max length; just below/at/above limits; first/last day of month; leap day; DST change.
- Invalid input: wrong type, missing fields, malformed formats. Assert the specific error.
- Failure of dependencies: timeout, 500 from an API, DB constraint violation.
- Regression: every bug fix gets a test named after the behavior it protects.
Use table-driven / parametrized tests (@pytest.mark.parametrize, test.each, Go table tests) when cases differ only in data.
4. Write them well
- Name = behavior:
returns_404_when_order_belongs_to_another_user. - Arrange / act / assert, visibly separated.
- Assert outcomes users care about (return values, HTTP responses, persisted rows, emitted events), not internal calls, unless the call is the behavior (e.g. “sends exactly one email”).
- Deterministic: freeze or inject time, seed randomness, no sleeps (use fake timers / polling with timeout), no dependence on test order, no real external network.
- Mocks at boundaries only (third-party HTTP, payment, email, clock). Over-mocking produces tests that pass while the product is broken.
- Test data: builders/factories with sensible defaults, overriding only fields that matter for the test.
5. Verify the tests can fail
For at least the key tests, temporarily break the code (invert a condition, return early) and confirm the test fails, then restore. A test that cannot fail is noise.
6. Report
List the tests added (names), the command to run them, the result, and any gaps you deliberately left (e.g. “no test for the S3 timeout path - needs a fake S3 client”).
Coverage percentage is a hint, not a goal. 100% line coverage with weak assertions is worse than 70% with sharp ones.