SKILL.md--- name: py-testing-async description: Async testing patterns with pytest-asyncio. Use when writing tests, mocking async code, testing database operations, or debugging test failures. --- # Python Async Testing ## Problem Statement Async testing requires specific patterns. pytest-asyncio has modes that affect behavior. Database tests need isolation. Mocking async functions differs from sync. Get these wrong and tests are flaky or don't catch bugs. --- ## Pattern: pytest-asyncio Configuration **Problem:** Pytest needs configuration for async tests. ```toml # pyproject.toml [tool.pytest.ini_options] asyncio_mode = "strict" # Requires explicit @pytest.mark.asyncio # OR asyncio_mode = "auto" # All async tests run automatically ``` ```python import pytest # With asyncio_mode = "strict" (this codebase) @pytest.mark.asyncio async def test_something(): result = await some_async_function() assert result == expected # Without the marker = test won't run as async! ``` --- ## Pattern: Async Fixtures **Problem:** Fixtures that provide async resources need specific handling. ```python import pytest from sqlalchemy.ext.asyncio import AsyncSession # ✅ CORRECT: Async fixture for session @pytest.fixture async def session() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: yield session await session.rollback() # Clean up after test # ✅ CORRECT: Async fixture for test data @pytest.fixture async def test_user(session: AsyncSession) -> User: user = User(email="test@example.com", hashed_password="...") session.add(user) await session.commit() await session.refresh(user) return user # ✅ CORRECT: Using async fixtures @pytest.mark.asyncio async def test_get_user(session: AsyncSession, test_user: User): result = await session.execute( select(User).where(User.id == test_user.id) ) user = result.scalar_one() assert user.email == "test@example.com" ``` --- ## Pattern: Database Test Isolation **Problem:** Tests polluting each other's database state. ```python # ✅ CORRECT: Transaction rollback per test @pytest.fixture async def session() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: # Start a transaction async with session.begin(): yield session # Rollback happens automatically when we exit # ✅ CORRECT: Nested transactions for complex tests @pytest.fixture async def session() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: await session.begin() yield session await session.rollback() # Alternative: Use separate test database # conftest.py @pytest.fixture(scope="session") def event_loop(): loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close() @pytest.fixture(scope="session") async def test_engine(): # Use SQLite for tests, PostgreSQL for prod engine = create_async_engine("sqlite+aiosqlite:///:memory:") async with engine.begin() as conn: await conn.run_sync(SQLModel.