Search code examples
pythonpytestfastapisuppress-warnings

PyTest fixture : how resolve warning FastAPI 'app' shortcut deprecated?


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 (https://www.starlette.io/release-notes/#0372):

    If you use pip:

    pip install --upgrade fastapi starlette
    

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