blob: 4ce25d68eebf93ddafcfadf95071d84aba34e228 [file] [log] [blame]
Brett Cannonbf364092006-03-01 04:25:17 +00001import unittest
2import __builtin__
3import exceptions
4import warnings
Brett Cannon129bd522007-01-30 21:34:36 +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 Cannonca2ca792006-09-09 07:11:46 +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
Brett Cannonbf364092006-03-01 04:25:17 +0000116 def test_raise_classic(self):
Brett Cannon129bd522007-01-30 21:34:36 +0000117 # Raising a classic class is okay (for now).
Brett Cannonbf364092006-03-01 04:25:17 +0000118 class ClassicClass:
119 pass
120 try:
121 raise ClassicClass
122 except ClassicClass:
123 pass
124 except:
125 self.fail("unable to raise classic class")
126 try:
127 raise ClassicClass()
128 except ClassicClass:
129 pass
130 except:
131 self.fail("unable to raise class class instance")
132
133 def test_raise_new_style_non_exception(self):
Brett Cannon129bd522007-01-30 21:34:36 +0000134 # You cannot raise a new-style class that does not inherit from
135 # BaseException; the ability was not possible until BaseException's
136 # introduction so no need to support new-style objects that do not
137 # inherit from it.
Brett Cannonbf364092006-03-01 04:25:17 +0000138 class NewStyleClass(object):
139 pass
140 try:
141 raise NewStyleClass
142 except TypeError:
143 pass
144 except:
Brett Cannon129bd522007-01-30 21:34:36 +0000145 self.fail("able to raise new-style class")
Brett Cannonbf364092006-03-01 04:25:17 +0000146 try:
147 raise NewStyleClass()
148 except TypeError:
149 pass
150 except:
Brett Cannon129bd522007-01-30 21:34:36 +0000151 self.fail("able to raise new-style class instance")
Brett Cannonbf364092006-03-01 04:25:17 +0000152
153 def test_raise_string(self):
Brett Cannon129bd522007-01-30 21:34:36 +0000154 # Raising a string raises TypeError.
Brett Cannonbf364092006-03-01 04:25:17 +0000155 try:
156 raise "spam"
Brett Cannon129bd522007-01-30 21:34:36 +0000157 except TypeError:
Brett Cannonbf364092006-03-01 04:25:17 +0000158 pass
159 except:
Brett Cannon129bd522007-01-30 21:34:36 +0000160 self.fail("was able to raise a string exception")
Brett Cannonbf364092006-03-01 04:25:17 +0000161
162 def test_catch_string(self):
Brett Cannon129bd522007-01-30 21:34:36 +0000163 # Catching a string should trigger a DeprecationWarning.
164 with guard_warnings_filter():
165 warnings.resetwarnings()
166 warnings.filterwarnings("error")
167 str_exc = "spam"
168 try:
169 try:
170 raise StandardError
171 except str_exc:
172 pass
173 except DeprecationWarning:
174 pass
175 except StandardError:
176 self.fail("catching a string exception did not raise "
177 "DeprecationWarning")
178 # Make sure that even if the string exception is listed in a tuple
179 # that a warning is raised.
180 try:
181 try:
182 raise StandardError
183 except (AssertionError, str_exc):
184 pass
185 except DeprecationWarning:
186 pass
187 except StandardError:
188 self.fail("catching a string exception specified in a tuple did "
189 "not raise DeprecationWarning")
190
Brett Cannonbf364092006-03-01 04:25:17 +0000191
192def test_main():
193 run_unittest(ExceptionClassTests, UsageTests)
194
195
196
197if __name__ == '__main__':
198 test_main()