Python: Mock() and @patch

unittest.mock was added to the Python standard library with Python 3.3.

Mock()

replace method of object

import unittest.mock

class MyClass:
    def my_method(self, x):
        raise NotImplementedError()

my_obj = MyClass()
my_obj.my_method = unittest.mock.Mock()
my_obj.my_method(3)

set return value

import unittest.mock

class MyClass:
    def my_method(self, x):
        raise NotImplementedError()

my_obj = MyClass()
my_obj.my_method = unittest.mock.Mock()
my_obj.my_method.return_value = 7
assert my_obj.my_method(3) == 7

return values on successive calls

import unittest.mock

class MyClass:
    def my_method(self, x):
        return 2 * x

my_obj = MyClass()
my_obj.my_method = unittest.mock.Mock()
my_obj.my_method.side_effect = [14, 16]
assert my_obj.my_method(7) == 14
assert my_obj.my_method(8) == 16

raise an exception

import unittest.mock

class MyClass:
    def my_method(self, x):
        return 2 * x

my_obj = MyClass()
my_obj.my_method = unittest.mock.Mock()
my_obj.my_method.side_effect = [14, Exception('bam!')]
assert my_obj.my_method(7) == 14
exception_caught = False
try:
    assert my_obj.my_method(8) == 16
except:
    exception_caught = True
assert exception_caught

replace object

import unittest.mock

class MyClass:
    def my_method(self):
        raise NotImplementedError()

my_obj = unittest.mock.Mock()
my_obj.my_method.return_value = 8
assert my_obj.my_method() == 8

replace attribute of object

import unittest.mock

class MyClass:
    def __init__(self):
        self.my_attribute = 7

my_obj = unittest.mock.Mock()
my_obj.my_attribute = 8
assert my_obj.my_attribute == 8

assert method called

import unittest.mock

class MyClass:
    def my_method(self, x):
        return 2 * x

my_obj = MyClass()
my_obj.my_method = unittest.mock.Mock()
my_obj.my_method.side_effect = [14, 16]
assert my_obj.my_method(7) == 14
my_obj.my_method.assert_called_with(7)
assert my_obj.my_method(8) == 16
my_obj.my_method.assert_called_with(8)

@patch

with

import logging
import unittest.mock

with unittest.mock.patch('logging.error') as mock_logging_error:
    logging.error('mock call')

logging.error('unmocked call')

patch method

patch class

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License