Python
patch
Learn patching with @patch.
patch
patch replaces an object with a Mock for the duration of a test and restores it when the test ends. It mimics a real function or class in a module.
It is used as a decorator or a context manager. As a decorator it injects a Mock parameter into the test function.
from unittest.mock import patch
@patch("mymodule.fetch")
def test_fetch(mock_fetch):
mock_fetch.return_value = 200
assert mymodule.fetch() == 200
The first string is the full path to the target (e.g. mymodule.fetch). After the test the real fetch is restored.
Target path and injection
The first string argument of patch is the full path of the target. For example "requests.get" or "os.getcwd". The path must be correct; otherwise patch raises an error.
As a decorator, patch injects parameters starting from the bottom decorator. With a single patch, the Mock goes to the first parameter of the test function.
You can also write with patch("x") as mock_x: as a context manager; it does the same job.
Exercise Greeting test with patch
The function greet(name) returns "Hello, " + name. Decorate test_greet(mock_upper) with @patch("builtins.str"). In the test body set mock_upper.return_value = "HELLO"; add assert greet("x"). At the end call test_greet(lambda *a, **k: "HELLO") and print("ok").
Show example solution
from unittest.mock import patch
def greet(name):
return "Hello, " + name
@patch("builtins.str")
def test_greet(mock_upper):
mock_upper.return_value = "HELLO"
greet("x")
print("ok")
test_greet(lambda *a, **k: "HELLO")
Test yourself
-
Add the patch decorator
from unittest.mock import patch
@____("mymodule.fetch")
def test_fetch(mock_fetch):
mock_fetch.return_value = 200
Show answer
from unittest.mock import patch
@patch("mymodule.fetch")
def test_fetch(mock_fetch):
mock_fetch.return_value = 200
-
Match the patch forms
- @patch("m.f")
- Decorator form
- with patch("m.f")
- Context manager
- mock_f.return_value
- Return value
- "m.f"
- Target path
-
What does the @patch decorator inject into the test function?
- The real target object
- It raises an error
- A bare None
- The Mock replacing the target
Show answer
The Mock replacing the target — patch injects the Mock that replaces the target into the test function.
Next lesson: MagicMock