"""Test configuration and fixtures.""" import pytest import asyncio from httpx import AsyncClient from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from app.main import app from app.core.database import get_db, Base # Test database URL (use SQLite for testing) TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db" # Create test engine and session factory test_engine = create_async_engine(TEST_DATABASE_URL, echo=False) TestAsyncSessionLocal = async_sessionmaker( test_engine, class_=AsyncSession, expire_on_commit=False, ) @pytest.fixture(scope="session") def anyio_backend(): """Specify the backend for anyio (pytest-asyncio).""" return "asyncio" @pytest.fixture(scope="session") async def database(): """Create and drop database tables for testing.""" async with test_engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield async with test_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) @pytest.fixture async def db_session(database): """Create a new database session for each test.""" async with TestAsyncSessionLocal() as session: yield session @pytest.fixture async def client(db_session): """Create a test client with database session.""" async def override_get_db(): yield db_session app.dependency_overrides[get_db] = override_get_db async with AsyncClient(app=app, base_url="http://test") as ac: yield ac app.dependency_overrides.clear() @pytest.fixture async def test_user(db_session): """Create a test user.""" from app.models.models import User from app.core.security import hash_password user = User( username="testuser", password_hash=hash_password("testpassword123"), email="test@example.com", is_active=True, ) db_session.add(user) await db_session.commit() await db_session.refresh(user) return user @pytest.fixture async def admin_user(db_session): """Create an admin test user.""" from app.models.models import User from app.core.security import hash_password user = User( username="admin", password_hash=hash_password("adminpassword123"), email="admin@example.com", privlevel="Admin", is_active=True, ) db_session.add(user) await db_session.commit() await db_session.refresh(user) return user @pytest.fixture def auth_headers(test_user): """Get auth headers for test user.""" from app.core.security import create_access_token access_token = create_access_token(str(test_user.id)) return {"Authorization": f"Bearer {access_token}"} @pytest.fixture def admin_headers(admin_user): """Get auth headers for admin user.""" from app.core.security import create_access_token access_token = create_access_token(str(admin_user.id)) return {"Authorization": f"Bearer {access_token}"} @pytest.fixture def refresh_token(test_user): """Get a refresh token for test user.""" from app.core.security import create_refresh_token return create_refresh_token(str(test_user.id))