Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: deserialize ignores new fields #12

Merged
merged 3 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion openaq/shared/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,13 @@ def load(cls, data: Mapping) -> _ResponseBase:
Returns:
Deserialized representation of the response data as a Python object.
"""
return cls(**cls._deserialize(data))
deserialized_data = cls._deserialize(data)

# Filter out fields that are not in the class annotations
expected_fields = {
k: v for k, v in deserialized_data.items() if k in cls.__annotations__
}
return cls(**expected_fields)

def dict(self) -> Dict:
"""Serializes response data to Python dictionary.
Expand Down
25 changes: 25 additions & 0 deletions tests/test_shared_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,28 @@ def test_responses_json(name: str, response_class: _ResponseBase):
assert json.loads(response) == json.loads(
response_class.load(json.loads(response)).json()
)


@pytest.mark.parametrize(
"extra_field,response_class",
[
('{"anotherField": null}', LocationsResponse),
],
)
def test_response_ignores_unexpected_fields(
extra_field: str, response_class: _ResponseBase
):
"""Tests that the response model ignores unexpected fields."""
base_response = read_response_file('locations')
base_json = json.loads(base_response)

modified_json = json.loads(extra_field)
base_json['results'][0].update(modified_json)

try:
response_instance = response_class.load(base_json)
assert not hasattr(
response_instance.results[0], 'anotherField'
), "Unexpected 'anotherField' was not ignored"
except Exception as e:
pytest.fail(f"Deserialization failed with unexpected field 'anotherField': {e}")
Loading