Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock patch a function that doesn't exist on a class

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.

like image 952
Jesse Webb Avatar asked Aug 21 '15 15:08

Jesse Webb


People also ask

How do you mock a function in Python?

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 .

Can we mock a class in Python?

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.

What is MagicMock?

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.


1 Answers

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.

like image 171
Jonathan Anderson Avatar answered Sep 20 '22 03:09

Jonathan Anderson