httpx AsyncClient with a passed Fastapi app works with arbitrary `base_url`s

26 views Asked by At

Here is an example from FastApi's documentation in Testing section:

The file main.py would have:

from fastapi import FastAPI

app = FastAPI()


@app.get("/") async def root():
    return {"message": "Tomato"} 

The file test_main.py would have the tests for main.py, it could look like this now:

import pytest from httpx import AsyncClient

from .main import app


@pytest.mark.anyio async def test_root():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}

base_url is supposed to be a prefix which is prepended to the requests created by the client. But I don't see any use-case for it here in this example. So my question is why should we include this "http://test" here? What is its purpose?

In fact it can be just base_url="http://" or anything:

@pytest.mark.anyio async def test_root():
    async with AsyncClient(app=app, base_url="http://www.facebook.com") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}

If I'm not wrong, it is just there to avoid parsing errors for schema and domain.

0

There are 0 answers