1

I would like to mock a method for unit testing like this:

get_tree_test.py

from company.marketing_tree import get_tree

class MidNightTests(TestCase):
 @mock.patch("company.analytics.get_fb_data", autospec=True)
    def test_first_midnight(self, mock_fb_data):
        mock_fb_data.return_value = {}
        get_tree()

get_tree.py

from company.analytics import get_fb_data

def get_tree():
    executor = ThreadPoolExecutor(max_workers=2)
    data_caller = executor.submit(get_data)
    info_caller = executor.submit(get_info)

def get_data():
    executor = ThreadPoolExecutor(max_workers=2)
    first_data = exeuctor.submit(get_fb_data)

I do see that mock_fb_data.return_value = {} is created as a mock object, but when I debug get_data() method I see that get_fb_data is a function and not a mock

What am I missing?

1 Answer 1

3

You need to patch the right place. Inside get_tree, you created a global name get_fb_data, which the code uses directly:

from company.analytics import get_fb_data

You need to patch that name, not the original company.analytics.get_fb_data name; patching works by replacing a name to point to the mock instead:

class MidNightTests(TestCase):
    @mock.patch("get_tree.get_fb_data", autospec=True)
    def test_first_midnight(self, mock_fb_data):
        mock_fb_data.return_value = {}
        get_tree()

See the Where to patch section of the unittest.mock documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.