2022-06-17 01:02:36 +02:00
|
|
|
import os
|
|
|
|
from typing import AsyncGenerator
|
|
|
|
|
2022-06-17 00:43:55 +02:00
|
|
|
import pytest
|
|
|
|
|
|
|
|
from alembic import command, config
|
2022-06-17 01:02:36 +02:00
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
|
|
from database.engine import engine
|
2022-06-17 00:43:55 +02:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
|
|
def tables():
|
|
|
|
"""Initialize a database before the tests, and then tear it down again
|
|
|
|
Starts from an empty database and runs through all the migrations to check those as well
|
|
|
|
while we're at it
|
|
|
|
"""
|
2022-06-17 01:02:36 +02:00
|
|
|
print("CWD: ", os.getcwd())
|
2022-06-17 01:14:22 +02:00
|
|
|
print("Contents: ", list(os.listdir(os.getcwd())))
|
2022-06-17 00:43:55 +02:00
|
|
|
alembic_config = config.Config("alembic.ini")
|
|
|
|
command.upgrade(alembic_config, "head")
|
|
|
|
yield
|
|
|
|
command.downgrade(alembic_config, "base")
|
2022-06-17 01:02:36 +02:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
async def database_session(tables) -> AsyncGenerator[AsyncSession, None]:
|
|
|
|
"""Fixture to create a session for every test
|
|
|
|
Rollbacks the transaction afterwards so that the future tests start with a clean database
|
|
|
|
"""
|
|
|
|
connection = await engine.connect()
|
|
|
|
transaction = await connection.begin()
|
|
|
|
session = AsyncSession(bind=connection, expire_on_commit=False)
|
|
|
|
|
|
|
|
yield session
|
|
|
|
|
|
|
|
# Clean up session & rollback transactions
|
|
|
|
await session.close()
|
|
|
|
if transaction.is_valid:
|
|
|
|
await transaction.rollback()
|
|
|
|
|
|
|
|
await connection.close()
|