Python 3.3+unittestfunction
unittest.mock.patch()
mocks
A decorator and a context manager that replace objects with mocks during a test. They isolate the code under test from its external dependencies.
Syntax
from unittest.mock import patch
@patch('module.ClassName')
def test(self, mock_cls): ...
with patch('module.func') as m: ...
The classic trap is patching the wrong place: patch the name where it is looked up, not where it was defined — if the module under test imported the name into its own namespace, patching the original module has no effect. With several stacked decorators the mocks arrive bottom-up, so the @patch closest to the function maps to the first parameter.
Examples
from unittest.mock import patch
import unittest
class Tests(unittest.TestCase):
@patch('builtins.input', return_value='42')
def test_input(self, mock_input):
self.assertEqual(input(), '42')
mock_input.assert_called_once()
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy