Search code examples
pythonpytestfastapisuppress-warnings

PyTest fixture : How to resolve FastAPI 'app' shortcut deprecated warning?


I am trying to solve one for all, this Warning while executing pytests:

/usr/local/lib/python3.11/site-packages/httpx/_client.py:680: 
DeprecationWarning: The 'app' shortcut is now deprecated. 
Use the explicit style 'transport=WSGITransport(app=...)' instead.
warnings.warn(message, DeprecationWarning)

I know that a similar question has been asked here:

How to write pytest tests for a FastAPI route involving dependency injection with Pydantic models using Annotated and Depends?

But still I cannot get how to avoid this warning.

I have this Python test fixture:

@pytest.fixture
def client(app: FastAPI) -> Generator:
    with TestClient(app, base_url="http://localhost") as client:
        yield client

But if I change this to the thing suggested in the link previously mentioned:

@pytest.fixture
def client()-> Generator:
  """Fixture to create a FastAPI test client."""
  # instead of app = app, use this to avoid the DeprecationWarning:
  with TestClient(transport=ASGITransport(app=app), base_url="http://localhost") as 
 client:
      yield client

My tests can't pass, and instead I have this new error:

TypeError: TestClient.__init__() got an unexpected keyword argument 'transport'

Solution

  • Just upgrade FastAPI and Starlette to the latest versions. This problem is already fixed in Starlette 0.37.2.

    If you use pip:

    pip install --upgrade fastapi starlette
    

    And use with TestClient(app, base_url="http://localhost") as client: as you did before.