""" Shared fixtures for the OCI CIS Agent test suite. Uses a temporary SQLite database and the real FastAPI app. """ import os import sys import tempfile import pytest from httpx import AsyncClient, ASGITransport # Ensure backend is importable sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) # Use temp dir for all data (DB, configs, reports, etc.) _tmpdir = tempfile.mkdtemp(prefix="cisagent_test_") os.environ["DATA_DIR"] = _tmpdir os.environ["APP_SECRET"] = "a" * 128 # valid 64-byte hex @pytest.fixture(scope="session") def anyio_backend(): return "asyncio" @pytest.fixture(scope="session") def app(): """Create the FastAPI app with a fresh DB, manually init since ASGI transport skips lifespan.""" import app as app_module # Disable rate limiting for tests app_module._LOGIN_MAX = 999999 app_module.init_db() return app_module.app @pytest.fixture(scope="session") async def client(app): """Async HTTP client for the test session.""" transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as c: yield c @pytest.fixture(scope="session") async def admin_token(client): """Login as admin and return JWT token.""" r = await client.post("/api/auth/login", json={"username": "admin", "password": "admin123"}) assert r.status_code == 200, f"Admin login failed: {r.text}" return r.json()["token"] @pytest.fixture(scope="session") def admin_headers(admin_token): """Auth headers for admin user.""" return {"Authorization": f"Bearer {admin_token}"} @pytest.fixture(scope="session") async def user_token(client, admin_headers): """Create a regular user and return their JWT token.""" r = await client.post("/api/auth/register", json={ "first_name": "Test", "last_name": "User", "username": "testuser", "email": "test@test.com", "password": "Test1234!", "role": "user" }, headers=admin_headers) assert r.status_code == 200, f"User creation failed: {r.text}" r2 = await client.post("/api/auth/login", json={"username": "testuser", "password": "Test1234!"}) assert r2.status_code == 200 return r2.json()["token"] @pytest.fixture(scope="session") def user_headers(user_token): """Auth headers for regular user.""" return {"Authorization": f"Bearer {user_token}"} @pytest.fixture(scope="session") async def viewer_token(client, admin_headers): """Create a viewer user and return their JWT token.""" r = await client.post("/api/auth/register", json={ "first_name": "View", "last_name": "Only", "username": "viewer", "email": "viewer@test.com", "password": "View1234!", "role": "viewer" }, headers=admin_headers) assert r.status_code == 200 r2 = await client.post("/api/auth/login", json={"username": "viewer", "password": "View1234!"}) assert r2.status_code == 200 return r2.json()["token"] @pytest.fixture(scope="session") def viewer_headers(viewer_token): return {"Authorization": f"Bearer {viewer_token}"}