what is it?
flexible mock object intended to replace the use of stubs and test doubles. callable; creates attributes as new mocks when you access them. records how you use them, allowing you to make assertions about what your code has done to them
example
examples from here
from unittest.mock import Mock
mock = Mock()
print(mock) # <Mock id='4561344720'>
# mock is not an object that we can use in our code
# we can pass it as an argument:
do_something(mock)
# we can also use it to patch an entire library:
json = mock
# we can run functions off our mock
json.loads('{"key": "value"}')
# and we can assert that our function was invoked:
json.loads.assert_called()patch
patch() decorators makes it easy to temporarily replace classes in a particular module with a Mock object
def complex_function():
# this function can do whatever
# it currently returns nothing
print('we did nothing')
def function_one():
# we will get a specific response if our function returns 'banana'
if complex_function() == 'banana':
return 'the patch worked'
return 'failure'from unittest.mock import patch
from python_practice import function_one
@patch('python_practice.complex_function', return_value='banana')
def test_function_one(self):
# setup
expected_result = 'the patch worked'
# act
actual_result = function_one()
#verify
assert actual_result == expected_result