python-3.x - 由于 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})
解决方案
推荐阅读
- oauth-2.0 - 多个客户端交换 AuthCode 以获取令牌
- python - 学习编码,我有一个关于 IF on python 的问题
- procedure - 程序genexus中的无限循环
- python - 我在列表中有一个列表,需要将其放入数据框
- javascript - 为什么 clearTimeout 在我的代码中不起作用?javascript
- java - Maven 包与 Tomcat 一起工作时出错:Maven 包将 .war 和 WEB-INF 放在目标中,Tomcat 在根目录中查找它
- reactjs - 如何在 react-leaflet 中捕获 MapControl 的鼠标单击和拖动事件
- javascript - 如何将 Ruby 会话变量传递给 JavaScript 标记
- html - 如何循环浏览具有多个对象的页面
- c - 在有序对结构数组上实现二进制搜索