首页 > 解决方案 > 由于 Mongoengine 连接未定义错误,使用 FastAPI、Mongoengine 和 Pytest 进行单元测试失败

问题描述

这是我试图模拟数据库的单元测试。/server_db_details 端点使用 fetch_details 函数返回数据库中存在的所有详细信息。我正在尝试对该函数进行修补,以便它始终在我的测试用例中返回所需的数据(附在下面)。

from .import client
from ..core.models import config_details_queries


def test_get_details(monkeypatch):
    data = [{"server_name": "test_server",
             "db_details": {"acm_db": "test_acm_db", "jcp_db": "test_jcp_db"},
             "user_name": "test_username",
             "password": "encrypted_test_password"}]
    test_response_data = {
        "status": 200, "msg": "List of all details",
        "data": data}

    async def mock_get():
        return test_response_data

    monkeypatch.setattr(config_details_queries, "fetch_details", mock_get)

    response = client.get("/server_db_details")
    assert response.status_code == 200
    assert response.json() == test_response_data

fetch_details 函数中有一个 try-except 块,它基本上捕获了一个异常,说没有定义 mongodb 连接。谁能帮我解决这个问题。我是测试和 TDD 的新手。

# Used to fetch all the details stored in the MongoDb document.
def fetch_details() -> List:
    details_list = []
    try:
        details = TPSmartFlowMigratorConfigDetails.objects
        for detail in details:
            db_details = [db_detail.as_dict()
                          for db_detail in detail.db_details]
            details_list.append({
                "_id": str(detail.id),
                "server_name": detail.server_name,
                "db_details": db_details,
                "user_name": detail.user_name,
                "password": detail.password
            })
        return details_list
    except Exception as e:
        print(e.args)

如果有帮助,还可以添加端点。

@router.get("/", responses={500: {}})
def get_details() -> JSONResponse:
    """
        Endpoint to fetch all the details stored in the MongoDb configuration
        database.
    """

    details: List = fetch_details()
    if details is not None:
        return JSONResponse(status_code=status.HTTP_200_OK, content={
            "status": 200,
            "msg": "List of all details",
            "data": details
        })
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={"status": 500, "msg": "Could not fetch details",
                 "data": None})

标签: python-3.xmongodbpytestmongoenginefastapi

解决方案


推荐阅读