blob: 7c98c460b96f252b38ca027488709e576e000695 [file] [log] [blame]
Brett Cannonbf364092006-03-01 04:25:17 +00001import unittest
Georg Brandl1a3284e2007-12-02 09:40:06 +00002import builtins
Brett Cannonbf364092006-03-01 04:25:17 +00003import warnings
Brett Cannonbf364092006-03-01 04:25:17 +00004import os
5from platform import system as platform_system
6
Guido van Rossum360e4b82007-05-14 22:51:27 +00007
Brett Cannonbf364092006-03-01 04:25:17 +00008class 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):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000014 self.assertTrue(issubclass(Exception, object))
Brett Cannonbf364092006-03-01 04:25:17 +000015
16 def verify_instance_interface(self, ins):
Guido van Rossumebe3e162007-05-17 18:20:34 +000017 for attr in ("args", "__str__", "__repr__"):
Georg Brandlc6c31782009-06-08 13:41:29 +000018 self.assertTrue(hasattr(ins, attr),
Guido van Rossumebe3e162007-05-17 18:20:34 +000019 "%s missing %s attribute" %
20 (ins.__class__.__name__, attr))
Brett Cannonbf364092006-03-01 04:25:17 +000021
22 def test_inheritance(self):
23 # Make sure the inheritance hierarchy matches the documentation
Brett Cannon4af7dcf2007-02-28 00:01:43 +000024 exc_set = set()
Georg Brandl1a3284e2007-12-02 09:40:06 +000025 for object_ in builtins.__dict__.values():
Brett Cannon4af7dcf2007-02-28 00:01:43 +000026 try:
27 if issubclass(object_, BaseException):
28 exc_set.add(object_.__name__)
29 except TypeError:
30 pass
31
Brett Cannonbf364092006-03-01 04:25:17 +000032 inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
33 'exception_hierarchy.txt'))
34 try:
35 superclass_name = inheritance_tree.readline().rstrip()
36 try:
Georg Brandl1a3284e2007-12-02 09:40:06 +000037 last_exc = getattr(builtins, superclass_name)
Brett Cannonbf364092006-03-01 04:25:17 +000038 except AttributeError:
39 self.fail("base class %s not a built-in" % superclass_name)
Ezio Melottib58e0bd2010-01-23 15:40:09 +000040 self.assertIn(superclass_name, exc_set,
41 '%s not found' % superclass_name)
Brett Cannonbf364092006-03-01 04:25:17 +000042 exc_set.discard(superclass_name)
43 superclasses = [] # Loop will insert base exception
44 last_depth = 0
45 for exc_line in inheritance_tree:
46 exc_line = exc_line.rstrip()
47 depth = exc_line.rindex('-')
48 exc_name = exc_line[depth+2:] # Slice past space
49 if '(' in exc_name:
50 paren_index = exc_name.index('(')
51 platform_name = exc_name[paren_index+1:-1]
Brett Cannon6b4ed742006-03-01 06:10:48 +000052 exc_name = exc_name[:paren_index-1] # Slice off space
Brett Cannonbf364092006-03-01 04:25:17 +000053 if platform_system() != platform_name:
54 exc_set.discard(exc_name)
55 continue
56 if '[' in exc_name:
57 left_bracket = exc_name.index('[')
58 exc_name = exc_name[:left_bracket-1] # cover space
59 try:
Georg Brandl1a3284e2007-12-02 09:40:06 +000060 exc = getattr(builtins, exc_name)
Brett Cannonbf364092006-03-01 04:25:17 +000061 except AttributeError:
62 self.fail("%s not a built-in exception" % exc_name)
63 if last_depth < depth:
64 superclasses.append((last_depth, last_exc))
65 elif last_depth > depth:
66 while superclasses[-1][0] >= depth:
67 superclasses.pop()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000068 self.assertTrue(issubclass(exc, superclasses[-1][1]),
Brett Cannonbf364092006-03-01 04:25:17 +000069 "%s is not a subclass of %s" % (exc.__name__,
70 superclasses[-1][1].__name__))
71 try: # Some exceptions require arguments; just skip them
72 self.verify_instance_interface(exc())
73 except TypeError:
74 pass
Benjamin Peterson577473f2010-01-19 00:09:57 +000075 self.assertIn(exc_name, exc_set)
Brett Cannonbf364092006-03-01 04:25:17 +000076 exc_set.discard(exc_name)
77 last_exc = exc
78 last_depth = depth
79 finally:
80 inheritance_tree.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000081 self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
Brett Cannonbf364092006-03-01 04:25:17 +000082
Guido van Rossumebe3e162007-05-17 18:20:34 +000083 interface_tests = ("length", "args", "str", "repr")
Brett Cannonbf364092006-03-01 04:25:17 +000084
85 def interface_test_driver(self, results):
86 for test_name, (given, expected) in zip(self.interface_tests, results):
Georg Brandlc6c31782009-06-08 13:41:29 +000087 self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
Brett Cannonbf364092006-03-01 04:25:17 +000088 given, expected))
89
90 def test_interface_single_arg(self):
91 # Make sure interface works properly when given a single argument
92 arg = "spam"
93 exc = Exception(arg)
Guido van Rossumebe3e162007-05-17 18:20:34 +000094 results = ([len(exc.args), 1], [exc.args[0], arg],
95 [str(exc), str(arg)],
96 [repr(exc), exc.__class__.__name__ + repr(exc.args)])
97 self.interface_test_driver(results)
Brett Cannonbf364092006-03-01 04:25:17 +000098
99 def test_interface_multi_arg(self):
100 # Make sure interface correct when multiple arguments given
101 arg_count = 3
102 args = tuple(range(arg_count))
103 exc = Exception(*args)
Guido van Rossumebe3e162007-05-17 18:20:34 +0000104 results = ([len(exc.args), arg_count], [exc.args, args],
105 [str(exc), str(args)],
106 [repr(exc), exc.__class__.__name__ + repr(exc.args)])
107 self.interface_test_driver(results)
Brett Cannonbf364092006-03-01 04:25:17 +0000108
109 def test_interface_no_arg(self):
110 # Make sure that with no args that interface is correct
111 exc = Exception()
Guido van Rossumebe3e162007-05-17 18:20:34 +0000112 results = ([len(exc.args), 0], [exc.args, tuple()],
113 [str(exc), ''],
114 [repr(exc), exc.__class__.__name__ + '()'])
115 self.interface_test_driver(results)
Brett Cannonbf364092006-03-01 04:25:17 +0000116
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:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000133 raise Exception
Thomas Woutersfa353652007-02-23 20:24:22 +0000134 except object_:
135 pass
136 except TypeError:
137 pass
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000138 except Exception:
Thomas Woutersfa353652007-02-23 20:24:22 +0000139 self.fail("TypeError expected when catching %s" % type(object_))
140
141 try:
142 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000143 raise Exception
Thomas Woutersfa353652007-02-23 20:24:22 +0000144 except (object_,):
145 pass
146 except TypeError:
147 return
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000148 except Exception:
Thomas Woutersfa353652007-02-23 20:24:22 +0000149 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 +0000182
Brett Cannonbf364092006-03-01 04:25:17 +0000183if __name__ == '__main__':
Brett Cannon58f2efb2013-06-13 21:18:43 -0400184 unittest.main()