fix test teardown
All checks were successful
Backend CI / unit-test (push) Successful in 24s

This commit is contained in:
2025-09-14 17:17:48 +02:00
parent 1d215c8032
commit 5753ad3767
3 changed files with 167 additions and 126 deletions

View File

@@ -11,14 +11,19 @@ from trading_journal import crud, models
@pytest.fixture
def engine() -> Engine:
def engine() -> Generator[Engine, None, None]:
e = create_engine(
"sqlite:///:memory:",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
SQLModel.metadata.create_all(e)
return e
try:
yield e
finally:
SQLModel.metadata.drop_all(e)
SQLModel.metadata.clear()
e.dispose()
@pytest.fixture
@@ -41,7 +46,7 @@ def make_cycle(session, user_id: int, friendly_name: str = "Test Cycle") -> int:
friendly_name=friendly_name,
symbol="AAPL",
underlying_currency="USD",
status="open",
status=models.CycleStatus.OPEN,
start_date=datetime.now().date(),
)
session.add(cycle)

View File

@@ -3,7 +3,7 @@ from contextlib import contextmanager, suppress
import pytest
from sqlalchemy import text
from sqlmodel import Session
from sqlmodel import Session, SQLModel
from trading_journal.db import Database, create_database
@@ -27,10 +27,27 @@ def session_ctx(db: Database) -> Generator[Session, None, None]:
# Normal completion: advance generator to let it commit/close.
with suppress(StopIteration):
next(gen)
finally:
# close the generator but DO NOT dispose the engine here
gen.close()
@contextmanager
def database_ctx(db: Database) -> Generator[Database, None, None]:
"""
Test-scoped context manager to ensure the Database (engine) is disposed at test end.
Use this to wrap test logic that needs the same in-memory engine across multiple sessions.
"""
try:
yield db
finally:
db.dispose()
SQLModel.metadata.clear()
def test_select_one_executes() -> None:
db = create_database(None) # in-memory by default
with database_ctx(db):
with session_ctx(db) as session:
val = session.exec(text("SELECT 1")).scalar_one()
assert int(val) == 1
@@ -38,8 +55,11 @@ def test_select_one_executes() -> None:
def test_in_memory_persists_across_sessions_when_using_staticpool() -> None:
db = create_database(None) # in-memory with StaticPool
with database_ctx(db):
with session_ctx(db) as s1:
s1.exec(text("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, val TEXT);"))
s1.exec(
text("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, val TEXT);")
)
s1.exec(text("INSERT INTO t (val) VALUES (:v)").bindparams(v="hello"))
with session_ctx(db) as s2:
got = s2.exec(text("SELECT val FROM t")).scalar_one()
@@ -48,6 +68,7 @@ def test_in_memory_persists_across_sessions_when_using_staticpool() -> None:
def test_sqlite_pragmas_applied() -> None:
db = create_database(None)
with database_ctx(db):
# PRAGMA returns integer 1 when foreign_keys ON
with session_ctx(db) as session:
fk = session.exec(text("PRAGMA foreign_keys")).scalar_one()
@@ -57,12 +78,20 @@ def test_sqlite_pragmas_applied() -> None:
def test_rollback_on_exception() -> None:
db = create_database(None)
db.init_db()
with database_ctx(db):
# Create table then insert and raise inside the same session to force rollback
with pytest.raises(RuntimeError): # noqa: PT012, SIM117
with session_ctx(db) as s:
s.exec(text("CREATE TABLE IF NOT EXISTS t_rb (id INTEGER PRIMARY KEY, val TEXT);"))
s.exec(text("INSERT INTO t_rb (val) VALUES (:v)").bindparams(v="will_rollback"))
s.exec(
text(
"CREATE TABLE IF NOT EXISTS t_rb (id INTEGER PRIMARY KEY, val TEXT);"
)
)
s.exec(
text("INSERT INTO t_rb (val) VALUES (:v)").bindparams(
v="will_rollback"
)
)
# simulate handler error -> should trigger rollback in get_session
raise RuntimeError("simulated failure")

View File

@@ -1,7 +1,7 @@
import pytest
from sqlalchemy import text
from sqlalchemy.pool import StaticPool
from sqlmodel import create_engine
from sqlmodel import SQLModel, create_engine
from trading_journal import db_migration
@@ -18,6 +18,7 @@ def test_run_migrations_0_to_1(monkeypatch: pytest.MonkeyPatch) -> None:
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
try:
monkeypatch.setattr(db_migration, "LATEST_VERSION", 1)
final_version = db_migration.run_migrations(engine)
assert final_version == 1
@@ -90,10 +91,13 @@ def test_run_migrations_0_to_1(monkeypatch: pytest.MonkeyPatch) -> None:
# validate each table columns
for tbl_name, cols in expected_schema.items():
info_rows = conn.execute(text(f"PRAGMA table_info({tbl_name})")).fetchall()
info_rows = conn.execute(
text(f"PRAGMA table_info({tbl_name})")
).fetchall()
# map: name -> (type, notnull, pk)
actual = {
r[1]: ((r[2] or "").upper(), int(r[3]), int(r[5])) for r in info_rows
r[1]: ((r[2] or "").upper(), int(r[3]), int(r[5]))
for r in info_rows
}
for colname, (exp_type, exp_notnull, exp_pk) in cols.items():
assert colname in actual, f"{tbl_name}: missing column {colname}"
@@ -122,3 +126,6 @@ def test_run_migrations_0_to_1(monkeypatch: pytest.MonkeyPatch) -> None:
]
for efk in fks:
assert efk in actual_fk_list, f"missing FK on {tbl_name}: {efk}"
finally:
engine.dispose()
SQLModel.metadata.clear()