blob: 1f72eadb6ed289edb011e39595f2fc9c952d7b3f [file] [log] [blame]
Brett Cannonbf364092006-03-01 04:25:17 +00001import unittest
2import __builtin__
3import exceptions
4import warnings
Thomas Wouters9fe394c2007-02-05 01:24:16 +00005from test.test_support import run_unittest, guard_warnings_filter
Brett Cannonbf364092006-03-01 04:25:17 +00006import os
7from platform import system as platform_system
8
9class ExceptionClassTests(unittest.TestCase):
10
11 """Tests for anything relating to exception objects themselves (e.g.,
12 inheritance hierarchy)"""
13
14 def test_builtins_new_style(self):
15 self.failUnless(issubclass(Exception, object))
16
17 def verify_instance_interface(self, ins):
Brett Cannonba7bf492007-02-27 00:15:55 +000018 for attr in ("args", "message", "__str__", "__repr__"):
Brett Cannonbf364092006-03-01 04:25:17 +000019 self.failUnless(hasattr(ins, attr), "%s missing %s attribute" %
20 (ins.__class__.__name__, attr))
21
22 def test_inheritance(self):
23 # Make sure the inheritance hierarchy matches the documentation
24 exc_set = set(x for x in dir(exceptions) if not x.startswith('_'))
25 inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
26 'exception_hierarchy.txt'))
27 try:
28 superclass_name = inheritance_tree.readline().rstrip()
29 try:
30 last_exc = getattr(__builtin__, superclass_name)
31 except AttributeError:
32 self.fail("base class %s not a built-in" % superclass_name)
33 self.failUnless(superclass_name in exc_set)
34 exc_set.discard(superclass_name)
35 superclasses = [] # Loop will insert base exception
36 last_depth = 0
37 for exc_line in inheritance_tree:
38 exc_line = exc_line.rstrip()
39 depth = exc_line.rindex('-')
40 exc_name = exc_line[depth+2:] # Slice past space
41 if '(' in exc_name:
42 paren_index = exc_name.index('(')
43 platform_name = exc_name[paren_index+1:-1]
Brett Cannon6b4ed742006-03-01 06:10:48 +000044 exc_name = exc_name[:paren_index-1] # Slice off space
Brett Cannonbf364092006-03-01 04:25:17 +000045 if platform_system() != platform_name:
46 exc_set.discard(exc_name)
47 continue
48 if '[' in exc_name:
49 left_bracket = exc_name.index('[')
50 exc_name = exc_name[:left_bracket-1] # cover space
51 try:
52 exc = getattr(__builtin__, exc_name)
53 except AttributeError:
54 self.fail("%s not a built-in exception" % exc_name)
55 if last_depth < depth:
56 superclasses.append((last_depth, last_exc))
57 elif last_depth > depth:
58 while superclasses[-1][0] >= depth:
59 superclasses.pop()
60 self.failUnless(issubclass(exc, superclasses[-1][1]),
61 "%s is not a subclass of %s" % (exc.__name__,
62 superclasses[-1][1].__name__))
63 try: # Some exceptions require arguments; just skip them
64 self.verify_instance_interface(exc())
65 except TypeError:
66 pass
67 self.failUnless(exc_name in exc_set)
68 exc_set.discard(exc_name)
69 last_exc = exc
70 last_depth = depth
71 finally:
72 inheritance_tree.close()
73 self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
74
Brett Cannonba7bf492007-02-27 00:15:55 +000075 interface_tests = ("length", "args", "message", "str", "unicode", "repr")
Brett Cannonbf364092006-03-01 04:25:17 +000076
77 def interface_test_driver(self, results):
78 for test_name, (given, expected) in zip(self.interface_tests, results):
79 self.failUnlessEqual(given, expected, "%s: %s != %s" % (test_name,
80 given, expected))
81
82 def test_interface_single_arg(self):
83 # Make sure interface works properly when given a single argument
84 arg = "spam"
85 exc = Exception(arg)
86 results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg],
87 [str(exc), str(arg)], [unicode(exc), unicode(arg)],
Brett Cannonba7bf492007-02-27 00:15:55 +000088 [repr(exc), exc.__class__.__name__ + repr(exc.args)])
Brett Cannonbf364092006-03-01 04:25:17 +000089 self.interface_test_driver(results)
90
91 def test_interface_multi_arg(self):
92 # Make sure interface correct when multiple arguments given
93 arg_count = 3
94 args = tuple(range(arg_count))
95 exc = Exception(*args)
96 results = ([len(exc.args), arg_count], [exc.args, args],
97 [exc.message, ''], [str(exc), str(args)],
98 [unicode(exc), unicode(args)],
Brett Cannonba7bf492007-02-27 00:15:55 +000099 [repr(exc), exc.__class__.__name__ + repr(exc.args)])
Brett Cannonbf364092006-03-01 04:25:17 +0000100 self.interface_test_driver(results)
101
102 def test_interface_no_arg(self):
103 # Make sure that with no args that interface is correct
104 exc = Exception()
105 results = ([len(exc.args), 0], [exc.args, tuple()], [exc.message, ''],
106 [str(exc), ''], [unicode(exc), u''],
Brett Cannonba7bf492007-02-27 00:15:55 +0000107 [repr(exc), exc.__class__.__name__ + '()'])
Brett Cannonbf364092006-03-01 04:25:17 +0000108 self.interface_test_driver(results)
109
110class UsageTests(unittest.TestCase):
111
112 """Test usage of exceptions"""
113
Thomas Woutersfa353652007-02-23 20:24:22 +0000114 def raise_fails(self, object_):
115 """Make sure that raising 'object_' triggers a TypeError."""
116 try:
117 raise object_
118 except TypeError:
119 return # What is expected.
120 self.fail("TypeError expected for raising %s" % type(object_))
121
122 def catch_fails(self, object_):
123 """Catching 'object_' should raise a TypeError."""
124 try:
125 try:
126 raise StandardError
127 except object_:
128 pass
129 except TypeError:
130 pass
131 except StandardError:
132 self.fail("TypeError expected when catching %s" % type(object_))
133
134 try:
135 try:
136 raise StandardError
137 except (object_,):
138 pass
139 except TypeError:
140 return
141 except StandardError:
142 self.fail("TypeError expected when catching %s as specified in a "
143 "tuple" % type(object_))
144
Brett Cannonbf364092006-03-01 04:25:17 +0000145 def test_raise_new_style_non_exception(self):
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000146 # You cannot raise a new-style class that does not inherit from
147 # BaseException; the ability was not possible until BaseException's
148 # introduction so no need to support new-style objects that do not
149 # inherit from it.
Brett Cannonbf364092006-03-01 04:25:17 +0000150 class NewStyleClass(object):
151 pass
Thomas Woutersfa353652007-02-23 20:24:22 +0000152 self.raise_fails(NewStyleClass)
153 self.raise_fails(NewStyleClass())
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000154
155 def test_raise_string(self):
156 # Raising a string raises TypeError.
Thomas Woutersfa353652007-02-23 20:24:22 +0000157 self.raise_fails("spam")
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000158
Brett Cannonf74225d2007-02-26 21:10:16 +0000159 def test_catch_non_BaseException(self):
160 # Tryinng to catch an object that does not inherit from BaseException
161 # is not allowed.
162 class NonBaseException(object):
163 pass
164 self.catch_fails(NonBaseException)
165 self.catch_fails(NonBaseException())
166
Brett Cannonba7bf492007-02-27 00:15:55 +0000167 def test_catch_BaseException_instance(self):
168 # Catching an instance of a BaseException subclass won't work.
169 self.catch_fails(BaseException())
170
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000171 def test_catch_string(self):
Brett Cannonf74225d2007-02-26 21:10:16 +0000172 # Catching a string is bad.
173 self.catch_fails("spam")
Brett Cannonbf364092006-03-01 04:25:17 +0000174
Brett Cannonbf364092006-03-01 04:25:17 +0000175def test_main():
176 run_unittest(ExceptionClassTests, UsageTests)
177
Brett Cannonbf364092006-03-01 04:25:17 +0000178if __name__ == '__main__':
179 test_main()