test_create_prefixed_exception.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """Regression tests for create_prefixed_exception.
  2. Some exceptions cannot be reconstructed from their ``args`` alone because
  3. their constructor signatures differ (json.JSONDecodeError needs
  4. ``(msg, doc, pos)``; openai SDK ``APIStatusError`` subclasses need keyword-only
  5. ``response``/``body``). The helper must never raise while prefixing and must
  6. surface the original type name + message. See HKUDS/LightRAG #2710 and #2794.
  7. """
  8. import json
  9. import pytest
  10. from lightrag.utils import create_prefixed_exception
  11. @pytest.mark.offline
  12. def test_reconstructable_exception_keeps_type_and_prefix():
  13. result = create_prefixed_exception(ValueError("boom"), "`entity`")
  14. assert isinstance(result, ValueError)
  15. assert str(result) == "`entity`: boom"
  16. @pytest.mark.offline
  17. def test_jsondecodeerror_does_not_raise_and_preserves_message():
  18. try:
  19. json.loads('{\n "x": "abc') # unterminated string -> JSONDecodeError
  20. except json.JSONDecodeError as exc:
  21. result = create_prefixed_exception(exc, "`entity`")
  22. # JSONDecodeError(msg) is missing (doc, pos): falls back to a clean RuntimeError
  23. assert isinstance(result, RuntimeError)
  24. assert result.args # never an empty/garbled exception
  25. assert "`entity`" in str(result)
  26. assert "JSONDecodeError" in str(result)
  27. assert "Unterminated string" in str(result)
  28. @pytest.mark.offline
  29. def test_keyword_only_constructor_exception_falls_back_cleanly():
  30. """Mimics openai.APIStatusError: keyword-only required args."""
  31. class KeywordOnlyError(Exception):
  32. def __init__(self, message, *, response, body):
  33. super().__init__(message)
  34. exc = KeywordOnlyError("Error code: 500", response=object(), body=None)
  35. result = create_prefixed_exception(exc, "chunk-1")
  36. assert isinstance(result, RuntimeError)
  37. assert str(result) == "chunk-1: KeywordOnlyError: Error code: 500"