Last active
September 6, 2021 18:50
-
-
Save wshayes/584ebe3bc57940398e3a6b9e2f68ebb8 to your computer and use it in GitHub Desktop.
[Example conftest.py for fastapi/sqlalchemy] #fastapi #pytest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From @euri10 -- https://gitter.im/tiangolo/fastapi?at=5cd915ed56271260f95275ac | |
import asyncio | |
import pytest | |
from sqlalchemy import create_engine | |
from sqlalchemy_utils import create_database, database_exists, drop_database | |
from starlette.config import environ | |
from starlette.testclient import TestClient | |
# This sets `os.environ`, but provides some additional protection. | |
# If we placed it below the application import, it would raise an error | |
# informing us that 'TESTING' had already been read from the environment. | |
environ["TESTING"] = "True" | |
environ["EMAILS_ENABLED"] = "False" | |
from app.app import app # isort:skip | |
from app.models import User, UserInCreate, clients, metadata, users # isort:skip | |
from app.settings import database # isort:skip | |
@pytest.fixture(scope="session", autouse=True) | |
def create_test_database(): | |
url = str(database.url) | |
engine = create_engine(url) | |
if database_exists(url): | |
drop_database(url) | |
create_database(url) # Create the test database. | |
metadata.create_all(engine) # Create the tables. | |
yield # Run the tests. | |
drop_database(url) # Drop the test database. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment