Estoy usando SQLAlchemy + Ormar y quiero escribir pruebas limpias, ya que es posible escribir con pytest-django :
import pytest
@pytest.mark.django_db
def test_user_count():
assert User.objects.count() == 0
Estoy usando FastAPI y no uso Django en absoluto, por lo que no es posible usar el decorador como el anterior.
Cómo escribir pruebas limpias en el modelo con acceso a la base de datos como se indicó anteriormente pero no con Django. Sería genial tener esa infraestructura para SQLAlchemy + Ormar, pero cambiar ORM también es una opción.
Ejemplo de modelo a probar:
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)Creo que esta discusión puede ser útil para ti https://github.com/collerek/ormar/discussions/136
El uso de un accesorio de uso automático debería ayudarlo a:
# 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)