在 Python 中得到响应后模拟 requests.json
Mock requests.json after getting response in Python
我有测试:
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 测试中的 return_value
数据。我试过模拟 requests.json
和 requests.get.json
,两者都没有属性错误,我模拟了 the_file.MyClient.get_product_info
,它不会导致错误但不起作用,它 return是真实数据。
如何模拟这个使用请求库的 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
有用。
我有测试:
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 测试中的 return_value
数据。我试过模拟 requests.json
和 requests.get.json
,两者都没有属性错误,我模拟了 the_file.MyClient.get_product_info
,它不会导致错误但不起作用,它 return是真实数据。
如何模拟这个使用请求库的 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
有用。