unittest.mock.patch: Replace Dependencies in Tests
What you’ll learn
Section titled “What you’ll learn”- How
patchreplaces a name for the duration of a test and restores it afterwards, as a decorator, a context manager or inside a pytest fixture. - The rule that causes most broken mocks: patch where the name is looked up, not where it is defined.
- How to script a mock with
return_valueandside_effect(values, sequences, exceptions) and verify calls withassert_called_once_withandcall_args_list. - Why
autospec=Trueshould be your default, and whatpatch.object,patch.dictandAsyncMockadd. - When to stop mocking and change the design instead.
Summary
Section titled “Summary”unittest.mock.patch(target, ...) imports the object named by the dotted string target, replaces it with a mock (a MagicMock, or an AsyncMock for async functions) or with an object you supply, and puts the original back when the decorated function or with block exits, even if it raises. It is part of the standard library since Python 3.3 and is current in Python 3.14. It works the same in unittest and pytest tests.
The problem it solves
Section titled “The problem it solves”OrdersPortal’s checkout charges a card through a payment gateway client that makes an HTTPS request. A unit test of the checkout logic should not depend on the network, a sandbox account, or the gateway’s latency.
The samples on this page are pytest modules: install pytest in a virtual environment, save the files in one folder and run pytest -v. They were run with pytest 9.2.0 on CPython 3.14.6; header lines are trimmed from the output.
import jsonfrom urllib.request import Request, urlopen
class PaymentDeclined(Exception): pass
class PaymentGateway: BASE_URL = "https://payments.example.test"
def charge(self, order_id: str, amount_cents: int, *, idempotency_key: str) -> str: body = json.dumps({"order_id": order_id, "amount_cents": amount_cents}).encode() request = Request(f"{self.BASE_URL}/charges", data=body, headers={"Idempotency-Key": idempotency_key}) with urlopen(request, timeout=5) as response: return json.load(response)["charge_id"]from payments import PaymentDeclined, PaymentGateway # checkout looks up PaymentGateway here
def checkout(order_id: str, amount_cents: int) -> dict: gateway = PaymentGateway() key = f"checkout-{order_id}" # same key on retry, so the gateway never double-charges for attempt in (1, 2): try: charge_id = gateway.charge(order_id, amount_cents, idempotency_key=key) except TimeoutError: if attempt == 2: raise continue except PaymentDeclined as exc: return {"order_id": order_id, "status": "payment_failed", "reason": str(exc)} return {"order_id": order_id, "status": "paid", "charge_id": charge_id}A test without patching really calls the network. example.test is a reserved name that never resolves, so it fails the way a test does when the network or sandbox is unavailable:
from checkout import checkout
def test_checkout_without_patch(): assert checkout("ORD-1001", 2500)["status"] == "paid"E socket.gaierror: [Errno -2] Name or service not knownE urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>1 failed in 0.13sEven with a working sandbox, the test would be slow and could not easily force a timeout or a declined card.
How it works
Section titled “How it works”patch has the signature patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs).
- Target. A string such as
"checkout.PaymentGateway". The module part is imported when the test runs (not at decoration time), and the attribute is replaced withsetattr. Extra keyword arguments configure the mock, for examplereturn_value=64. - Forms. As a decorator, the mock is passed to the test as an extra argument; as a context manager,
with patch(...) as m:binds it;p.start()/p.stop()control it manually. A pytest fixture thatyields insidewith patch(...)makes it reusable, as the realistic example shows. - Restoration. The original is put back on exit, even if the test fails. By default
patchrefuses to replace an attribute that does not exist;create=Trueoverrides that, which lets tests pass against an API that does not exist.
Patch where the name is looked up
Section titled “Patch where the name is looked up”patch changes one name. checkout.py ran from payments import PaymentGateway, which copied a reference into the checkout module namespace at import time. Patching payments.PaymentGateway replaces the other name, and checkout keeps using the real class:
from unittest.mock import patchfrom urllib.error import URLError
import pytest
from checkout import checkout
def test_patching_where_defined_misses(): # checkout.py did `from payments import PaymentGateway`, so it holds its own # reference. Replacing payments.PaymentGateway does not change that reference. with patch("payments.PaymentGateway") as gateway_cls: with pytest.raises(URLError): # the real class ran and tried the network checkout("ORD-1001", 2500) gateway_cls.assert_not_called()
def test_patching_where_looked_up_works(): with patch("checkout.PaymentGateway") as gateway_cls: gateway_cls.return_value.charge.return_value = "ch_1001" assert checkout("ORD-1001", 2500)["status"] == "paid" gateway_cls.assert_called_once_with()test_where.py::test_patching_where_defined_misses PASSED [ 50%]test_where.py::test_patching_where_looked_up_works PASSED [100%]If checkout.py had used import payments and called payments.PaymentGateway(), the lookup would happen in the payments module at call time, and "payments.PaymentGateway" would be the right target.
Scripting and checking the mock
Section titled “Scripting and checking the mock”return_valueis what a call returns. For a patched class,cls.return_valueis the instance the code creates, socls.return_value.charge.return_valuesets whatinstance.charge()returns.side_effectoverrides that: an exception (class or instance) is raised, an iterable supplies one result per call (exception items are raised), and a function is called with the same arguments.- Assertions include
assert_called_once_with(...),assert_called_with(...)(last call only),assert_not_called(),assert_any_call(...),call_count,call_argsandcall_args_list, which compares againstcall(...)objects. Async mocks addassert_awaited_once_with(...)and friends.
Other patchers and specs
Section titled “Other patchers and specs”import asyncioimport osfrom unittest.mock import AsyncMock, MagicMock, create_autospec, patch
import pytest
from payments import PaymentGateway
class OrderApiClient: async def fetch_status(self, order_id: str) -> str: raise RuntimeError("would call the network")
def test_patch_object_creates_async_mock_for_async_methods(): with patch.object(OrderApiClient, "fetch_status", return_value="shipped") as fetch: assert isinstance(fetch, AsyncMock) assert asyncio.run(OrderApiClient().fetch_status("ORD-7")) == "shipped" # A plain mock on the class is not a method, so `self` is not recorded. fetch.assert_awaited_once_with("ORD-7")
@patch.dict(os.environ, {"ORDERSPORTAL_REGION": "eu"})def test_patch_dict_sets_environment(): assert os.environ["ORDERSPORTAL_REGION"] == "eu"
def test_patch_dict_restored_afterwards(): assert "ORDERSPORTAL_REGION" not in os.environ
@patch("os.cpu_count", return_value=64) # applied last -> second mock argument@patch("os.getcwd", return_value="/srv") # applied first -> first mock argumentdef test_stacked_decorators_inject_bottom_up(mock_getcwd, mock_cpu_count): assert (os.getcwd(), os.cpu_count()) == ("/srv", 64)
def test_plain_mock_accepts_any_call_but_autospec_does_not(): loose = MagicMock() loose.charge("ORD-1", 100, idem_key="k") # wrong keyword: silently accepted strict = create_autospec(PaymentGateway, instance=True) with pytest.raises(TypeError, match="missing a required keyword-only argument: 'idempotency_key'"): strict.charge("ORD-1", 100, idem_key="k")test_tools.py::test_patch_object_creates_async_mock_for_async_methods PASSED [ 20%]test_tools.py::test_patch_dict_sets_environment PASSED [ 40%]test_tools.py::test_patch_dict_restored_afterwards PASSED [ 60%]test_tools.py::test_stacked_decorators_inject_bottom_up PASSED [ 80%]test_tools.py::test_plain_mock_accepts_any_call_but_autospec_does_not PASSED [100%]patch.object(obj, "attr")patches an attribute on an object you already hold, so there is no string to get wrong.patch.dict(mapping, values)sets keys for the test and restores the dictionary afterwards;clear=Truestarts from empty.AsyncMockis created automatically when the target is an async function (Python 3.8+); calling it returns an awaitable.- Stacked decorators apply bottom-up, so the bottom decorator’s mock is the first extra argument.
- Specs. A bare
MagicMockaccepts any attribute and any call.spec/spec_setrestrict attribute names;autospec=True(orcreate_autospec) also checks call signatures recursively, so the test fails when the real API changes. Separately, mocks raiseAttributeErrorfor misspelled assertion names such asassret_called_onceorcalled_once_with, but nothing catches a typo in a configuration attribute likereturn_vlaueexcept a spec.
Realistic example
Section titled “Realistic example”The checkout tests put the patch in a fixture, use autospec=True so the mock matches PaymentGateway’s real signature, and drive the retry and decline paths with side_effect. Fixtures are covered on the pytest fixtures page; asserting on raised exceptions on the pytest.raises page.
from unittest.mock import call, patch
import pytest
from checkout import checkoutfrom payments import PaymentDeclined
@pytest.fixturedef gateway(): # autospec: the mock has PaymentGateway's real methods and signatures. with patch("checkout.PaymentGateway", autospec=True) as gateway_cls: yield gateway_cls.return_value # the instance checkout() creates
def test_successful_checkout(gateway): gateway.charge.return_value = "ch_1001" assert checkout("ORD-1001", 2500) == {"order_id": "ORD-1001", "status": "paid", "charge_id": "ch_1001"} gateway.charge.assert_called_once_with("ORD-1001", 2500, idempotency_key="checkout-ORD-1001")
def test_timeout_is_retried_with_the_same_idempotency_key(gateway): gateway.charge.side_effect = [TimeoutError("gateway timed out"), "ch_1002"] # one item per call assert checkout("ORD-1002", 990)["status"] == "paid" expected = call("ORD-1002", 990, idempotency_key="checkout-ORD-1002") assert gateway.charge.call_args_list == [expected, expected]
def test_second_timeout_propagates(gateway): gateway.charge.side_effect = TimeoutError("gateway timed out") # raised on every call with pytest.raises(TimeoutError): checkout("ORD-1003", 990) assert gateway.charge.call_count == 2
def test_declined_payment_is_reported(gateway): gateway.charge.side_effect = PaymentDeclined("insufficient funds") result = checkout("ORD-1004", 12000) assert result == {"order_id": "ORD-1004", "status": "payment_failed", "reason": "insufficient funds"}test_checkout.py::test_successful_checkout PASSED [ 25%]test_checkout.py::test_timeout_is_retried_with_the_same_idempotency_key PASSED [ 50%]test_checkout.py::test_second_timeout_propagates PASSED [ 75%]test_checkout.py::test_declined_payment_is_reported PASSED [100%]
============================== 4 passed in 0.27s ===============================The retry test checks a business rule (both attempts reuse the idempotency key) that is hard to provoke against a real gateway. Without autospec, renaming idempotency_key in PaymentGateway would leave these tests green while production breaks.
Common mistakes
Section titled “Common mistakes”- Patching where the object is defined. After
from payments import PaymentGateway, patch"checkout.PaymentGateway". The test above shows the wrong target silently running real code. - Mocks without a spec. A plain
MagicMockaccepts calls with wrong arguments and attributes that do not exist. Useautospec=Truefor anything with a real interface. - Asserting only on mocks. A test that checks
assert_called_once_withbut never the function’s result tests the implementation, not the behavior. Assert outcomes first; check calls when the call itself is the contract (charging, sending, deleting). - Patching what you own deep inside. If a test needs five patches, the unit has too many hidden dependencies. Pass the dependency in (a parameter or constructor argument) and use a fake.
- Forgetting
selfwithautospecon a class attribute.patch.object(OrderApiClient, "fetch_status", autospec=True)recordsselfas the first argument; without autospec it does not. - Patching
datetime.datetime.now. Built-in types cannot be patched attribute by attribute. Patch the module-level name your code uses ("orders.datetime") with a mock whosenowreturns a fixed value, or inject a clock. - Leaving a manual patcher running. After
p.start(), registerp.stop()in a cleanup or fixture teardown.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Tool | Notes |
|---|---|---|
| Replace a network, payment, email or clock dependency | patch(..., autospec=True) |
Patch where it is looked up |
| Set environment variables or a config dict | patch.dict or pytest monkeypatch.setenv |
Both restore on exit |
| Simple attribute swap in a pytest test | monkeypatch.setattr |
Same lookup rule; no call recording |
| Verify calls, arguments and order | Mock/MagicMock assertions |
Use only when the call is the contract |
| Your own collaborator with a small interface | A fake class passed in as a parameter | No patching, clearer tests |
| Integration with the real service | No mock; a sandbox and a separate test suite | Catches what mocks cannot |
Compatibility
Section titled “Compatibility”unittest.mock has been in the standard library since Python 3.3 (earlier as the third-party mock package). patch returns an AsyncMock for async targets since Python 3.8, ThreadingMock was added in 3.13, and seal() (which stops a mock creating new attributes) in 3.7. Everything on this page runs unchanged on Python 3.14.
Interview questions
Section titled “Interview questions”1. orders.py does from payments import PaymentGateway. Which target do you patch, and why?
"orders.PaymentGateway". The import copied a reference into orders’ namespace, and patch replaces a name, not the object. Patching payments.PaymentGateway changes a name orders never looks at again.
2. What is the difference between return_value and side_effect?
return_value is returned by every call. side_effect, when set, takes precedence: an exception is raised, an iterable supplies one result per call, and a function is called with the call’s arguments (its return value is used unless it returns DEFAULT).
3. Why prefer autospec=True?
It builds the mock from the real object, so missing attributes raise AttributeError and calls with the wrong signature raise TypeError. Without it, tests keep passing after the real API changes.
4. Senior scenario: OrdersPortal’s service layer has tests with six stacked @patch decorators each, and every refactor breaks dozens of tests even when behavior is unchanged. What do you change?
The tests are coupled to import paths and call details instead of behavior. Introduce explicit dependencies: pass the gateway, mailer and clock into the service (constructor or function parameters), and write small in-memory fakes that behave like the real thing. Unit tests then construct the service with fakes and assert on outcomes; patch remains for true edges you do not control (third-party clients, time), always with autospec. Add a thin contract or integration suite against the real gateway’s sandbox so the fakes are kept honest.
Key takeaways
Section titled “Key takeaways”patchtemporarily replaces a name and always restores it, as a decorator, context manager or inside a fixture.- Patch where the name is looked up, which after
from x import yis the importing module. - Script mocks with
return_valueandside_effect; verify calls only when the call is the contract. - Use
autospec=Trueso mocks fail when the real interface changes. - Heavy patching is a design smell; inject dependencies and use fakes.
Related pages
Section titled “Related pages”- pytest fixtures: wrapping a patch in a reusable fixture, and
monkeypatch. - pytest.raises: asserting on errors produced by
side_effect. - pytest parametrize: running one patched test against many inputs.
- async/await: the coroutines
AsyncMockstands in for. - Context managers: how
with patch(...)restores state. - Imports: why
from x import ycreates a separate name.