Pytest/FastAPI asyncio tests run individually but fail when run as a group

I have a set of pytest tests that when run individually pass, but when run as a group fail. I am using an in-memory SQLite database, which is set up and torn down in async fixtures with the scope set to “function”. I have annotated the code and have seen this occurring. When the tests are run as a group it appears as if the database tables are created but the contents of the database are not added.

The code below is the top half of the test file. test_team_endpoint ansd test_Active_team_endpoint both pass when run as

poetry run pytest team_test.py::test_team_endpoint

poetry run pytest team_test.py::test_active_team_endpoint

but when run as

poetry run pytest team_test.py

then test_team_endpoint passes but test_active_team_endpoint fails with a 404 as no teams had been found in the database.

import pytest
import pytest_asyncio
from fastapi.testclient import TestClient
from backend.db.models.club_model import Club
from backend.db.models.team_model import Team
from loguru import logger
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from internaladminserver.application import get_app
from internaladminserver.model.dependencies import get_db_session
from internaladminserver.tests import database1
from internaladminserver.tests.database1 import club_data, team_data
from internaladminserver.tests.team.expected_results import (
    test_active_team_endpoint_result, test_invalid_id_result,
    test_team_endpoint_by_id_result,
    test_team_endpoint_by_id_result_updated_club_id, test_team_endpoint_result,
    test_unknown_id_result)

# Use an asynchronous in-memory SQLite database with StaticPool and session
SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///:memory:"

engine = create_async_engine(
    SQLALCHEMY_DATABASE_URL,
    connect_args={"check_same_thread": False},
    poolclass=StaticPool,
)


AsyncSessionFactory = sessionmaker(
    bind=engine, class_=AsyncSession, expire_on_commit=True
)


@pytest_asyncio.fixture(scope="function")
async def populate_db():
    """
    Populate the database with test data.
    """
    async with engine.begin() as conn:
        await conn.run_sync(lambda conn: Team.__table__.create(conn))
        await conn.run_sync(lambda conn: Club.__table__.create(conn))

    async with AsyncSessionFactory() as session:
        try:
            session.add_all(club_data)
            session.add_all(team_data)
            await session.commit()
            await session.begin()
            yield session
        finally:
            await session.close()

    async with engine.begin() as conn:
        await conn.run_sync(lambda conn: Club.__table__.drop(conn))
        await conn.run_sync(lambda conn: Team.__table__.drop(conn))


@pytest_asyncio.fixture(scope="function")
async def create_client(populate_db):
    """
    Create a new FastAPI test client for a test.
    """
    async def override_get_db():
        async with populate_db as session:
            yield session

    app = get_app()
    app.dependency_overrides[get_db_session] = override_get_db

    with TestClient(app) as client:
        yield client


@pytest.mark.asyncio
async def test_team_endpoint(create_client):
    response = create_client.get("/api/team")
    assert response.status_code == 200
    assert response.json() == test_team_endpoint_result


@pytest.mark.asyncio
async def test_active_team_endpoint(create_client):
    response = create_client.get("/api/team?status=active")
    assert response.status_code == 200
    assert response.json() == test_active_team_endpoint_result


I have annotated the code and can see that the database and session are torn down and recreated each time. I have checked the session functions and confirmed that the ones that need awaiting are awaited. I have naturally searched stackoverflow, asked ChatGPT and other sources of information.

my pytest.ini

[pytest]
filterwarnings =
    ignore::DeprecationWarning
    ignore::PendingDeprecationWarning
    ignore::UserWarning
asyncio_mode = auto

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật