| 1 |
import unittest |
| 2 |
import builtins |
| 3 |
import os |
| 4 |
from platform import system as platform_system |
| 5 |
|
| 6 |
|
| 7 |
class 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): |
| 13 |
self.assertIsSubclass(Exception, object) |
| 14 |
|
| 15 |
def verify_instance_interface(self, ins): |
| 16 |
for attr in ("args", "__str__", "__repr__"): |
| 17 |
self.assertHasAttr(ins, attr) |
| 18 |
|
| 19 |
def test_inheritance(self): |
| 20 |
# Make sure the inheritance hierarchy matches the documentation |
| 21 |
exc_set = set() |
| 22 |
for object_ in builtins.__dict__.values(): |
| 23 |
try: |
| 24 |
if issubclass(object_, BaseException): |
| 25 |
exc_set.add(object_.__name__) |
| 26 |
except TypeError: |
| 27 |
pass |
| 28 |
|
| 29 |
inheritance_tree = open( |
| 30 |
os.path.join(os.path.split(__file__)[0], 'exception_hierarchy.txt'), |
| 31 |
encoding="utf-8") |
| 32 |
try: |
| 33 |
superclass_name = inheritance_tree.readline().rstrip() |
| 34 |
try: |
| 35 |
last_exc = getattr(builtins, superclass_name) |
| 36 |
except AttributeError: |
| 37 |
self.fail("base class %s not a built-in" % superclass_name) |
| 38 |
self.assertIn(superclass_name, exc_set, |
| 39 |
'%s not found' % superclass_name) |
| 40 |
exc_set.discard(superclass_name) |
| 41 |
superclasses = [] # Loop will insert base exception |
| 42 |
last_depth = 0 |
| 43 |
for exc_line in inheritance_tree: |
| 44 |
exc_line = exc_line.rstrip() |
| 45 |
depth = exc_line.rindex('─') |
| 46 |
exc_name = exc_line[depth+2:] # Slice past space |
| 47 |
if '(' in exc_name: |
| 48 |
paren_index = exc_name.index('(') |
| 49 |
platform_name = exc_name[paren_index+1:-1] |
| 50 |
exc_name = exc_name[:paren_index-1] # Slice off space |
| 51 |
if platform_system() != platform_name: |
| 52 |
exc_set.discard(exc_name) |
| 53 |
continue |
| 54 |
if '[' in exc_name: |
| 55 |
left_bracket = exc_name.index('[') |
| 56 |
exc_name = exc_name[:left_bracket-1] # cover space |
| 57 |
try: |
| 58 |
exc = getattr(builtins, exc_name) |
| 59 |
except AttributeError: |
| 60 |
self.fail("%s not a built-in exception" % exc_name) |
| 61 |
if last_depth < depth: |
| 62 |
superclasses.append((last_depth, last_exc)) |
| 63 |
elif last_depth > depth: |
| 64 |
while superclasses[-1][0] >= depth: |
| 65 |
superclasses.pop() |
| 66 |
self.assertIsSubclass(exc, superclasses[-1][1], |
| 67 |
"%s is not a subclass of %s" % (exc.__name__, |
| 68 |
superclasses[-1][1].__name__)) |
| 69 |
try: # Some exceptions require arguments; just skip them |
| 70 |
self.verify_instance_interface(exc()) |
| 71 |
except TypeError: |
| 72 |
pass |
| 73 |
self.assertIn(exc_name, exc_set) |
| 74 |
exc_set.discard(exc_name) |
| 75 |
last_exc = exc |
| 76 |
last_depth = depth |
| 77 |
finally: |
| 78 |
inheritance_tree.close() |
| 79 |
|
| 80 |
# Underscore-prefixed (private) exceptions don't need to be documented |
| 81 |
exc_set = set(e for e in exc_set if not e.startswith('_')) |
| 82 |
self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set) |
| 83 |
|
| 84 |
interface_tests = ("length", "args", "str", "repr") |
| 85 |
|
| 86 |
def interface_test_driver(self, results): |
| 87 |
for test_name, (given, expected) in zip(self.interface_tests, results): |
| 88 |
self.assertEqual(given, expected, "%s: %s != %s" % (test_name, |
| 89 |
given, expected)) |
| 90 |
|
| 91 |
def test_interface_single_arg(self): |
| 92 |
# Make sure interface works properly when given a single argument |
| 93 |
arg = "spam" |
| 94 |
exc = Exception(arg) |
| 95 |
results = ([len(exc.args), 1], [exc.args[0], arg], |
| 96 |
[str(exc), str(arg)], |
| 97 |
[repr(exc), '%s(%r)' % (exc.__class__.__name__, arg)]) |
| 98 |
self.interface_test_driver(results) |
| 99 |
|
| 100 |
def test_interface_multi_arg(self): |
| 101 |
# Make sure interface correct when multiple arguments given |
| 102 |
arg_count = 3 |
| 103 |
args = tuple(range(arg_count)) |
| 104 |
exc = Exception(*args) |
| 105 |
results = ([len(exc.args), arg_count], [exc.args, args], |
| 106 |
[str(exc), str(args)], |
| 107 |
[repr(exc), exc.__class__.__name__ + repr(exc.args)]) |
| 108 |
self.interface_test_driver(results) |
| 109 |
|
| 110 |
def test_interface_no_arg(self): |
| 111 |
# Make sure that with no args that interface is correct |
| 112 |
exc = Exception() |
| 113 |
results = ([len(exc.args), 0], [exc.args, tuple()], |
| 114 |
[str(exc), ''], |
| 115 |
[repr(exc), exc.__class__.__name__ + '()']) |
| 116 |
self.interface_test_driver(results) |
| 117 |
|
| 118 |
def test_setstate_refcount_no_crash(self): |
| 119 |
# gh-97591: Acquire strong reference before calling tp_hash slot |
| 120 |
# in PyObject_SetAttr. |
| 121 |
import gc |
| 122 |
d = {} |
| 123 |
class HashThisKeyWillClearTheDict(str): |
| 124 |
def __hash__(self) -> int: |
| 125 |
d.clear() |
| 126 |
return super().__hash__() |
| 127 |
class Value(str): |
| 128 |
pass |
| 129 |
exc = Exception() |
| 130 |
|
| 131 |
d[HashThisKeyWillClearTheDict()] = Value() # refcount of Value() is 1 now |
| 132 |
|
| 133 |
# Exception.__setstate__ should acquire a strong reference of key and |
| 134 |
# value in the dict. Otherwise, Value()'s refcount would go below |
| 135 |
# zero in the tp_hash call in PyObject_SetAttr(), and it would cause |
| 136 |
# crash in GC. |
| 137 |
exc.__setstate__(d) # __hash__() is called again here, clearing the dict. |
| 138 |
|
| 139 |
# This GC would crash if the refcount of Value() goes below zero. |
| 140 |
gc.collect() |
| 141 |
|
| 142 |
|
| 143 |
class UsageTests(unittest.TestCase): |
| 144 |
|
| 145 |
"""Test usage of exceptions""" |
| 146 |
|
| 147 |
def raise_fails(self, object_): |
| 148 |
"""Make sure that raising 'object_' triggers a TypeError.""" |
| 149 |
try: |
| 150 |
raise object_ |
| 151 |
except TypeError: |
| 152 |
return # What is expected. |
| 153 |
self.fail("TypeError expected for raising %s" % type(object_)) |
| 154 |
|
| 155 |
def catch_fails(self, object_): |
| 156 |
"""Catching 'object_' should raise a TypeError.""" |
| 157 |
try: |
| 158 |
try: |
| 159 |
raise Exception |
| 160 |
except object_: |
| 161 |
pass |
| 162 |
except TypeError: |
| 163 |
pass |
| 164 |
except Exception: |
| 165 |
self.fail("TypeError expected when catching %s" % type(object_)) |
| 166 |
|
| 167 |
try: |
| 168 |
try: |
| 169 |
raise Exception |
| 170 |
except (object_,): |
| 171 |
pass |
| 172 |
except TypeError: |
| 173 |
return |
| 174 |
except Exception: |
| 175 |
self.fail("TypeError expected when catching %s as specified in a " |
| 176 |
"tuple" % type(object_)) |
| 177 |
|
| 178 |
def test_raise_new_style_non_exception(self): |
| 179 |
# You cannot raise a new-style class that does not inherit from |
| 180 |
# BaseException; the ability was not possible until BaseException's |
| 181 |
# introduction so no need to support new-style objects that do not |
| 182 |
# inherit from it. |
| 183 |
class NewStyleClass(object): |
| 184 |
pass |
| 185 |
self.raise_fails(NewStyleClass) |
| 186 |
self.raise_fails(NewStyleClass()) |
| 187 |
|
| 188 |
def test_raise_string(self): |
| 189 |
# Raising a string raises TypeError. |
| 190 |
self.raise_fails("spam") |
| 191 |
|
| 192 |
def test_catch_non_BaseException(self): |
| 193 |
# Trying to catch an object that does not inherit from BaseException |
| 194 |
# is not allowed. |
| 195 |
class NonBaseException(object): |
| 196 |
pass |
| 197 |
self.catch_fails(NonBaseException) |
| 198 |
self.catch_fails(NonBaseException()) |
| 199 |
|
| 200 |
def test_catch_BaseException_instance(self): |
| 201 |
# Catching an instance of a BaseException subclass won't work. |
| 202 |
self.catch_fails(BaseException()) |
| 203 |
|
| 204 |
def test_catch_string(self): |
| 205 |
# Catching a string is bad. |
| 206 |
self.catch_fails("spam") |
| 207 |
|
| 208 |
|
| 209 |
if __name__ == '__main__': |
| 210 |
unittest.main() |