import os import pytest import sqlalchemy from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker from dapd_db_schema.schemas.uow_meta import AuditLog from dapd_db_schema.schemas.uow_meta import UnitOfWork, UnitOfWorkStatusEnum class TestSession: def __init__(self) -> None: connection_string_tpl = 'postgresql+psycopg2://{user}:{password}@{host}:{port}/{db}' self._workflow_engine = sqlalchemy.create_engine( connection_string_tpl.format( user=os.environ['PG_USER'], password=os.environ['PG_PASSWORD'], host=os.environ['PG_HOST'], port=os.environ['PG_PORT'], db=os.environ['PG_WORKFLOW_DB'], ) ) self._etl_engine = sqlalchemy.create_engine( connection_string_tpl.format( user=os.environ['PG_USER'], password=os.environ['PG_PASSWORD'], host=os.environ['PG_HOST'], port=os.environ['PG_PORT'], db=os.environ['PG_ETL_DB'], ) ) self._uow_meta_engine = sqlalchemy.create_engine( connection_string_tpl.format( user=os.environ['PG_USER'], password=os.environ['PG_PASSWORD'], host=os.environ['PG_HOST'], port=os.environ['PG_PORT'], db=os.environ['PG_ETL_DB'], ), connect_args={'options': '-csearch_path=uow_meta'} ) workflow_session_cls = sessionmaker(bind=self._workflow_engine) self.workflow_session = workflow_session_cls(autocommit=True, autoflush=True) etl_session_cls = sessionmaker(bind=self._etl_engine) self.etl_session = etl_session_cls(autocommit=True, autoflush=True) uow_meta_session_cls = sessionmaker(bind=self._uow_meta_engine) self.uow_meta_session = uow_meta_session_cls(autocommit=True, autoflush=True) @property def etl_engine(self) -> Engine: return self._etl_engine @property def workflow_engine(self) -> Engine: return self._workflow_engine @property def uow_meta_engine(self) -> Engine: return self._uow_meta_engine def close(self) -> None: self._workflow_engine.dispose() self._etl_engine.dispose() self._uow_meta_engine.dispose() @pytest.fixture(scope='session') def db(): test_session = TestSession() yield test_session test_session.close() @pytest.fixture def unit_of_work(db): instance = UnitOfWork( project='dapd', fact='fact_playlist_track_dynamics', dimensions=['dim_playlist', 'dim_track'], status=UnitOfWorkStatusEnum.EXPORT_IN_PROGRESS, version='v1', first_fact_id=0, last_fact_id=0, ) db.uow_meta_session.add(instance) db.uow_meta_session.flush() yield instance db.uow_meta_session.query(AuditLog).filter(AuditLog.uow_id == instance.uow_id).delete() db.uow_meta_session.delete(instance) db.uow_meta_session.flush()