102 lines
2.8 KiB
Python
102 lines
2.8 KiB
Python
import pytest
|
|
from typing import Generator
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from app.database import Base, get_db
|
|
from app.main import app
|
|
from app.models.user import User, UserRole
|
|
from app.core.security import hash_password, create_access_token
|
|
|
|
# In-memory SQLite database for fast isolated unit tests
|
|
TEST_DATABASE_URL = "sqlite:///:memory:"
|
|
|
|
test_engine = create_engine(
|
|
TEST_DATABASE_URL,
|
|
connect_args={"check_same_thread": False},
|
|
poolclass=StaticPool,
|
|
)
|
|
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
|
|
|
|
|
|
@pytest.fixture(scope="session", autouse=True)
|
|
def setup_test_db():
|
|
Base.metadata.create_all(bind=test_engine)
|
|
yield
|
|
Base.metadata.drop_all(bind=test_engine)
|
|
|
|
|
|
@pytest.fixture
|
|
def db_session() -> Generator:
|
|
connection = test_engine.connect()
|
|
transaction = connection.begin()
|
|
session = TestingSessionLocal(bind=connection)
|
|
|
|
yield session
|
|
|
|
session.close()
|
|
transaction.rollback()
|
|
connection.close()
|
|
|
|
|
|
@pytest.fixture
|
|
def client(db_session) -> Generator:
|
|
def override_get_db():
|
|
try:
|
|
yield db_session
|
|
finally:
|
|
pass
|
|
|
|
app.dependency_overrides[get_db] = override_get_db
|
|
with TestClient(app) as test_client:
|
|
yield test_client
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
@pytest.fixture
|
|
def admin_user(db_session) -> User:
|
|
user = db_session.query(User).filter(User.username == "test_admin").first()
|
|
if not user:
|
|
user = User(
|
|
username="test_admin",
|
|
email="admin@test.com",
|
|
hashed_password=hash_password("AdminPass123!"),
|
|
full_name="Test Administrator",
|
|
role=UserRole.SUPER_ADMIN.value,
|
|
is_active=True
|
|
)
|
|
db_session.add(user)
|
|
db_session.commit()
|
|
db_session.refresh(user)
|
|
return user
|
|
|
|
|
|
@pytest.fixture
|
|
def viewer_user(db_session) -> User:
|
|
user = db_session.query(User).filter(User.username == "test_viewer").first()
|
|
if not user:
|
|
user = User(
|
|
username="test_viewer",
|
|
email="viewer@test.com",
|
|
hashed_password=hash_password("ViewerPass123!"),
|
|
full_name="Test Regular Viewer",
|
|
role=UserRole.VIEWER.value,
|
|
is_active=True
|
|
)
|
|
db_session.add(user)
|
|
db_session.commit()
|
|
db_session.refresh(user)
|
|
return user
|
|
|
|
|
|
@pytest.fixture
|
|
def admin_token(admin_user) -> str:
|
|
return create_access_token(data={"sub": str(admin_user.id), "username": admin_user.username, "role": admin_user.role})
|
|
|
|
|
|
@pytest.fixture
|
|
def viewer_token(viewer_user) -> str:
|
|
return create_access_token(data={"sub": str(viewer_user.id), "username": viewer_user.username, "role": viewer_user.role})
|