From b4a3a87e6e15c1724f1861f4fe41f893156cc62d Mon Sep 17 00:00:00 2001 From: stijndcl Date: Wed, 29 Jun 2022 00:25:51 +0200 Subject: [PATCH] Use alembic in tests again? --- alembic/env.py | 8 +++++++- tests/conftest.py | 7 +++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/alembic/env.py b/alembic/env.py index f28faf3..82eae2b 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -68,4 +68,10 @@ async def run_migrations_online() -> None: if context.is_offline_mode(): run_migrations_offline() else: - asyncio.run(run_migrations_online()) + # Wonky way to use the Pytest event loop instead of another one + try: + loop = asyncio.get_running_loop() + if loop and loop.is_running(): + loop.create_task(run_migrations_online()) + except RuntimeError: + asyncio.run(run_migrations_online()) diff --git a/tests/conftest.py b/tests/conftest.py index 799c3bc..ded04d5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,7 @@ from unittest.mock import MagicMock import pytest from sqlalchemy.ext.asyncio import AsyncSession +from alembic import config, command from database.engine import engine from database.models import Base from didier import Didier @@ -20,8 +21,10 @@ def event_loop() -> Generator: @pytest.fixture(scope="session") async def tables(event_loop): """Initialize a database before the tests, and then tear it down again""" - async with engine.begin() as connection: - await connection.run_sync(Base.metadata.create_all) + alembic_config: config.Config = config.Config("alembic.ini") + command.upgrade(alembic_config, "head") + yield + command.downgrade(alembic_config, "base") @pytest.fixture