Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import os
import sys

import pytest

# utils._handle_ptt_exception builds EXCEPTION_MAPPING from real PyPtt exception
# classes, so it needs the real PyPtt (not the empty stub sibling tests inject).
# Swap it in, then restore sys.modules so those tests aren't disturbed.
_SHARED = ("PyPtt", "utils")


def test_parameter_error_maps_to_parameter_error_code():
src_dir = os.path.dirname(os.path.abspath(__file__))
if src_dir not in sys.path:
sys.path.insert(0, src_dir)
snapshot = {m: sys.modules.get(m) for m in _SHARED}
try:
if not getattr(sys.modules.get("PyPtt"), "__file__", None):
for m in _SHARED:
sys.modules.pop(m, None)
import PyPtt

if not hasattr(PyPtt, "ParameterError"):
pytest.skip("real PyPtt not installed")
import utils

# ParameterError → 專屬 PARAMETER_ERROR,且保留 PyPtt 的原始訊息。
result = utils._handle_ptt_exception(PyPtt.ParameterError("boom"), {})
assert result["success"] is False
assert result["code"] == "PARAMETER_ERROR"
assert "boom" in result["message"]

# 其他未收錄的例外仍走 UNKNOWN_ERROR(回歸保護)。
other = utils._handle_ptt_exception(RuntimeError("x"), {})
assert other["code"] == "UNKNOWN_ERROR"
finally:
for m in _SHARED:
mod = snapshot[m]
if mod is None:
sys.modules.pop(m, None)
else:
sys.modules[m] = mod


if __name__ == "__main__":
test_parameter_error_maps_to_parameter_error_code()
print("OK")
4 changes: 4 additions & 0 deletions src/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ def _handle_ptt_exception(e: Exception, kwargs: Dict[str, Any]) -> Dict[str, Any
else message_format
)
return {"success": False, "message": message, "code": code}
if isinstance(e, PyPtt.ParameterError):
# PyPtt 對參數問題(如 bad_post_type=OTHER 卻沒給 reason、reason 超長)丟
# ParameterError,訊息本身就講清楚了;給它專屬 code,別誤標成 UNKNOWN_ERROR。
return {"success": False, "message": f"參數錯誤: {e}", "code": "PARAMETER_ERROR"}
return {
"success": False,
"message": f"操作時發生未知錯誤: {e}",
Expand Down
Loading