Files
syops/backend/tests/test_api_error_contract.py

78 lines
3.2 KiB
Python

"""
backend/tests/test_api_error_contract.py
用途:冒烟验证标准 JSON API 错误 envelope 与 Dify Tool API legacy 错误格式。
依赖:tests.conftest 的 client/app fixture、parse_api_error。
逻辑:Wave 1 AppError 契约回归;Tool 路由刻意保持 { ok, error_code, message }。
"""
from tests.conftest import parse_api_error
def _assert_standard_error_envelope(body: dict, *, code: str, status: int) -> dict:
"""断言标准 API 失败响应结构,返回 error 子对象供后续字段检查。"""
assert isinstance(body, dict)
assert body.get('success') is False
assert 'timestamp' in body
error = parse_api_error(body)
assert error.get('code') == code
assert isinstance(error.get('message'), str) and error['message'].strip()
assert isinstance(error.get('details'), dict)
assert isinstance(error.get('retryable'), bool)
return error
def test_validation_error_returns_standard_envelope(client):
"""注册缺参 → VALIDATION.INVALID_PARAM + envelope。"""
res = client.post('/api/user/register', json={'username': 'only-name'})
assert res.status_code == 400
_assert_standard_error_envelope(res.get_json(), code='VALIDATION.INVALID_PARAM', status=400)
def test_unauthorized_error_returns_standard_envelope(client):
"""未登录访问受保护路由 → AUTH.UNAUTHORIZED + envelope。"""
res = client.get('/api/user/leave-balance')
assert res.status_code == 401
_assert_standard_error_envelope(res.get_json(), code='AUTH.UNAUTHORIZED', status=401)
def test_app_error_code_not_duplicated_in_details(app, client):
"""AUTH.PASSWORD_LOGIN_DISABLED:主码在 error.code,不在 details.error_code。"""
with app.app_context():
app.config['AUTH_ALLOW_LOCAL_PASSWORD_LOGIN'] = False
res = client.post('/api/user/login', json={'username': 'u', 'password': 'p'})
assert res.status_code == 403
body = res.get_json()
error = _assert_standard_error_envelope(body, code='AUTH.PASSWORD_LOGIN_DISABLED', status=403)
assert 'error_code' not in (error.get('details') or {})
def test_file_check_tool_api_uses_dify_legacy_format(app, client):
"""文件检核 Tool API 保持 { ok, error_code, message },不走标准 envelope。"""
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/file-check/tools/tasks')
assert res.status_code == 401
body = res.get_json()
assert body.get('ok') is False
assert body.get('error_code') == 'missing_auth'
assert isinstance(body.get('message'), str)
assert 'success' not in body
def test_shipping_notice_tool_api_uses_dify_legacy_format(app, client):
"""发货通知 Tool API 保持 { ok, error_code, message },不走标准 envelope。"""
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'test-key'
res = client.post(
'/api/shipping-notice/tools/create_task',
headers={'Content-Type': 'application/json'},
json={'source_type': 'manual'},
)
assert res.status_code == 401
body = res.get_json()
assert body.get('ok') is False
assert body.get('error_code') == 'missing_auth'
assert isinstance(body.get('message'), str)
assert 'success' not in body