@denis
In FastAPI, you can set up and tear down a database between tests using fixture functions.
Here is an example of how to set up and tear down a database between tests in FastAPI:
1
|
pip install sqlalchemy |
1 2 3 4 5 6 7 8 9 10 11 12 |
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import pytest from app.models import Base, engine, SessionLocal @pytest.fixture(scope="session") def create_test_database(): Base.metadata.create_all(bind=engine) yield Base.metadata.drop_all(bind=engine) @pytest.fixture def db_session(create_test_database): session = SessionLocal() yield session session.close() |
1 2 3 4 5 6 7 |
def test_create_user(db_session): # Test code that uses the database session ... def test_update_user(db_session): # Test code that uses the database session ... |
By following these steps, you can easily set up and tear down a database between tests in FastAPI using fixture functions.