"""统一 API 响应包装与业务异常单元测试""" import pytest from app.api.response import ApiError, error, ok class TestOk: def test_ok_structure(self) -> None: data = {"items": [1, 2, 3]} assert ok(data) == {"code": 0, "data": {"items": [1, 2, 3]}, "message": "ok"} def test_ok_none_data(self) -> None: assert ok(None) == {"code": 0, "data": None, "message": "ok"} class TestError: def test_error_structure(self) -> None: assert error(1004, "文档不存在") == {"code": 1004, "data": None, "message": "文档不存在"} def test_error_code_passthrough(self) -> None: result = error(2000, "服务器内部错误") assert result["code"] == 2000 assert result["message"] == "服务器内部错误" class TestApiError: def test_attributes(self) -> None: exc = ApiError(1004, "文档不存在") assert exc.code == 1004 assert exc.message == "文档不存在" def test_is_exception_with_message(self) -> None: exc = ApiError(1004, "文档不存在") assert isinstance(exc, Exception) assert str(exc) == "文档不存在" def test_raise_and_catch(self) -> None: with pytest.raises(ApiError) as exc_info: raise ApiError(1001, "请求参数校验失败") assert exc_info.value.code == 1001 assert exc_info.value.message == "请求参数校验失败"