question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to use TestClient with requests_mock?

See original GitHub issue

Suppose I have a route in my API that creates an http request to an external resource using requests package. When creating a starlette TestClient, it creates four adapters for ws, wss, http and https, so that it can handle all requests to the API. This is problematic since if I want to mock a route with requests_mock.Mocker() for requests to use, all the adapters created by TestClient get overwritten and do not get matched anymore resulting in NoMockAddressError.

I want to create a test with a mocked response for the address I use in my tested API route, so that the route actually sends the request, gets the response and returns it. How do I go about using TestClient along with requests_mock.Mocker? Can I somehow extend TestClient’s http matchers or should I do it differently? Below is an example of a test that is not working for me:

queue.py

import fastapi
import requests

router = fastapi.APIRouter()
@router.get('/queue/')
def queue_messages():
    return requests.get('http://test-url/stats').json()

conftest.py

import fastapi
import pytest
import starlette.testclient

from source import queue

@pytest.fixture(scope='function')
def test_server():
    app = fastapi.FastAPI()

    app.include_router(queue.router, prefix='/api')

    return starlette.testclient.TestClient(app)

test_queue.py

def test_queue_get(requests_mock, test_server):
    stats = { ... }
    requests_mock.get('http://test-url/stats', json=stats)

    response = test_server.get('/api/queue/')
    assert response.json() == {'messages': 45}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

9reactions
madisppcommented, Nov 25, 2021

I got it working by adding client.base_url to exceptions (real_http=True) for the requests_mock’s fixture. I keep my TestClient in the module scope but have to override requests_mock in its function scope:

@pytest.fixture(scope="module")
def module_client():
    with TestClient(app) as c:
        yield c

@pytest.fixture
def client(module_client, requests_mock):
    test_app_base_url_prefix_regex = re.compile(fr"{re.escape(module_client.base_url)}(/.*)?")
    requests_mock.register_uri(ANY, test_app_base_url_prefix_regex, real_http=True)
    return module_client
5reactions
four43commented, Sep 21, 2021

It works fine for me (on FastAPI) even without real_http :

This doesn’t seem to work anymore due to the TestClient using a base_url of http://testserver? I keep getting

> requests_mock.exceptions.NoMockAddress: No mock address: GET http://testserver/route

../../../.venv/lib/python3.9/site-packages/requests_mock/adapter.py:261: NoMockAddress
Read more comments on GitHub >

github_iconTop Results From Across the Web

requests-mock-flask - PyPI
'Helpers to use requests_mock and responses with a Flask test client.'
Read more >
Mocking External APIs in Python
The following tutorial demonstrates how to test the use of an external API using Python mock objects. Integrating with a third-party application is...
Read more >
requests-like wrapper for flask's test_client - python
Features: Wrapper around the Flask test client. Automatically set the request headers. Content-Type: Application/json when passing ...
Read more >
Python responses.RequestsMock() Examples
RequestsMock () as rsps: rsps.add( responses. ... requests to Idunn should generate 10 requests to Wikipedia API """ client = TestClient(app) with responses....
Read more >
Testing - FastAPI
Create a TestClient by passing your FastAPI application to it. Create functions with a name that starts with test_ (this is standard pytest...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found