PYTHONPython

conftest

real world projects / task api / tests

PYTHON
conftest.py🐍
"""Test fixtures for API testing."""

import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from app.main import app
from app.database import Base, get_db


# Use in-memory SQLite for tests
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def override_get_db():
    """Override database dependency for testing."""
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()


@pytest.fixture(scope="function")
def test_db():
    """Create fresh database for each test."""
    Base.metadata.create_all(bind=engine)
    yield
    Base.metadata.drop_all(bind=engine)


@pytest.fixture(scope="function")
def client(test_db):
    """Create test client with database override."""
    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()


@pytest.fixture
def auth_headers(client):
    """Create a user and return auth headers."""
    # Register user
    client.post("/api/users/register", json={
        "email": "test@example.com",
        "username": "testuser",
        "password": "testpassword123"
    })
    
    # Login
    response = client.post("/api/users/login", data={
        "username": "testuser",
        "password": "testpassword123"
    })
    
    token = response.json()["access_token"]
    return {"Authorization": f"Bearer {token}"}
PreviousNext