【问题标题】:Mock requests.json after getting response in Python在 Python 中获得响应后模拟 requests.json
【发布时间】:2017-04-13 20:49:02
【问题描述】:

我有测试:

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,它不会导致错误但不起作用,它会返回真实数据。

如何模拟这个使用 requests 库的get_product_info

【问题讨论】:

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


    【解决方案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 很有用。

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 2018-08-09
      • 2017-01-12
      相关资源
      最近更新 更多