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