How can I use a in memory database for pytest or avoid that data acutally will write in database after the test, like Django TestCase?
I don't want to change my code. I've created a function for creating a user with validation and more. For that function I used SQLAchemy with a asynchronous ContextManager for connection setup.
Like:
class DatabaseConnection:
async def __aenter__(self):
...
async def __aexit__(self, exc_type, exc_val, exc_tb):
...
My user creation looks like this then:
async def create_user(self, username: str, display_name: str, biography: str):
""" Create a new user in the database. """
# Validation with Pydantic ...
# Run the SQLAlchemy session and create the user
async with DatabaseConnection() as session:
...
Now when I start to test this function in pytest, it writes the data in the database but its only a test and I don't want to save useless and unreal data in my database.
conftest.py
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from initialisier import AsyncSessionLocal
import logging
logger = logging.getLogger(__name__)
@pytest.fixture
async def db_session():
async with AsyncSessionLocal() as session:
try:
yield session
except Exception as e:
logger.error(f"Error during test: {e}", exc_info=True)
finally:
await session.rollback()
test_service.py
@pytest.mark.asyncio
async def test_create_user_success(self, db_session, monkeypatch):
""" Test creating a user successfully. """
async def fake_enter(self):
return db_session
monkeypatch.setattr("connection.DatabaseConnection.__aenter__", fake_enter)
user = await self.service.create(
username=self.username, display_name=self.display_name, biography=self.biography
)
assert user is not None
assert user.username == self.username
assert user.display_name == self.display_name
assert user.biography == self.biography
assert user.id is not None