I am using SQLAlchemy + Ormar and I want to write clean tests as it is possible to write with pytest-django :
import pytest @pytest.mark.django_db def test_user_count(): assert User.objects.count() == 0I'm using FastAPI and I don't use Django at all, so it's not possible to use the decorator like above.
How to write clean tests on model with database access as above but not with Django. It would be great to have that infrastructure for SQLAlchemy + Ormar, but changing ORM is also an option.
Example of model to test:
class User(ormar.Model): class Meta: metadata = metadata database = database id: int = ormar.BigInteger(primary_key=True) phone: str = ormar.String(max_length=100) account: str = ormar.String(max_length=100)I think this discussion may be useful for you https://github.com/collerek/ormar/discussions/136
Using an auto wear accessory should help you:
# fixture @pytest.fixture(autouse=True, scope="module") # adjust your scope def create_test_database(): engine = sqlalchemy.create_engine(DATABASE_URL) metadata.drop_all(engine) # i like to drop also before - even if test crash in the middle we start clean metadata.create_all(engine) yield metadata.drop_all(engine) # actual test - note to test async you need pytest-asyncio and mark test as asyncio @pytest.mark.asyncio async def test_actual_logic(): async with database: # <= note this is the same database that used in ormar Models ... (logic)