didier/tests/conftest.py

57 lines
1.5 KiB
Python
Raw Normal View History

2022-06-22 02:05:04 +02:00
import asyncio
from typing import AsyncGenerator, Generator
2022-06-21 21:06:11 +02:00
from unittest.mock import MagicMock
2022-06-17 01:02:36 +02:00
2022-06-17 00:43:55 +02:00
import pytest
2022-06-17 01:02:36 +02:00
from sqlalchemy.ext.asyncio import AsyncSession
from database.engine import engine
2022-06-23 11:53:21 +02:00
from database.models import Base
2022-06-21 21:06:11 +02:00
from didier import Didier
2022-06-17 00:43:55 +02:00
@pytest.fixture(scope="session")
2022-06-22 02:05:04 +02:00
def event_loop() -> Generator:
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="session")
2022-06-23 11:53:21 +02:00
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)
2022-06-17 01:02:36 +02:00
@pytest.fixture
2022-06-22 02:05:04 +02:00
async def database_session(tables, event_loop) -> AsyncGenerator[AsyncSession, None]:
2022-06-17 01:02:36 +02:00
"""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()
2022-06-21 21:06:11 +02:00
@pytest.fixture
def mock_client() -> Didier:
"""Fixture to get a mock Didier instance
The mock uses 0 as the id
"""
mock_client = MagicMock()
mock_user = MagicMock()
mock_user.id = 0
mock_client.user = mock_user
return mock_client