import asyncio import pytest import uuid import sys from httpx import AsyncClient, ASGITransport from main import app from core.database import Base from sqlalchemy.ext.asyncio import AsyncSession from typing import AsyncGenerator from unittest.mock import AsyncMock from models.workspace import Workspace from models.user import User, UserRole from core.security import get_password_hash if sys.platform == 'win32': asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker from sqlalchemy.pool import NullPool from core.config import get_settings settings = get_settings() test_engine = create_async_engine( settings.async_database_url, poolclass=NullPool, future=True ) test_async_session_factory = async_sessionmaker( test_engine, class_=AsyncSession, expire_on_commit=False, ) # --- DATABASE SETUP (ONCE PER TEST) --- @pytest.fixture(scope="function", autouse=True) async def setup_database(): """Wipes and seeds the database for testing. BE CAREFUL with DATABASE_URL.""" async with test_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) from sqlalchemy import text await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector")) await conn.run_sync(Base.metadata.create_all) # Seed minimal test data async with test_async_session_factory() as db: ws_a_id = uuid.uuid4() ws_a = Workspace(id=ws_a_id, name="Test Workspace A") db.add(ws_a) from models.user_workspace import UserWorkspace # password is 'password123' admin_a = User( email="admin@a.com", full_name="Admin A", hashed_password=get_password_hash("password123"), global_role=UserRole.SC_ADMIN, is_active=True ) db.add(admin_a) await db.flush() # Link Admin A to Workspace A db.add(UserWorkspace(user_id=admin_a.id, workspace_id=ws_a_id, role=UserRole.SC_ADMIN, is_primary=True)) cust_a = User( email="customer@a.com", full_name="Customer A", hashed_password=get_password_hash("password123"), is_active=True ) db.add(cust_a) await db.flush() # Link Customer A to Workspace A db.add(UserWorkspace(user_id=cust_a.id, workspace_id=ws_a_id, role=UserRole.CUSTOMER_USER, is_primary=True)) ws_b_id = uuid.uuid4() ws_b = Workspace(id=ws_b_id, name="Test Workspace B") db.add(ws_b) cust_b = User( email="customer@b.com", full_name="Customer B", hashed_password=get_password_hash("password123"), is_active=True ) db.add(cust_b) await db.flush() # Link Customer B to Workspace B db.add(UserWorkspace(user_id=cust_b.id, workspace_id=ws_b_id, role=UserRole.CUSTOMER_USER, is_primary=True)) await db.commit() yield # --- ASYNC CLIENT FIXTURE --- @pytest.fixture async def client() -> AsyncGenerator[AsyncClient, None]: from core.deps import get_arq_pool, get_db mock_arq = AsyncMock() app.dependency_overrides[get_arq_pool] = lambda: mock_arq async def override_get_db(): async with test_async_session_factory() as session: yield session app.dependency_overrides[get_db] = override_get_db transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as ac: yield ac app.dependency_overrides.clear() # --- TOKEN FIXTURES --- @pytest.fixture async def token_a(client: AsyncClient) -> str: res = await client.post("/api/v1/auth/login", data={"username": "customer@a.com", "password": "password123"}) assert res.status_code == 200, f"Login failed for customer@a.com: {res.text}" return res.json()["access_token"] @pytest.fixture async def admin_token_a(client: AsyncClient) -> str: res = await client.post( "/api/v1/auth/login", data={"username": "admin@a.com", "password": "password123"}, headers={"X-Nexus-Portal": "internal"} ) assert res.status_code == 200, f"Login failed for admin@a.com: {res.text}" return res.json()["access_token"] @pytest.fixture async def token_b(client: AsyncClient) -> str: res = await client.post("/api/v1/auth/login", data={"username": "customer@b.com", "password": "password123"}) assert res.status_code == 200, f"Login failed for customer@b.com: {res.text}" return res.json()["access_token"] @pytest.fixture async def db_session() -> AsyncGenerator[AsyncSession, None]: async with test_async_session_factory() as db: yield db @pytest.fixture async def workspace_b_id(db_session: AsyncSession) -> str: from sqlalchemy import select stmt = select(Workspace).where(Workspace.name == "Test Workspace B") ws = (await db_session.execute(stmt)).scalar_one() return str(ws.id)