I was trying to get async fixture to work with my test:
import pytest
from httpx import AsyncClient
from app.main import app
@pytest.fixture
async def client():
print("Client does get called")
async with AsyncClient(app, base_url="http://test") as client:
yield client
@pytest.mark.asyncio
async def test_create_get(client: AsyncClient):
print("Do you see me?")
response = await client.get("/testing/hello-world")
assert response.status_code == 200
assert response.json() == {"message": "Hello, World!"}
The test fails with the following output:
CLIENT: Server listening on port 60099...
Received JSON data: ['sources/tests/api/testing/test_simple_api.py::test_create_get']
============================= test session starts =============================
platform win32 -- Python 3.11.3, pytest-7.4.0, pluggy-1.2.0
rootdir: c:\code\myapp
plugins: anyio-3.7.1, asyncio-0.21.1
asyncio: mode=Mode.STRICT
collected 1 item
sources\tests\api\testing\test_simple_api.py F [100%]pytest session has finished, exit status: 1 in discovery? False
================================== FAILURES ===================================
_______________________________ test_create_get _______________________________
client = <async_generator object client at 0x000001F5B71E8820>
@pytest.mark.asyncio
async def test_create_get(client):
print("Do you see me?")
> response = await client.get("/testing/hello-world")
E AttributeError: 'async_generator' object has no attribute 'get'
sources\tests\api\testing\test_simple_api.py:16: AttributeError
---------------------------- Captured stdout call -----------------------------
Do you see me?
=========================== short test summary info ===========================
FAILED sources/tests/api/testing/test_simple_api.py::test_create_get - Attrib...
============================== 1 failed in 0.44s ==============================
From this, if I try and debug I don't hit breakpoints in the fixture setup, but I do in the test function.
When I run the test, I don't see any console output from the fixture.
The following does work:
import pytest
from httpx import AsyncClient
from app.main import app
@pytest.mark.asyncio
async def test_create_get():
async with AsyncClient(app=app, base_url="http://test") as ac:
resp = await ac.get("/testing/hello-world")
assert resp.status_code == 200
assert resp.json() == {"message": "Hello, World!"}
But I wanted to get a reusable client setup in a fixture and I cannot spot what I am missing.
requirements.txt
fastapi==0.95.0
uvicorn==0.21.1
httpx==0.24.1
pytest==7.4.0
pytest-asyncio==0.21.1
I am running from VSCode on Windows 10 with Python 11 installed in my .venv.
Even this example states the same fixture setup.