Add conftest.py for globally used fixtures

This commit is contained in:
linuskmr 2021-12-23 18:25:32 +01:00
parent dde11213c0
commit fc08032f0a

View file

@ -0,0 +1,39 @@
# Conftest.py includes globally used functions. These are especially fixtures, which are used for dependency injection.
# See https://www.tutorialspoint.com/pytest/pytest_conftest_py.htm
# See https://gist.github.com/peterhurford/09f7dcda0ab04b95c026c60fa49c2a68
import pytest
from sqlmodel import create_engine, Session, SQLModel
from fastapi.testclient import TestClient
from sqlmodel.pool import StaticPool
from src import database
from src.main import app
@pytest.fixture(name="session")
def session_fixture():
"""Creates a mock session, that access an in-memory temporary database."""
engine = create_engine(
"sqlite://", # In memory database
connect_args={"check_same_thread": False}, # FastAPI's async functions may execute on different threads
poolclass=StaticPool # All threads should access shared memory
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
@pytest.fixture(name="client")
def client_fixture(session: Session):
"""Creates a FastAPI TestClient with a mocked session dependency. This causes FastAPI to inject the fake session
into path operation functions, so that we have full control over the mocked database."""
def get_session_override():
return session
app.dependency_overrides[database.get_session] = get_session_override
client = TestClient(app)
yield client
app.dependency_overrides.clear()