802_traceback.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import traceback
  2. import sys
  3. if sys.argv[0].endswith('.pyc'):
  4. exit()
  5. try:
  6. a = {'123': 4}
  7. b = a[6]
  8. except KeyError:
  9. actual = traceback.format_exc()
  10. assert traceback.print_exc() is None
  11. assert traceback.format_exc() == actual
  12. expected = '''Traceback (most recent call last):
  13. File "tests/802_traceback.py", line 9
  14. b = a[6]
  15. KeyError: 6'''
  16. if actual != expected:
  17. print('--- ACTUAL RESULT -----')
  18. print(actual)
  19. print('--- EXPECTED RESULT ---')
  20. print(expected)
  21. exit(1)
  22. def format_from_helper():
  23. return traceback.format_exc()
  24. def format_from_try():
  25. try:
  26. return format_from_helper()
  27. except Exception:
  28. assert False
  29. assert traceback.format_exc() is None
  30. assert format_from_try() is None
  31. assert traceback.print_exc() is None
  32. try:
  33. raise ValueError('outer')
  34. except ValueError:
  35. outer = traceback.format_exc()
  36. assert outer.endswith('ValueError: outer')
  37. assert format_from_helper() == outer
  38. assert format_from_try() == outer
  39. # A try body has no exception of its own and must not hide its handler.
  40. try:
  41. assert traceback.format_exc() == outer
  42. assert format_from_try() == outer
  43. raise KeyError('inner')
  44. except KeyError:
  45. inner = traceback.format_exc()
  46. assert inner.endswith("KeyError: 'inner'")
  47. assert format_from_try() == inner
  48. # Leaving the inner handler restores the outer exception.
  49. assert traceback.format_exc() == outer
  50. assert format_from_try() == outer
  51. assert traceback.format_exc() is None
  52. assert format_from_try() is None
  53. def handle_in_helper():
  54. try:
  55. raise RuntimeError('helper')
  56. except RuntimeError:
  57. actual = traceback.format_exc()
  58. assert actual.endswith('RuntimeError: helper')
  59. assert format_from_try() == actual
  60. try:
  61. raise ValueError('caller')
  62. except ValueError:
  63. caller = traceback.format_exc()
  64. handle_in_helper()
  65. assert traceback.format_exc() == caller
  66. assert format_from_try() == caller
  67. class BrokenStr(Exception):
  68. def __str__(self):
  69. raise RuntimeError('str failed')
  70. try:
  71. raise BrokenStr()
  72. except BrokenStr:
  73. actual = traceback.format_exc()
  74. assert actual.endswith('BrokenStr: <exception str() failed>')
  75. assert format_from_try() == actual
  76. assert traceback.print_exc() is None
  77. assert traceback.format_exc() == actual
  78. assert traceback.format_exc() is None