|
| 1 | +from typing import cast |
| 2 | + |
| 3 | +import pytest |
| 4 | +from pydantic import BaseModel |
| 5 | + |
| 6 | +from hyperbrowser.exceptions import HyperbrowserError |
| 7 | +from hyperbrowser.transport.base import APIResponse |
| 8 | + |
| 9 | + |
| 10 | +class _SampleResponseModel(BaseModel): |
| 11 | + name: str |
| 12 | + retries: int = 0 |
| 13 | + |
| 14 | + |
| 15 | +class _RaisesHyperbrowserModel: |
| 16 | + def __init__(self, **kwargs): |
| 17 | + _ = kwargs |
| 18 | + raise HyperbrowserError("model validation failed") |
| 19 | + |
| 20 | + |
| 21 | +def test_api_response_from_json_parses_model_data() -> None: |
| 22 | + response = APIResponse.from_json( |
| 23 | + {"name": "job-1", "retries": 2}, _SampleResponseModel |
| 24 | + ) |
| 25 | + |
| 26 | + assert isinstance(response.data, _SampleResponseModel) |
| 27 | + assert response.status_code == 200 |
| 28 | + assert response.data.name == "job-1" |
| 29 | + assert response.data.retries == 2 |
| 30 | + |
| 31 | + |
| 32 | +def test_api_response_from_json_rejects_non_mapping_inputs() -> None: |
| 33 | + with pytest.raises( |
| 34 | + HyperbrowserError, |
| 35 | + match=( |
| 36 | + "Failed to parse response data for _SampleResponseModel: " |
| 37 | + "expected a mapping but received list" |
| 38 | + ), |
| 39 | + ): |
| 40 | + APIResponse.from_json( |
| 41 | + cast("dict[str, object]", ["not-a-mapping"]), |
| 42 | + _SampleResponseModel, |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +def test_api_response_from_json_wraps_non_hyperbrowser_errors() -> None: |
| 47 | + with pytest.raises( |
| 48 | + HyperbrowserError, |
| 49 | + match="Failed to parse response data for _SampleResponseModel", |
| 50 | + ) as exc_info: |
| 51 | + APIResponse.from_json({"retries": 1}, _SampleResponseModel) |
| 52 | + |
| 53 | + assert exc_info.value.original_error is not None |
| 54 | + |
| 55 | + |
| 56 | +def test_api_response_from_json_preserves_hyperbrowser_errors() -> None: |
| 57 | + with pytest.raises(HyperbrowserError, match="model validation failed") as exc_info: |
| 58 | + APIResponse.from_json({}, _RaisesHyperbrowserModel) |
| 59 | + |
| 60 | + assert exc_info.value.original_error is None |
0 commit comments