[英]Why is the requests-mock decorator pattern throwing a "fixture 'm' not found" error with pytest?
I'm making an HTTP GET request using the requests library.我正在使用请求库发出 HTTP GET 请求。 For example (truncated):例如(截断):
requests.get("http://123-fake-api.com")
I've written a test following the requests-mock decorator pattern.我已经按照请求模拟装饰器模式编写了一个测试。
import requests
import requests_mock
@requests_mock.Mocker()
def test(m):
m.get("http://123-fake-api.com", text="Hello!")
response = requests.get("http://123-fake-api.com").text
assert response.text == "Hello!"
When I run the test with pytest , I get the following error.当我使用pytest运行测试时,出现以下错误。
E fixture 'm' not found
Why is the requests-mock decorator throwing a "fixture 'm' not found" error?为什么请求模拟装饰器会抛出“找不到夹具‘m’”错误? And how do I resolve it?我该如何解决?
You're getting the error because the Requests Mock decorator is not recognized in Python 3 ( see GitHub issue ).您收到错误是因为在 Python 3 中无法识别 Requests Mock 装饰器(请参阅 GitHub 问题)。 To resolve the error, use the workaround referenced in How to use pytest capsys on tests that have mocking decorators?要解决该错误,请使用如何在具有模拟装饰器的测试中使用 pytest capsys 中引用的解决方法? . .
import requests
import requests_mock
@requests_mock.Mocker(kw="mock")
def test(**kwargs):
kwargs["mock"].get("http://123-fake-api.com", text="Hello!")
response = requests.get("http://123-fake-api.com")
assert response.text == "Hello!"
You can also use one of the following alternatives.您还可以使用以下替代方法之一。
Use Requests Mock as a pytest fixture .使用 Requests Mock 作为pytest fixture 。
import requests
def test_fixture(requests_mock):
requests_mock.get("http://123-fake-api.com", text="Hello!")
response = requests.get("http://123-fake-api.com")
assert response.text == "Hello!"
Use Requests Mock as a context manager .使用 Requests Mock 作为上下文管理器。
import requests
import requests_mock
def test_context_manager():
with requests_mock.Mocker() as mock_request:
mock_request.get("http://123-fake-api.com", text="Hello!")
response = requests.get("http://123-fake-api.com")
assert response.text == "Hello!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.