blob: e39a397fd351b0e7621de37dc150ef3f87f491f0 [file] [log] [blame]
Brett Cannonbf364092006-03-01 04:25:17 +00001import unittest
2import __builtin__
Brett Cannonbf364092006-03-01 04:25:17 +00003import warnings
Thomas Wouters9fe394c2007-02-05 01:24:16 +00004from test.test_support import run_unittest, guard_warnings_filter
Brett Cannonbf364092006-03-01 04:25:17 +00005import os
6from platform import system as platform_system
7
8class 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 Cannonba7bf492007-02-27 00:15:55 +000017 for attr in ("args", "message", "__str__", "__repr__"):
Brett Cannonbf364092006-03-01 04:25:17 +000018 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 Cannon4af7dcf2007-02-28 00:01:43 +000023 exc_set = set()
Brett Cannon3695bf32007-02-28 00:32:07 +000024 for object_ in __builtin__.__dict__.values():
Brett Cannon4af7dcf2007-02-28 00:01:43 +000025 try:
26 if issubclass(object_, BaseException):
27 exc_set.add(object_.__name__)
28 except TypeError:
29 pass
30
Brett Cannonbf364092006-03-01 04:25:17 +000031 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)
Guido van Rossum805365e2007-05-07 22:24:25 +000039 self.failUnless(superclass_name in exc_set,
40 '%s not found' % superclass_name)
Brett Cannonbf364092006-03-01 04:25:17 +000041 exc_set.discard(superclass_name)
42 superclasses = [] # Loop will insert base exception
43 last_depth = 0
44 for exc_line in inheritance_tree:
45 exc_line = exc_line.rstrip()
46 depth = exc_line.rindex('-')
47 exc_name = exc_line[depth+2:] # Slice past space
48 if '(' in exc_name:
49 paren_index = exc_name.index('(')
50 platform_name = exc_name[paren_index+1:-1]
Brett Cannon6b4ed742006-03-01 06:10:48 +000051 exc_name = exc_name[:paren_index-1] # Slice off space
Brett Cannonbf364092006-03-01 04:25:17 +000052 if platform_system() != platform_name:
53 exc_set.discard(exc_name)
54 continue
55 if '[' in exc_name:
56 left_bracket = exc_name.index('[')
57 exc_name = exc_name[:left_bracket-1] # cover space
58 try:
59 exc = getattr(__builtin__, exc_name)
60 except AttributeError:
61 self.fail("%s not a built-in exception" % exc_name)
62 if last_depth < depth:
63 superclasses.append((last_depth, last_exc))
64 elif last_depth > depth:
65 while superclasses[-1][0] >= depth:
66 superclasses.pop()
67 self.failUnless(issubclass(exc, superclasses[-1][1]),
68 "%s is not a subclass of %s" % (exc.__name__,
69 superclasses[-1][1].__name__))
70 try: # Some exceptions require arguments; just skip them
71 self.verify_instance_interface(exc())
72 except TypeError:
73 pass
74 self.failUnless(exc_name in exc_set)
75 exc_set.discard(exc_name)
76 last_exc = exc
77 last_depth = depth
78 finally:
79 inheritance_tree.close()
80 self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
81
Brett Cannonba7bf492007-02-27 00:15:55 +000082 interface_tests = ("length", "args", "message", "str", "unicode", "repr")
Brett Cannonbf364092006-03-01 04:25:17 +000083
84 def interface_test_driver(self, results):
85 for test_name, (given, expected) in zip(self.interface_tests, results):
86 self.failUnlessEqual(given, expected, "%s: %s != %s" % (test_name,
87 given, expected))
88
89 def test_interface_single_arg(self):
90 # Make sure interface works properly when given a single argument
91 arg = "spam"
92 exc = Exception(arg)
93 results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg],
Guido van Rossumef87d6e2007-05-02 19:09:54 +000094 [str(exc), str(arg)], [str(exc), str(arg)],
Brett Cannonba7bf492007-02-27 00:15:55 +000095 [repr(exc), exc.__class__.__name__ + repr(exc.args)])
Brett Cannonbf364092006-03-01 04:25:17 +000096 self.interface_test_driver(results)
97
98 def test_interface_multi_arg(self):
99 # Make sure interface correct when multiple arguments given
100 arg_count = 3
101 args = tuple(range(arg_count))
102 exc = Exception(*args)
103 results = ([len(exc.args), arg_count], [exc.args, args],
104 [exc.message, ''], [str(exc), str(args)],
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000105 [str(exc), str(args)],
Brett Cannonba7bf492007-02-27 00:15:55 +0000106 [repr(exc), exc.__class__.__name__ + repr(exc.args)])
Brett Cannonbf364092006-03-01 04:25:17 +0000107 self.interface_test_driver(results)
108
109 def test_interface_no_arg(self):
110 # Make sure that with no args that interface is correct
111 exc = Exception()
112 results = ([len(exc.args), 0], [exc.args, tuple()], [exc.message, ''],
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000113 [str(exc), ''], [str(exc), ''],
Brett Cannonba7bf492007-02-27 00:15:55 +0000114 [repr(exc), exc.__class__.__name__ + '()'])
Brett Cannonbf364092006-03-01 04:25:17 +0000115 self.interface_test_driver(results)
116
117class UsageTests(unittest.TestCase):
118
119 """Test usage of exceptions"""
120
Thomas Woutersfa353652007-02-23 20:24:22 +0000121 def raise_fails(self, object_):
122 """Make sure that raising 'object_' triggers a TypeError."""
123 try:
124 raise object_
125 except TypeError:
126 return # What is expected.
127 self.fail("TypeError expected for raising %s" % type(object_))
128
129 def catch_fails(self, object_):
130 """Catching 'object_' should raise a TypeError."""
131 try:
132 try:
133 raise StandardError
134 except object_:
135 pass
136 except TypeError:
137 pass
138 except StandardError:
139 self.fail("TypeError expected when catching %s" % type(object_))
140
141 try:
142 try:
143 raise StandardError
144 except (object_,):
145 pass
146 except TypeError:
147 return
148 except StandardError:
149 self.fail("TypeError expected when catching %s as specified in a "
150 "tuple" % type(object_))
151
Brett Cannonbf364092006-03-01 04:25:17 +0000152 def test_raise_new_style_non_exception(self):
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000153 # You cannot raise a new-style class that does not inherit from
154 # BaseException; the ability was not possible until BaseException's
155 # introduction so no need to support new-style objects that do not
156 # inherit from it.
Brett Cannonbf364092006-03-01 04:25:17 +0000157 class NewStyleClass(object):
158 pass
Thomas Woutersfa353652007-02-23 20:24:22 +0000159 self.raise_fails(NewStyleClass)
160 self.raise_fails(NewStyleClass())
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000161
162 def test_raise_string(self):
163 # Raising a string raises TypeError.
Thomas Woutersfa353652007-02-23 20:24:22 +0000164 self.raise_fails("spam")
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000165
Brett Cannonf74225d2007-02-26 21:10:16 +0000166 def test_catch_non_BaseException(self):
167 # Tryinng 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
Brett Cannonba7bf492007-02-27 00:15:55 +0000174 def test_catch_BaseException_instance(self):
175 # Catching an instance of a BaseException subclass won't work.
176 self.catch_fails(BaseException())
177
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000178 def test_catch_string(self):
Brett Cannonf74225d2007-02-26 21:10:16 +0000179 # Catching a string is bad.
180 self.catch_fails("spam")
Brett Cannonbf364092006-03-01 04:25:17 +0000181
Brett Cannonbf364092006-03-01 04:25:17 +0000182def test_main():
183 run_unittest(ExceptionClassTests, UsageTests)
184
Brett Cannonbf364092006-03-01 04:25:17 +0000185if __name__ == '__main__':
186 test_main()