python - 在 Python 中获得响应后模拟 requests.json

标签 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

最佳答案

您应该能够只修补 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有用。

关于python - 在 Python 中获得响应后模拟 requests.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401459/

相关文章:

Python 单元测试 : How to unit test the module which contains database operations?

python - 使用 unittest.mock 在 python 中修补 SMTP 客户端

python-3.x - 在 python 中模拟 BigQuery 连接

python - 小型物联网设备数据库

unit-testing - JSON渲染对于ControllerUnitTestCase中的域对象失败

python - 在 Sklearn Pipeline 中组合功能

unit-testing - 带有 ngrx 的 angular 2 组件 - 运行单元测试时出错

c# - 如何使用 InMemory 数据库检查在单元测试中正确添加的记录

python - 我如何从文本文件中读取包含函数的字典?

python - 如何以模块化的方式设计应用程序?