microblog/tests/conftest.py

53 lines
1.5 KiB
Python
Raw Normal View History

2022-06-22 18:11:22 +00:00
from typing import Generator
import pytest
from fastapi.testclient import TestClient
from app.database import Base
2022-07-10 13:29:51 +00:00
from app.database import SessionLocal
2022-06-29 18:43:17 +00:00
from app.database import async_engine
from app.database import async_session
2022-06-22 18:11:22 +00:00
from app.database import engine
from app.main import app
2022-06-29 18:43:17 +00:00
@pytest.fixture
async def async_db_session():
async with async_session() as session:
async with async_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield session
async with async_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
2022-06-22 18:11:22 +00:00
@pytest.fixture
def db() -> Generator:
Base.metadata.create_all(bind=engine)
try:
2022-07-10 13:29:51 +00:00
yield SessionLocal()
finally:
try:
Base.metadata.drop_all(bind=engine)
except Exception:
# XXX: for some reason, the teardown occasionally fails because of this
pass
2022-06-22 18:11:22 +00:00
@pytest.fixture
def exclude_fastapi_middleware():
"""Workaround for https://github.com/encode/starlette/issues/472"""
user_middleware = app.user_middleware.copy()
app.user_middleware = []
app.middleware_stack = app.build_middleware_stack()
yield
app.user_middleware = user_middleware
app.middleware_stack = app.build_middleware_stack()
@pytest.fixture
def client(db, exclude_fastapi_middleware) -> Generator:
2022-06-29 18:43:17 +00:00
# app.dependency_overrides[get_db] = _get_db_for_testing
2022-06-22 18:11:22 +00:00
with TestClient(app) as c:
yield c