blob: 2a6bac1218c75a16f424a219cbf260ef08347924 [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):
Thomas Wouters89f507f2006-12-13 04:49:30 +000018 for attr in ("args", "message", "__str__", "__repr__", "__getitem__"):
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
75 interface_tests = ("length", "args", "message", "str", "unicode", "repr",
76 "indexing")
77
78 def interface_test_driver(self, results):
79 for test_name, (given, expected) in zip(self.interface_tests, results):
80 self.failUnlessEqual(given, expected, "%s: %s != %s" % (test_name,
81 given, expected))
82
83 def test_interface_single_arg(self):
84 # Make sure interface works properly when given a single argument
85 arg = "spam"
86 exc = Exception(arg)
87 results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg],
88 [str(exc), str(arg)], [unicode(exc), unicode(arg)],
89 [repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc[0], arg])
90 self.interface_test_driver(results)
91
92 def test_interface_multi_arg(self):
93 # Make sure interface correct when multiple arguments given
94 arg_count = 3
95 args = tuple(range(arg_count))
96 exc = Exception(*args)
97 results = ([len(exc.args), arg_count], [exc.args, args],
98 [exc.message, ''], [str(exc), str(args)],
99 [unicode(exc), unicode(args)],
100 [repr(exc), exc.__class__.__name__ + repr(exc.args)],
101 [exc[-1], args[-1]])
102 self.interface_test_driver(results)
103
104 def test_interface_no_arg(self):
105 # Make sure that with no args that interface is correct
106 exc = Exception()
107 results = ([len(exc.args), 0], [exc.args, tuple()], [exc.message, ''],
108 [str(exc), ''], [unicode(exc), u''],
109 [repr(exc), exc.__class__.__name__ + '()'], [True, True])
110 self.interface_test_driver(results)
111
112class UsageTests(unittest.TestCase):
113
114 """Test usage of exceptions"""
115
Thomas Woutersfa353652007-02-23 20:24:22 +0000116 def raise_fails(self, object_):
117 """Make sure that raising 'object_' triggers a TypeError."""
118 try:
119 raise object_
120 except TypeError:
121 return # What is expected.
122 self.fail("TypeError expected for raising %s" % type(object_))
123
124 def catch_fails(self, object_):
125 """Catching 'object_' should raise a TypeError."""
126 try:
127 try:
128 raise StandardError
129 except object_:
130 pass
131 except TypeError:
132 pass
133 except StandardError:
134 self.fail("TypeError expected when catching %s" % type(object_))
135
136 try:
137 try:
138 raise StandardError
139 except (object_,):
140 pass
141 except TypeError:
142 return
143 except StandardError:
144 self.fail("TypeError expected when catching %s as specified in a "
145 "tuple" % type(object_))
146
Brett Cannonbf364092006-03-01 04:25:17 +0000147 def test_raise_new_style_non_exception(self):
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000148 # You cannot raise a new-style class that does not inherit from
149 # BaseException; the ability was not possible until BaseException's
150 # introduction so no need to support new-style objects that do not
151 # inherit from it.
Brett Cannonbf364092006-03-01 04:25:17 +0000152 class NewStyleClass(object):
153 pass
Thomas Woutersfa353652007-02-23 20:24:22 +0000154 self.raise_fails(NewStyleClass)
155 self.raise_fails(NewStyleClass())
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000156
157 def test_raise_string(self):
158 # Raising a string raises TypeError.
Thomas Woutersfa353652007-02-23 20:24:22 +0000159 self.raise_fails("spam")
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000160
Brett Cannonf74225d2007-02-26 21:10:16 +0000161 def test_catch_non_BaseException(self):
162 # Tryinng to catch an object that does not inherit from BaseException
163 # is not allowed.
164 class NonBaseException(object):
165 pass
166 self.catch_fails(NonBaseException)
167 self.catch_fails(NonBaseException())
168
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000169 def test_catch_string(self):
Brett Cannonf74225d2007-02-26 21:10:16 +0000170 # Catching a string is bad.
171 self.catch_fails("spam")
Brett Cannonbf364092006-03-01 04:25:17 +0000172
Brett Cannonbf364092006-03-01 04:25:17 +0000173def test_main():
174 run_unittest(ExceptionClassTests, UsageTests)
175
Brett Cannonbf364092006-03-01 04:25:17 +0000176if __name__ == '__main__':
177 test_main()