Debian Codegraph @

tests/test_pickle_exception.py

raw
1 import os
2 from traceback import format_exception
3
4 try:
5 import copyreg
6 except ImportError:
7 # Python 2
8 import copy_reg as copyreg
9
10 import pickle
11 import sys
12
13 import pytest
14
15 import tblib.pickling_support
16
17 has_python311 = sys.version_info >= (3, 11)
18
19
20 @pytest.fixture
21 def clear_dispatch_table():
22 bak = copyreg.dispatch_table.copy()
23 copyreg.dispatch_table.clear()
24 yield None
25 copyreg.dispatch_table.clear()
26 copyreg.dispatch_table.update(bak)
27
28
29 class CustomError(Exception):
30 pass
31
32
33 def strip_locations(tb_text):
34 return tb_text.replace(' ~~^~~\n', '').replace(' ^^^^^^^^^^^^^^^^^\n', '')
35
36
37 @pytest.mark.parametrize('protocol', [None, *list(range(1, pickle.HIGHEST_PROTOCOL + 1))])
38 @pytest.mark.parametrize('how', ['global', 'instance', 'class'])
39 def test_install(clear_dispatch_table, how, protocol):
40 if how == 'global':
41 tblib.pickling_support.install()
42 elif how == 'class':
43 tblib.pickling_support.install(CustomError, ValueError, ZeroDivisionError)
44
45 try:
46 try:
47 try:
48 1 / 0 # noqa: B018
49 finally:
50 # The ValueError's __context__ will be the ZeroDivisionError
51 raise ValueError('blah')
52 except Exception as e:
53 # Python 3 only syntax
54 # raise CustomError("foo") from e
55 new_e = CustomError('foo')
56 new_e.__cause__ = e
57 if has_python311:
58 new_e.add_note('note 1')
59 new_e.add_note('note 2')
60 raise new_e from e
61 except Exception as e:
62 exc = e
63 else:
64 raise AssertionError
65
66 expected_format_exception = strip_locations(''.join(format_exception(type(exc), exc, exc.__traceback__)))
67
68 # Populate Exception.__dict__, which is used in some cases
69 exc.x = 1
70 exc.__cause__.x = 2
71 exc.__cause__.__context__.x = 3
72
73 if how == 'instance':
74 tblib.pickling_support.install(exc)
75 if protocol:
76 exc = pickle.loads(pickle.dumps(exc, protocol=protocol))
77
78 assert isinstance(exc, CustomError)
79 assert exc.args == ('foo',)
80 assert exc.x == 1
81 assert exc.__traceback__ is not None
82
83 assert isinstance(exc.__cause__, ValueError)
84 assert exc.__cause__.__traceback__ is not None
85 assert exc.__cause__.x == 2
86 assert exc.__cause__.__cause__ is None
87
88 assert isinstance(exc.__cause__.__context__, ZeroDivisionError)
89 assert exc.__cause__.__context__.x == 3
90 assert exc.__cause__.__context__.__cause__ is None
91 assert exc.__cause__.__context__.__context__ is None
92
93 if has_python311:
94 assert exc.__notes__ == ['note 1', 'note 2']
95
96 assert expected_format_exception == strip_locations(''.join(format_exception(type(exc), exc, exc.__traceback__)))
97
98
99 @tblib.pickling_support.install
100 class RegisteredError(Exception):
101 pass
102
103
104 def test_install_decorator():
105 with pytest.raises(RegisteredError) as ewrap:
106 raise RegisteredError('foo')
107 exc = ewrap.value
108 exc.x = 1
109 exc = pickle.loads(pickle.dumps(exc))
110
111 assert isinstance(exc, RegisteredError)
112 assert exc.args == ('foo',)
113 assert exc.x == 1
114 assert exc.__traceback__ is not None
115
116
117 @pytest.mark.skipif(not has_python311, reason='no BaseExceptionGroup before Python 3.11')
118 def test_install_instance_recursively(clear_dispatch_table):
119 exc = BaseExceptionGroup('test', [ValueError('foo'), CustomError('bar')]) # noqa: F821
120 exc.exceptions[0].__cause__ = ZeroDivisionError('baz')
121 exc.exceptions[0].__cause__.__context__ = AttributeError('quux')
122
123 tblib.pickling_support.install(exc)
124
125 installed = {c for c in copyreg.dispatch_table if issubclass(c, BaseException)}
126 assert installed == {ExceptionGroup, ValueError, CustomError, ZeroDivisionError, AttributeError} # noqa: F821
127
128
129 def test_install_typeerror():
130 with pytest.raises(TypeError):
131 tblib.pickling_support.install('foo')
132
133
134 @pytest.mark.parametrize('protocol', [None, *list(range(1, pickle.HIGHEST_PROTOCOL + 1))])
135 @pytest.mark.parametrize('how', ['global', 'instance', 'class'])
136 def test_get_locals(clear_dispatch_table, how, protocol):
137 def get_locals(frame):
138 if 'my_variable' in frame.f_locals:
139 return {'my_variable': int(frame.f_locals['my_variable'])}
140 else:
141 return {}
142
143 if how == 'global':
144 tblib.pickling_support.install(get_locals=get_locals)
145 elif how == 'class':
146 tblib.pickling_support.install(CustomError, ValueError, ZeroDivisionError, get_locals=get_locals)
147
148 def func(my_arg='2'):
149 my_variable = '1'
150 raise ValueError(my_variable)
151
152 try:
153 func()
154 except Exception as e:
155 exc = e
156 else:
157 raise AssertionError
158
159 f_locals = exc.__traceback__.tb_next.tb_frame.f_locals
160 assert 'my_variable' in f_locals
161 assert f_locals['my_variable'] == '1'
162
163 if how == 'instance':
164 tblib.pickling_support.install(exc, get_locals=get_locals)
165
166 exc = pickle.loads(pickle.dumps(exc, protocol=protocol))
167 assert exc.__traceback__.tb_next.tb_frame.f_locals == {'my_variable': 1}
168
169
170 class CustomWithAttributesException(Exception):
171 def __init__(self, message, arg1, arg2, arg3):
172 super().__init__(message)
173 self.values12 = (arg1, arg2)
174 self.value3 = arg3
175
176
177 def test_custom_with_attributes():
178 try:
179 raise CustomWithAttributesException('bar', 1, 2, 3)
180 except Exception as e:
181 exc = e
182
183 tblib.pickling_support.install(exc)
184 exc = pickle.loads(pickle.dumps(exc))
185
186 assert isinstance(exc, CustomWithAttributesException)
187 assert exc.args == ('bar',)
188 assert exc.values12 == (1, 2)
189 assert exc.value3 == 3
190 assert exc.__traceback__ is not None
191
192
193 class CustomOSError(OSError):
194 def __init__(self, message, errno, strerror: str, filename, none: None, filename2):
195 super().__init__(errno, strerror, filename, none, filename2)
196 self.message = message
197
198
199 def test_custom_oserror():
200 try:
201 raise CustomOSError('bar', 2, 'err', 3, None, 5)
202 except Exception as e:
203 exc = e
204
205 tblib.pickling_support.install(exc)
206 exc = pickle.loads(pickle.dumps(exc))
207
208 assert isinstance(exc, CustomOSError)
209 assert exc.message == 'bar'
210 assert exc.errno == 2
211 assert exc.strerror == 'err'
212 assert exc.filename == 3
213 assert exc.filename2 == 5
214 assert exc.__traceback__ is not None
215
216
217 def test_oserror():
218 try:
219 raise OSError(2, 'err', 3, None, 5)
220 except Exception as e:
221 exc = e
222
223 tblib.pickling_support.install(exc)
224 exc = pickle.loads(pickle.dumps(exc))
225
226 assert isinstance(exc, OSError)
227 assert exc.errno == 2
228 assert exc.strerror == 'err'
229 assert exc.filename == 3
230 assert exc.filename2 == 5
231 assert exc.__traceback__ is not None
232
233
234 class OpenError(Exception):
235 pass
236
237
238 def bad_open():
239 try:
240 raise PermissionError(13, 'Booboo', 'filename', None, None)
241 except Exception as e:
242 raise OpenError(e) from e
243
244
245 def test_permissionerror():
246 try:
247 bad_open()
248 except Exception as e:
249 exc = e
250
251 tblib.pickling_support.install(exc)
252 exc = pickle.loads(pickle.dumps(exc))
253
254 assert isinstance(exc, OpenError)
255 assert exc.__traceback__ is not None
256 assert repr(exc) == "OpenError(PermissionError(13, 'Booboo'))"
257 assert str(exc) == "[Errno 13] Booboo: 'filename'"
258 assert exc.args[0].errno == 13
259 assert exc.args[0].strerror == 'Booboo'
260 assert exc.args[0].filename == 'filename'
261
262
263 class BadError(Exception):
264 def __init__(self):
265 super().__init__('Bad Bad Bad!')
266
267
268 def test_baderror():
269 try:
270 raise BadError
271 except Exception as e:
272 exc = e
273
274 tblib.pickling_support.install(exc)
275 exc = pickle.loads(pickle.dumps(exc))
276
277 assert isinstance(exc, BadError)
278 assert exc.args == ('Bad Bad Bad!',)
279 assert exc.__traceback__ is not None
280
281
282 class BadError2(Exception):
283 def __init__(self, stuff):
284 super().__init__()
285 self.stuff = stuff
286
287
288 def test_baderror2():
289 try:
290 raise BadError2('123')
291 except Exception as e:
292 exc = e
293
294 tblib.pickling_support.install(exc)
295 exc = pickle.loads(pickle.dumps(exc))
296
297 assert isinstance(exc, BadError2)
298 assert exc.args == ()
299 assert exc.stuff == '123'
300 assert exc.__traceback__ is not None
301
302
303 class CustomReduceException(Exception):
304 def __init__(self, message, arg1, arg2, arg3):
305 super().__init__(message)
306 self.values12 = (arg1, arg2)
307 self.value3 = arg3
308
309 def __reduce__(self):
310 return self.__class__, self.args + self.values12 + (self.value3,)
311
312
313 def test_custom_reduce():
314 try:
315 raise CustomReduceException('foo', 1, 2, 3)
316 except Exception as e:
317 exc = e
318
319 tblib.pickling_support.install(exc)
320 exc = pickle.loads(pickle.dumps(exc))
321
322 assert isinstance(exc, CustomReduceException)
323 assert exc.args == ('foo',)
324 assert exc.values12 == (1, 2)
325 assert exc.value3 == 3
326 assert exc.__traceback__ is not None
327
328
329 class CustomReduceExException(Exception):
330 def __init__(self, message, arg1, arg2, protocol):
331 super().__init__(message)
332 self.values12 = (arg1, arg2)
333 self.value3 = protocol
334
335 def __reduce_ex__(self, protocol):
336 return self.__class__, self.args + self.values12 + (self.value3,)
337
338
339 @pytest.mark.parametrize('protocol', [None, *list(range(1, pickle.HIGHEST_PROTOCOL + 1))])
340 def test_custom_reduce_ex(protocol):
341 try:
342 raise CustomReduceExException('foo', 1, 2, 3)
343 except Exception as e:
344 exc = e
345
346 tblib.pickling_support.install(exc)
347 exc = pickle.loads(pickle.dumps(exc, protocol=protocol))
348
349 assert isinstance(exc, CustomReduceExException)
350 assert exc.args == ('foo',)
351 assert exc.values12 == (1, 2)
352 assert exc.value3 == 3
353 assert exc.__traceback__ is not None
354
355
356 def test_oserror_simple():
357 try:
358 raise OSError(13, 'Permission denied')
359 except Exception as e:
360 exc = e
361
362 tblib.pickling_support.install(exc)
363 exc = pickle.loads(pickle.dumps(exc))
364
365 assert isinstance(exc, OSError)
366 assert exc.args == (13, 'Permission denied')
367 assert exc.errno == 13
368 assert exc.strerror == 'Permission denied'
369 assert exc.__traceback__ is not None
370
371
372 def test_real_oserror():
373 try:
374 os.open('non-existing-file', os.O_RDONLY)
375 except Exception as e:
376 exc = e
377 else:
378 pytest.fail('os.open should have raised an OSError')
379
380 str_output = str(exc)
381 tblib.pickling_support.install(exc)
382 exc = pickle.loads(pickle.dumps(exc))
383
384 assert isinstance(exc, OSError)
385 assert exc.errno == 2
386 assert str_output == str(exc)
387
388
389 def test_timeouterror():
390 try:
391 raise TimeoutError('stuff')
392 except Exception as e:
393 exc = e
394 else:
395 pytest.fail('os.open should have raised an TimeoutError')
396
397 str_output = str(exc)
398 tblib.pickling_support.install(exc)
399 exc = pickle.loads(pickle.dumps(exc))
400
401 assert isinstance(exc, TimeoutError)
402 assert exc.errno is None
403 assert str_output == str(exc)
404
405
406 @pytest.mark.skipif(not has_python311, reason='ExceptionGroup needs Python 3.11')
407 def test_exception_group():
408 errors = []
409 try:
410 e = CustomWithAttributesException('bar', 1, 2, 3)
411 e.add_note('test_custom_with_attributes')
412 raise e
413 except Exception as e:
414 errors.append(e)
415
416 try:
417 e = CustomOSError('bar', 2, 'err', 3, None, 5)
418 e.add_note('test_custom_oserror')
419 raise e
420 except Exception as e:
421 errors.append(e)
422
423 try:
424 e = OSError(2, 'err', 3, None, 5)
425 e.add_note('test_oserror')
426 raise e
427 except Exception as e:
428 errors.append(e)
429
430 try:
431 bad_open()
432 except Exception as e:
433 e.add_note('test_permissionerror')
434 errors.append(e)
435
436 try:
437 raise BadError
438 except Exception as e:
439 e.add_note('test_baderror')
440 errors.append(e)
441
442 try:
443 e = BadError2('123')
444 e.add_note('test_baderror2')
445 raise e
446 except Exception as e:
447 errors.append(e)
448
449 try:
450 e = CustomReduceException('foo', 1, 2, 3)
451 e.add_note('test_custom_reduce')
452 raise e
453 except Exception as e:
454 errors.append(e)
455
456 try:
457 e = OSError(13, 'Permission denied')
458 e.add_note('test_oserror_simple')
459 raise e
460 except Exception as e:
461 errors.append(e)
462
463 try:
464 os.open('non-existing-file', os.O_RDONLY)
465 except Exception as e:
466 e.add_note('test_real_oserror')
467 real_oserror_str = str(e)
468 errors.append(e)
469 else:
470 pytest.fail('os.open should have raised an OSError')
471
472 try:
473 raise ExceptionGroup('group error', errors) # noqa: F821
474 except Exception as e:
475 exc = e
476
477 assert len(exc.exceptions) == 9 # before pickling
478
479 tblib.pickling_support.install()
480 exc = pickle.loads(pickle.dumps(exc))
481
482 assert len(exc.exceptions) == 9 # after unpickling
483
484 assert exc.exceptions[0].__notes__ == ['test_custom_with_attributes']
485 assert isinstance(exc.exceptions[0], CustomWithAttributesException)
486 assert exc.exceptions[0].args == ('bar',)
487 assert exc.exceptions[0].values12 == (1, 2)
488 assert exc.exceptions[0].value3 == 3
489 assert exc.exceptions[0].__traceback__ is not None
490
491 assert exc.exceptions[1].__notes__ == ['test_custom_oserror']
492 assert isinstance(exc.exceptions[1], CustomOSError)
493 assert exc.exceptions[1].message == 'bar'
494 assert exc.exceptions[1].errno == 2
495 assert exc.exceptions[1].strerror == 'err'
496 assert exc.exceptions[1].filename == 3
497 assert exc.exceptions[1].filename2 == 5
498 assert exc.exceptions[1].__traceback__ is not None
499
500 assert exc.exceptions[2].__notes__ == ['test_oserror']
501 assert isinstance(exc.exceptions[2], OSError)
502 assert exc.exceptions[2].errno == 2
503 assert exc.exceptions[2].strerror == 'err'
504 assert exc.exceptions[2].filename == 3
505 assert exc.exceptions[2].filename2 == 5
506 assert exc.exceptions[2].__traceback__ is not None
507
508 assert exc.exceptions[3].__notes__ == ['test_permissionerror']
509 assert isinstance(exc.exceptions[3], OpenError)
510 assert exc.exceptions[3].__traceback__ is not None
511 assert repr(exc.exceptions[3]) == "OpenError(PermissionError(13, 'Booboo'))"
512 assert str(exc.exceptions[3]) == "[Errno 13] Booboo: 'filename'"
513 assert exc.exceptions[3].args[0].errno == 13
514 assert exc.exceptions[3].args[0].strerror == 'Booboo'
515 assert exc.exceptions[3].args[0].filename == 'filename'
516
517 assert exc.exceptions[4].__notes__ == ['test_baderror']
518 assert isinstance(exc.exceptions[4], BadError)
519 assert exc.exceptions[4].args == ('Bad Bad Bad!',)
520 assert exc.exceptions[4].__traceback__ is not None
521
522 assert exc.exceptions[5].__notes__ == ['test_baderror2']
523 assert isinstance(exc.exceptions[5], BadError2)
524 assert exc.exceptions[5].args == ()
525 assert exc.exceptions[5].stuff == '123'
526 assert exc.exceptions[5].__traceback__ is not None
527
528 assert exc.exceptions[6].__notes__ == ['test_custom_reduce']
529 assert isinstance(exc.exceptions[6], CustomReduceException)
530 assert exc.exceptions[6].args == ('foo',)
531 assert exc.exceptions[6].values12 == (1, 2)
532 assert exc.exceptions[6].value3 == 3
533 assert exc.exceptions[6].__traceback__ is not None
534
535 assert exc.exceptions[7].__notes__ == ['test_oserror_simple']
536 assert isinstance(exc.exceptions[7], OSError)
537 assert exc.exceptions[7].args == (13, 'Permission denied')
538 assert exc.exceptions[7].errno == 13
539 assert exc.exceptions[7].strerror == 'Permission denied'
540 assert exc.exceptions[7].__traceback__ is not None
541
542 assert exc.exceptions[8].__notes__ == ['test_real_oserror']
543 assert isinstance(exc.exceptions[8], OSError)
544 assert exc.exceptions[8].errno == 2
545 assert str(exc.exceptions[8]) == real_oserror_str