Files
WonderQ-Project/WonderQ-Admin/tests/test_api_response.py
duanshuwen e082bd2d98 feat(api): 实现三端统一的JSON API响应契约
- 新增`api_response.py`统一响应封装工具类,提供标准成功/错误响应构造方法
- 重构WonderQ-Admin全局异常处理器,将所有异常转换为标准响应格式
- 修改所有公共和管理端接口的返回逻辑,统一使用`code`(与HTTP状态码一致)、`msg`和`data`的三层结构
- 新增`api-response-contract.md`文档,定义完整的三端统一JSON响应规范
- 更新所有领域API文档,明确业务数据需位于`data`字段内,补充响应格式说明
- 为WonderQ-MiniAPP和WonderQ-Admin-UI新增响应解析逻辑和类型定义,自动完成协议校验和错误处理
- 更新所有测试用例,适配新的响应结构确保接口符合契约要求
- 新增`module-config-api.md`模块配置API文档,补充站点模块配置的接口约定
- 更新项目README文档,调整文档分类顺序将响应契约置于首位
2026-08-19 22:02:20 +08:00

66 lines
1.7 KiB
Python

import json
import pytest
from fastapi.testclient import TestClient
from app.api_response import error_response
from app.database import get_db
from app.main import create_app
class EmptyDb:
def scalar(self, _statement):
return None
def test_health_uses_the_standard_success_envelope():
response = TestClient(create_app()).get("/health")
assert response.status_code == 200
assert response.json() == {
"code": 200,
"msg": "success",
"data": {"ok": True, "service": "miniapp-api"},
}
def test_public_not_found_uses_the_standard_error_envelope():
app = create_app()
app.dependency_overrides[get_db] = lambda: EmptyDb()
try:
response = TestClient(app).get("/api/public/details/missing-detail")
finally:
app.dependency_overrides.clear()
assert response.status_code == 404
assert response.json() == {
"code": 404,
"msg": "详情不存在",
"data": None,
}
def test_request_validation_uses_the_standard_error_envelope():
response = TestClient(create_app()).post("/api/public/leads", json={})
assert response.status_code == 400
body = response.json()
assert body["code"] == 400
assert body["data"] is None
assert body["errorCode"] == "VALIDATION_ERROR"
assert body["msg"]
@pytest.mark.parametrize("status_code", [400, 401, 404, 409, 422, 500])
def test_supported_error_statuses_keep_the_same_envelope(status_code):
response = error_response(status_code, "示例错误", error_code="EXAMPLE_ERROR")
assert response.status_code == status_code
assert json.loads(response.body) == {
"code": status_code,
"msg": "示例错误",
"data": None,
"errorCode": "EXAMPLE_ERROR",
}