Python in production · mid
Reliable pytest suites and mocking in the right place
Flaky tests usually share state, and a mock only works when you patch the name where it is looked up. Fixtures, monkeypatch and dependency injection keep tests independent.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Flaky tests that pass alone and fail in the full run share state: module-level settings or singletons, fixtures with a too wide scope returning mutable objects, patches never stopped, environment variables, caches, database rows not rolled back, shared files or ports between xdist workers, time zones, unseeded randomness and real network calls.
- Reproduce: random order with a fixed seed (pytest-randomly prints it), run with and without xdist (-n), --lf, and bisect the order.
- Fix: monkeypatch (undone automatically), function-scoped fixtures with yield teardown, tmp_path, a transaction per test or a database per xdist worker, an autouse fixture that clears caches, and frozen time.
- The 12:30 am case: the code uses the UTC date and the test uses the local IST date, which differ between midnight and 5:30 am IST.
- Quarantine known-flaky tests with an owner and a deadline instead of blind re-runs. Keep random order on and track the flake rate.
- Patch where the name is looked up, not where it is defined. If orders/service.py does from payments.gateway import charge, patch orders.service.charge, not payments.gateway.charge.
- A plain mock accepts any call. autospec=True or create_autospec checks signatures. mock.patch as a decorator or context manager and monkeypatch.setattr undo themselves.
- Better design: pass the gateway client in (dependency injection) with a fake that matches a Protocol. Block real network in unit tests (pytest-socket, respx or responses). Do not mock pure logic; contract tests against the sandbox run separately.
The red pen
Common traps: mistake → fix
Mistake: Re-run until green is a fix
Fix: it hides shared state.
Mistake: Add sleep to fix a flaky test
Fix: the cause is order or state, not time.
Mistake: Patch the definition site of a function
Fix: patch the module that imports it.
Mistake: Asserting that the mock was called is enough
Fix: check the arguments and the result too.
Easy to hard
Questions interviewers ask, easy to hard
- One CI run in five fails in different tests, and each passes alone. How do you fix it?
- Why does mock.patch not stop the real API call?
- What is the difference between mock and autospec?
- How do you make time-dependent tests stable?
- How does dependency injection make a service easier to test?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.