How to mock an import
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Mocking an import in Python tests is really about replacing the dependency at the place where the code under test looks it up. If you patch the wrong path, the real dependency still runs, and the test becomes flaky, slow, or unexpectedly stateful.
Patch Where the Symbol Is Used
This is the rule that matters most. If service.py imports fetch_data from client.py, then tests should patch service.fetch_data, not client.fetch_data.
Patching client.fetch_data would not affect service.load_user after the import binding has already happened.
Patch Module Attributes With patch.object
If the module imports another module rather than a symbol, patch the attribute on that imported module object.
This is a clean pattern when the dependency is used as a module attribute rather than bound directly into the local namespace.
Replace Entire Modules With sys.modules
Sometimes you need to fake an optional dependency or inject a synthetic module before import time. In that case, sys.modules can be useful.
In real tests, use fixtures or context-managed setup so the fake module does not leak into unrelated tests.
Use autospec When You Want Stricter Mocks
Loose mocks are convenient, but they can silently accept wrong arguments. autospec=True makes the patched object respect the original signature more closely.
This helps catch call-signature drift when real functions change over time but tests still pass because the mock accepts anything.
Sometimes the Best Fix Is Better Design
Heavy import mocking often signals tight coupling. If a class or function can accept a dependency explicitly, tests become simpler and less fragile.
Now the test can provide a fake client directly instead of patching imports deep in the module graph. That usually leads to clearer tests and cleaner production code.
Pytest Fixtures Make Repeated Mocking Cleaner
In pytest projects, fixtures are a good way to centralize common patches.
This avoids duplicated setup code and makes teardown automatic.
Validate More Than Call Counts
A mock assertion such as assert_called_once_with is useful, but it should not be the only assertion. Good tests usually check both how the dependency was called and what the business logic returned.
That matters because a test can pass on interaction alone while still hiding a broken return value, incorrect transformation, or swallowed exception.
Common Pitfalls
The biggest mistake is patching the definition site instead of the usage site. In Python, import binding means those are often different paths.
Another issue is leaving patched objects active beyond the intended scope. Leaky mocks contaminate other tests and are hard to diagnose in larger suites.
Developers also overuse mocks for simple collaborators that could just be lightweight fake objects. Excessive patching can make tests obscure and brittle.
Finally, if an import is hard to mock cleanly, that is often a design hint. The code may need a clearer dependency boundary rather than a more clever patch.
Summary
- Patch the dependency where the code under test looks it up, not where it was originally defined.
- Use
patch.objectwhen a module attribute is the thing being called. - Use
sys.modulesinjection only when you need to fake an entire module at import time. - Add
autospecwhen you want mocks to respect real call signatures. - Prefer explicit dependency injection when mocking imports starts to dominate the test design.
Related reading
- How to modify list entries during for loop?
- How to monitor queue health in celery
- How to move a model between two Django apps Django 1.7
- How to Multi-thread an Operation Within a Loop in Python
- How to mock AWS DynamoDB service?
- How to mock JWT authentication in a Spring Boot Unit Test?
- How to normalize a NumPy array to within a certain range?
- How to obtain a Thread id in Python?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.