1 | n/a | # Python test set -- part 5, built-in exceptions |
---|
2 | n/a | |
---|
3 | n/a | import os |
---|
4 | n/a | import sys |
---|
5 | n/a | import unittest |
---|
6 | n/a | import pickle |
---|
7 | n/a | import weakref |
---|
8 | n/a | import errno |
---|
9 | n/a | |
---|
10 | n/a | from test.support import (TESTFN, captured_stderr, check_impl_detail, |
---|
11 | n/a | check_warnings, cpython_only, gc_collect, run_unittest, |
---|
12 | n/a | no_tracing, unlink, import_module) |
---|
13 | n/a | |
---|
14 | n/a | class NaiveException(Exception): |
---|
15 | n/a | def __init__(self, x): |
---|
16 | n/a | self.x = x |
---|
17 | n/a | |
---|
18 | n/a | class SlottedNaiveException(Exception): |
---|
19 | n/a | __slots__ = ('x',) |
---|
20 | n/a | def __init__(self, x): |
---|
21 | n/a | self.x = x |
---|
22 | n/a | |
---|
23 | n/a | class BrokenStrException(Exception): |
---|
24 | n/a | def __str__(self): |
---|
25 | n/a | raise Exception("str() is broken") |
---|
26 | n/a | |
---|
27 | n/a | # XXX This is not really enough, each *operation* should be tested! |
---|
28 | n/a | |
---|
29 | n/a | class ExceptionTests(unittest.TestCase): |
---|
30 | n/a | |
---|
31 | n/a | def raise_catch(self, exc, excname): |
---|
32 | n/a | try: |
---|
33 | n/a | raise exc("spam") |
---|
34 | n/a | except exc as err: |
---|
35 | n/a | buf1 = str(err) |
---|
36 | n/a | try: |
---|
37 | n/a | raise exc("spam") |
---|
38 | n/a | except exc as err: |
---|
39 | n/a | buf2 = str(err) |
---|
40 | n/a | self.assertEqual(buf1, buf2) |
---|
41 | n/a | self.assertEqual(exc.__name__, excname) |
---|
42 | n/a | |
---|
43 | n/a | def testRaising(self): |
---|
44 | n/a | self.raise_catch(AttributeError, "AttributeError") |
---|
45 | n/a | self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") |
---|
46 | n/a | |
---|
47 | n/a | self.raise_catch(EOFError, "EOFError") |
---|
48 | n/a | fp = open(TESTFN, 'w') |
---|
49 | n/a | fp.close() |
---|
50 | n/a | fp = open(TESTFN, 'r') |
---|
51 | n/a | savestdin = sys.stdin |
---|
52 | n/a | try: |
---|
53 | n/a | try: |
---|
54 | n/a | import marshal |
---|
55 | n/a | marshal.loads(b'') |
---|
56 | n/a | except EOFError: |
---|
57 | n/a | pass |
---|
58 | n/a | finally: |
---|
59 | n/a | sys.stdin = savestdin |
---|
60 | n/a | fp.close() |
---|
61 | n/a | unlink(TESTFN) |
---|
62 | n/a | |
---|
63 | n/a | self.raise_catch(OSError, "OSError") |
---|
64 | n/a | self.assertRaises(OSError, open, 'this file does not exist', 'r') |
---|
65 | n/a | |
---|
66 | n/a | self.raise_catch(ImportError, "ImportError") |
---|
67 | n/a | self.assertRaises(ImportError, __import__, "undefined_module") |
---|
68 | n/a | |
---|
69 | n/a | self.raise_catch(IndexError, "IndexError") |
---|
70 | n/a | x = [] |
---|
71 | n/a | self.assertRaises(IndexError, x.__getitem__, 10) |
---|
72 | n/a | |
---|
73 | n/a | self.raise_catch(KeyError, "KeyError") |
---|
74 | n/a | x = {} |
---|
75 | n/a | self.assertRaises(KeyError, x.__getitem__, 'key') |
---|
76 | n/a | |
---|
77 | n/a | self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") |
---|
78 | n/a | |
---|
79 | n/a | self.raise_catch(MemoryError, "MemoryError") |
---|
80 | n/a | |
---|
81 | n/a | self.raise_catch(NameError, "NameError") |
---|
82 | n/a | try: x = undefined_variable |
---|
83 | n/a | except NameError: pass |
---|
84 | n/a | |
---|
85 | n/a | self.raise_catch(OverflowError, "OverflowError") |
---|
86 | n/a | x = 1 |
---|
87 | n/a | for dummy in range(128): |
---|
88 | n/a | x += x # this simply shouldn't blow up |
---|
89 | n/a | |
---|
90 | n/a | self.raise_catch(RuntimeError, "RuntimeError") |
---|
91 | n/a | self.raise_catch(RecursionError, "RecursionError") |
---|
92 | n/a | |
---|
93 | n/a | self.raise_catch(SyntaxError, "SyntaxError") |
---|
94 | n/a | try: exec('/\n') |
---|
95 | n/a | except SyntaxError: pass |
---|
96 | n/a | |
---|
97 | n/a | self.raise_catch(IndentationError, "IndentationError") |
---|
98 | n/a | |
---|
99 | n/a | self.raise_catch(TabError, "TabError") |
---|
100 | n/a | try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", |
---|
101 | n/a | '<string>', 'exec') |
---|
102 | n/a | except TabError: pass |
---|
103 | n/a | else: self.fail("TabError not raised") |
---|
104 | n/a | |
---|
105 | n/a | self.raise_catch(SystemError, "SystemError") |
---|
106 | n/a | |
---|
107 | n/a | self.raise_catch(SystemExit, "SystemExit") |
---|
108 | n/a | self.assertRaises(SystemExit, sys.exit, 0) |
---|
109 | n/a | |
---|
110 | n/a | self.raise_catch(TypeError, "TypeError") |
---|
111 | n/a | try: [] + () |
---|
112 | n/a | except TypeError: pass |
---|
113 | n/a | |
---|
114 | n/a | self.raise_catch(ValueError, "ValueError") |
---|
115 | n/a | self.assertRaises(ValueError, chr, 17<<16) |
---|
116 | n/a | |
---|
117 | n/a | self.raise_catch(ZeroDivisionError, "ZeroDivisionError") |
---|
118 | n/a | try: x = 1/0 |
---|
119 | n/a | except ZeroDivisionError: pass |
---|
120 | n/a | |
---|
121 | n/a | self.raise_catch(Exception, "Exception") |
---|
122 | n/a | try: x = 1/0 |
---|
123 | n/a | except Exception as e: pass |
---|
124 | n/a | |
---|
125 | n/a | self.raise_catch(StopAsyncIteration, "StopAsyncIteration") |
---|
126 | n/a | |
---|
127 | n/a | def testSyntaxErrorMessage(self): |
---|
128 | n/a | # make sure the right exception message is raised for each of |
---|
129 | n/a | # these code fragments |
---|
130 | n/a | |
---|
131 | n/a | def ckmsg(src, msg): |
---|
132 | n/a | try: |
---|
133 | n/a | compile(src, '<fragment>', 'exec') |
---|
134 | n/a | except SyntaxError as e: |
---|
135 | n/a | if e.msg != msg: |
---|
136 | n/a | self.fail("expected %s, got %s" % (msg, e.msg)) |
---|
137 | n/a | else: |
---|
138 | n/a | self.fail("failed to get expected SyntaxError") |
---|
139 | n/a | |
---|
140 | n/a | s = '''while 1: |
---|
141 | n/a | try: |
---|
142 | n/a | pass |
---|
143 | n/a | finally: |
---|
144 | n/a | continue''' |
---|
145 | n/a | |
---|
146 | n/a | if not sys.platform.startswith('java'): |
---|
147 | n/a | ckmsg(s, "'continue' not supported inside 'finally' clause") |
---|
148 | n/a | |
---|
149 | n/a | s = '''if 1: |
---|
150 | n/a | try: |
---|
151 | n/a | continue |
---|
152 | n/a | except: |
---|
153 | n/a | pass''' |
---|
154 | n/a | |
---|
155 | n/a | ckmsg(s, "'continue' not properly in loop") |
---|
156 | n/a | ckmsg("continue\n", "'continue' not properly in loop") |
---|
157 | n/a | |
---|
158 | n/a | def testSyntaxErrorOffset(self): |
---|
159 | n/a | def check(src, lineno, offset): |
---|
160 | n/a | with self.assertRaises(SyntaxError) as cm: |
---|
161 | n/a | compile(src, '<fragment>', 'exec') |
---|
162 | n/a | self.assertEqual(cm.exception.lineno, lineno) |
---|
163 | n/a | self.assertEqual(cm.exception.offset, offset) |
---|
164 | n/a | |
---|
165 | n/a | check('def fact(x):\n\treturn x!\n', 2, 10) |
---|
166 | n/a | check('1 +\n', 1, 4) |
---|
167 | n/a | check('def spam():\n print(1)\n print(2)', 3, 10) |
---|
168 | n/a | check('Python = "Python" +', 1, 20) |
---|
169 | n/a | check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20) |
---|
170 | n/a | |
---|
171 | n/a | @cpython_only |
---|
172 | n/a | def testSettingException(self): |
---|
173 | n/a | # test that setting an exception at the C level works even if the |
---|
174 | n/a | # exception object can't be constructed. |
---|
175 | n/a | |
---|
176 | n/a | class BadException(Exception): |
---|
177 | n/a | def __init__(self_): |
---|
178 | n/a | raise RuntimeError("can't instantiate BadException") |
---|
179 | n/a | |
---|
180 | n/a | class InvalidException: |
---|
181 | n/a | pass |
---|
182 | n/a | |
---|
183 | n/a | def test_capi1(): |
---|
184 | n/a | import _testcapi |
---|
185 | n/a | try: |
---|
186 | n/a | _testcapi.raise_exception(BadException, 1) |
---|
187 | n/a | except TypeError as err: |
---|
188 | n/a | exc, err, tb = sys.exc_info() |
---|
189 | n/a | co = tb.tb_frame.f_code |
---|
190 | n/a | self.assertEqual(co.co_name, "test_capi1") |
---|
191 | n/a | self.assertTrue(co.co_filename.endswith('test_exceptions.py')) |
---|
192 | n/a | else: |
---|
193 | n/a | self.fail("Expected exception") |
---|
194 | n/a | |
---|
195 | n/a | def test_capi2(): |
---|
196 | n/a | import _testcapi |
---|
197 | n/a | try: |
---|
198 | n/a | _testcapi.raise_exception(BadException, 0) |
---|
199 | n/a | except RuntimeError as err: |
---|
200 | n/a | exc, err, tb = sys.exc_info() |
---|
201 | n/a | co = tb.tb_frame.f_code |
---|
202 | n/a | self.assertEqual(co.co_name, "__init__") |
---|
203 | n/a | self.assertTrue(co.co_filename.endswith('test_exceptions.py')) |
---|
204 | n/a | co2 = tb.tb_frame.f_back.f_code |
---|
205 | n/a | self.assertEqual(co2.co_name, "test_capi2") |
---|
206 | n/a | else: |
---|
207 | n/a | self.fail("Expected exception") |
---|
208 | n/a | |
---|
209 | n/a | def test_capi3(): |
---|
210 | n/a | import _testcapi |
---|
211 | n/a | self.assertRaises(SystemError, _testcapi.raise_exception, |
---|
212 | n/a | InvalidException, 1) |
---|
213 | n/a | |
---|
214 | n/a | if not sys.platform.startswith('java'): |
---|
215 | n/a | test_capi1() |
---|
216 | n/a | test_capi2() |
---|
217 | n/a | test_capi3() |
---|
218 | n/a | |
---|
219 | n/a | def test_WindowsError(self): |
---|
220 | n/a | try: |
---|
221 | n/a | WindowsError |
---|
222 | n/a | except NameError: |
---|
223 | n/a | pass |
---|
224 | n/a | else: |
---|
225 | n/a | self.assertIs(WindowsError, OSError) |
---|
226 | n/a | self.assertEqual(str(OSError(1001)), "1001") |
---|
227 | n/a | self.assertEqual(str(OSError(1001, "message")), |
---|
228 | n/a | "[Errno 1001] message") |
---|
229 | n/a | # POSIX errno (9 aka EBADF) is untranslated |
---|
230 | n/a | w = OSError(9, 'foo', 'bar') |
---|
231 | n/a | self.assertEqual(w.errno, 9) |
---|
232 | n/a | self.assertEqual(w.winerror, None) |
---|
233 | n/a | self.assertEqual(str(w), "[Errno 9] foo: 'bar'") |
---|
234 | n/a | # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) |
---|
235 | n/a | w = OSError(0, 'foo', 'bar', 3) |
---|
236 | n/a | self.assertEqual(w.errno, 2) |
---|
237 | n/a | self.assertEqual(w.winerror, 3) |
---|
238 | n/a | self.assertEqual(w.strerror, 'foo') |
---|
239 | n/a | self.assertEqual(w.filename, 'bar') |
---|
240 | n/a | self.assertEqual(w.filename2, None) |
---|
241 | n/a | self.assertEqual(str(w), "[WinError 3] foo: 'bar'") |
---|
242 | n/a | # Unknown win error becomes EINVAL (22) |
---|
243 | n/a | w = OSError(0, 'foo', None, 1001) |
---|
244 | n/a | self.assertEqual(w.errno, 22) |
---|
245 | n/a | self.assertEqual(w.winerror, 1001) |
---|
246 | n/a | self.assertEqual(w.strerror, 'foo') |
---|
247 | n/a | self.assertEqual(w.filename, None) |
---|
248 | n/a | self.assertEqual(w.filename2, None) |
---|
249 | n/a | self.assertEqual(str(w), "[WinError 1001] foo") |
---|
250 | n/a | # Non-numeric "errno" |
---|
251 | n/a | w = OSError('bar', 'foo') |
---|
252 | n/a | self.assertEqual(w.errno, 'bar') |
---|
253 | n/a | self.assertEqual(w.winerror, None) |
---|
254 | n/a | self.assertEqual(w.strerror, 'foo') |
---|
255 | n/a | self.assertEqual(w.filename, None) |
---|
256 | n/a | self.assertEqual(w.filename2, None) |
---|
257 | n/a | |
---|
258 | n/a | @unittest.skipUnless(sys.platform == 'win32', |
---|
259 | n/a | 'test specific to Windows') |
---|
260 | n/a | def test_windows_message(self): |
---|
261 | n/a | """Should fill in unknown error code in Windows error message""" |
---|
262 | n/a | ctypes = import_module('ctypes') |
---|
263 | n/a | # this error code has no message, Python formats it as hexadecimal |
---|
264 | n/a | code = 3765269347 |
---|
265 | n/a | with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): |
---|
266 | n/a | ctypes.pythonapi.PyErr_SetFromWindowsErr(code) |
---|
267 | n/a | |
---|
268 | n/a | def testAttributes(self): |
---|
269 | n/a | # test that exception attributes are happy |
---|
270 | n/a | |
---|
271 | n/a | exceptionList = [ |
---|
272 | n/a | (BaseException, (), {'args' : ()}), |
---|
273 | n/a | (BaseException, (1, ), {'args' : (1,)}), |
---|
274 | n/a | (BaseException, ('foo',), |
---|
275 | n/a | {'args' : ('foo',)}), |
---|
276 | n/a | (BaseException, ('foo', 1), |
---|
277 | n/a | {'args' : ('foo', 1)}), |
---|
278 | n/a | (SystemExit, ('foo',), |
---|
279 | n/a | {'args' : ('foo',), 'code' : 'foo'}), |
---|
280 | n/a | (OSError, ('foo',), |
---|
281 | n/a | {'args' : ('foo',), 'filename' : None, 'filename2' : None, |
---|
282 | n/a | 'errno' : None, 'strerror' : None}), |
---|
283 | n/a | (OSError, ('foo', 'bar'), |
---|
284 | n/a | {'args' : ('foo', 'bar'), |
---|
285 | n/a | 'filename' : None, 'filename2' : None, |
---|
286 | n/a | 'errno' : 'foo', 'strerror' : 'bar'}), |
---|
287 | n/a | (OSError, ('foo', 'bar', 'baz'), |
---|
288 | n/a | {'args' : ('foo', 'bar'), |
---|
289 | n/a | 'filename' : 'baz', 'filename2' : None, |
---|
290 | n/a | 'errno' : 'foo', 'strerror' : 'bar'}), |
---|
291 | n/a | (OSError, ('foo', 'bar', 'baz', None, 'quux'), |
---|
292 | n/a | {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}), |
---|
293 | n/a | (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'), |
---|
294 | n/a | {'args' : ('errnoStr', 'strErrorStr'), |
---|
295 | n/a | 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', |
---|
296 | n/a | 'filename' : 'filenameStr'}), |
---|
297 | n/a | (OSError, (1, 'strErrorStr', 'filenameStr'), |
---|
298 | n/a | {'args' : (1, 'strErrorStr'), 'errno' : 1, |
---|
299 | n/a | 'strerror' : 'strErrorStr', |
---|
300 | n/a | 'filename' : 'filenameStr', 'filename2' : None}), |
---|
301 | n/a | (SyntaxError, (), {'msg' : None, 'text' : None, |
---|
302 | n/a | 'filename' : None, 'lineno' : None, 'offset' : None, |
---|
303 | n/a | 'print_file_and_line' : None}), |
---|
304 | n/a | (SyntaxError, ('msgStr',), |
---|
305 | n/a | {'args' : ('msgStr',), 'text' : None, |
---|
306 | n/a | 'print_file_and_line' : None, 'msg' : 'msgStr', |
---|
307 | n/a | 'filename' : None, 'lineno' : None, 'offset' : None}), |
---|
308 | n/a | (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', |
---|
309 | n/a | 'textStr')), |
---|
310 | n/a | {'offset' : 'offsetStr', 'text' : 'textStr', |
---|
311 | n/a | 'args' : ('msgStr', ('filenameStr', 'linenoStr', |
---|
312 | n/a | 'offsetStr', 'textStr')), |
---|
313 | n/a | 'print_file_and_line' : None, 'msg' : 'msgStr', |
---|
314 | n/a | 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}), |
---|
315 | n/a | (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
---|
316 | n/a | 'textStr', 'print_file_and_lineStr'), |
---|
317 | n/a | {'text' : None, |
---|
318 | n/a | 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
---|
319 | n/a | 'textStr', 'print_file_and_lineStr'), |
---|
320 | n/a | 'print_file_and_line' : None, 'msg' : 'msgStr', |
---|
321 | n/a | 'filename' : None, 'lineno' : None, 'offset' : None}), |
---|
322 | n/a | (UnicodeError, (), {'args' : (),}), |
---|
323 | n/a | (UnicodeEncodeError, ('ascii', 'a', 0, 1, |
---|
324 | n/a | 'ordinal not in range'), |
---|
325 | n/a | {'args' : ('ascii', 'a', 0, 1, |
---|
326 | n/a | 'ordinal not in range'), |
---|
327 | n/a | 'encoding' : 'ascii', 'object' : 'a', |
---|
328 | n/a | 'start' : 0, 'reason' : 'ordinal not in range'}), |
---|
329 | n/a | (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1, |
---|
330 | n/a | 'ordinal not in range'), |
---|
331 | n/a | {'args' : ('ascii', bytearray(b'\xff'), 0, 1, |
---|
332 | n/a | 'ordinal not in range'), |
---|
333 | n/a | 'encoding' : 'ascii', 'object' : b'\xff', |
---|
334 | n/a | 'start' : 0, 'reason' : 'ordinal not in range'}), |
---|
335 | n/a | (UnicodeDecodeError, ('ascii', b'\xff', 0, 1, |
---|
336 | n/a | 'ordinal not in range'), |
---|
337 | n/a | {'args' : ('ascii', b'\xff', 0, 1, |
---|
338 | n/a | 'ordinal not in range'), |
---|
339 | n/a | 'encoding' : 'ascii', 'object' : b'\xff', |
---|
340 | n/a | 'start' : 0, 'reason' : 'ordinal not in range'}), |
---|
341 | n/a | (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"), |
---|
342 | n/a | {'args' : ('\u3042', 0, 1, 'ouch'), |
---|
343 | n/a | 'object' : '\u3042', 'reason' : 'ouch', |
---|
344 | n/a | 'start' : 0, 'end' : 1}), |
---|
345 | n/a | (NaiveException, ('foo',), |
---|
346 | n/a | {'args': ('foo',), 'x': 'foo'}), |
---|
347 | n/a | (SlottedNaiveException, ('foo',), |
---|
348 | n/a | {'args': ('foo',), 'x': 'foo'}), |
---|
349 | n/a | ] |
---|
350 | n/a | try: |
---|
351 | n/a | # More tests are in test_WindowsError |
---|
352 | n/a | exceptionList.append( |
---|
353 | n/a | (WindowsError, (1, 'strErrorStr', 'filenameStr'), |
---|
354 | n/a | {'args' : (1, 'strErrorStr'), |
---|
355 | n/a | 'strerror' : 'strErrorStr', 'winerror' : None, |
---|
356 | n/a | 'errno' : 1, |
---|
357 | n/a | 'filename' : 'filenameStr', 'filename2' : None}) |
---|
358 | n/a | ) |
---|
359 | n/a | except NameError: |
---|
360 | n/a | pass |
---|
361 | n/a | |
---|
362 | n/a | for exc, args, expected in exceptionList: |
---|
363 | n/a | try: |
---|
364 | n/a | e = exc(*args) |
---|
365 | n/a | except: |
---|
366 | n/a | print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr) |
---|
367 | n/a | raise |
---|
368 | n/a | else: |
---|
369 | n/a | # Verify module name |
---|
370 | n/a | if not type(e).__name__.endswith('NaiveException'): |
---|
371 | n/a | self.assertEqual(type(e).__module__, 'builtins') |
---|
372 | n/a | # Verify no ref leaks in Exc_str() |
---|
373 | n/a | s = str(e) |
---|
374 | n/a | for checkArgName in expected: |
---|
375 | n/a | value = getattr(e, checkArgName) |
---|
376 | n/a | self.assertEqual(repr(value), |
---|
377 | n/a | repr(expected[checkArgName]), |
---|
378 | n/a | '%r.%s == %r, expected %r' % ( |
---|
379 | n/a | e, checkArgName, |
---|
380 | n/a | value, expected[checkArgName])) |
---|
381 | n/a | |
---|
382 | n/a | # test for pickling support |
---|
383 | n/a | for p in [pickle]: |
---|
384 | n/a | for protocol in range(p.HIGHEST_PROTOCOL + 1): |
---|
385 | n/a | s = p.dumps(e, protocol) |
---|
386 | n/a | new = p.loads(s) |
---|
387 | n/a | for checkArgName in expected: |
---|
388 | n/a | got = repr(getattr(new, checkArgName)) |
---|
389 | n/a | want = repr(expected[checkArgName]) |
---|
390 | n/a | self.assertEqual(got, want, |
---|
391 | n/a | 'pickled "%r", attribute "%s' % |
---|
392 | n/a | (e, checkArgName)) |
---|
393 | n/a | |
---|
394 | n/a | def testWithTraceback(self): |
---|
395 | n/a | try: |
---|
396 | n/a | raise IndexError(4) |
---|
397 | n/a | except: |
---|
398 | n/a | tb = sys.exc_info()[2] |
---|
399 | n/a | |
---|
400 | n/a | e = BaseException().with_traceback(tb) |
---|
401 | n/a | self.assertIsInstance(e, BaseException) |
---|
402 | n/a | self.assertEqual(e.__traceback__, tb) |
---|
403 | n/a | |
---|
404 | n/a | e = IndexError(5).with_traceback(tb) |
---|
405 | n/a | self.assertIsInstance(e, IndexError) |
---|
406 | n/a | self.assertEqual(e.__traceback__, tb) |
---|
407 | n/a | |
---|
408 | n/a | class MyException(Exception): |
---|
409 | n/a | pass |
---|
410 | n/a | |
---|
411 | n/a | e = MyException().with_traceback(tb) |
---|
412 | n/a | self.assertIsInstance(e, MyException) |
---|
413 | n/a | self.assertEqual(e.__traceback__, tb) |
---|
414 | n/a | |
---|
415 | n/a | def testInvalidTraceback(self): |
---|
416 | n/a | try: |
---|
417 | n/a | Exception().__traceback__ = 5 |
---|
418 | n/a | except TypeError as e: |
---|
419 | n/a | self.assertIn("__traceback__ must be a traceback", str(e)) |
---|
420 | n/a | else: |
---|
421 | n/a | self.fail("No exception raised") |
---|
422 | n/a | |
---|
423 | n/a | def testInvalidAttrs(self): |
---|
424 | n/a | self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1) |
---|
425 | n/a | self.assertRaises(TypeError, delattr, Exception(), '__cause__') |
---|
426 | n/a | self.assertRaises(TypeError, setattr, Exception(), '__context__', 1) |
---|
427 | n/a | self.assertRaises(TypeError, delattr, Exception(), '__context__') |
---|
428 | n/a | |
---|
429 | n/a | def testNoneClearsTracebackAttr(self): |
---|
430 | n/a | try: |
---|
431 | n/a | raise IndexError(4) |
---|
432 | n/a | except: |
---|
433 | n/a | tb = sys.exc_info()[2] |
---|
434 | n/a | |
---|
435 | n/a | e = Exception() |
---|
436 | n/a | e.__traceback__ = tb |
---|
437 | n/a | e.__traceback__ = None |
---|
438 | n/a | self.assertEqual(e.__traceback__, None) |
---|
439 | n/a | |
---|
440 | n/a | def testChainingAttrs(self): |
---|
441 | n/a | e = Exception() |
---|
442 | n/a | self.assertIsNone(e.__context__) |
---|
443 | n/a | self.assertIsNone(e.__cause__) |
---|
444 | n/a | |
---|
445 | n/a | e = TypeError() |
---|
446 | n/a | self.assertIsNone(e.__context__) |
---|
447 | n/a | self.assertIsNone(e.__cause__) |
---|
448 | n/a | |
---|
449 | n/a | class MyException(OSError): |
---|
450 | n/a | pass |
---|
451 | n/a | |
---|
452 | n/a | e = MyException() |
---|
453 | n/a | self.assertIsNone(e.__context__) |
---|
454 | n/a | self.assertIsNone(e.__cause__) |
---|
455 | n/a | |
---|
456 | n/a | def testChainingDescriptors(self): |
---|
457 | n/a | try: |
---|
458 | n/a | raise Exception() |
---|
459 | n/a | except Exception as exc: |
---|
460 | n/a | e = exc |
---|
461 | n/a | |
---|
462 | n/a | self.assertIsNone(e.__context__) |
---|
463 | n/a | self.assertIsNone(e.__cause__) |
---|
464 | n/a | self.assertFalse(e.__suppress_context__) |
---|
465 | n/a | |
---|
466 | n/a | e.__context__ = NameError() |
---|
467 | n/a | e.__cause__ = None |
---|
468 | n/a | self.assertIsInstance(e.__context__, NameError) |
---|
469 | n/a | self.assertIsNone(e.__cause__) |
---|
470 | n/a | self.assertTrue(e.__suppress_context__) |
---|
471 | n/a | e.__suppress_context__ = False |
---|
472 | n/a | self.assertFalse(e.__suppress_context__) |
---|
473 | n/a | |
---|
474 | n/a | def testKeywordArgs(self): |
---|
475 | n/a | # test that builtin exception don't take keyword args, |
---|
476 | n/a | # but user-defined subclasses can if they want |
---|
477 | n/a | self.assertRaises(TypeError, BaseException, a=1) |
---|
478 | n/a | |
---|
479 | n/a | class DerivedException(BaseException): |
---|
480 | n/a | def __init__(self, fancy_arg): |
---|
481 | n/a | BaseException.__init__(self) |
---|
482 | n/a | self.fancy_arg = fancy_arg |
---|
483 | n/a | |
---|
484 | n/a | x = DerivedException(fancy_arg=42) |
---|
485 | n/a | self.assertEqual(x.fancy_arg, 42) |
---|
486 | n/a | |
---|
487 | n/a | @no_tracing |
---|
488 | n/a | def testInfiniteRecursion(self): |
---|
489 | n/a | def f(): |
---|
490 | n/a | return f() |
---|
491 | n/a | self.assertRaises(RecursionError, f) |
---|
492 | n/a | |
---|
493 | n/a | def g(): |
---|
494 | n/a | try: |
---|
495 | n/a | return g() |
---|
496 | n/a | except ValueError: |
---|
497 | n/a | return -1 |
---|
498 | n/a | self.assertRaises(RecursionError, g) |
---|
499 | n/a | |
---|
500 | n/a | def test_str(self): |
---|
501 | n/a | # Make sure both instances and classes have a str representation. |
---|
502 | n/a | self.assertTrue(str(Exception)) |
---|
503 | n/a | self.assertTrue(str(Exception('a'))) |
---|
504 | n/a | self.assertTrue(str(Exception('a', 'b'))) |
---|
505 | n/a | |
---|
506 | n/a | def testExceptionCleanupNames(self): |
---|
507 | n/a | # Make sure the local variable bound to the exception instance by |
---|
508 | n/a | # an "except" statement is only visible inside the except block. |
---|
509 | n/a | try: |
---|
510 | n/a | raise Exception() |
---|
511 | n/a | except Exception as e: |
---|
512 | n/a | self.assertTrue(e) |
---|
513 | n/a | del e |
---|
514 | n/a | self.assertNotIn('e', locals()) |
---|
515 | n/a | |
---|
516 | n/a | def testExceptionCleanupState(self): |
---|
517 | n/a | # Make sure exception state is cleaned up as soon as the except |
---|
518 | n/a | # block is left. See #2507 |
---|
519 | n/a | |
---|
520 | n/a | class MyException(Exception): |
---|
521 | n/a | def __init__(self, obj): |
---|
522 | n/a | self.obj = obj |
---|
523 | n/a | class MyObj: |
---|
524 | n/a | pass |
---|
525 | n/a | |
---|
526 | n/a | def inner_raising_func(): |
---|
527 | n/a | # Create some references in exception value and traceback |
---|
528 | n/a | local_ref = obj |
---|
529 | n/a | raise MyException(obj) |
---|
530 | n/a | |
---|
531 | n/a | # Qualified "except" with "as" |
---|
532 | n/a | obj = MyObj() |
---|
533 | n/a | wr = weakref.ref(obj) |
---|
534 | n/a | try: |
---|
535 | n/a | inner_raising_func() |
---|
536 | n/a | except MyException as e: |
---|
537 | n/a | pass |
---|
538 | n/a | obj = None |
---|
539 | n/a | obj = wr() |
---|
540 | n/a | self.assertTrue(obj is None, "%s" % obj) |
---|
541 | n/a | |
---|
542 | n/a | # Qualified "except" without "as" |
---|
543 | n/a | obj = MyObj() |
---|
544 | n/a | wr = weakref.ref(obj) |
---|
545 | n/a | try: |
---|
546 | n/a | inner_raising_func() |
---|
547 | n/a | except MyException: |
---|
548 | n/a | pass |
---|
549 | n/a | obj = None |
---|
550 | n/a | obj = wr() |
---|
551 | n/a | self.assertTrue(obj is None, "%s" % obj) |
---|
552 | n/a | |
---|
553 | n/a | # Bare "except" |
---|
554 | n/a | obj = MyObj() |
---|
555 | n/a | wr = weakref.ref(obj) |
---|
556 | n/a | try: |
---|
557 | n/a | inner_raising_func() |
---|
558 | n/a | except: |
---|
559 | n/a | pass |
---|
560 | n/a | obj = None |
---|
561 | n/a | obj = wr() |
---|
562 | n/a | self.assertTrue(obj is None, "%s" % obj) |
---|
563 | n/a | |
---|
564 | n/a | # "except" with premature block leave |
---|
565 | n/a | obj = MyObj() |
---|
566 | n/a | wr = weakref.ref(obj) |
---|
567 | n/a | for i in [0]: |
---|
568 | n/a | try: |
---|
569 | n/a | inner_raising_func() |
---|
570 | n/a | except: |
---|
571 | n/a | break |
---|
572 | n/a | obj = None |
---|
573 | n/a | obj = wr() |
---|
574 | n/a | self.assertTrue(obj is None, "%s" % obj) |
---|
575 | n/a | |
---|
576 | n/a | # "except" block raising another exception |
---|
577 | n/a | obj = MyObj() |
---|
578 | n/a | wr = weakref.ref(obj) |
---|
579 | n/a | try: |
---|
580 | n/a | try: |
---|
581 | n/a | inner_raising_func() |
---|
582 | n/a | except: |
---|
583 | n/a | raise KeyError |
---|
584 | n/a | except KeyError as e: |
---|
585 | n/a | # We want to test that the except block above got rid of |
---|
586 | n/a | # the exception raised in inner_raising_func(), but it |
---|
587 | n/a | # also ends up in the __context__ of the KeyError, so we |
---|
588 | n/a | # must clear the latter manually for our test to succeed. |
---|
589 | n/a | e.__context__ = None |
---|
590 | n/a | obj = None |
---|
591 | n/a | obj = wr() |
---|
592 | n/a | # guarantee no ref cycles on CPython (don't gc_collect) |
---|
593 | n/a | if check_impl_detail(cpython=False): |
---|
594 | n/a | gc_collect() |
---|
595 | n/a | self.assertTrue(obj is None, "%s" % obj) |
---|
596 | n/a | |
---|
597 | n/a | # Some complicated construct |
---|
598 | n/a | obj = MyObj() |
---|
599 | n/a | wr = weakref.ref(obj) |
---|
600 | n/a | try: |
---|
601 | n/a | inner_raising_func() |
---|
602 | n/a | except MyException: |
---|
603 | n/a | try: |
---|
604 | n/a | try: |
---|
605 | n/a | raise |
---|
606 | n/a | finally: |
---|
607 | n/a | raise |
---|
608 | n/a | except MyException: |
---|
609 | n/a | pass |
---|
610 | n/a | obj = None |
---|
611 | n/a | if check_impl_detail(cpython=False): |
---|
612 | n/a | gc_collect() |
---|
613 | n/a | obj = wr() |
---|
614 | n/a | self.assertTrue(obj is None, "%s" % obj) |
---|
615 | n/a | |
---|
616 | n/a | # Inside an exception-silencing "with" block |
---|
617 | n/a | class Context: |
---|
618 | n/a | def __enter__(self): |
---|
619 | n/a | return self |
---|
620 | n/a | def __exit__ (self, exc_type, exc_value, exc_tb): |
---|
621 | n/a | return True |
---|
622 | n/a | obj = MyObj() |
---|
623 | n/a | wr = weakref.ref(obj) |
---|
624 | n/a | with Context(): |
---|
625 | n/a | inner_raising_func() |
---|
626 | n/a | obj = None |
---|
627 | n/a | if check_impl_detail(cpython=False): |
---|
628 | n/a | gc_collect() |
---|
629 | n/a | obj = wr() |
---|
630 | n/a | self.assertTrue(obj is None, "%s" % obj) |
---|
631 | n/a | |
---|
632 | n/a | def test_exception_target_in_nested_scope(self): |
---|
633 | n/a | # issue 4617: This used to raise a SyntaxError |
---|
634 | n/a | # "can not delete variable 'e' referenced in nested scope" |
---|
635 | n/a | def print_error(): |
---|
636 | n/a | e |
---|
637 | n/a | try: |
---|
638 | n/a | something |
---|
639 | n/a | except Exception as e: |
---|
640 | n/a | print_error() |
---|
641 | n/a | # implicit "del e" here |
---|
642 | n/a | |
---|
643 | n/a | def test_generator_leaking(self): |
---|
644 | n/a | # Test that generator exception state doesn't leak into the calling |
---|
645 | n/a | # frame |
---|
646 | n/a | def yield_raise(): |
---|
647 | n/a | try: |
---|
648 | n/a | raise KeyError("caught") |
---|
649 | n/a | except KeyError: |
---|
650 | n/a | yield sys.exc_info()[0] |
---|
651 | n/a | yield sys.exc_info()[0] |
---|
652 | n/a | yield sys.exc_info()[0] |
---|
653 | n/a | g = yield_raise() |
---|
654 | n/a | self.assertEqual(next(g), KeyError) |
---|
655 | n/a | self.assertEqual(sys.exc_info()[0], None) |
---|
656 | n/a | self.assertEqual(next(g), KeyError) |
---|
657 | n/a | self.assertEqual(sys.exc_info()[0], None) |
---|
658 | n/a | self.assertEqual(next(g), None) |
---|
659 | n/a | |
---|
660 | n/a | # Same test, but inside an exception handler |
---|
661 | n/a | try: |
---|
662 | n/a | raise TypeError("foo") |
---|
663 | n/a | except TypeError: |
---|
664 | n/a | g = yield_raise() |
---|
665 | n/a | self.assertEqual(next(g), KeyError) |
---|
666 | n/a | self.assertEqual(sys.exc_info()[0], TypeError) |
---|
667 | n/a | self.assertEqual(next(g), KeyError) |
---|
668 | n/a | self.assertEqual(sys.exc_info()[0], TypeError) |
---|
669 | n/a | self.assertEqual(next(g), TypeError) |
---|
670 | n/a | del g |
---|
671 | n/a | self.assertEqual(sys.exc_info()[0], TypeError) |
---|
672 | n/a | |
---|
673 | n/a | def test_generator_leaking2(self): |
---|
674 | n/a | # See issue 12475. |
---|
675 | n/a | def g(): |
---|
676 | n/a | yield |
---|
677 | n/a | try: |
---|
678 | n/a | raise RuntimeError |
---|
679 | n/a | except RuntimeError: |
---|
680 | n/a | it = g() |
---|
681 | n/a | next(it) |
---|
682 | n/a | try: |
---|
683 | n/a | next(it) |
---|
684 | n/a | except StopIteration: |
---|
685 | n/a | pass |
---|
686 | n/a | self.assertEqual(sys.exc_info(), (None, None, None)) |
---|
687 | n/a | |
---|
688 | n/a | def test_generator_leaking3(self): |
---|
689 | n/a | # See issue #23353. When gen.throw() is called, the caller's |
---|
690 | n/a | # exception state should be save and restored. |
---|
691 | n/a | def g(): |
---|
692 | n/a | try: |
---|
693 | n/a | yield |
---|
694 | n/a | except ZeroDivisionError: |
---|
695 | n/a | yield sys.exc_info()[1] |
---|
696 | n/a | it = g() |
---|
697 | n/a | next(it) |
---|
698 | n/a | try: |
---|
699 | n/a | 1/0 |
---|
700 | n/a | except ZeroDivisionError as e: |
---|
701 | n/a | self.assertIs(sys.exc_info()[1], e) |
---|
702 | n/a | gen_exc = it.throw(e) |
---|
703 | n/a | self.assertIs(sys.exc_info()[1], e) |
---|
704 | n/a | self.assertIs(gen_exc, e) |
---|
705 | n/a | self.assertEqual(sys.exc_info(), (None, None, None)) |
---|
706 | n/a | |
---|
707 | n/a | def test_generator_leaking4(self): |
---|
708 | n/a | # See issue #23353. When an exception is raised by a generator, |
---|
709 | n/a | # the caller's exception state should still be restored. |
---|
710 | n/a | def g(): |
---|
711 | n/a | try: |
---|
712 | n/a | 1/0 |
---|
713 | n/a | except ZeroDivisionError: |
---|
714 | n/a | yield sys.exc_info()[0] |
---|
715 | n/a | raise |
---|
716 | n/a | it = g() |
---|
717 | n/a | try: |
---|
718 | n/a | raise TypeError |
---|
719 | n/a | except TypeError: |
---|
720 | n/a | # The caller's exception state (TypeError) is temporarily |
---|
721 | n/a | # saved in the generator. |
---|
722 | n/a | tp = next(it) |
---|
723 | n/a | self.assertIs(tp, ZeroDivisionError) |
---|
724 | n/a | try: |
---|
725 | n/a | next(it) |
---|
726 | n/a | # We can't check it immediately, but while next() returns |
---|
727 | n/a | # with an exception, it shouldn't have restored the old |
---|
728 | n/a | # exception state (TypeError). |
---|
729 | n/a | except ZeroDivisionError as e: |
---|
730 | n/a | self.assertIs(sys.exc_info()[1], e) |
---|
731 | n/a | # We used to find TypeError here. |
---|
732 | n/a | self.assertEqual(sys.exc_info(), (None, None, None)) |
---|
733 | n/a | |
---|
734 | n/a | def test_generator_doesnt_retain_old_exc(self): |
---|
735 | n/a | def g(): |
---|
736 | n/a | self.assertIsInstance(sys.exc_info()[1], RuntimeError) |
---|
737 | n/a | yield |
---|
738 | n/a | self.assertEqual(sys.exc_info(), (None, None, None)) |
---|
739 | n/a | it = g() |
---|
740 | n/a | try: |
---|
741 | n/a | raise RuntimeError |
---|
742 | n/a | except RuntimeError: |
---|
743 | n/a | next(it) |
---|
744 | n/a | self.assertRaises(StopIteration, next, it) |
---|
745 | n/a | |
---|
746 | n/a | def test_generator_finalizing_and_exc_info(self): |
---|
747 | n/a | # See #7173 |
---|
748 | n/a | def simple_gen(): |
---|
749 | n/a | yield 1 |
---|
750 | n/a | def run_gen(): |
---|
751 | n/a | gen = simple_gen() |
---|
752 | n/a | try: |
---|
753 | n/a | raise RuntimeError |
---|
754 | n/a | except RuntimeError: |
---|
755 | n/a | return next(gen) |
---|
756 | n/a | run_gen() |
---|
757 | n/a | gc_collect() |
---|
758 | n/a | self.assertEqual(sys.exc_info(), (None, None, None)) |
---|
759 | n/a | |
---|
760 | n/a | def _check_generator_cleanup_exc_state(self, testfunc): |
---|
761 | n/a | # Issue #12791: exception state is cleaned up as soon as a generator |
---|
762 | n/a | # is closed (reference cycles are broken). |
---|
763 | n/a | class MyException(Exception): |
---|
764 | n/a | def __init__(self, obj): |
---|
765 | n/a | self.obj = obj |
---|
766 | n/a | class MyObj: |
---|
767 | n/a | pass |
---|
768 | n/a | |
---|
769 | n/a | def raising_gen(): |
---|
770 | n/a | try: |
---|
771 | n/a | raise MyException(obj) |
---|
772 | n/a | except MyException: |
---|
773 | n/a | yield |
---|
774 | n/a | |
---|
775 | n/a | obj = MyObj() |
---|
776 | n/a | wr = weakref.ref(obj) |
---|
777 | n/a | g = raising_gen() |
---|
778 | n/a | next(g) |
---|
779 | n/a | testfunc(g) |
---|
780 | n/a | g = obj = None |
---|
781 | n/a | obj = wr() |
---|
782 | n/a | self.assertIs(obj, None) |
---|
783 | n/a | |
---|
784 | n/a | def test_generator_throw_cleanup_exc_state(self): |
---|
785 | n/a | def do_throw(g): |
---|
786 | n/a | try: |
---|
787 | n/a | g.throw(RuntimeError()) |
---|
788 | n/a | except RuntimeError: |
---|
789 | n/a | pass |
---|
790 | n/a | self._check_generator_cleanup_exc_state(do_throw) |
---|
791 | n/a | |
---|
792 | n/a | def test_generator_close_cleanup_exc_state(self): |
---|
793 | n/a | def do_close(g): |
---|
794 | n/a | g.close() |
---|
795 | n/a | self._check_generator_cleanup_exc_state(do_close) |
---|
796 | n/a | |
---|
797 | n/a | def test_generator_del_cleanup_exc_state(self): |
---|
798 | n/a | def do_del(g): |
---|
799 | n/a | g = None |
---|
800 | n/a | self._check_generator_cleanup_exc_state(do_del) |
---|
801 | n/a | |
---|
802 | n/a | def test_generator_next_cleanup_exc_state(self): |
---|
803 | n/a | def do_next(g): |
---|
804 | n/a | try: |
---|
805 | n/a | next(g) |
---|
806 | n/a | except StopIteration: |
---|
807 | n/a | pass |
---|
808 | n/a | else: |
---|
809 | n/a | self.fail("should have raised StopIteration") |
---|
810 | n/a | self._check_generator_cleanup_exc_state(do_next) |
---|
811 | n/a | |
---|
812 | n/a | def test_generator_send_cleanup_exc_state(self): |
---|
813 | n/a | def do_send(g): |
---|
814 | n/a | try: |
---|
815 | n/a | g.send(None) |
---|
816 | n/a | except StopIteration: |
---|
817 | n/a | pass |
---|
818 | n/a | else: |
---|
819 | n/a | self.fail("should have raised StopIteration") |
---|
820 | n/a | self._check_generator_cleanup_exc_state(do_send) |
---|
821 | n/a | |
---|
822 | n/a | def test_3114(self): |
---|
823 | n/a | # Bug #3114: in its destructor, MyObject retrieves a pointer to |
---|
824 | n/a | # obsolete and/or deallocated objects. |
---|
825 | n/a | class MyObject: |
---|
826 | n/a | def __del__(self): |
---|
827 | n/a | nonlocal e |
---|
828 | n/a | e = sys.exc_info() |
---|
829 | n/a | e = () |
---|
830 | n/a | try: |
---|
831 | n/a | raise Exception(MyObject()) |
---|
832 | n/a | except: |
---|
833 | n/a | pass |
---|
834 | n/a | self.assertEqual(e, (None, None, None)) |
---|
835 | n/a | |
---|
836 | n/a | def test_unicode_change_attributes(self): |
---|
837 | n/a | # See issue 7309. This was a crasher. |
---|
838 | n/a | |
---|
839 | n/a | u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo') |
---|
840 | n/a | self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo") |
---|
841 | n/a | u.end = 2 |
---|
842 | n/a | self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo") |
---|
843 | n/a | u.end = 5 |
---|
844 | n/a | u.reason = 0x345345345345345345 |
---|
845 | n/a | self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997") |
---|
846 | n/a | u.encoding = 4000 |
---|
847 | n/a | self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997") |
---|
848 | n/a | u.start = 1000 |
---|
849 | n/a | self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997") |
---|
850 | n/a | |
---|
851 | n/a | u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo') |
---|
852 | n/a | self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo") |
---|
853 | n/a | u.end = 2 |
---|
854 | n/a | self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo") |
---|
855 | n/a | u.end = 5 |
---|
856 | n/a | u.reason = 0x345345345345345345 |
---|
857 | n/a | self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997") |
---|
858 | n/a | u.encoding = 4000 |
---|
859 | n/a | self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997") |
---|
860 | n/a | u.start = 1000 |
---|
861 | n/a | self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997") |
---|
862 | n/a | |
---|
863 | n/a | u = UnicodeTranslateError('xxxx', 1, 5, 'foo') |
---|
864 | n/a | self.assertEqual(str(u), "can't translate characters in position 1-4: foo") |
---|
865 | n/a | u.end = 2 |
---|
866 | n/a | self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo") |
---|
867 | n/a | u.end = 5 |
---|
868 | n/a | u.reason = 0x345345345345345345 |
---|
869 | n/a | self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997") |
---|
870 | n/a | u.start = 1000 |
---|
871 | n/a | self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997") |
---|
872 | n/a | |
---|
873 | n/a | def test_unicode_errors_no_object(self): |
---|
874 | n/a | # See issue #21134. |
---|
875 | n/a | klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError |
---|
876 | n/a | for klass in klasses: |
---|
877 | n/a | self.assertEqual(str(klass.__new__(klass)), "") |
---|
878 | n/a | |
---|
879 | n/a | @no_tracing |
---|
880 | n/a | def test_badisinstance(self): |
---|
881 | n/a | # Bug #2542: if issubclass(e, MyException) raises an exception, |
---|
882 | n/a | # it should be ignored |
---|
883 | n/a | class Meta(type): |
---|
884 | n/a | def __subclasscheck__(cls, subclass): |
---|
885 | n/a | raise ValueError() |
---|
886 | n/a | class MyException(Exception, metaclass=Meta): |
---|
887 | n/a | pass |
---|
888 | n/a | |
---|
889 | n/a | with captured_stderr() as stderr: |
---|
890 | n/a | try: |
---|
891 | n/a | raise KeyError() |
---|
892 | n/a | except MyException as e: |
---|
893 | n/a | self.fail("exception should not be a MyException") |
---|
894 | n/a | except KeyError: |
---|
895 | n/a | pass |
---|
896 | n/a | except: |
---|
897 | n/a | self.fail("Should have raised KeyError") |
---|
898 | n/a | else: |
---|
899 | n/a | self.fail("Should have raised KeyError") |
---|
900 | n/a | |
---|
901 | n/a | def g(): |
---|
902 | n/a | try: |
---|
903 | n/a | return g() |
---|
904 | n/a | except RecursionError: |
---|
905 | n/a | return sys.exc_info() |
---|
906 | n/a | e, v, tb = g() |
---|
907 | n/a | self.assertTrue(isinstance(v, RecursionError), type(v)) |
---|
908 | n/a | self.assertIn("maximum recursion depth exceeded", str(v)) |
---|
909 | n/a | |
---|
910 | n/a | |
---|
911 | n/a | @cpython_only |
---|
912 | n/a | def test_MemoryError(self): |
---|
913 | n/a | # PyErr_NoMemory always raises the same exception instance. |
---|
914 | n/a | # Check that the traceback is not doubled. |
---|
915 | n/a | import traceback |
---|
916 | n/a | from _testcapi import raise_memoryerror |
---|
917 | n/a | def raiseMemError(): |
---|
918 | n/a | try: |
---|
919 | n/a | raise_memoryerror() |
---|
920 | n/a | except MemoryError as e: |
---|
921 | n/a | tb = e.__traceback__ |
---|
922 | n/a | else: |
---|
923 | n/a | self.fail("Should have raises a MemoryError") |
---|
924 | n/a | return traceback.format_tb(tb) |
---|
925 | n/a | |
---|
926 | n/a | tb1 = raiseMemError() |
---|
927 | n/a | tb2 = raiseMemError() |
---|
928 | n/a | self.assertEqual(tb1, tb2) |
---|
929 | n/a | |
---|
930 | n/a | @cpython_only |
---|
931 | n/a | def test_exception_with_doc(self): |
---|
932 | n/a | import _testcapi |
---|
933 | n/a | doc2 = "This is a test docstring." |
---|
934 | n/a | doc4 = "This is another test docstring." |
---|
935 | n/a | |
---|
936 | n/a | self.assertRaises(SystemError, _testcapi.make_exception_with_doc, |
---|
937 | n/a | "error1") |
---|
938 | n/a | |
---|
939 | n/a | # test basic usage of PyErr_NewException |
---|
940 | n/a | error1 = _testcapi.make_exception_with_doc("_testcapi.error1") |
---|
941 | n/a | self.assertIs(type(error1), type) |
---|
942 | n/a | self.assertTrue(issubclass(error1, Exception)) |
---|
943 | n/a | self.assertIsNone(error1.__doc__) |
---|
944 | n/a | |
---|
945 | n/a | # test with given docstring |
---|
946 | n/a | error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2) |
---|
947 | n/a | self.assertEqual(error2.__doc__, doc2) |
---|
948 | n/a | |
---|
949 | n/a | # test with explicit base (without docstring) |
---|
950 | n/a | error3 = _testcapi.make_exception_with_doc("_testcapi.error3", |
---|
951 | n/a | base=error2) |
---|
952 | n/a | self.assertTrue(issubclass(error3, error2)) |
---|
953 | n/a | |
---|
954 | n/a | # test with explicit base tuple |
---|
955 | n/a | class C(object): |
---|
956 | n/a | pass |
---|
957 | n/a | error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4, |
---|
958 | n/a | (error3, C)) |
---|
959 | n/a | self.assertTrue(issubclass(error4, error3)) |
---|
960 | n/a | self.assertTrue(issubclass(error4, C)) |
---|
961 | n/a | self.assertEqual(error4.__doc__, doc4) |
---|
962 | n/a | |
---|
963 | n/a | # test with explicit dictionary |
---|
964 | n/a | error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "", |
---|
965 | n/a | error4, {'a': 1}) |
---|
966 | n/a | self.assertTrue(issubclass(error5, error4)) |
---|
967 | n/a | self.assertEqual(error5.a, 1) |
---|
968 | n/a | self.assertEqual(error5.__doc__, "") |
---|
969 | n/a | |
---|
970 | n/a | @cpython_only |
---|
971 | n/a | def test_memory_error_cleanup(self): |
---|
972 | n/a | # Issue #5437: preallocated MemoryError instances should not keep |
---|
973 | n/a | # traceback objects alive. |
---|
974 | n/a | from _testcapi import raise_memoryerror |
---|
975 | n/a | class C: |
---|
976 | n/a | pass |
---|
977 | n/a | wr = None |
---|
978 | n/a | def inner(): |
---|
979 | n/a | nonlocal wr |
---|
980 | n/a | c = C() |
---|
981 | n/a | wr = weakref.ref(c) |
---|
982 | n/a | raise_memoryerror() |
---|
983 | n/a | # We cannot use assertRaises since it manually deletes the traceback |
---|
984 | n/a | try: |
---|
985 | n/a | inner() |
---|
986 | n/a | except MemoryError as e: |
---|
987 | n/a | self.assertNotEqual(wr(), None) |
---|
988 | n/a | else: |
---|
989 | n/a | self.fail("MemoryError not raised") |
---|
990 | n/a | self.assertEqual(wr(), None) |
---|
991 | n/a | |
---|
992 | n/a | @no_tracing |
---|
993 | n/a | def test_recursion_error_cleanup(self): |
---|
994 | n/a | # Same test as above, but with "recursion exceeded" errors |
---|
995 | n/a | class C: |
---|
996 | n/a | pass |
---|
997 | n/a | wr = None |
---|
998 | n/a | def inner(): |
---|
999 | n/a | nonlocal wr |
---|
1000 | n/a | c = C() |
---|
1001 | n/a | wr = weakref.ref(c) |
---|
1002 | n/a | inner() |
---|
1003 | n/a | # We cannot use assertRaises since it manually deletes the traceback |
---|
1004 | n/a | try: |
---|
1005 | n/a | inner() |
---|
1006 | n/a | except RecursionError as e: |
---|
1007 | n/a | self.assertNotEqual(wr(), None) |
---|
1008 | n/a | else: |
---|
1009 | n/a | self.fail("RecursionError not raised") |
---|
1010 | n/a | self.assertEqual(wr(), None) |
---|
1011 | n/a | |
---|
1012 | n/a | def test_errno_ENOTDIR(self): |
---|
1013 | n/a | # Issue #12802: "not a directory" errors are ENOTDIR even on Windows |
---|
1014 | n/a | with self.assertRaises(OSError) as cm: |
---|
1015 | n/a | os.listdir(__file__) |
---|
1016 | n/a | self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception) |
---|
1017 | n/a | |
---|
1018 | n/a | def test_unraisable(self): |
---|
1019 | n/a | # Issue #22836: PyErr_WriteUnraisable() should give sensible reports |
---|
1020 | n/a | class BrokenDel: |
---|
1021 | n/a | def __del__(self): |
---|
1022 | n/a | exc = ValueError("del is broken") |
---|
1023 | n/a | # The following line is included in the traceback report: |
---|
1024 | n/a | raise exc |
---|
1025 | n/a | |
---|
1026 | n/a | class BrokenExceptionDel: |
---|
1027 | n/a | def __del__(self): |
---|
1028 | n/a | exc = BrokenStrException() |
---|
1029 | n/a | # The following line is included in the traceback report: |
---|
1030 | n/a | raise exc |
---|
1031 | n/a | |
---|
1032 | n/a | for test_class in (BrokenDel, BrokenExceptionDel): |
---|
1033 | n/a | with self.subTest(test_class): |
---|
1034 | n/a | obj = test_class() |
---|
1035 | n/a | with captured_stderr() as stderr: |
---|
1036 | n/a | del obj |
---|
1037 | n/a | report = stderr.getvalue() |
---|
1038 | n/a | self.assertIn("Exception ignored", report) |
---|
1039 | n/a | self.assertIn(test_class.__del__.__qualname__, report) |
---|
1040 | n/a | self.assertIn("test_exceptions.py", report) |
---|
1041 | n/a | self.assertIn("raise exc", report) |
---|
1042 | n/a | if test_class is BrokenExceptionDel: |
---|
1043 | n/a | self.assertIn("BrokenStrException", report) |
---|
1044 | n/a | self.assertIn("<exception str() failed>", report) |
---|
1045 | n/a | else: |
---|
1046 | n/a | self.assertIn("ValueError", report) |
---|
1047 | n/a | self.assertIn("del is broken", report) |
---|
1048 | n/a | self.assertTrue(report.endswith("\n")) |
---|
1049 | n/a | |
---|
1050 | n/a | def test_unhandled(self): |
---|
1051 | n/a | # Check for sensible reporting of unhandled exceptions |
---|
1052 | n/a | for exc_type in (ValueError, BrokenStrException): |
---|
1053 | n/a | with self.subTest(exc_type): |
---|
1054 | n/a | try: |
---|
1055 | n/a | exc = exc_type("test message") |
---|
1056 | n/a | # The following line is included in the traceback report: |
---|
1057 | n/a | raise exc |
---|
1058 | n/a | except exc_type: |
---|
1059 | n/a | with captured_stderr() as stderr: |
---|
1060 | n/a | sys.__excepthook__(*sys.exc_info()) |
---|
1061 | n/a | report = stderr.getvalue() |
---|
1062 | n/a | self.assertIn("test_exceptions.py", report) |
---|
1063 | n/a | self.assertIn("raise exc", report) |
---|
1064 | n/a | self.assertIn(exc_type.__name__, report) |
---|
1065 | n/a | if exc_type is BrokenStrException: |
---|
1066 | n/a | self.assertIn("<exception str() failed>", report) |
---|
1067 | n/a | else: |
---|
1068 | n/a | self.assertIn("test message", report) |
---|
1069 | n/a | self.assertTrue(report.endswith("\n")) |
---|
1070 | n/a | |
---|
1071 | n/a | |
---|
1072 | n/a | class ImportErrorTests(unittest.TestCase): |
---|
1073 | n/a | |
---|
1074 | n/a | def test_attributes(self): |
---|
1075 | n/a | # Setting 'name' and 'path' should not be a problem. |
---|
1076 | n/a | exc = ImportError('test') |
---|
1077 | n/a | self.assertIsNone(exc.name) |
---|
1078 | n/a | self.assertIsNone(exc.path) |
---|
1079 | n/a | |
---|
1080 | n/a | exc = ImportError('test', name='somemodule') |
---|
1081 | n/a | self.assertEqual(exc.name, 'somemodule') |
---|
1082 | n/a | self.assertIsNone(exc.path) |
---|
1083 | n/a | |
---|
1084 | n/a | exc = ImportError('test', path='somepath') |
---|
1085 | n/a | self.assertEqual(exc.path, 'somepath') |
---|
1086 | n/a | self.assertIsNone(exc.name) |
---|
1087 | n/a | |
---|
1088 | n/a | exc = ImportError('test', path='somepath', name='somename') |
---|
1089 | n/a | self.assertEqual(exc.name, 'somename') |
---|
1090 | n/a | self.assertEqual(exc.path, 'somepath') |
---|
1091 | n/a | |
---|
1092 | n/a | msg = "'invalid' is an invalid keyword argument for this function" |
---|
1093 | n/a | with self.assertRaisesRegex(TypeError, msg): |
---|
1094 | n/a | ImportError('test', invalid='keyword') |
---|
1095 | n/a | |
---|
1096 | n/a | with self.assertRaisesRegex(TypeError, msg): |
---|
1097 | n/a | ImportError('test', name='name', invalid='keyword') |
---|
1098 | n/a | |
---|
1099 | n/a | with self.assertRaisesRegex(TypeError, msg): |
---|
1100 | n/a | ImportError('test', path='path', invalid='keyword') |
---|
1101 | n/a | |
---|
1102 | n/a | with self.assertRaisesRegex(TypeError, msg): |
---|
1103 | n/a | ImportError(invalid='keyword') |
---|
1104 | n/a | |
---|
1105 | n/a | with self.assertRaisesRegex(TypeError, msg): |
---|
1106 | n/a | ImportError('test', invalid='keyword', another=True) |
---|
1107 | n/a | |
---|
1108 | n/a | def test_reset_attributes(self): |
---|
1109 | n/a | exc = ImportError('test', name='name', path='path') |
---|
1110 | n/a | self.assertEqual(exc.args, ('test',)) |
---|
1111 | n/a | self.assertEqual(exc.msg, 'test') |
---|
1112 | n/a | self.assertEqual(exc.name, 'name') |
---|
1113 | n/a | self.assertEqual(exc.path, 'path') |
---|
1114 | n/a | |
---|
1115 | n/a | # Reset not specified attributes |
---|
1116 | n/a | exc.__init__() |
---|
1117 | n/a | self.assertEqual(exc.args, ()) |
---|
1118 | n/a | self.assertEqual(exc.msg, None) |
---|
1119 | n/a | self.assertEqual(exc.name, None) |
---|
1120 | n/a | self.assertEqual(exc.path, None) |
---|
1121 | n/a | |
---|
1122 | n/a | def test_non_str_argument(self): |
---|
1123 | n/a | # Issue #15778 |
---|
1124 | n/a | with check_warnings(('', BytesWarning), quiet=True): |
---|
1125 | n/a | arg = b'abc' |
---|
1126 | n/a | exc = ImportError(arg) |
---|
1127 | n/a | self.assertEqual(str(arg), str(exc)) |
---|
1128 | n/a | |
---|
1129 | n/a | |
---|
1130 | n/a | if __name__ == '__main__': |
---|
1131 | n/a | unittest.main() |
---|