Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

4.3 KB
Raw Blame
from collections.abc import AsyncGenerator, Generator
from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, MagicMock

import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from httpx import ASGITransport, AsyncClient

from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.main import http_exception_handler
from llm_gateway.rate_limiting.billable_credits_throttle import BillableCreditThrottle
from llm_gateway.rate_limiting.cost_throttles import (
    ProductCostThrottle,
    UserCostBurstThrottle,
    UserCostSustainedThrottle,
)
from llm_gateway.rate_limiting.runner import ThrottleRunner
from llm_gateway.rate_limiting.throttles import Throttle
from llm_gateway.request_context import request_context_var
from llm_gateway.services.desktop_access_resolver import DesktopAccessDecision
from llm_gateway.services.quota_resolver import QuotaResourceStatus


@pytest.fixture(autouse=True)
def _reset_request_context() -> Generator[None]:
    token = request_context_var.set(None)
    yield
    request_context_var.reset(token)


def _make_fake_quota_resolver() -> AsyncMock:
    resolver = AsyncMock()
    resolver.get_resource_status = AsyncMock(return_value=QuotaResourceStatus(limited=False))
    return resolver


def create_test_app(
    mock_db_pool: MagicMock,
    throttles: list[Throttle] | None = None,
) -> FastAPI:
    from llm_gateway.api.health import health_router
    from llm_gateway.api.routes import router

    quota_resolver = _make_fake_quota_resolver()
    default_throttles: list[Throttle] = [
        BillableCreditThrottle(),
        ProductCostThrottle(redis=None),
        UserCostBurstThrottle(redis=None),
        UserCostSustainedThrottle(redis=None),
    ]

    @asynccontextmanager
    async def test_lifespan(app: FastAPI) -> AsyncGenerator[None]:
        app.state.db_pool = mock_db_pool
        app.state.redis = None
        app.state.throttle_runner = ThrottleRunner(throttles=throttles if throttles is not None else default_throttles)
        app.state.http_client = MagicMock()
        app.state.billing_period_resolver = AsyncMock()
        app.state.billing_period_resolver.get_period = AsyncMock(return_value=None)
        app.state.desktop_access_resolver = AsyncMock()
        app.state.desktop_access_resolver.resolve_access = AsyncMock(
            return_value=DesktopAccessDecision(status="allowed")
        )
        app.state.anthropic_circuit_breaker = None
        app.state.quota_resolver = quota_resolver
        yield

    app = FastAPI(title="LLM Gateway Test", lifespan=test_lifespan)
    app.exception_handler(HTTPException)(http_exception_handler)

    app.include_router(health_router)
    app.include_router(router)
    return app


@pytest.fixture
def mock_db_pool() -> MagicMock:
    pool = MagicMock()
    conn = AsyncMock()
    conn.fetchrow = AsyncMock(return_value=None)
    conn.fetchval = AsyncMock(return_value=1)
    conn.fetch = AsyncMock(return_value=[])
    pool.acquire = AsyncMock(return_value=conn)
    pool.release = AsyncMock()
    return pool


@pytest.fixture
def authenticated_user() -> AuthenticatedUser:
    return AuthenticatedUser(
        user_id=1,
        team_id=1,
        auth_method="personal_api_key",
        distinct_id="test-distinct-id",
        scopes=["llm_gateway:read"],
    )


@pytest.fixture
def app(mock_db_pool: MagicMock) -> Generator[FastAPI]:
    application = create_test_app(mock_db_pool)
    yield application


@pytest.fixture
def client(app: FastAPI) -> Generator[TestClient]:
    with TestClient(app) as c:
        yield c


@pytest.fixture
async def async_client(app: FastAPI) -> AsyncGenerator[AsyncClient]:
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        yield ac


@pytest.fixture
def authenticated_client(mock_db_pool: MagicMock) -> Generator[TestClient]:
    app = create_test_app(mock_db_pool)

    conn = AsyncMock()
    conn.fetchrow = AsyncMock(
        return_value={
            "id": "key_id",
            "user_id": 1,
            "scopes": ["llm_gateway:read"],
            "current_team_id": 1,
            "distinct_id": "test-distinct-id",
            "is_staff": False,
        }
    )
    mock_db_pool.acquire = AsyncMock(return_value=conn)
    mock_db_pool.release = AsyncMock()

    with TestClient(app) as c:
        yield c