I'm making an HTTP GET request using the requests library. 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.
E fixture 'm' not found
Why is the requests-mock decorator throwing a "fixture 'm' not found" error? 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). To resolve the error, use the workaround referenced in How to use pytest capsys on tests that have mocking decorators?.
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.
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.
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With