43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
from __future__ import annotations
|
|
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from typing import Iterator
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
from hockey_data.models import Base
|
|
|
|
|
|
class LocalTestDatabase:
|
|
"""SQLite-only adapter for unit tests.
|
|
|
|
Production deliberately requires PostgreSQL; tests use this lightweight
|
|
adapter so they do not weaken or bypass the production database policy.
|
|
"""
|
|
|
|
def __init__(self, path: Path) -> None:
|
|
self.engine = create_engine(f"sqlite:///{Path(path).as_posix()}", future=True)
|
|
self.SessionFactory = sessionmaker(
|
|
bind=self.engine,
|
|
autoflush=False,
|
|
expire_on_commit=False,
|
|
future=True,
|
|
)
|
|
|
|
def create_all(self) -> None:
|
|
Base.metadata.create_all(self.engine)
|
|
|
|
@contextmanager
|
|
def session(self) -> Iterator[Session]:
|
|
session = self.SessionFactory()
|
|
try:
|
|
yield session
|
|
session.commit()
|
|
except Exception:
|
|
session.rollback()
|
|
raise
|
|
finally:
|
|
session.close()
|