3
3
from unittest import mock
4
4
5
5
import pytest
6
+ import pytest_asyncio
6
7
from fastapi .testclient import TestClient
7
8
from sqlalchemy .ext .asyncio import async_sessionmaker
8
9
9
10
from 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
11
14
from tests .mocks import MockAzureCredential
12
15
13
16
POSTGRES_HOST = "localhost"
@@ -51,12 +54,22 @@ def mock_session_env(monkeypatch_session):
51
54
yield
52
55
53
56
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 ):
56
67
"""Create a FastAPI app."""
57
68
if not Path ("src/static/" ).exists ():
58
69
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
60
73
61
74
62
75
@pytest .fixture (scope = "function" )
@@ -67,20 +80,21 @@ def mock_default_azure_credential(mock_session_env):
67
80
yield mock_default_azure_credential
68
81
69
82
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 ):
72
85
"""Create a test client."""
73
-
74
86
with TestClient (app ) as test_client :
75
87
yield test_client
76
88
77
89
78
- @pytest .fixture (scope = "function" )
79
- def db_session ():
90
+ @pytest_asyncio .fixture (scope = "function" )
91
+ async def db_session ():
80
92
"""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 )
82
95
session = async_sesion ()
83
96
session .begin ()
84
97
yield session
85
98
session .rollback ()
86
99
session .close ()
100
+ await engine .dispose ()
0 commit comments