[英]FastAPI dependency override faild
I'm using MongoMock to test my FastAPI app, but I can' override FastAPI's Dependency.我正在使用 MongoMock 来测试我的 FastAPI 应用程序,但我无法覆盖 FastAPI 的依赖项。
The create_test_data
will insert some fake test data with MongoMock' Client and return the task_id
which is need by api request. create_test_data
将使用 MongoMock 的客户端插入一些伪造的测试数据,并返回task_id
请求所需的 task_id。
from mongomock import MongoClient
from fastapi.testclient import TestClient
from pytest import fixture
from app import app
from core.utils.db_utils import get_db
from models.tasks import TaskCreate
from models.frequency import Frequency
@fixture(name="conn")
def conn_fixture():
with MongoClient() as conn:
yield conn
@fixture(name="client")
def client_fixture(conn: MongoClient):
def get_conn_override():
return conn
app.dependency_overrides[get_db] = get_conn_override
client = TestClient(app)
yield client
app.dependency_overrides.clear()
def test_wrong_api_log(conn: MongoClient, client: TestClient):
task_id = create_test_data(conn=conn, platform="test")
assert task_id
response = client.get(url=f"/api/tasks/{task_id}")
assert response.text
In "test_wrong_api_log" function, the first assert with task_id can pass, but the second one, can't pass seems like override FastAPI's dependency faild cause.在“test_wrong_api_log”function 中,第一个带有 task_id 的断言可以通过,但第二个不能通过似乎是覆盖 FastAPI 的依赖失败原因。
Following code is get_db
, the connect_to_mongo
will return an pymongo's MongoClient not MongoMock's MongoClient.以下代码是get_db
, connect_to_mongo
将返回 pymongo 的 MongoClient 而不是 MongoMock 的 MongoClient。
from db.mongodb_utils import connect_to_mongo
def get_db():
db_client = connect_to_mongo()
try:
yield db_client
finally:
db_client.close()
Is there anyway to resolve this problem?无论如何要解决这个问题?
You neither ever call your client_fixture
.你永远不会打电话给你的client_fixture
。 In addition, your conn
should call your fixture too.此外,您的conn
也应该调用您的夹具。
Try this尝试这个
def test_wrong_api_log(conn_fixture: MongoClient, client_fixture: TestClient):
task_id = create_test_data(conn=conn_fixture, platform="test")
assert task_id
response = client_fixture.get(url=f"/api/tasks/{task_id}")
assert response.text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.