Using Python's mock framework, is it possible to mock patch a function that doesn't exist on a class. If so, how?
For example:
example.py
import mock
import unittest
class MyClass(object):
pass
class MyTests(unittest.TestCase):
def test_mock_non_existent_function(self):
with mock.patch('example.MyClass.my_function'):
pass
Running that test raises an error:
Error
Traceback (most recent call last):
File "/Users/jesse/Code/my_proj/lib/mock.py", line 1193, in patched
File "/Users/jesse/Code/my_proj/lib/mock.py", line 1268, in __enter__
File "/Users/jesse/Code/my_proj/lib/mock.py", line 1242, in get_original
AttributeError: <class 'example.MyClass'> does not have the attribute 'my_function'
Using Python 2.7.9
and mock 1.0.1
.
How do we mock in Python? Mocking in Python is done by using patch to hijack an API function or object creation call. When patch intercepts a call, it returns a MagicMock object by default. By setting properties on the MagicMock object, you can mock the API call to return any value you want or raise an Exception .
Once you patch a class, references to the class are completely replaced by the mock instance. mock. patch is usually used when you are testing something that creates a new instance of a class inside of the test.
To begin with, MagicMock is a subclass of Mock . class MagicMock(MagicMixin, Mock) As a result, MagicMock provides everything that Mock provides and more. Rather than thinking of Mock as being a stripped down version of MagicMock, think of MagicMock as an extended version of Mock.
I believe the answer here is to use the create
parameter:
with mock.patch.object(MyClass, 'my_function', create=True)
This works when replacing the equivalent line in the original code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With