简体   繁体   中英

FastAPI dependency override faild

I'm using MongoMock to test my FastAPI app, but I can' override FastAPI's Dependency.

The create_test_data will insert some fake test data with MongoMock' Client and return the task_id which is need by api request.

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.

Following code is get_db , the connect_to_mongo will return an pymongo's MongoClient not MongoMock's 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 . In addition, your conn should call your fixture too.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM