ยปCore Development>Code coverage>Lib/test/test_baseexception.py

Python code coverage for Lib/test/test_baseexception.py

#countcontent
1n/aimport unittest
2n/aimport builtins
3n/aimport os
4n/afrom platform import system as platform_system
5n/a
6n/a
7n/aclass ExceptionClassTests(unittest.TestCase):
8n/a
9n/a """Tests for anything relating to exception objects themselves (e.g.,
10n/a inheritance hierarchy)"""
11n/a
12n/a def test_builtins_new_style(self):
13n/a self.assertTrue(issubclass(Exception, object))
14n/a
15n/a def verify_instance_interface(self, ins):
16n/a for attr in ("args", "__str__", "__repr__"):
17n/a self.assertTrue(hasattr(ins, attr),
18n/a "%s missing %s attribute" %
19n/a (ins.__class__.__name__, attr))
20n/a
21n/a def test_inheritance(self):
22n/a # Make sure the inheritance hierarchy matches the documentation
23n/a exc_set = set()
24n/a for object_ in builtins.__dict__.values():
25n/a try:
26n/a if issubclass(object_, BaseException):
27n/a exc_set.add(object_.__name__)
28n/a except TypeError:
29n/a pass
30n/a
31n/a inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
32n/a 'exception_hierarchy.txt'))
33n/a try:
34n/a superclass_name = inheritance_tree.readline().rstrip()
35n/a try:
36n/a last_exc = getattr(builtins, superclass_name)
37n/a except AttributeError:
38n/a self.fail("base class %s not a built-in" % superclass_name)
39n/a self.assertIn(superclass_name, exc_set,
40n/a '%s not found' % superclass_name)
41n/a exc_set.discard(superclass_name)
42n/a superclasses = [] # Loop will insert base exception
43n/a last_depth = 0
44n/a for exc_line in inheritance_tree:
45n/a exc_line = exc_line.rstrip()
46n/a depth = exc_line.rindex('-')
47n/a exc_name = exc_line[depth+2:] # Slice past space
48n/a if '(' in exc_name:
49n/a paren_index = exc_name.index('(')
50n/a platform_name = exc_name[paren_index+1:-1]
51n/a exc_name = exc_name[:paren_index-1] # Slice off space
52n/a if platform_system() != platform_name:
53n/a exc_set.discard(exc_name)
54n/a continue
55n/a if '[' in exc_name:
56n/a left_bracket = exc_name.index('[')
57n/a exc_name = exc_name[:left_bracket-1] # cover space
58n/a try:
59n/a exc = getattr(builtins, exc_name)
60n/a except AttributeError:
61n/a self.fail("%s not a built-in exception" % exc_name)
62n/a if last_depth < depth:
63n/a superclasses.append((last_depth, last_exc))
64n/a elif last_depth > depth:
65n/a while superclasses[-1][0] >= depth:
66n/a superclasses.pop()
67n/a self.assertTrue(issubclass(exc, superclasses[-1][1]),
68n/a "%s is not a subclass of %s" % (exc.__name__,
69n/a superclasses[-1][1].__name__))
70n/a try: # Some exceptions require arguments; just skip them
71n/a self.verify_instance_interface(exc())
72n/a except TypeError:
73n/a pass
74n/a self.assertIn(exc_name, exc_set)
75n/a exc_set.discard(exc_name)
76n/a last_exc = exc
77n/a last_depth = depth
78n/a finally:
79n/a inheritance_tree.close()
80n/a self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
81n/a
82n/a interface_tests = ("length", "args", "str", "repr")
83n/a
84n/a def interface_test_driver(self, results):
85n/a for test_name, (given, expected) in zip(self.interface_tests, results):
86n/a self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
87n/a given, expected))
88n/a
89n/a def test_interface_single_arg(self):
90n/a # Make sure interface works properly when given a single argument
91n/a arg = "spam"
92n/a exc = Exception(arg)
93n/a results = ([len(exc.args), 1], [exc.args[0], arg],
94n/a [str(exc), str(arg)],
95n/a [repr(exc), exc.__class__.__name__ + repr(exc.args)])
96n/a self.interface_test_driver(results)
97n/a
98n/a def test_interface_multi_arg(self):
99n/a # Make sure interface correct when multiple arguments given
100n/a arg_count = 3
101n/a args = tuple(range(arg_count))
102n/a exc = Exception(*args)
103n/a results = ([len(exc.args), arg_count], [exc.args, args],
104n/a [str(exc), str(args)],
105n/a [repr(exc), exc.__class__.__name__ + repr(exc.args)])
106n/a self.interface_test_driver(results)
107n/a
108n/a def test_interface_no_arg(self):
109n/a # Make sure that with no args that interface is correct
110n/a exc = Exception()
111n/a results = ([len(exc.args), 0], [exc.args, tuple()],
112n/a [str(exc), ''],
113n/a [repr(exc), exc.__class__.__name__ + '()'])
114n/a self.interface_test_driver(results)
115n/a
116n/aclass UsageTests(unittest.TestCase):
117n/a
118n/a """Test usage of exceptions"""
119n/a
120n/a def raise_fails(self, object_):
121n/a """Make sure that raising 'object_' triggers a TypeError."""
122n/a try:
123n/a raise object_
124n/a except TypeError:
125n/a return # What is expected.
126n/a self.fail("TypeError expected for raising %s" % type(object_))
127n/a
128n/a def catch_fails(self, object_):
129n/a """Catching 'object_' should raise a TypeError."""
130n/a try:
131n/a try:
132n/a raise Exception
133n/a except object_:
134n/a pass
135n/a except TypeError:
136n/a pass
137n/a except Exception:
138n/a self.fail("TypeError expected when catching %s" % type(object_))
139n/a
140n/a try:
141n/a try:
142n/a raise Exception
143n/a except (object_,):
144n/a pass
145n/a except TypeError:
146n/a return
147n/a except Exception:
148n/a self.fail("TypeError expected when catching %s as specified in a "
149n/a "tuple" % type(object_))
150n/a
151n/a def test_raise_new_style_non_exception(self):
152n/a # You cannot raise a new-style class that does not inherit from
153n/a # BaseException; the ability was not possible until BaseException's
154n/a # introduction so no need to support new-style objects that do not
155n/a # inherit from it.
156n/a class NewStyleClass(object):
157n/a pass
158n/a self.raise_fails(NewStyleClass)
159n/a self.raise_fails(NewStyleClass())
160n/a
161n/a def test_raise_string(self):
162n/a # Raising a string raises TypeError.
163n/a self.raise_fails("spam")
164n/a
165n/a def test_catch_non_BaseException(self):
166n/a # Tryinng to catch an object that does not inherit from BaseException
167n/a # is not allowed.
168n/a class NonBaseException(object):
169n/a pass
170n/a self.catch_fails(NonBaseException)
171n/a self.catch_fails(NonBaseException())
172n/a
173n/a def test_catch_BaseException_instance(self):
174n/a # Catching an instance of a BaseException subclass won't work.
175n/a self.catch_fails(BaseException())
176n/a
177n/a def test_catch_string(self):
178n/a # Catching a string is bad.
179n/a self.catch_fails("spam")
180n/a
181n/a
182n/aif __name__ == '__main__':
183n/a unittest.main()