Skip to content
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
14 changes: 11 additions & 3 deletions snap_http/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import json
from abc import ABC, abstractproperty
from dataclasses import dataclass
from dataclasses import dataclass, fields
from functools import cached_property
from io import BytesIO
from pathlib import Path
Expand Down Expand Up @@ -38,13 +38,21 @@ class SnapdResponse:
change: Union[str, None] = None
warning_timestamp: Union[str, None] = None
warning_count: Union[int, None] = None
suggested_currency: Union[str, None] = None

@classmethod
def from_http_response(
cls: Type["SnapdResponse"], response: Dict[str, Any]
) -> SnapdResponse:
return cls(**{k.replace("-", "_"): v for k, v in response.items()})

# In case snapd returns to us unknown fields in its response
cls_fields = {f.name for f in fields(cls)}
filtered_fields = {}

for k, v in response.items():
key = k.replace("-", "_")
if key in cls_fields:
filtered_fields[key] = v
return cls(**filtered_fields)

class AbstractRequestBody(ABC):
"""An abstract base class for the request body of a HTTP request."""
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,22 @@ def test_assertion_data_serialization():
body = types.AssertionData("assertion-header: value\n\nsignature")
assert body.content_type == "application/x.ubuntu.assertion"
assert body.serialized == b"assertion-header: value\n\nsignature"


def test_data_serialization_filter():
"""Test filtering of unknown response data fields."""
mock_response = {
"type": "async",
"status_code": 200,
"status": "Accepted",
"result": None,
"unknown": "bogus",
}

resp = types.SnapdResponse.from_http_response(mock_response)

assert not hasattr(resp, "unknown")
assert resp.type == "async"
assert resp.status_code == 200
assert resp.status == "Accepted"
assert resp.result is None