Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 937
Ryan Payne Avatar asked Jan 17 '20 23:01

Ryan Payne


1 Answers

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!"

Additional Options

You can also use one of the following alternatives.

1. pytest plugin for requests-mock

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!"

2. Context Manager

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!"
like image 102
Ryan Payne Avatar answered Oct 29 '22 02:10

Ryan Payne