Skip to content

Instantly share code, notes, and snippets.

@timhughes
Last active April 13, 2020 02:00
Show Gist options
  • Save timhughes/014575d06148de5d1ffe804c087dc976 to your computer and use it in GitHub Desktop.
Save timhughes/014575d06148de5d1ffe804c087dc976 to your computer and use it in GitHub Desktop.
Failed example at test isolation
import secrets
from datetime import timedelta
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from fastapp import settings, crud
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session, sessionmaker
# from fastapp.main import app
# Create a test database and override app
from fastapp.db.session import DBBase, get_db
from fastapp.models.user import UserModel
from fastapp.routers.utils.security import create_access_token
from fastapp.schemas.user import UserCreateSchema
engine = create_engine(
settings.TEST_DATABASE_URI,
pool_pre_ping=True,
connect_args={"check_same_thread": False},
)
TestSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
DBBase.metadata.create_all(engine)
def override_get_db():
try:
db = TestSessionLocal()
yield db
finally:
db.close()
@pytest.yield_fixture
def db_session() -> Session:
"""Returns an sqlalchemy session, and after the test tears down everything properly."""
connection = engine.connect()
# begin the nested transaction
transaction = connection.begin()
# use the connection with the already started transaction
session = Session(bind=connection)
yield session
session.close()
# roll back the broader transaction
transaction.rollback()
# put back the connection to the connection pool
connection.close()
@pytest.fixture
def app(db_session) -> FastAPI:
from fastapp.main import get_application # local import for testing purpose
app = get_application()
app.dependency_overrides[get_db] = override_get_db
return app
@pytest.fixture
def client(app) -> TestClient:
client = TestClient(app)
yield client
print("end client")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment