简体   繁体   中英

python's mock return value of a method called within another method doesn't work

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM