Junior — Middle
What tool or library do you use to simulate the process when developing with FastAPI?
sobes.tech AI
Answer from AI
For mocking during development with FastAPI, the library pytest along with pytest-mock or the standard module unittest.mock are often used. This allows dependencies, such as databases or external APIs, to be replaced in order to test the application's logic in isolation.
Example of using unittest.mock to replace a dependency:
from fastapi import FastAPI, Depends
from unittest.mock import MagicMock
import pytest
app = FastAPI()
def get_data():
# Imagine this is a database query
return "real data"
@app.get("/items")
def read_items(data=Depends(get_data)):
return {"data": data}
# In the test
@pytest.fixture
def mock_get_data(monkeypatch):
monkeypatch.setattr("main.get_data", lambda: "stub")
def test_read_items(mock_get_data):
from fastapi.testclient import TestClient
client = TestClient(app)
response = client.get("/items")
assert response.json() == {"data": "stub"}
Thus, it is possible to simulate the behavior of dependencies and test the FastAPI application without real calls.