|
| 1 | +import pickle |
| 2 | +from pathlib import Path |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from cattrs._compat import ExceptionGroup |
| 8 | +from cattrs.errors import ( |
| 9 | + BaseValidationError, |
| 10 | + ClassValidationError, |
| 11 | + ForbiddenExtraKeysError, |
| 12 | + IterableValidationError, |
| 13 | + StructureHandlerNotFoundError, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +@pytest.mark.parametrize( |
| 18 | + "err_cls, err_args", |
| 19 | + [ |
| 20 | + (StructureHandlerNotFoundError, ("Structure Message", int)), |
| 21 | + (ForbiddenExtraKeysError, ("Forbidden Message", int, {"foo", "bar"})), |
| 22 | + (ForbiddenExtraKeysError, ("", str, {"foo", "bar"})), |
| 23 | + (ForbiddenExtraKeysError, (None, list, {"foo", "bar"})), |
| 24 | + ( |
| 25 | + BaseValidationError, |
| 26 | + ("BaseValidation Message", [ValueError("Test BaseValidation")], int), |
| 27 | + ), |
| 28 | + ( |
| 29 | + IterableValidationError, |
| 30 | + ("IterableValidation Msg", [ValueError("Test IterableValidation")], int), |
| 31 | + ), |
| 32 | + ( |
| 33 | + ClassValidationError, |
| 34 | + ("ClassValidation Message", [ValueError("Test ClassValidation")], int), |
| 35 | + ), |
| 36 | + ], |
| 37 | +) |
| 38 | +def test_errors_pickling( |
| 39 | + err_cls: type[Exception], err_args: tuple[Any, ...], tmp_path: Path |
| 40 | +) -> None: |
| 41 | + """Test if a round of pickling and unpickling works for errors.""" |
| 42 | + before = err_cls(*err_args) |
| 43 | + |
| 44 | + assert before.args == err_args |
| 45 | + |
| 46 | + with (tmp_path / (err_cls.__name__.lower() + ".pypickle")).open("wb") as f: |
| 47 | + pickle.dump(before, f) |
| 48 | + |
| 49 | + with (tmp_path / (err_cls.__name__.lower() + ".pypickle")).open("rb") as f: |
| 50 | + after = pickle.load(f) # noqa: S301 |
| 51 | + |
| 52 | + assert isinstance(after, err_cls) |
| 53 | + assert str(after) == str(before) |
| 54 | + if issubclass(err_cls, ExceptionGroup): |
| 55 | + assert after.message == before.message |
| 56 | + assert after.args[0] == before.args[0] |
| 57 | + |
| 58 | + # We need to do the exceptions within the group (i.e. args[1]) |
| 59 | + # separately, as on unpickling new objects are created and hence |
| 60 | + # they will never be equal to the original ones. |
| 61 | + for after_exc, before_exc in zip(after.exceptions, before.exceptions): |
| 62 | + assert str(after_exc) == str(before_exc) |
| 63 | + |
| 64 | + # The problem with args[1] might be also for other parameters, but |
| 65 | + # we ignore this here and if needed then we need a separate test |
| 66 | + assert after.args[2:] == before.args[2:] |
| 67 | + |
| 68 | + else: |
| 69 | + assert after.args == err_args |
| 70 | + assert after.args == before.args |
| 71 | + |
| 72 | + assert after.__cause__ == before.__cause__ |
| 73 | + assert after.__context__ == before.__context__ |
| 74 | + assert after.__traceback__ == before.__traceback__ |
0 commit comments