r/FastAPI • u/bluewalt • Dec 18 '24
feedback request I eventually found a way to run unit tests very simply in FastAPI.
After struggling with my unit tests architecture, I ended up with a way that seems very simple and efficient to me. Instead of using FastAPI-level dependency overriding, I simply ensure that pytest always run with overrided env vars. In my conftest.py file, I have one fixture to set the test db up, and one fixture for a test itself.
Here is the (partial) code below. Please tell me if you think this sucks and I'm missing something.
conftest.py
@pytest.fixture(autouse=True, scope="session")
def setup_test_database():
"""Prepare the test database before running tests for the whole session."""
db = settings.POSTGRES_DB
user = settings.POSTGRES_USER
password = settings.POSTGRES_PASSWORD
with admin_engine.connect() as connection:
terminate_active_connections(connection, db=db)
drop_database_if_it_exists(connection, db=db)
drop_role_if_it_exists(connection, user=user)
create_database_user(connection, user=user, password=password)
create_database_with_owner(connection, db=db, user=user)
yield # Run all tests
@pytest.fixture(autouse=True, scope="function")
def reset_database():
"""
Drop all tables and recreate them before each test.
NOTE: this is not performant, as all test functions will run this.
However, this will prevent from any leakage between test.
"""
# Drop and recreate tables
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
# Run the test
yield
pyproject.toml
[tool.pytest.ini_options]
# Overrides local settings for tests. Be careful, you could break current env when running tests, if this is not set.
env = [
"ENVIRONMENT=test",
"DEBUG=False",
"POSTGRES_USER=testuser",
"POSTGRES_PASSWORD=testpwd",
"POSTGRES_DB=testdb",
]
database.py
engine = create_engine(
settings.POSTGRES_URI, # will be overrided when running tests
echo=settings.DATABASE_ECHO,
)
# Admin engine to manage databases (connects to the "postgres" default database)
# It has its own USER/PASSWORD settings because local one are overrided when running tests
admin_engine = create_engine(
settings.POSTGRES_ADMIN_URI,
echo=settings.DATABASE_ECHO,
isolation_level="AUTOCOMMIT", # required from operation like DROP DATABASE
)
27
Upvotes
7
u/unconscionable Dec 18 '24
Depending on your project, I probably wouldn't bother dropping and recreating everything every test case, it will make your test suite significantly slower as your project grows in complexity. For a small project it might never get long enough to care, but if your application grows to be quite large, 5 years down the line you'll have a build that will take an hour to run, and you don't want that - try to keep your build under 10 mins max or you'll never get anything done.
I'd recommend you use factoryboy to create sqlalchemy models for your test cases and don't worry about leftover data between tests - just blow it out before you run your first test and call it a day.
2
u/Sergey_jo Dec 18 '24
Why do you want to create a database for testing instead of mock the parts that communicate with the database since you most properly are testing the api logic not the orm.
2
u/SnowToad23 Dec 18 '24 edited Dec 18 '24
Nice one, however this looks quite potentially dangerous if you accidentally run tests within your production environment... Check out the way I handled this, using fixtures to create a test DB instance in a docker container, and using a transaction to efficiently achieve test isolation of DB state (like Django does).
https://github.com/Finndersen/python-db-project-template
It also means that the DB is not set up for tests that don't need it
You may have to do some extra work to adapt it for FastAPI, in terms of providing the test DB connection/session as a dependency
3
u/Doomdice Dec 18 '24
Consider using the testcontainers-python module. New DB every run--this approach forces you to run migrations too so you'll catch any breakages there. Yeah you still don't want to teardown the whole thing between test cases but you can put it in a pytest fixture that will live however long you specify (session, module, etc).
https://github.com/testcontainers/testcontainers-python
2
u/block63 Dec 18 '24
gonna try this
1
u/singlebit Dec 19 '24
!remindme 1 week
0
u/TwinsenDinoFly Dec 18 '24
Interesting