获得响应python后模拟requests.json

时间:2017-04-13 20:49:02

标签: python unit-testing python-unittest.mock

我有测试

class MyTests(TestCase):

    def setUp(self):
        self.myclient = MyClient()

    @mock.patch('the_file.requests.json')
    def test_myfunc(self, mock_item):
        mock_item.return_value = [
                    {'itemId': 1},
                    {'itemId': 2},
        ]
        item_ids = self.myclient.get_item_ids()
        self.assertEqual(item_ids, [1, 2])

在我有的文件中

import requests

class MyClient(object):

    def get_product_info(self):
            response = requests.get(PRODUCT_INFO_URL)
            return response.json()

我的目标是模拟get_product_info()以返回测试中的return_value数据。我曾尝试模仿requests.jsonrequests.get.json,两个错误都没有属性,我嘲笑the_file.MyClient.get_product_info这不会导致错误但不起作用,它会返回真实数据。

如何模拟使用请求库的get_product_info?谢谢

1 个答案:

答案 0 :(得分:1)

您应该能够修补get_product_info()

from unittest.mock import patch


class MyClient(object):
    def get_product_info(self):
        return 'x'

with patch('__main__.MyClient.get_product_info', return_value='z'):
    client = MyClient()
    info = client.get_product_info()
    print('Info is {}'.format(info))
    # >> Info is z

只需将__main__切换为模块名称即可。您可能还会发现patch.object有用。