1

I have some code that I would like to test, it is a fairly vanilla GET request wrapper, but the implementation of it requests data from the API multiple times with different IDs.

Adding mock JSON responses for the tests is problematic as there are hundreds of calls with these IDs and we want to test against one fixed response.

The target URI looks like https://someurl.com/api/v1/id/1234/data?params

The issue we are having is not wanting to add a line of code for every mock endpoint.

Eg. rather than have

mocker.get('https://someurl.com/api/v1/id/1234/data?params',
           json={},
           status_code=200)
mocker.get('https://someurl.com/api/v1/id/5678/data?params',
           json={},
           status_code=200)

I would like to implement some sort of wildcard matching, like this:

mocker.get(re.compile('https://someurl.com/api/v1/id/*/data?params'),
           json={},
           status_code=200)

This should be possible if I understand the docs correctly but this returns an error:

Failed: [undefined]requests_mock.exceptions.NoMockAddress: No mock address: GET https://someurl.com/api/v1/id/1234/data?params
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Phil Gunning
  • 212
  • 1
  • 8

1 Answers1

0

That's because * and ? are qualifiers in the regular expression syntax. Once you adjust the pattern to escape the question mark (\?) and turn the star to a greedy match-any qualifier (.*), things should work as expected:

>>> requests_mock.register_uri(
...     'GET',
...     re.compile(r'https://someurl.com/api/v1/id/.*/data\?params'),
...     json={},
...     status_code=200
... )
>>> requests.get('https://someurl.com/api/v1/id/1234/data?params').status_code
200
>>> requests.get('https://someurl.com/api/v1/id/lorem-ipsum-dolor-sit-amet/data?params').status_code
200
hoefling
  • 59,418
  • 12
  • 147
  • 194