[英]How to mock Requests Response using monkeypatch
I am trying to mock the response of api call with pytest in using monkeypatch but without success.我试图在使用 monkeypatch 时模拟 api 调用 pytest 的响应但没有成功。
In a file functions.py, I have a function call an external API to get data in json format and I want to test this function在文件 functions.py 中,我有一个 function 调用外部 API 以获取 json 格式的数据,我想测试这个 function
def api_call(url, token):
try:
headers = {"Authorization": "Bearer %s" % token['accessToken']}
session = requests.Session()
response = session.get(url, headers=headers)
json_data = response.json()
return json_data
except Exception as err:
print(f'Other error occurred: {err}')
My test function in file test_functions.py:我在文件 test_functions.py 中的测试 function:
from lib import requests
import functions as extfunction
class MockResponse:
def __init__(self, json_data):
self.json_data = json_data
def json(self):
return self.json_data
def test_api_call_get(monkeypatch):
fake_token = {'accessToken' : 'djksjdskjdsjdsljdsmqqqq'}
def mock_get(*args, **kwargs):
return MockResponse({'results': 'test', 'total_sum' : 2000})
monkeypatch.setattr(requests, 'get', mock_get)
# extfunction.api_call, which contains requests.get, uses the monkeypatch
fake_url = 'https://api-test/v2'
response = extfunction.api_call(fake_url, fake_token)
assert response['results'] == 'test'
assert response['total_sum'] == 2000
During test execution, my function api_call (using requests with Get Method) is not mocked and I have an error because function is really called with fake parameters (such as fake_token)在测试执行期间,我的 function api_call(使用带有 Get 方法的请求)没有被模拟,我有一个错误,因为 function 确实是用假参数(例如 fake_token)调用的
How can I do to fake my response?我该怎么做才能伪造我的回复?
Thanks谢谢
You should use the responses library, which is made for this purpose.您应该使用为此目的而创建的响应库。
A code snippet would look like:代码片段如下所示:
import functions as extfunction
import responses
@responses.activate
def test_api_call_get():
fake_token = {'accessToken' : 'djksjdskjdsjdsljdsmqqqq'}
responses.add(responses.GET, 'https://api-test/v2',
json={'results': 'test', 'total_sum' : 2000})
# extfunction.api_call, which contains requests.get, uses the monkeypatch
fake_url = 'https://api-test/v2'
response = extfunction.api_call(fake_url, fake_token)
assert response['results'] == 'test'
assert response['total_sum'] == 2000
The monkeypatch is modifying the requests function get(), as in monkeypatch 正在修改请求 function get(),如
response = requests.get(url, headers=headers)
When you are using requests.Session().get()当您使用 requests.Session().get()
This can be monkeypatched by modifying the Session class instead of the requests module.这可以通过修改 Session class 而不是请求模块来进行猴子修补。
monkeypatch.setattr(requests.Session, 'get', mock_get)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.