import asyncio import os 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.WindowsSelectorEventLoopPolicy()) 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 DATABASE SAFETY # Tests MUST NOT touch production data. This function resolves the database # URL to use and hard-fails if there is any risk of hitting a production DB. # # Priority: # 1. TEST_DATABASE_URL env var (recommended for CI and local dev) # 2. DATABASE_URL — accepted ONLY if it clearly points to localhost / a # database whose name contains "test" # --------------------------------------------------------------------------- _SAFE_URL_SIGNALS = ["test", "localhost", "127.0.0.1", "::1", ":memory:", "mem"] def _get_safe_test_db_url() -> str: explicit = os.environ.get("TEST_DATABASE_URL", "").strip() if explicit: return explicit fallback = settings.async_database_url raw = (settings.DATABASE_URL or "").lower() if not any(sig in raw for sig in _SAFE_URL_SIGNALS): raise RuntimeError( "\n\n" " *** DESTRUCTIVE TEST BLOCKED — production database detected ***\n" "\n" " Tests would DROP ALL TABLES in the connected database.\n" "\n" " Fix: set TEST_DATABASE_URL to a dedicated test database URL.\n" " Example:\n" " TEST_DATABASE_URL=postgresql+psycopg://user:pw@localhost/nexus_test\n" f"\n Detected host: {settings.database_host}\n" ) return fallback _TEST_DB_URL = _get_safe_test_db_url() test_engine = create_async_engine(_TEST_DB_URL, poolclass=NullPool, future=True) test_async_session_factory = async_sessionmaker( test_engine, class_=AsyncSession, expire_on_commit=False ) # --------------------------------------------------------------------------- # DATABASE SETUP FIXTURE # Drops and recreates the entire schema once per test function that requests # it (directly or transitively via the token fixtures below). This guarantees # every test starts from a clean, predictable state confined to the TEST # database — production data is never touched. # --------------------------------------------------------------------------- @pytest.fixture(scope="function") async def setup_database(): """ Wipes the test database, recreates the schema, and seeds baseline data. All test data lives in the TEST_DATABASE_URL — never in production. """ from sqlalchemy import text async with test_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector")) await conn.run_sync(Base.metadata.create_all) async with test_async_session_factory() as db: from models.user_workspace import UserWorkspace # --- Workspace A --- ws_a_id = uuid.uuid4() ws_a = Workspace(id=ws_a_id, name="Test Workspace A") db.add(ws_a) 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() 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() db.add(UserWorkspace(user_id=cust_a.id, workspace_id=ws_a_id, role=UserRole.CUSTOMER_USER, is_primary=True)) # --- Workspace B --- ws_b_id = uuid.uuid4() ws_b = Workspace(id=ws_b_id, name="Test Workspace B") db.add(ws_b) admin_b = User( email="admin@b.com", full_name="Admin B", hashed_password=get_password_hash("password123"), global_role=UserRole.SC_ADMIN, is_active=True, ) db.add(admin_b) await db.flush() db.add(UserWorkspace(user_id=admin_b.id, workspace_id=ws_b_id, role=UserRole.SC_ADMIN, is_primary=True)) 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() db.add(UserWorkspace(user_id=cust_b.id, workspace_id=ws_b_id, role=UserRole.CUSTOMER_USER, is_primary=True)) await db.commit() yield # --------------------------------------------------------------------------- # HTTP CLIENT # --------------------------------------------------------------------------- @pytest.fixture async def client(setup_database) -> AsyncGenerator[AsyncClient, None]: """Async HTTP client wired to the test database. Depends on setup_database so the schema is always seeded before any request is made.""" 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 # Each fixture logs in as the corresponding seeded user. The dependency on # `client` (which depends on `setup_database`) ensures the test workspace is # always ready before the login request is issued. # --------------------------------------------------------------------------- @pytest.fixture async def token_a(client: AsyncClient) -> str: """Access token for customer@a.com (Workspace A).""" 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: """Access token for admin@a.com (Workspace A, SC_ADMIN).""" 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: """Access token for customer@b.com (Workspace B).""" 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 admin_token_b(client: AsyncClient) -> str: """Access token for admin@b.com (Workspace B, SC_ADMIN).""" res = await client.post( "/api/v1/auth/login", data={"username": "admin@b.com", "password": "password123"}, headers={"X-Nexus-Portal": "internal"}, ) assert res.status_code == 200, f"Login failed for admin@b.com: {res.text}" return res.json()["access_token"] # --------------------------------------------------------------------------- # DATABASE SESSION (for direct DB assertions in tests) # --------------------------------------------------------------------------- @pytest.fixture async def db_session(setup_database) -> AsyncGenerator[AsyncSession, None]: async with test_async_session_factory() as db: yield db # --------------------------------------------------------------------------- # WORKSPACE ID HELPERS # --------------------------------------------------------------------------- @pytest.fixture async def workspace_a_id(db_session: AsyncSession) -> str: from sqlalchemy import select stmt = select(Workspace).where(Workspace.name == "Test Workspace A") ws = (await db_session.execute(stmt)).scalar_one() return str(ws.id) @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)