|
| 1 | +from types import MappingProxyType |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from hyperbrowser.client.managers.serialization_utils import ( |
| 6 | + serialize_model_dump_to_dict, |
| 7 | +) |
| 8 | +from hyperbrowser.exceptions import HyperbrowserError |
| 9 | + |
| 10 | + |
| 11 | +class _ModelWithPayload: |
| 12 | + def __init__(self, payload): |
| 13 | + self.payload = payload |
| 14 | + self.calls = [] |
| 15 | + |
| 16 | + def model_dump(self, *, exclude_none, by_alias): |
| 17 | + self.calls.append((exclude_none, by_alias)) |
| 18 | + return self.payload |
| 19 | + |
| 20 | + |
| 21 | +class _ModelWithRuntimeError: |
| 22 | + def model_dump(self, *, exclude_none, by_alias): |
| 23 | + _ = exclude_none |
| 24 | + _ = by_alias |
| 25 | + raise RuntimeError("broken model_dump") |
| 26 | + |
| 27 | + |
| 28 | +class _ModelWithHyperbrowserError: |
| 29 | + def model_dump(self, *, exclude_none, by_alias): |
| 30 | + _ = exclude_none |
| 31 | + _ = by_alias |
| 32 | + raise HyperbrowserError("custom failure") |
| 33 | + |
| 34 | + |
| 35 | +def test_serialize_model_dump_to_dict_returns_payload_and_forwards_flags(): |
| 36 | + model = _ModelWithPayload({"value": 1}) |
| 37 | + |
| 38 | + payload = serialize_model_dump_to_dict( |
| 39 | + model, |
| 40 | + error_message="serialize failure", |
| 41 | + exclude_none=False, |
| 42 | + by_alias=False, |
| 43 | + ) |
| 44 | + |
| 45 | + assert payload == {"value": 1} |
| 46 | + assert model.calls == [(False, False)] |
| 47 | + |
| 48 | + |
| 49 | +def test_serialize_model_dump_to_dict_wraps_runtime_errors(): |
| 50 | + with pytest.raises(HyperbrowserError, match="serialize failure") as exc_info: |
| 51 | + serialize_model_dump_to_dict( |
| 52 | + _ModelWithRuntimeError(), |
| 53 | + error_message="serialize failure", |
| 54 | + ) |
| 55 | + |
| 56 | + assert isinstance(exc_info.value.original_error, RuntimeError) |
| 57 | + |
| 58 | + |
| 59 | +def test_serialize_model_dump_to_dict_preserves_hyperbrowser_errors(): |
| 60 | + with pytest.raises(HyperbrowserError, match="custom failure") as exc_info: |
| 61 | + serialize_model_dump_to_dict( |
| 62 | + _ModelWithHyperbrowserError(), |
| 63 | + error_message="serialize failure", |
| 64 | + ) |
| 65 | + |
| 66 | + assert exc_info.value.original_error is None |
| 67 | + |
| 68 | + |
| 69 | +def test_serialize_model_dump_to_dict_rejects_non_dict_payloads(): |
| 70 | + with pytest.raises(HyperbrowserError, match="serialize failure") as exc_info: |
| 71 | + serialize_model_dump_to_dict( |
| 72 | + _ModelWithPayload(MappingProxyType({"value": 1})), |
| 73 | + error_message="serialize failure", |
| 74 | + ) |
| 75 | + |
| 76 | + assert exc_info.value.original_error is None |
0 commit comments