Skip to content

Commit bd06a43

Browse files
committed
Replaced 'start_postgres' with same test-safe functions as for ISPyB database
1 parent ee04386 commit bd06a43

1 file changed

Lines changed: 54 additions & 10 deletions

File tree

tests/conftest.py

Lines changed: 54 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import os
23
from configparser import ConfigParser
34
from pathlib import Path
45
from typing import Any, Generator, Type, TypeVar
@@ -12,8 +13,6 @@
1213
from sqlalchemy.orm import sessionmaker
1314

1415
from murfey.util.db import Session as MurfeySession
15-
from murfey.util.db import clear, setup
16-
from tests import murfey_db_engine, murfey_db_url
1716

1817

1918
@pytest.fixture(scope="session")
@@ -243,12 +242,57 @@ def ispyb_db_session(
243242
"""
244243

245244

245+
@pytest.fixture(scope="session")
246+
def murfey_db_engine():
247+
url = (
248+
f"postgresql+psycopg2://{os.environ['POSTGRES_USER']}:{os.environ['POSTGRES_PASSWORD']}"
249+
f"@{os.environ['POSTGRES_HOST']}:{os.environ['POSTGRES_PORT']}/{os.environ['POSTGRES_DB']}"
250+
)
251+
engine = create_engine(url)
252+
yield engine
253+
engine.dispose()
254+
255+
256+
@pytest.fixture(scope="session")
257+
def murfey_db_session_factory(murfey_db_engine):
258+
return sessionmaker(bind=murfey_db_engine, expire_on_commit=False)
259+
260+
261+
@pytest.fixture(scope="session")
262+
def seed_murfey_db(murfey_db_session_factory):
263+
# Populate Murfey database with initial values
264+
murfey_session: SQLAlchemySession = murfey_db_session_factory()
265+
_ = get_or_create_db_entry(
266+
session=murfey_session,
267+
table=MurfeySession,
268+
lookup_kwargs={
269+
"name": f"{ExampleVisit.proposal_code}{ExampleVisit.proposal_number}-{ExampleVisit.visit_number}",
270+
},
271+
)
272+
murfey_session.close()
273+
274+
246275
@pytest.fixture
247-
def start_postgres():
248-
clear(murfey_db_url)
249-
setup(murfey_db_url)
250-
251-
murfey_session = MurfeySession(id=2, name="cm12345-6")
252-
with SQLAlchemySession(murfey_db_engine) as murfey_db:
253-
murfey_db.add(murfey_session)
254-
murfey_db.commit()
276+
def murfey_db_session(
277+
murfey_db_session_factory,
278+
murfey_db_engine: Engine,
279+
seed_murfey_db,
280+
) -> Generator[SQLAlchemySession, None, None]:
281+
"""
282+
Returns a test-safe session that wraps each test in a rollback-safe save point
283+
"""
284+
connection = murfey_db_engine.connect()
285+
transaction = connection.begin()
286+
287+
session: SQLAlchemySession = murfey_db_session_factory(bind=connection)
288+
session.begin_nested() # Save point for test
289+
290+
# Trigger the restart_savepoint function after the end of the transaction
291+
event.listen(session, "after_transaction_end", restart_savepoint)
292+
293+
try:
294+
yield session
295+
finally:
296+
session.close()
297+
transaction.rollback()
298+
connection.close()

0 commit comments

Comments
 (0)