I want to write tests for my FastAPI endpoints
example for my code:
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/todos")
async def get_todo_by_title(title: str,current_user: User = Depends(get_current_user))
document = await collection.find_one({"title": title})
return document
client = TestClient(app)
def test_get_todo_by_title():
response = client.get("/todos")
assert response.status_code == 200
What the best way to test my endpoints?
I want to use fake DB for testing, something like json file
db = {
todos: [...]
}
It is not the best option to use fake data from a JSON file. Instead, you can use a testing DB (based on the env you are running your app through), or any other DB (dev, stg, ..etc), and delete your test data after running all unit tests.
Here is how to simply apply the latter approach in FastAPI;
conftest.py
Unit tests should look like the following sample.
test_X_endpoints.py