conftest.py
1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import sys
import os
from pathlib import Path
def _ensure_local_deps_on_path() -> None:
deps = Path(__file__).resolve().parents[1] / ".deps"
if deps.exists():
deps_str = str(deps)
if deps_str not in sys.path:
sys.path.insert(0, deps_str)
_ensure_local_deps_on_path()
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.infrastructure.database import Base, get_db
import app.model # noqa: F401
from app.infrastructure.session_store import clear_default_store_for_tests
from app.infrastructure.schema_patch import ensure_runtime_schema
SQLALCHEMY_DATABASE_URL = os.getenv("TEST_DATABASE_URL", "")
engine = None
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False)
def get_test_database_url() -> str:
if not SQLALCHEMY_DATABASE_URL:
raise RuntimeError("TEST_DATABASE_URL is required for backend tests")
return SQLALCHEMY_DATABASE_URL
def init_testing_database():
global engine
if engine is None:
engine = create_engine(get_test_database_url(), pool_pre_ping=True)
TestingSessionLocal.configure(bind=engine)
Base.metadata.create_all(bind=engine)
ensure_runtime_schema(engine)
return engine
def get_testing_engine():
return init_testing_database()
def override_get_db():
try:
db = TestingSessionLocal()
yield db
finally:
db.close()
@pytest.fixture
def db_session():
init_testing_database()
db = TestingSessionLocal()
yield db
db.close()
@pytest.fixture
def test_app():
from app.main import app
init_testing_database()
app.dependency_overrides[get_db] = override_get_db
try:
yield app
finally:
app.dependency_overrides.pop(get_db, None)
@pytest.fixture(autouse=True)
def clear_session_kv_store():
clear_default_store_for_tests()
yield