Kayavak / Recaps / Testing
Recaps · Volume 11
Testing
The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.
114
Key ideas
- Goal: justified confidence that a change is safe, at acceptable cost; tests are one layer among types, static analysis, review, observability and progressive delivery.
- Levels: unit, integration, contract, E2E, performance, chaos; lower is faster and more precise, higher is broader and slower.
- Shapes: the pyramid (many unit, few E2E), the trophy (integration-heavy, static analysis at the base), the honeycomb (for microservices, mostly integration and contract); choose by where your bugs actually come from.
- A good test is fast, deterministic, isolated, readable, tests behaviour not implementation, and fails for one clear reason.
- Coverage shows what was executed, not what was checked; use it to find untested code, not as a target.
- Flakiness is usually a race, shared state, time or environment; quarantine with an owner, never ignore.
- Shift left and right: test early in development and verify in production (canaries, synthetic checks, SLOs).
Numbers to remember
- Lab: unit ≈ 1 ms, integration ≈ 7 ms, E2E ≈ 0.4–0.5 s per test (≈500× a unit test).
- Lab: a 0.2 s sleep against a 50–300 ms response failed 33–42% of runs; auto-waiting failed 0%.
- 1,000 tests at 0.1% flakiness: suite green only 36.8% of the time.
Pitfalls
- Coverage targets that reward tests without assertions.
- Testing implementation details, so refactors break tests that should pass.
- Fixed sleeps in UI and async tests.
- One giant E2E suite as the main safety net.
- Tests sharing data or depending on order.
- Retrying failures silently instead of tracking flakes.
Glossary
- Test pyramid / trophy / honeycomb: models of how many tests to have at each level.
- System under test (SUT): what a test exercises.
- Deterministic: same inputs, same result, every run.
- Quarantine: running a known-flaky test outside the gating suite until fixed.
- Shift left: catching problems earlier in the development cycle.
115
Key ideas
- A unit is a unit of behaviour, not necessarily one class or function; test through its public interface.
- FIRST: fast, isolated, repeatable, self-validating, timely.
- Arrange-act-assert; one reason to fail; names that read as behaviour.
- Table-driven / parametrised tests for many cases; boundary values at every rule edge.
- Property-based tests (Hypothesis, jqwik, fast-check, proptest, rapid) for invariants, round-trips and model comparisons; shrinking gives minimal failures.
- Test doubles: stub, fake, mock, spy; prefer fakes and state checks; mock only real side effects.
- Hidden inputs (clock, TZ, randomness, env, global state) make tests flaky; inject them.
- Coverage finds untested code; mutation testing measures whether tests check behaviour.
- Concurrency: race detectors (
go test -race, TSan), stress and jcstress-style tests.
Numbers to remember
- Lab: weak suite 100% coverage but 6/18 mutants killed; boundary suite 17/18 (one equivalent).
- Lab: racy counter failed 10/20 plain runs, 100% under
-race; one lost-update run counted 9,576 of 10,000.
- A healthy unit test runs in about a millisecond; a whole unit suite should run in seconds.
Pitfalls
- Assertion-free or assert-something tests chasing coverage.
- Mocking everything, so tests break on refactors and miss real bugs.
- Testing private methods directly instead of behaviour.
- Real time, randomness or network in unit tests.
- Shared mutable fixtures leaking state between tests.
- Treating every surviving mutant as a missing test (some are equivalent).
Glossary
- Mutant / killed / survived: a deliberately bugged copy / detected by tests / not detected.
- Equivalent mutant: a change that doesn't alter behaviour.
- Fixture: reusable setup (pytest fixture, JUnit
@BeforeEach).
- Dependency injection: passing collaborators in so tests can substitute them.
- Data race: unsynchronised concurrent access where at least one is a write.
116
Key ideas
- Purpose: verify your code against real boundaries (databases, brokers, HTTP services, file systems, caches) where doubles encode only your assumptions.
- Same engine as production: same database and major version, started per run (Testcontainers, docker compose, a CI service container).
- Clean state per test: rollback, truncate, per-worker or per-test databases; migrations applied once per run.
- Concurrency bugs need real databases and deliberate interleaving (barriers, latches) to show deterministically.
- HTTP and service fakes (WireMock, httptest, MSW, respx) for success and every failure: errors, bad bodies, slowness, resets.
- Brokers: test serialisation, ordering, redelivery and idempotent consumers against a real Kafka, RabbitMQ or NATS.
- Scope: narrow integration tests (one adapter, one dependency) are fast and precise; broad ones go toward E2E.
Numbers to remember
- Lab: rollback 1.0 ms, truncate 7.0 ms, new connection 10.1 ms, fresh template database 120 ms per test.
- Lab: naive read-check-write oversold 20/20 runs; row lock 0/20.
- Lab: no timeout turned a 3 s provider hang into a 3 s request.
Pitfalls
- SQLite or H2 standing in for PostgreSQL or MySQL.
- Tests depending on data left by other tests; shared databases between parallel workers.
- Only testing happy paths against fakes.
- Mocking your own repository layer in "integration" tests.
- Clients without timeouts.
- Slow, broad integration suites that duplicate E2E tests.
Glossary
- Testcontainers: libraries that start real dependencies in throwaway containers for tests.
- Type affinity: SQLite's loose column typing.
- Template database: a PostgreSQL database copied to create fresh ones quickly.
- Service virtualisation: simulating a dependency's API and behaviour.
- Narrow vs broad integration test: one boundary vs many components together.
117
Key ideas
- Problem: independently deployed services must agree on interfaces; shared E2E environments are slow and brittle.
- Consumer-driven contracts (Pact): consumer tests against a mock provider produce a pact; the provider verifies it against the real service with provider states.
- Matchers capture shape and type, not incidental values; consumers ask for the minimum they use.
- Postel's law: be liberal in what you accept (ignore unknown fields); additive changes are safe.
- Broker workflow: publish pacts with versions and branches; record deployments;
can-i-deploy gates releases; webhooks trigger provider verification when a pact changes.
- Variants: message pacts for events; bi-directional contracts (provider's OpenAPI vs consumer pacts); schema-first contracts with OpenAPI/AsyncAPI/protobuf plus breaking-change checks (buf breaking, oasdiff).
- Evolution: expand and contract; version only when you must.
Numbers to remember
- Lab: consumer test 0.07 s; each provider verification 6–7 ms.
- Lab: rename of one field → FAILED with a key-level diff; added field → VERIFIED.
Pitfalls
- Consumers asserting on every field and exact values, freezing the provider.
- Using contract tests as functional tests of provider business logic.
- Provider verification not run on every provider change (or not gating deploys).
- Pacts not versioned by consumer branch and environment.
- Strict deserialisers that reject unknown fields, making additive changes breaking.
Glossary
- Pact: the contract file of interactions.
- Mock provider: Pact's stand-in the consumer test calls.
- Provider state: named setup the provider performs before an interaction.
- Pact Broker / PactFlow: service storing pacts and verification results.
- can-i-deploy: check that a version is compatible with what's deployed in an environment.
118
Key ideas
- Purpose: verify a few critical journeys through the assembled system as a user would; the rest belongs lower in the stack.
- Playwright: auto-waiting actions, web-first assertions (
expect), isolated browser contexts, fixtures, network interception, tracing, codegen, multi-browser (Chromium, Firefox, WebKit).
- Locators: role, label, text first;
data-testid when nothing user-facing exists; avoid CSS/XPath tied to structure.
- Determinism: no sleeps; own your test data (create it per test or seed it); isolate contexts; control time and third parties.
- Speed: reuse authentication state, parallelise to the hardware, shard across machines, run the smallest critical set on every change and the rest nightly.
- Evidence: traces, videos and screenshots retained on failure.
- Beyond functional: accessibility checks (axe), visual comparisons, cross-browser runs.
Numbers to remember
- Lab: about 0.55 s per journey locally; a redesign broke the CSS test and not the user-facing one.
- Lab: 2 workers on 2 cores gave 1.4×; 8 workers were 1.4× slower than serial.
- Lab: a failing run's trace was 18 KiB with 4 screenshots and 2 network requests.
Pitfalls
- Hundreds of E2E tests as the main safety net.
- Fixed sleeps; CSS selectors tied to styling.
- Tests sharing accounts or data, failing when run in parallel.
- Logging in through the UI in every test.
- Mocking your own backend in "end-to-end" tests.
- Retrying failures without reading traces.
Glossary
- Browser context: an isolated session (cookies, storage) inside one browser.
- Web-first assertion: an assertion that retries until it passes or times out.
- Storage state: saved cookies and local storage used to skip login.
- Sharding: splitting a suite across machines.
- Trace viewer: Playwright's tool for replaying a recorded run.
119
Key ideas
- Questions first: capacity, latency at expected load, breaking behaviour, regressions, long-run stability.
- Vocabulary: throughput, latency percentiles (not averages), concurrency, utilisation, saturation, errors.
- Little's law: concurrency = throughput × latency; use it to sanity-check results and size pools.
- Open vs closed workload models: open (arrival rate) matches real traffic and reveals overload; closed (fixed users) hides it.
- Near capacity, latency rises steeply; above it, queues grow without bound.
- Test types: smoke, load, stress, spike, soak, breakpoint.
- Tools: k6, Gatling, JMeter, Locust, wrk2/vegeta for HTTP; thresholds make tests gates.
- Trustworthy results: realistic workload and data, production-like environment, separate load generators, warm-up, repeated runs, baselines, and watch for coordinated omission and dropped arrivals.
Numbers to remember
- Lab: capacity 4 slots ÷ 20 ms = 200/s; measured plateau ≈ 191/s.
- Lab: 180/s → p95 32 ms; 210/s → p95 1.01 s (5% over capacity).
- Lab: 20 → 25 ms per request cut capacity 20% and made p95 at 150/s 2.7× worse.
- k6 exits 99 when thresholds fail.
Pitfalls
- Reporting averages; ignoring tail percentiles.
- Closed-model tests that slow down with the system and never find the cliff.
- Load generator on the same busy machine, or itself saturated (dropped iterations).
- Testing with tiny or unrealistic data sets and cold caches without saying so.
- Single runs compared with no baseline; noisy shared CI runners.
- Testing only below capacity.
Glossary
- VU: virtual user in k6.
- Arrival rate: requests started per second in an open model.
- Saturation: a resource at its limit, with work queueing.
- Soak test: long run to find leaks and degradation.
- Coordinated omission: a measurement flaw where slow responses suppress the requests that would have recorded the delay.
120
Key ideas
- Principles: define steady state in measurable terms; hypothesise it holds under a fault; inject realistic faults; minimise blast radius; automate; run continuously.
- Faults to inject: dependency latency, errors, hangs, resets; instance and pod loss; zone loss; resource exhaustion; clock skew; bad config; expired credentials.
- Patterns under test: timeouts and deadlines, retries with backoff, jitter and budgets, idempotency, fallbacks and graceful degradation, bulkheads, circuit breakers, load shedding.
- Safety: start in test, then a small slice of production; abort conditions from monitoring; rollback automated; people informed.
- Tools: Toxiproxy (network), Chaos Mesh and LitmusChaos (Kubernetes), AWS FIS and Azure Chaos Studio (cloud), Gremlin, and plain
kill, tc netem and stress-ng.
- Game days: rehearsed experiments with the team watching, to test people and runbooks as well as software.
Numbers to remember
- Lab: 1 s of DB latency → naive service 3.5% success, p50 5 s; resilient service 100% success, p50 151 ms.
- Lab: naive service's backlog kept p95 at 4.4 s after the fault ended.
- Lab: probe-based abort took 7.1 s; a monitoring-based abort should take a couple of seconds.
Pitfalls
- Chaos without a hypothesis or steady-state metric ("let's see what happens").
- Starting in production at full scope; no abort or rollback.
- Fallbacks that serve stale data where staleness is harmful.
- Counting degraded responses as healthy without marking them.
- Retries without budgets amplifying the outage.
- Experiments chosen at random rather than from incidents and architecture.
Glossary
- Steady state: measurable normal behaviour.
- Blast radius: scope of potential impact.
- Abort condition: a limit that stops an experiment.
- Toxic: a Toxiproxy fault (latency, timeout, reset_peer…).
- Graceful degradation: reduced but useful service under failure.
- Game day: a planned, team-wide failure exercise.