test_pep352.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import unittest
  2. import __builtin__
  3. import exceptions
  4. import warnings
  5. from test.test_support import run_unittest, check_warnings
  6. import os
  7. import sys
  8. from platform import system as platform_system
  9. DEPRECATION_WARNINGS = ["BaseException.message has been deprecated"]
  10. if sys.py3kwarning:
  11. DEPRECATION_WARNINGS.extend(
  12. ["exceptions must derive from BaseException",
  13. "catching classes that don't inherit from BaseException is not allowed",
  14. "__get(item|slice)__ not supported for exception classes"])
  15. _deprecations = [(msg, DeprecationWarning) for msg in DEPRECATION_WARNINGS]
  16. # Silence Py3k and other deprecation warnings
  17. def ignore_deprecation_warnings(func):
  18. """Ignore the known DeprecationWarnings."""
  19. def wrapper(*args, **kw):
  20. with check_warnings(*_deprecations, quiet=True):
  21. return func(*args, **kw)
  22. return wrapper
  23. class ExceptionClassTests(unittest.TestCase):
  24. """Tests for anything relating to exception objects themselves (e.g.,
  25. inheritance hierarchy)"""
  26. def test_builtins_new_style(self):
  27. self.assertTrue(issubclass(Exception, object))
  28. @ignore_deprecation_warnings
  29. def verify_instance_interface(self, ins):
  30. for attr in ("args", "message", "__str__", "__repr__", "__getitem__"):
  31. self.assertTrue(hasattr(ins, attr),
  32. "%s missing %s attribute" %
  33. (ins.__class__.__name__, attr))
  34. def test_inheritance(self):
  35. # Make sure the inheritance hierarchy matches the documentation
  36. exc_set = set(x for x in dir(exceptions) if not x.startswith('_'))
  37. inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
  38. 'exception_hierarchy.txt'))
  39. try:
  40. superclass_name = inheritance_tree.readline().rstrip()
  41. try:
  42. last_exc = getattr(__builtin__, superclass_name)
  43. except AttributeError:
  44. self.fail("base class %s not a built-in" % superclass_name)
  45. self.assertIn(superclass_name, exc_set)
  46. exc_set.discard(superclass_name)
  47. superclasses = [] # Loop will insert base exception
  48. last_depth = 0
  49. for exc_line in inheritance_tree:
  50. exc_line = exc_line.rstrip()
  51. depth = exc_line.rindex('-')
  52. exc_name = exc_line[depth+2:] # Slice past space
  53. if '(' in exc_name:
  54. paren_index = exc_name.index('(')
  55. platform_name = exc_name[paren_index+1:-1]
  56. exc_name = exc_name[:paren_index-1] # Slice off space
  57. if platform_system() != platform_name:
  58. exc_set.discard(exc_name)
  59. continue
  60. if '[' in exc_name:
  61. left_bracket = exc_name.index('[')
  62. exc_name = exc_name[:left_bracket-1] # cover space
  63. try:
  64. exc = getattr(__builtin__, exc_name)
  65. except AttributeError:
  66. self.fail("%s not a built-in exception" % exc_name)
  67. if last_depth < depth:
  68. superclasses.append((last_depth, last_exc))
  69. elif last_depth > depth:
  70. while superclasses[-1][0] >= depth:
  71. superclasses.pop()
  72. self.assertTrue(issubclass(exc, superclasses[-1][1]),
  73. "%s is not a subclass of %s" % (exc.__name__,
  74. superclasses[-1][1].__name__))
  75. try: # Some exceptions require arguments; just skip them
  76. self.verify_instance_interface(exc())
  77. except TypeError:
  78. pass
  79. self.assertIn(exc_name, exc_set)
  80. exc_set.discard(exc_name)
  81. last_exc = exc
  82. last_depth = depth
  83. finally:
  84. inheritance_tree.close()
  85. self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
  86. interface_tests = ("length", "args", "message", "str", "unicode", "repr",
  87. "indexing")
  88. def interface_test_driver(self, results):
  89. for test_name, (given, expected) in zip(self.interface_tests, results):
  90. self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
  91. given, expected))
  92. @ignore_deprecation_warnings
  93. def test_interface_single_arg(self):
  94. # Make sure interface works properly when given a single argument
  95. arg = "spam"
  96. exc = Exception(arg)
  97. results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg],
  98. [str(exc), str(arg)], [unicode(exc), unicode(arg)],
  99. [repr(exc), exc.__class__.__name__ + repr(exc.args)],
  100. [exc[0], arg])
  101. self.interface_test_driver(results)
  102. @ignore_deprecation_warnings
  103. def test_interface_multi_arg(self):
  104. # Make sure interface correct when multiple arguments given
  105. arg_count = 3
  106. args = tuple(range(arg_count))
  107. exc = Exception(*args)
  108. results = ([len(exc.args), arg_count], [exc.args, args],
  109. [exc.message, ''], [str(exc), str(args)],
  110. [unicode(exc), unicode(args)],
  111. [repr(exc), exc.__class__.__name__ + repr(exc.args)],
  112. [exc[-1], args[-1]])
  113. self.interface_test_driver(results)
  114. @ignore_deprecation_warnings
  115. def test_interface_no_arg(self):
  116. # Make sure that with no args that interface is correct
  117. exc = Exception()
  118. results = ([len(exc.args), 0], [exc.args, tuple()],
  119. [exc.message, ''],
  120. [str(exc), ''], [unicode(exc), u''],
  121. [repr(exc), exc.__class__.__name__ + '()'], [True, True])
  122. self.interface_test_driver(results)
  123. def test_message_deprecation(self):
  124. # As of Python 2.6, BaseException.message is deprecated.
  125. with check_warnings(("", DeprecationWarning)):
  126. BaseException().message
  127. class UsageTests(unittest.TestCase):
  128. """Test usage of exceptions"""
  129. def raise_fails(self, object_):
  130. """Make sure that raising 'object_' triggers a TypeError."""
  131. try:
  132. raise object_
  133. except TypeError:
  134. return # What is expected.
  135. self.fail("TypeError expected for raising %s" % type(object_))
  136. def catch_fails(self, object_):
  137. """Catching 'object_' should raise a TypeError."""
  138. try:
  139. try:
  140. raise StandardError
  141. except object_:
  142. pass
  143. except TypeError:
  144. pass
  145. except StandardError:
  146. self.fail("TypeError expected when catching %s" % type(object_))
  147. try:
  148. try:
  149. raise StandardError
  150. except (object_,):
  151. pass
  152. except TypeError:
  153. return
  154. except StandardError:
  155. self.fail("TypeError expected when catching %s as specified in a "
  156. "tuple" % type(object_))
  157. @ignore_deprecation_warnings
  158. def test_raise_classic(self):
  159. # Raising a classic class is okay (for now).
  160. class ClassicClass:
  161. pass
  162. try:
  163. raise ClassicClass
  164. except ClassicClass:
  165. pass
  166. except:
  167. self.fail("unable to raise classic class")
  168. try:
  169. raise ClassicClass()
  170. except ClassicClass:
  171. pass
  172. except:
  173. self.fail("unable to raise classic class instance")
  174. def test_raise_new_style_non_exception(self):
  175. # You cannot raise a new-style class that does not inherit from
  176. # BaseException; the ability was not possible until BaseException's
  177. # introduction so no need to support new-style objects that do not
  178. # inherit from it.
  179. class NewStyleClass(object):
  180. pass
  181. self.raise_fails(NewStyleClass)
  182. self.raise_fails(NewStyleClass())
  183. def test_raise_string(self):
  184. # Raising a string raises TypeError.
  185. self.raise_fails("spam")
  186. def test_catch_string(self):
  187. # Catching a string should trigger a DeprecationWarning.
  188. with warnings.catch_warnings():
  189. warnings.resetwarnings()
  190. warnings.filterwarnings("error")
  191. str_exc = "spam"
  192. with self.assertRaises(DeprecationWarning):
  193. try:
  194. raise StandardError
  195. except str_exc:
  196. pass
  197. # Make sure that even if the string exception is listed in a tuple
  198. # that a warning is raised.
  199. with self.assertRaises(DeprecationWarning):
  200. try:
  201. raise StandardError
  202. except (AssertionError, str_exc):
  203. pass
  204. def test_main():
  205. run_unittest(ExceptionClassTests, UsageTests)
  206. if __name__ == '__main__':
  207. test_main()