fix: resolve config folders API bugs and test infrastructure
- Fix validation error handler to serialize ValueError objects safely
- Add GET /config-folders/{id} endpoint (was missing)
- Fix project overrides API to accept project_id in body instead of query param
- Add flag_modified for SQLAlchemy JSONB change detection
- Fix DELETE endpoint to return 204 status code
- Fix conftest.py to use single SQLite engine per test
- Install aiosqlite dependency
- Fix frontend ToolWorkshopPage tests button names
Config folders tests: 13/13 passing
Docker build tests: 10/10 passing
Readiness probe tests: 13/13 passing
This commit is contained in:
+131
-70
@@ -3,6 +3,7 @@
|
||||
import asyncio
|
||||
import os
|
||||
from typing import AsyncGenerator, Generator
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
@@ -11,82 +12,142 @@ from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
# Set test environment BEFORE importing app modules
|
||||
os.environ["APP_ENV"] = "testing"
|
||||
os.environ["SECRET_KEY"] = "test-secret-key-for-testing-only-do-not-use-in-production"
|
||||
os.environ["DATABASE_URL"] = "sqlite+aiosqlite:///:memory:"
|
||||
|
||||
from src.config import Settings, build_database_url
|
||||
from src.models.base import Base
|
||||
from src.main import app
|
||||
|
||||
|
||||
# Unit test fixtures (SQLite in-memory)
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def sqlite_engine():
|
||||
"""Create a SQLite in-memory engine for unit tests."""
|
||||
engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(engine)
|
||||
yield engine
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_session(sqlite_engine) -> Generator:
|
||||
"""Provide a SQLite session for unit tests."""
|
||||
connection = sqlite_engine.connect()
|
||||
transaction = connection.begin()
|
||||
session = sessionmaker(bind=connection)()
|
||||
|
||||
yield session
|
||||
|
||||
session.close()
|
||||
transaction.rollback()
|
||||
connection.close()
|
||||
|
||||
|
||||
# Integration test fixtures (PostgreSQL)
|
||||
|
||||
TEST_DATABASE_URL = build_database_url(
|
||||
user="headquarter",
|
||||
password="headquarter",
|
||||
host="localhost",
|
||||
port=5432,
|
||||
database="headquarter",
|
||||
)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture(scope="session")
|
||||
async def postgres_engine():
|
||||
"""Create a PostgreSQL engine for integration tests."""
|
||||
engine = create_async_engine(TEST_DATABASE_URL)
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
yield engine
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db_session(postgres_engine) -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Provide a database session with transaction rollback."""
|
||||
async with postgres_engine.connect() as connection:
|
||||
transaction = await connection.begin_nested()
|
||||
session_factory = async_sessionmaker(
|
||||
connection, expire_on_commit=False, class_=AsyncSession
|
||||
)
|
||||
session = session_factory()
|
||||
|
||||
yield session
|
||||
|
||||
await session.close()
|
||||
await transaction.rollback()
|
||||
from src.auth.dependencies import get_db_session
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_client() -> Generator[TestClient, None, None]:
|
||||
"""Provide a FastAPI test client."""
|
||||
with TestClient(app) as client:
|
||||
yield client
|
||||
"""Provide a FastAPI test client with SQLite database."""
|
||||
# Create a single engine for this test
|
||||
engine = create_async_engine(
|
||||
"sqlite+aiosqlite:///:memory:",
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
|
||||
# Create tables
|
||||
async def init_db():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
asyncio.run(init_db())
|
||||
|
||||
async def override_get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_sessionmaker(engine, expire_on_commit=False)() as session:
|
||||
yield session
|
||||
|
||||
# Override the dependency
|
||||
app.dependency_overrides[get_db_session] = override_get_db_session
|
||||
|
||||
# Patch startup events to prevent PostgreSQL connection attempts
|
||||
with patch("src.main.init_database") as mock_init, \
|
||||
patch("src.main.seed_builtin_tool_types") as mock_seed:
|
||||
mock_init.return_value = True
|
||||
mock_seed.return_value = None
|
||||
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
yield client
|
||||
finally:
|
||||
# Clean up overrides
|
||||
app.dependency_overrides.pop(get_db_session, None)
|
||||
asyncio.run(engine.dispose())
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def configure_test_env(monkeypatch):
|
||||
"""Configure environment for testing."""
|
||||
monkeypatch.setenv("DATABASE_URL", TEST_DATABASE_URL)
|
||||
monkeypatch.setenv("APP_ENV", "testing")
|
||||
@pytest.fixture
|
||||
def authenticated_client(test_client) -> Generator[TestClient, None, None]:
|
||||
"""Provide an authenticated test client with a test user."""
|
||||
import uuid
|
||||
from src.auth.session import create_session_cookie
|
||||
from src.models.user import User
|
||||
|
||||
user_id = str(uuid.uuid4())
|
||||
settings = Settings()
|
||||
|
||||
# Create user in database using the same engine as test_client
|
||||
# We need to access the engine from the test_client fixture
|
||||
# Since we can't easily do that, we'll create the user via API call
|
||||
# But we need the user to exist before any API calls
|
||||
# So we need to create the user using the overridden dependency
|
||||
|
||||
async def create_test_user():
|
||||
# Get the override function
|
||||
override_fn = app.dependency_overrides.get(get_db_session)
|
||||
if override_fn:
|
||||
gen = override_fn()
|
||||
session = await gen.asend(None)
|
||||
try:
|
||||
user = User(
|
||||
id=uuid.UUID(user_id),
|
||||
email="test@headquarter.local",
|
||||
name="Test User",
|
||||
authentik_id=f"authentik-{user_id}",
|
||||
avatar_url=None,
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
finally:
|
||||
await gen.aclose()
|
||||
|
||||
asyncio.run(create_test_user())
|
||||
|
||||
# Create session cookie
|
||||
session_cookie = create_session_cookie(
|
||||
settings=settings,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
# Set cookie on client
|
||||
test_client.cookies.set("session", session_cookie)
|
||||
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_client(test_client) -> Generator[TestClient, None, None]:
|
||||
"""Provide an authenticated test client with an admin user."""
|
||||
import uuid
|
||||
from src.auth.session import create_session_cookie
|
||||
from src.models.user import User
|
||||
|
||||
user_id = str(uuid.uuid4())
|
||||
settings = Settings()
|
||||
|
||||
async def create_admin_user():
|
||||
override_fn = app.dependency_overrides.get(get_db_session)
|
||||
if override_fn:
|
||||
gen = override_fn()
|
||||
session = await gen.asend(None)
|
||||
try:
|
||||
user = User(
|
||||
id=uuid.UUID(user_id),
|
||||
email="admin@headquarter.local",
|
||||
name="Admin User",
|
||||
authentik_id=f"authentik-admin-{user_id}",
|
||||
avatar_url=None,
|
||||
is_admin=True,
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
finally:
|
||||
await gen.aclose()
|
||||
|
||||
asyncio.run(create_admin_user())
|
||||
|
||||
# Create session cookie
|
||||
session_cookie = create_session_cookie(
|
||||
settings=settings,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
# Set cookie on client
|
||||
test_client.cookies.set("session", session_cookie)
|
||||
|
||||
yield test_client
|
||||
|
||||
Reference in New Issue
Block a user