From fc08032f0a2a4fd82101a70098f9d733a71060a3 Mon Sep 17 00:00:00 2001 From: linuskmr Date: Thu, 23 Dec 2021 18:25:32 +0100 Subject: [PATCH] Add conftest.py for globally used fixtures --- backend/src/routes/conftest.py | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 backend/src/routes/conftest.py diff --git a/backend/src/routes/conftest.py b/backend/src/routes/conftest.py new file mode 100644 index 0000000..1bda08c --- /dev/null +++ b/backend/src/routes/conftest.py @@ -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() \ No newline at end of file