72 lines
1.7 KiB
Python
72 lines
1.7 KiB
Python
"""
|
|
Pytest fixtures and configuration for Newzy tests.
|
|
"""
|
|
|
|
import pytest
|
|
from sqlalchemy import text
|
|
|
|
from config import settings
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def test_db_url():
|
|
"""Database URL for testing."""
|
|
return "sqlite:///./test_newzy.db"
|
|
|
|
|
|
@pytest.fixture(scope="function")
|
|
def db_engine(test_db_url):
|
|
"""Create an engine for the test database."""
|
|
from sqlalchemy import create_engine
|
|
|
|
engine = create_engine(
|
|
test_db_url,
|
|
connect_args={"check_same_thread": False},
|
|
)
|
|
return engine
|
|
|
|
|
|
@pytest.fixture(scope="function")
|
|
def db_session(db_engine):
|
|
"""Create a database session for testing."""
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
SessionLocal = sessionmaker(bind=db_engine)
|
|
session = SessionLocal()
|
|
|
|
try:
|
|
yield session
|
|
finally:
|
|
session.close()
|
|
|
|
|
|
@pytest.fixture(scope="function")
|
|
def test_db(db_engine, db_session):
|
|
"""Setup and teardown for database tables in tests."""
|
|
from db.session import Base, engine as app_engine
|
|
from models.article import Article
|
|
from models.author import Author
|
|
from models.category import Category
|
|
|
|
# Create tables
|
|
Base.metadata.create_all(bind=db_engine)
|
|
|
|
# Clean up old test tables if any
|
|
for table in Base.metadata.sorted_tables:
|
|
db_session.execute(text(f"DELETE FROM {table.name}"))
|
|
db_session.commit()
|
|
|
|
yield db_session
|
|
|
|
# Cleanup after test
|
|
Base.metadata.drop_all(bind=db_engine)
|
|
|
|
|
|
@pytest.fixture
|
|
def create_db():
|
|
"""Create database tables."""
|
|
from db.session import Base, engine as app_engine
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
return lambda: Base.metadata.drop_all(bind=engine)
|