Skip to content

Instantly share code, notes, and snippets.

@saichenko
Created October 14, 2021 19:38
Show Gist options
  • Save saichenko/508e43c2e1169c86d91b0c322ce65d07 to your computer and use it in GitHub Desktop.
Save saichenko/508e43c2e1169c86d91b0c322ce65d07 to your computer and use it in GitHub Desktop.
Example of configuring a database with Alembic migrations using the 'pytest-async-sqlalchemy' lib
import asyncio
import pytest
from alembic.command import upgrade as alembic_upgrade
from alembic.config import Config as AlembicConfig
from pytest_async_sqlalchemy import create_database, drop_database
@pytest.fixture(scope="session")
def event_loop():
"""Create an instance of the default event loop for the test session."""
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="session")
def _database_url():
"""Return database url with driver."""
return 'postgresql+asyncpg://user:1234@localhost/dbtest'
@pytest.fixture(scope="session")
async def database(database_url, event_loop):
"""Set up database with alembic migrations."""
await create_database(database_url)
alembic_config = AlembicConfig('alembic.ini')
alembic_upgrade(alembic_config, 'head')
try:
yield database_url
finally:
await drop_database(database_url)
@saichenko
Copy link
Author

By the way, make sure your test database url for Alembic does not contain a driver and is configured correctly in env.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment