test_baseexception.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import unittest
  2. import builtins
  3. import os
  4. from platform import system as platform_system
  5. class ExceptionClassTests(unittest.TestCase):
  6. """Tests for anything relating to exception objects themselves (e.g.,
  7. inheritance hierarchy)"""
  8. def test_builtins_new_style(self):
  9. self.assertTrue(issubclass(Exception, object))
  10. def verify_instance_interface(self, ins):
  11. for attr in ("args", "__str__", "__repr__"):
  12. self.assertTrue(hasattr(ins, attr),
  13. "%s missing %s attribute" %
  14. (ins.__class__.__name__, attr))
  15. def test_inheritance(self):
  16. # Make sure the inheritance hierarchy matches the documentation
  17. exc_set = set()
  18. for object_ in builtins.__dict__.values():
  19. try:
  20. if issubclass(object_, BaseException):
  21. exc_set.add(object_.__name__)
  22. except TypeError:
  23. pass
  24. inheritance_tree = open(
  25. os.path.join(os.path.split(__file__)[0], 'exception_hierarchy.txt'),
  26. encoding="utf-8")
  27. try:
  28. superclass_name = inheritance_tree.readline().rstrip()
  29. try:
  30. last_exc = getattr(builtins, superclass_name)
  31. except AttributeError:
  32. self.fail("base class %s not a built-in" % superclass_name)
  33. self.assertIn(superclass_name, exc_set,
  34. '%s not found' % superclass_name)
  35. exc_set.discard(superclass_name)
  36. superclasses = [] # Loop will insert base exception
  37. last_depth = 0
  38. for exc_line in inheritance_tree:
  39. exc_line = exc_line.rstrip()
  40. depth = exc_line.rindex('─')
  41. exc_name = exc_line[depth+2:] # Slice past space
  42. if '(' in exc_name:
  43. paren_index = exc_name.index('(')
  44. platform_name = exc_name[paren_index+1:-1]
  45. exc_name = exc_name[:paren_index-1] # Slice off space
  46. if platform_system() != platform_name:
  47. exc_set.discard(exc_name)
  48. continue
  49. if '[' in exc_name:
  50. left_bracket = exc_name.index('[')
  51. exc_name = exc_name[:left_bracket-1] # cover space
  52. try:
  53. exc = getattr(builtins, exc_name)
  54. except AttributeError:
  55. self.fail("%s not a built-in exception" % exc_name)
  56. if last_depth < depth:
  57. superclasses.append((last_depth, last_exc))
  58. elif last_depth > depth:
  59. while superclasses[-1][0] >= depth:
  60. superclasses.pop()
  61. self.assertTrue(issubclass(exc, superclasses[-1][1]),
  62. "%s is not a subclass of %s" % (exc.__name__,
  63. superclasses[-1][1].__name__))
  64. try: # Some exceptions require arguments; just skip them
  65. self.verify_instance_interface(exc())
  66. except TypeError:
  67. pass
  68. self.assertIn(exc_name, exc_set)
  69. exc_set.discard(exc_name)
  70. last_exc = exc
  71. last_depth = depth
  72. finally:
  73. inheritance_tree.close()
  74. self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
  75. interface_tests = ("length", "args", "str", "repr")
  76. def interface_test_driver(self, results):
  77. for test_name, (given, expected) in zip(self.interface_tests, results):
  78. self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
  79. given, expected))
  80. def test_interface_single_arg(self):
  81. # Make sure interface works properly when given a single argument
  82. arg = "spam"
  83. exc = Exception(arg)
  84. results = ([len(exc.args), 1], [exc.args[0], arg],
  85. [str(exc), str(arg)],
  86. [repr(exc), '%s(%r)' % (exc.__class__.__name__, arg)])
  87. self.interface_test_driver(results)
  88. def test_interface_multi_arg(self):
  89. # Make sure interface correct when multiple arguments given
  90. arg_count = 3
  91. args = tuple(range(arg_count))
  92. exc = Exception(*args)
  93. results = ([len(exc.args), arg_count], [exc.args, args],
  94. [str(exc), str(args)],
  95. [repr(exc), exc.__class__.__name__ + repr(exc.args)])
  96. self.interface_test_driver(results)
  97. def test_interface_no_arg(self):
  98. # Make sure that with no args that interface is correct
  99. exc = Exception()
  100. results = ([len(exc.args), 0], [exc.args, tuple()],
  101. [str(exc), ''],
  102. [repr(exc), exc.__class__.__name__ + '()'])
  103. self.interface_test_driver(results)
  104. def test_setstate_refcount_no_crash(self):
  105. # gh-97591: Acquire strong reference before calling tp_hash slot
  106. # in PyObject_SetAttr.
  107. import gc
  108. d = {}
  109. class HashThisKeyWillClearTheDict(str):
  110. def __hash__(self) -> int:
  111. d.clear()
  112. return super().__hash__()
  113. class Value(str):
  114. pass
  115. exc = Exception()
  116. d[HashThisKeyWillClearTheDict()] = Value() # refcount of Value() is 1 now
  117. # Exception.__setstate__ should aquire a strong reference of key and
  118. # value in the dict. Otherwise, Value()'s refcount would go below
  119. # zero in the tp_hash call in PyObject_SetAttr(), and it would cause
  120. # crash in GC.
  121. exc.__setstate__(d) # __hash__() is called again here, clearing the dict.
  122. # This GC would crash if the refcount of Value() goes below zero.
  123. gc.collect()
  124. class UsageTests(unittest.TestCase):
  125. """Test usage of exceptions"""
  126. def raise_fails(self, object_):
  127. """Make sure that raising 'object_' triggers a TypeError."""
  128. try:
  129. raise object_
  130. except TypeError:
  131. return # What is expected.
  132. self.fail("TypeError expected for raising %s" % type(object_))
  133. def catch_fails(self, object_):
  134. """Catching 'object_' should raise a TypeError."""
  135. try:
  136. try:
  137. raise Exception
  138. except object_:
  139. pass
  140. except TypeError:
  141. pass
  142. except Exception:
  143. self.fail("TypeError expected when catching %s" % type(object_))
  144. try:
  145. try:
  146. raise Exception
  147. except (object_,):
  148. pass
  149. except TypeError:
  150. return
  151. except Exception:
  152. self.fail("TypeError expected when catching %s as specified in a "
  153. "tuple" % type(object_))
  154. def test_raise_new_style_non_exception(self):
  155. # You cannot raise a new-style class that does not inherit from
  156. # BaseException; the ability was not possible until BaseException's
  157. # introduction so no need to support new-style objects that do not
  158. # inherit from it.
  159. class NewStyleClass(object):
  160. pass
  161. self.raise_fails(NewStyleClass)
  162. self.raise_fails(NewStyleClass())
  163. def test_raise_string(self):
  164. # Raising a string raises TypeError.
  165. self.raise_fails("spam")
  166. def test_catch_non_BaseException(self):
  167. # Trying to catch an object that does not inherit from BaseException
  168. # is not allowed.
  169. class NonBaseException(object):
  170. pass
  171. self.catch_fails(NonBaseException)
  172. self.catch_fails(NonBaseException())
  173. def test_catch_BaseException_instance(self):
  174. # Catching an instance of a BaseException subclass won't work.
  175. self.catch_fails(BaseException())
  176. def test_catch_string(self):
  177. # Catching a string is bad.
  178. self.catch_fails("spam")
  179. if __name__ == '__main__':
  180. unittest.main()