blob: c32468269a7310d9efca3ba163071c8f7c89dd38 [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 os
4from platform import system as platform_system
5
Guido van Rossum360e4b82007-05-14 22:51:27 +00006
Brett Cannonbf364092006-03-01 04:25:17 +00007class ExceptionClassTests(unittest.TestCase):
8
9 """Tests for anything relating to exception objects themselves (e.g.,
10 inheritance hierarchy)"""
11
12 def test_builtins_new_style(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000013 self.assertTrue(issubclass(Exception, object))
Brett Cannonbf364092006-03-01 04:25:17 +000014
15 def verify_instance_interface(self, ins):
Guido van Rossumebe3e162007-05-17 18:20:34 +000016 for attr in ("args", "__str__", "__repr__"):
Georg Brandlc6c31782009-06-08 13:41:29 +000017 self.assertTrue(hasattr(ins, attr),
Guido van Rossumebe3e162007-05-17 18:20:34 +000018 "%s missing %s attribute" %
19 (ins.__class__.__name__, attr))
Brett Cannonbf364092006-03-01 04:25:17 +000020
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()
Georg Brandl1a3284e2007-12-02 09:40:06 +000024 for object_ in builtins.__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:
Georg Brandl1a3284e2007-12-02 09:40:06 +000036 last_exc = getattr(builtins, superclass_name)
Brett Cannonbf364092006-03-01 04:25:17 +000037 except AttributeError:
38 self.fail("base class %s not a built-in" % superclass_name)
Ezio Melottib58e0bd2010-01-23 15:40:09 +000039 self.assertIn(superclass_name, 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:
Georg Brandl1a3284e2007-12-02 09:40:06 +000059 exc = getattr(builtins, exc_name)
Brett Cannonbf364092006-03-01 04:25:17 +000060 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()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000067 self.assertTrue(issubclass(exc, superclasses[-1][1]),
Brett Cannonbf364092006-03-01 04:25:17 +000068 "%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
Benjamin Peterson577473f2010-01-19 00:09:57 +000074 self.assertIn(exc_name, exc_set)
Brett Cannonbf364092006-03-01 04:25:17 +000075 exc_set.discard(exc_name)
76 last_exc = exc
77 last_depth = depth
78 finally:
79 inheritance_tree.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000080 self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
Brett Cannonbf364092006-03-01 04:25:17 +000081
Guido van Rossumebe3e162007-05-17 18:20:34 +000082 interface_tests = ("length", "args", "str", "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):
Georg Brandlc6c31782009-06-08 13:41:29 +000086 self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
Brett Cannonbf364092006-03-01 04:25:17 +000087 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)
Guido van Rossumebe3e162007-05-17 18:20:34 +000093 results = ([len(exc.args), 1], [exc.args[0], arg],
94 [str(exc), str(arg)],
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +020095 [repr(exc), '%s(%r)' % (exc.__class__.__name__, arg)])
Guido van Rossumebe3e162007-05-17 18:20:34 +000096 self.interface_test_driver(results)
Brett Cannonbf364092006-03-01 04:25:17 +000097
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)
Guido van Rossumebe3e162007-05-17 18:20:34 +0000103 results = ([len(exc.args), arg_count], [exc.args, args],
104 [str(exc), str(args)],
105 [repr(exc), exc.__class__.__name__ + repr(exc.args)])
106 self.interface_test_driver(results)
Brett Cannonbf364092006-03-01 04:25:17 +0000107
108 def test_interface_no_arg(self):
109 # Make sure that with no args that interface is correct
110 exc = Exception()
Guido van Rossumebe3e162007-05-17 18:20:34 +0000111 results = ([len(exc.args), 0], [exc.args, tuple()],
112 [str(exc), ''],
113 [repr(exc), exc.__class__.__name__ + '()'])
114 self.interface_test_driver(results)
Brett Cannonbf364092006-03-01 04:25:17 +0000115
116class UsageTests(unittest.TestCase):
117
118 """Test usage of exceptions"""
119
Thomas Woutersfa353652007-02-23 20:24:22 +0000120 def raise_fails(self, object_):
121 """Make sure that raising 'object_' triggers a TypeError."""
122 try:
123 raise object_
124 except TypeError:
125 return # What is expected.
126 self.fail("TypeError expected for raising %s" % type(object_))
127
128 def catch_fails(self, object_):
129 """Catching 'object_' should raise a TypeError."""
130 try:
131 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000132 raise Exception
Thomas Woutersfa353652007-02-23 20:24:22 +0000133 except object_:
134 pass
135 except TypeError:
136 pass
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000137 except Exception:
Thomas Woutersfa353652007-02-23 20:24:22 +0000138 self.fail("TypeError expected when catching %s" % type(object_))
139
140 try:
141 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000142 raise Exception
Thomas Woutersfa353652007-02-23 20:24:22 +0000143 except (object_,):
144 pass
145 except TypeError:
146 return
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000147 except Exception:
Thomas Woutersfa353652007-02-23 20:24:22 +0000148 self.fail("TypeError expected when catching %s as specified in a "
149 "tuple" % type(object_))
150
Brett Cannonbf364092006-03-01 04:25:17 +0000151 def test_raise_new_style_non_exception(self):
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000152 # You cannot raise a new-style class that does not inherit from
153 # BaseException; the ability was not possible until BaseException's
154 # introduction so no need to support new-style objects that do not
155 # inherit from it.
Brett Cannonbf364092006-03-01 04:25:17 +0000156 class NewStyleClass(object):
157 pass
Thomas Woutersfa353652007-02-23 20:24:22 +0000158 self.raise_fails(NewStyleClass)
159 self.raise_fails(NewStyleClass())
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000160
161 def test_raise_string(self):
162 # Raising a string raises TypeError.
Thomas Woutersfa353652007-02-23 20:24:22 +0000163 self.raise_fails("spam")
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000164
Brett Cannonf74225d2007-02-26 21:10:16 +0000165 def test_catch_non_BaseException(self):
Mike53f7a7c2017-12-14 14:04:53 +0300166 # Trying to catch an object that does not inherit from BaseException
Brett Cannonf74225d2007-02-26 21:10:16 +0000167 # is not allowed.
168 class NonBaseException(object):
169 pass
170 self.catch_fails(NonBaseException)
171 self.catch_fails(NonBaseException())
172
Brett Cannonba7bf492007-02-27 00:15:55 +0000173 def test_catch_BaseException_instance(self):
174 # Catching an instance of a BaseException subclass won't work.
175 self.catch_fails(BaseException())
176
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000177 def test_catch_string(self):
Brett Cannonf74225d2007-02-26 21:10:16 +0000178 # Catching a string is bad.
179 self.catch_fails("spam")
Brett Cannonbf364092006-03-01 04:25:17 +0000180
Brett Cannonbf364092006-03-01 04:25:17 +0000181
Brett Cannonbf364092006-03-01 04:25:17 +0000182if __name__ == '__main__':
Brett Cannon58f2efb2013-06-13 21:18:43 -0400183 unittest.main()