How to reuse requests_mock in many tests

There are different testing functions that read from the same api.

Eg.: GET: https://my.api/people

I want to mock the response of this request. Hence I'm using requests_mock library.

Imagine the following tests:

def test_get_people_names():
   names = [name for name in people_service.getPeople()] # this goes to the API GET URL
   assert len(names) > 0

def test_get_people_ages():
   ages = [age for age in people_service.getPeople()]
   assert len(ages) > 0

With this code, I want to test that people_service is doing its trick to access the correct API, not the API functionality.

With requests_mock I saw that I can do:

def test_get_people_ages(requests_mock):
   requests_mock.get('https//my.api/people', text=SOME_JSON)
   ages = [age for age in people_service.getPeople()]
   assert len(ages) > 0

What could I do to avoid rewriting the same line (requests_mock.get...) for every test?

(If there's the need to change the API or json, I can change in only 1 place)

The thing is that this requests_mock doesn't look like it's a class (lowercased name) and can be used in a context management fashion (in this case, the class Mock).

Could I just use this Mock object here and there after passing this get argument? What would be the impact of this (not using context management or not using it locally)?


You could just create another fixture using the request_mock fixture.

@pytest.fixture
def your_requests_mock(requests_mock):
    # Use return to be able to access requests_mock attributes
    return requests_mock.get('https//my.api/people', text=SOME_JSON)

def test_get_people_ages(your_requests_mock):
    ...

As you can see, you can just apply that to all your test functions that should mock out the request and you are good to go.