15

I'm currently trying to do unit tests using the requests_mock library in order to patch requests. I've written the following code:

def test_general_search(requests_mock):
    params = {'query': 'testsetset', 'exact': 0, 'max_pages': '1', 'category': 'username'}
    requests_mock.get(f'{MOCK_ADDRESS}', json=MOCK_RESPONSE)
    client = Client(MOCK_ADDRESS, auth=MOCK_CREDS, headers=MOCK_HEADERS)
    res = general_search(client, params)
    assert ...

But I am getting the following error:

requests_mock.exceptions.NoMockAddress: No mock address: GET https://fake-url.com/search?query=username%3Atestsetset&page=1

Can anyone help me out with figuring out how to solve it? I've used mock as a pytest feature.

Lior Dahan
  • 682
  • 2
  • 7
  • 19
  • I made code like this work with `MOCK_ADDRESS = 'https://fake-url.com/search'`. Please could you say what `MOCK_ADDRESS` is in your code? My guess is that your `MOCK_ADDRESS` maybe does not have `/search` or similar. – Adam Dangoor Aug 28 '20 at 10:26
  • what is MOCK_ADDRESS? – user3412172 Dec 31 '20 at 16:33

1 Answers1

11

This occurs when something about the mock request

in this case

requests_mock.get(f'{MOCK_ADDRESS}', json=MOCK_RESPONSE)

does not match exactly the get request of the code being tested. So I'd say you need to print out both the URL in the test class and the one in the tested code.

For example, I was getting the same error, until I did something like

    @requests_mock.Mocker(kw='mock')
    def test_get_data_from_endpoints(self, **kwargs):
        kwargs['mock'].get('http://testurl.org', json=response_1)

More info here: https://requests-mock.readthedocs.io/en/latest/matching.html#query-strings

Michael Millar
  • 1,364
  • 2
  • 24
  • 46