How to use TestClient with requests_mock?
See original GitHub issueSuppose 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:
- Created 4 years ago
- Comments:9 (3 by maintainers)
Top GitHub Comments
I got it working by adding
client.base_url
to exceptions (real_http=True
) for therequests_mock
’s fixture. I keep myTestClient
in the module scope but have to overriderequests_mock
in its function scope:This doesn’t seem to work anymore due to the TestClient using a
base_url
ofhttp://testserver
? I keep getting