Files
card-game/backend/tests/conftest.py

65 lines
1.8 KiB
Python

import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.database import Base, get_db
from app.main import app
# Use in-memory SQLite for tests (faster, isolated)
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)
@pytest.fixture(scope="function")
def db():
Base.metadata.create_all(bind=engine)
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
Base.metadata.drop_all(bind=engine)
@pytest.fixture(scope="function")
def client(db):
def override_get_db():
try:
yield db
finally:
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
@pytest.fixture
def registered_user(client):
"""Register a test user and return credentials."""
user_data = {
"email": "testuser@example.com",
"password": "testpassword123",
"nickname": "testuser"
}
response = client.post("/auth/register", json=user_data)
assert response.status_code == 200
return user_data
@pytest.fixture
def auth_token(client, registered_user):
"""Get auth token for registered user."""
response = client.post("/auth/login", json={
"email": registered_user["email"],
"password": registered_user["password"]
})
assert response.status_code == 200
return response.json()["access_token"]
@pytest.fixture
def auth_headers(auth_token):
"""Auth headers for authenticated requests."""
return {"Authorization": f"Bearer {auth_token}"}