CodeBlanks Logo Icon CodeBlanks

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.

Practice 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").

Starter code

main.py
# import patch from unittest.mock
# greet(name): return "Hello, " + name
# test_greet: decorate with @patch
# call test_greet with a simple Mock and print "ok"

Sample solution

main.py
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")

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add the patch decorator

Question
from unittest.mock import patch

@____("mymodule.fetch")
def test_fetch(mock_fetch):
    mock_fetch.return_value = 200
Answer
from unittest.mock import patch

@patch("mymodule.fetch")
def test_fetch(mock_fetch):
    mock_fetch.return_value = 200

Explanation: The patch decorator swaps the target for a Mock during the test.

2 Match the patch forms

Term Meaning
@patch("m.f") Decorator form
with patch("m.f") Context manager
mock_f.return_value Return value
"m.f" Target path

3 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 Correct answer

Explanation: patch injects the Mock that replaces the target into the test function.

All lessons in Advanced