33from unittest import mock
44
55import pytest
6+ import pytest_asyncio
67from fastapi .testclient import TestClient
78from sqlalchemy .ext .asyncio import async_sessionmaker
89
910from fastapi_app import create_app
10- from fastapi_app .globals import global_storage
11+ from fastapi_app .postgres_engine import create_postgres_engine_from_env
12+ from fastapi_app .setup_postgres_database import create_db_schema
13+ from fastapi_app .setup_postgres_seeddata import seed_data
1114from tests .mocks import MockAzureCredential
1215
1316POSTGRES_HOST = "localhost"
@@ -51,12 +54,22 @@ def mock_session_env(monkeypatch_session):
5154 yield
5255
5356
54- @pytest .fixture (scope = "session" )
55- def app (mock_session_env ):
57+ async def create_and_seed_db ():
58+ """Create and seed the database."""
59+ engine = await create_postgres_engine_from_env ()
60+ await create_db_schema (engine )
61+ await seed_data (engine )
62+ await engine .dispose ()
63+
64+
65+ @pytest_asyncio .fixture (scope = "session" )
66+ async def app (mock_session_env ):
5667 """Create a FastAPI app."""
5768 if not Path ("src/static/" ).exists ():
5869 pytest .skip ("Please generate frontend files first!" )
59- return create_app (testing = True )
70+ app = create_app (testing = True )
71+ await create_and_seed_db ()
72+ return app
6073
6174
6275@pytest .fixture (scope = "function" )
@@ -67,20 +80,21 @@ def mock_default_azure_credential(mock_session_env):
6780 yield mock_default_azure_credential
6881
6982
70- @pytest .fixture (scope = "function" )
71- def test_client (monkeypatch , app , mock_default_azure_credential ):
83+ @pytest_asyncio .fixture (scope = "function" )
84+ async def test_client (monkeypatch , app , mock_default_azure_credential ):
7285 """Create a test client."""
73-
7486 with TestClient (app ) as test_client :
7587 yield test_client
7688
7789
78- @pytest .fixture (scope = "function" )
79- def db_session ():
90+ @pytest_asyncio .fixture (scope = "function" )
91+ async def db_session ():
8092 """Create a new database session with a rollback at the end of the test."""
81- async_sesion = async_sessionmaker (autocommit = False , autoflush = False , bind = global_storage .engine )
93+ engine = await create_postgres_engine_from_env ()
94+ async_sesion = async_sessionmaker (autocommit = False , autoflush = False , bind = engine )
8295 session = async_sesion ()
8396 session .begin ()
8497 yield session
8598 session .rollback ()
8699 session .close ()
100+ await engine .dispose ()
0 commit comments