Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 1 | import unittest |
| 2 | import __builtin__ |
| 3 | import exceptions |
| 4 | import warnings |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 5 | from test.test_support import run_unittest |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 6 | import os |
| 7 | from platform import system as platform_system |
| 8 | |
Senthil Kumaran | ce8e33a | 2010-01-08 19:04:16 +0000 | [diff] [blame^] | 9 | def ignore_message_warning(): |
| 10 | """Ignore the DeprecationWarning for BaseException.message.""" |
| 11 | warnings.resetwarnings() |
| 12 | warnings.filterwarnings("ignore", "BaseException.message", |
| 13 | DeprecationWarning) |
Brett Cannon | 229cee2 | 2007-05-05 01:34:02 +0000 | [diff] [blame] | 14 | |
| 15 | |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 16 | class ExceptionClassTests(unittest.TestCase): |
| 17 | |
| 18 | """Tests for anything relating to exception objects themselves (e.g., |
| 19 | inheritance hierarchy)""" |
| 20 | |
| 21 | def test_builtins_new_style(self): |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 22 | self.assertTrue(issubclass(Exception, object)) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 23 | |
| 24 | def verify_instance_interface(self, ins): |
Senthil Kumaran | ce8e33a | 2010-01-08 19:04:16 +0000 | [diff] [blame^] | 25 | with warnings.catch_warnings(): |
| 26 | ignore_message_warning() |
| 27 | for attr in ("args", "message", "__str__", "__repr__", |
| 28 | "__getitem__"): |
| 29 | self.assertTrue(hasattr(ins, attr), |
| 30 | "%s missing %s attribute" % |
| 31 | (ins.__class__.__name__, attr)) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 32 | |
| 33 | def test_inheritance(self): |
| 34 | # Make sure the inheritance hierarchy matches the documentation |
| 35 | exc_set = set(x for x in dir(exceptions) if not x.startswith('_')) |
| 36 | inheritance_tree = open(os.path.join(os.path.split(__file__)[0], |
| 37 | 'exception_hierarchy.txt')) |
| 38 | try: |
| 39 | superclass_name = inheritance_tree.readline().rstrip() |
| 40 | try: |
| 41 | last_exc = getattr(__builtin__, superclass_name) |
| 42 | except AttributeError: |
| 43 | self.fail("base class %s not a built-in" % superclass_name) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 44 | self.assertTrue(superclass_name in exc_set) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 45 | exc_set.discard(superclass_name) |
| 46 | superclasses = [] # Loop will insert base exception |
| 47 | last_depth = 0 |
| 48 | for exc_line in inheritance_tree: |
| 49 | exc_line = exc_line.rstrip() |
| 50 | depth = exc_line.rindex('-') |
| 51 | exc_name = exc_line[depth+2:] # Slice past space |
| 52 | if '(' in exc_name: |
| 53 | paren_index = exc_name.index('(') |
| 54 | platform_name = exc_name[paren_index+1:-1] |
Brett Cannon | 6b4ed74 | 2006-03-01 06:10:48 +0000 | [diff] [blame] | 55 | exc_name = exc_name[:paren_index-1] # Slice off space |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 56 | if platform_system() != platform_name: |
| 57 | exc_set.discard(exc_name) |
| 58 | continue |
| 59 | if '[' in exc_name: |
| 60 | left_bracket = exc_name.index('[') |
| 61 | exc_name = exc_name[:left_bracket-1] # cover space |
| 62 | try: |
| 63 | exc = getattr(__builtin__, exc_name) |
| 64 | except AttributeError: |
| 65 | self.fail("%s not a built-in exception" % exc_name) |
| 66 | if last_depth < depth: |
| 67 | superclasses.append((last_depth, last_exc)) |
| 68 | elif last_depth > depth: |
| 69 | while superclasses[-1][0] >= depth: |
| 70 | superclasses.pop() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 71 | self.assertTrue(issubclass(exc, superclasses[-1][1]), |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 72 | "%s is not a subclass of %s" % (exc.__name__, |
| 73 | superclasses[-1][1].__name__)) |
| 74 | try: # Some exceptions require arguments; just skip them |
| 75 | self.verify_instance_interface(exc()) |
| 76 | except TypeError: |
| 77 | pass |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 78 | self.assertTrue(exc_name in exc_set) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 79 | exc_set.discard(exc_name) |
| 80 | last_exc = exc |
| 81 | last_depth = depth |
| 82 | finally: |
| 83 | inheritance_tree.close() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 84 | self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 85 | |
| 86 | interface_tests = ("length", "args", "message", "str", "unicode", "repr", |
| 87 | "indexing") |
| 88 | |
| 89 | def interface_test_driver(self, results): |
| 90 | for test_name, (given, expected) in zip(self.interface_tests, results): |
Georg Brandl | 19e79f7 | 2009-06-03 23:23:45 +0000 | [diff] [blame] | 91 | self.assertEqual(given, expected, "%s: %s != %s" % (test_name, |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 92 | given, expected)) |
| 93 | |
| 94 | def test_interface_single_arg(self): |
| 95 | # Make sure interface works properly when given a single argument |
| 96 | arg = "spam" |
| 97 | exc = Exception(arg) |
Senthil Kumaran | ce8e33a | 2010-01-08 19:04:16 +0000 | [diff] [blame^] | 98 | with warnings.catch_warnings(): |
| 99 | ignore_message_warning() |
| 100 | results = ([len(exc.args), 1], [exc.args[0], arg], |
| 101 | [exc.message, arg], |
| 102 | [str(exc), str(arg)], [unicode(exc), unicode(arg)], |
| 103 | [repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc[0], |
| 104 | arg]) |
| 105 | self.interface_test_driver(results) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 106 | |
| 107 | def test_interface_multi_arg(self): |
| 108 | # Make sure interface correct when multiple arguments given |
| 109 | arg_count = 3 |
| 110 | args = tuple(range(arg_count)) |
| 111 | exc = Exception(*args) |
Senthil Kumaran | ce8e33a | 2010-01-08 19:04:16 +0000 | [diff] [blame^] | 112 | with warnings.catch_warnings(): |
| 113 | ignore_message_warning() |
| 114 | results = ([len(exc.args), arg_count], [exc.args, args], |
| 115 | [exc.message, ''], [str(exc), str(args)], |
| 116 | [unicode(exc), unicode(args)], |
| 117 | [repr(exc), exc.__class__.__name__ + repr(exc.args)], |
| 118 | [exc[-1], args[-1]]) |
| 119 | self.interface_test_driver(results) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 120 | |
| 121 | def test_interface_no_arg(self): |
| 122 | # Make sure that with no args that interface is correct |
| 123 | exc = Exception() |
Senthil Kumaran | ce8e33a | 2010-01-08 19:04:16 +0000 | [diff] [blame^] | 124 | with warnings.catch_warnings(): |
| 125 | ignore_message_warning() |
| 126 | results = ([len(exc.args), 0], [exc.args, tuple()], |
| 127 | [exc.message, ''], |
| 128 | [str(exc), ''], [unicode(exc), u''], |
| 129 | [repr(exc), exc.__class__.__name__ + '()'], [True, True]) |
| 130 | self.interface_test_driver(results) |
Brett Cannon | 229cee2 | 2007-05-05 01:34:02 +0000 | [diff] [blame] | 131 | |
| 132 | |
| 133 | def test_message_deprecation(self): |
| 134 | # As of Python 2.6, BaseException.message is deprecated. |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 135 | with warnings.catch_warnings(): |
Brett Cannon | 229cee2 | 2007-05-05 01:34:02 +0000 | [diff] [blame] | 136 | warnings.resetwarnings() |
| 137 | warnings.filterwarnings('error') |
| 138 | |
| 139 | try: |
| 140 | BaseException().message |
| 141 | except DeprecationWarning: |
| 142 | pass |
| 143 | else: |
| 144 | self.fail("BaseException.message not deprecated") |
| 145 | |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 146 | |
| 147 | class UsageTests(unittest.TestCase): |
| 148 | |
| 149 | """Test usage of exceptions""" |
| 150 | |
Brett Cannon | 6fbb96e | 2007-02-23 14:28:25 +0000 | [diff] [blame] | 151 | def raise_fails(self, object_): |
| 152 | """Make sure that raising 'object_' triggers a TypeError.""" |
| 153 | try: |
| 154 | raise object_ |
| 155 | except TypeError: |
| 156 | return # What is expected. |
| 157 | self.fail("TypeError expected for raising %s" % type(object_)) |
| 158 | |
| 159 | def catch_fails(self, object_): |
| 160 | """Catching 'object_' should raise a TypeError.""" |
| 161 | try: |
| 162 | try: |
| 163 | raise StandardError |
| 164 | except object_: |
| 165 | pass |
| 166 | except TypeError: |
| 167 | pass |
| 168 | except StandardError: |
| 169 | self.fail("TypeError expected when catching %s" % type(object_)) |
| 170 | |
| 171 | try: |
| 172 | try: |
| 173 | raise StandardError |
| 174 | except (object_,): |
| 175 | pass |
| 176 | except TypeError: |
| 177 | return |
| 178 | except StandardError: |
| 179 | self.fail("TypeError expected when catching %s as specified in a " |
| 180 | "tuple" % type(object_)) |
| 181 | |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 182 | def test_raise_classic(self): |
Brett Cannon | 129bd52 | 2007-01-30 21:34:36 +0000 | [diff] [blame] | 183 | # Raising a classic class is okay (for now). |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 184 | class ClassicClass: |
| 185 | pass |
| 186 | try: |
| 187 | raise ClassicClass |
| 188 | except ClassicClass: |
| 189 | pass |
| 190 | except: |
| 191 | self.fail("unable to raise classic class") |
| 192 | try: |
| 193 | raise ClassicClass() |
| 194 | except ClassicClass: |
| 195 | pass |
| 196 | except: |
| 197 | self.fail("unable to raise class class instance") |
| 198 | |
| 199 | def test_raise_new_style_non_exception(self): |
Brett Cannon | 129bd52 | 2007-01-30 21:34:36 +0000 | [diff] [blame] | 200 | # You cannot raise a new-style class that does not inherit from |
| 201 | # BaseException; the ability was not possible until BaseException's |
| 202 | # introduction so no need to support new-style objects that do not |
| 203 | # inherit from it. |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 204 | class NewStyleClass(object): |
| 205 | pass |
Brett Cannon | 6fbb96e | 2007-02-23 14:28:25 +0000 | [diff] [blame] | 206 | self.raise_fails(NewStyleClass) |
| 207 | self.raise_fails(NewStyleClass()) |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 208 | |
| 209 | def test_raise_string(self): |
Brett Cannon | 129bd52 | 2007-01-30 21:34:36 +0000 | [diff] [blame] | 210 | # Raising a string raises TypeError. |
Brett Cannon | 6fbb96e | 2007-02-23 14:28:25 +0000 | [diff] [blame] | 211 | self.raise_fails("spam") |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 212 | |
| 213 | def test_catch_string(self): |
Brett Cannon | 129bd52 | 2007-01-30 21:34:36 +0000 | [diff] [blame] | 214 | # Catching a string should trigger a DeprecationWarning. |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 215 | with warnings.catch_warnings(): |
Brett Cannon | 129bd52 | 2007-01-30 21:34:36 +0000 | [diff] [blame] | 216 | warnings.resetwarnings() |
| 217 | warnings.filterwarnings("error") |
| 218 | str_exc = "spam" |
| 219 | try: |
| 220 | try: |
| 221 | raise StandardError |
| 222 | except str_exc: |
| 223 | pass |
| 224 | except DeprecationWarning: |
| 225 | pass |
| 226 | except StandardError: |
| 227 | self.fail("catching a string exception did not raise " |
| 228 | "DeprecationWarning") |
| 229 | # Make sure that even if the string exception is listed in a tuple |
| 230 | # that a warning is raised. |
| 231 | try: |
| 232 | try: |
| 233 | raise StandardError |
| 234 | except (AssertionError, str_exc): |
| 235 | pass |
| 236 | except DeprecationWarning: |
| 237 | pass |
| 238 | except StandardError: |
| 239 | self.fail("catching a string exception specified in a tuple did " |
| 240 | "not raise DeprecationWarning") |
| 241 | |
Brett Cannon | bf36409 | 2006-03-01 04:25:17 +0000 | [diff] [blame] | 242 | |
| 243 | def test_main(): |
| 244 | run_unittest(ExceptionClassTests, UsageTests) |
| 245 | |
| 246 | |
| 247 | |
| 248 | if __name__ == '__main__': |
| 249 | test_main() |