[英]`requests_mock` applies to all requests even if they are not set and throws NoMockAddress exception
I found that requests_mock
used as a fixture with pytest
applies to all requests even if they are not set.我发现requests_mock
用作pytest
的夹具适用于所有请求,即使它们没有设置。
I'm not sure if it's a requests_mock
/ pytest
bug or I'm missing something.我不确定它是requests_mock
/ pytest
错误还是我遗漏了什么。 Eventually, I don't need to mock 'api-b' call but I can't find out how to avoid it.最终,我不需要模拟 'api-b' 调用,但我不知道如何避免它。
def test_reqs(requests_mock):
requests_mock.get('https://api-a.com/')
requests.get('https://api-b.com/')
assert requests.get('https://api-a.com/')
I'm writing integration tests using pytest
, requests-mock
, and pytest-mock
for an API endpoint.我正在使用pytest
、 requests-mock
和pytest-mock
为 API 端点编写集成测试。 Under the hood, this endpoint makes several calls to different third party API's that I need to mock.在幕后,此端点多次调用我需要模拟的不同第三方 API。
Some of those calls can be mocked by requests_mock
.其中一些调用可以被requests_mock
模拟。 But some of them can't because they make a call from the inside of a third-party module.但其中一些不能,因为它们是从第三方模块内部进行调用的。
I tried to use pytest-mock
to mock the last one and found out that it basically doesn't work.我尝试使用pytest-mock
模拟最后一个,发现它基本上不起作用。 requests_mock
is still trying to mock that call and throws the next error: requests_mock.exceptions.NoMockAddress: No mock address: GET https://api-b.com/
requests_mock
仍在尝试模拟该调用并抛出下一个错误: requests_mock.exceptions.NoMockAddress: No mock address: GET https://api-b.com/
As requests-mock
doc says, you can achieve this behavior by setting real_http=True
while initiating the requests_mock.Mocker()
.正如requests-mock
文档所说,您可以通过在启动requests_mock.Mocker()
时设置real_http=True
来实现此行为。
with requests_mock.Mocker(real_http=True) as m:
m.get('http://test.com', text='resp')
requests.get('http://test.com').text
But nothing said of how to use it with pytest
.但是没有说如何将它与pytest
一起使用。 As pytest
test receives request_mock object as an argument (fixture), you can set it in your test explicitly.由于pytest
测试接收 request_mock 对象作为参数(夹具),您可以在测试中显式设置它。
def test_reqs(requests_mock):
requests_mock.real_http = True
requests_mock.get('https://api-a.com/')
requests.get('https://google.com/')
assert requests.get('https://api-a.com/')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.