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