Skip to content
Open
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
58 changes: 40 additions & 18 deletions openfga_sdk/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,10 +550,18 @@ def __deserialize(self, data, klass):

if type(klass) is str:
if klass.startswith("list["):
if not isinstance(data, list):
raise FgaValidationException(
f"Invalid response type for `{klass}`: expected a list, got {type(data).__name__}"
)
Comment on lines +553 to +556
sub_kls = re.match(r"list\[(.*)\]", klass).group(1)
return [self.__deserialize(sub_data, sub_kls) for sub_data in data]

if klass.startswith("dict["):
if not isinstance(data, dict):
raise FgaValidationException(
f"Invalid response type for `{klass}`: expected a dict, got {type(data).__name__}"
)
sub_kls = re.match(r"dict\[([^,]*), (.*)\]", klass).group(2)
return {k: self.__deserialize(v, sub_kls) for k, v in data.items()}

Expand Down Expand Up @@ -858,19 +866,24 @@ def _apply_auth_params(self, headers, queries, auth_setting):
raise ApiValueError("Authentication token must be in `query` or `header`")

def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.

:param data: str.
:param klass: class literal.

:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return str(data)
except TypeError:
return data
"""Deserialize a JSON primitive without coercing it to another type."""
valid = False
if klass is bool:
valid = type(data) is bool
elif klass is int:
valid = type(data) is int
elif klass is float:
valid = type(data) is int or type(data) is float
elif klass is str:
valid = type(data) is str
elif klass is bytes:
valid = type(data) is bytes or type(data) is str

if not valid:
raise FgaValidationException(
f"Invalid response type: expected `{klass.__name__}`, got `{type(data).__name__}`"
)
return klass(data) if klass is not bytes or type(data) is bytes else data

def __deserialize_object(self, value):
"""Return an original value.
Expand All @@ -885,6 +898,10 @@ def __deserialize_date(self, string):
:param string: str.
:return: date.
"""
if not isinstance(string, str):
raise FgaValidationException(
f"Invalid response type: expected `str`, got `{type(string).__name__}`"
)
try:
return parse(string).date()
except ImportError:
Expand All @@ -902,6 +919,10 @@ def __deserialize_datetime(self, string):
:param string: str.
:return: datetime.
"""
if not isinstance(string, str):
raise FgaValidationException(
f"Invalid response type: expected `str`, got `{type(string).__name__}`"
)
try:
return parse(string)
except ImportError:
Expand Down Expand Up @@ -929,12 +950,13 @@ def __deserialize_model(self, data, klass):
if not klass.openapi_types and has_discriminator is False:
return data

if not isinstance(data, dict):
raise FgaValidationException(
f"Invalid response type for `{klass.__name__}`: expected a dict, got {type(data).__name__}"
)
Comment on lines +953 to +956

kwargs = {}
if (
data is not None
and klass.openapi_types is not None
and isinstance(data, list | dict)
):
if data is not None and klass.openapi_types is not None:
for attr, attr_type in klass.openapi_types.items():
if klass.attribute_map[attr] in data:
value = data[klass.attribute_map[attr]]
Expand Down
58 changes: 40 additions & 18 deletions openfga_sdk/sync/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,10 +543,18 @@ def __deserialize(self, data, klass):

if type(klass) is str:
if klass.startswith("list["):
if not isinstance(data, list):
raise FgaValidationException(
f"Invalid response type for `{klass}`: expected a list, got {type(data).__name__}"
)
sub_kls = re.match(r"list\[(.*)\]", klass).group(1)
return [self.__deserialize(sub_data, sub_kls) for sub_data in data]

if klass.startswith("dict["):
if not isinstance(data, dict):
raise FgaValidationException(
f"Invalid response type for `{klass}`: expected a dict, got {type(data).__name__}"
)
sub_kls = re.match(r"dict\[([^,]*), (.*)\]", klass).group(2)
return {k: self.__deserialize(v, sub_kls) for k, v in data.items()}

Expand Down Expand Up @@ -851,19 +859,24 @@ def _apply_auth_params(self, headers, queries, auth_setting):
raise ApiValueError("Authentication token must be in `query` or `header`")

def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.

:param data: str.
:param klass: class literal.

:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return str(data)
except TypeError:
return data
"""Deserialize a JSON primitive without coercing it to another type."""
valid = False
if klass is bool:
valid = type(data) is bool
elif klass is int:
valid = type(data) is int
elif klass is float:
valid = type(data) is int or type(data) is float
elif klass is str:
valid = type(data) is str
elif klass is bytes:
valid = type(data) is bytes or type(data) is str

if not valid:
raise FgaValidationException(
f"Invalid response type: expected `{klass.__name__}`, got `{type(data).__name__}`"
)
return klass(data) if klass is not bytes or type(data) is bytes else data

def __deserialize_object(self, value):
"""Return an original value.
Expand All @@ -878,6 +891,10 @@ def __deserialize_date(self, string):
:param string: str.
:return: date.
"""
if not isinstance(string, str):
raise FgaValidationException(
f"Invalid response type: expected `str`, got `{type(string).__name__}`"
)
try:
return parse(string).date()
except ImportError:
Expand All @@ -895,6 +912,10 @@ def __deserialize_datetime(self, string):
:param string: str.
:return: datetime.
"""
if not isinstance(string, str):
raise FgaValidationException(
f"Invalid response type: expected `str`, got `{type(string).__name__}`"
)
try:
return parse(string)
except ImportError:
Expand Down Expand Up @@ -922,12 +943,13 @@ def __deserialize_model(self, data, klass):
if not klass.openapi_types and has_discriminator is False:
return data

if not isinstance(data, dict):
raise FgaValidationException(
f"Invalid response type for `{klass.__name__}`: expected a dict, got {type(data).__name__}"
)

kwargs = {}
if (
data is not None
and klass.openapi_types is not None
and isinstance(data, list | dict)
):
if data is not None and klass.openapi_types is not None:
for attr, attr_type in klass.openapi_types.items():
if klass.attribute_map[attr] in data:
value = data[klass.attribute_map[attr]]
Expand Down
48 changes: 48 additions & 0 deletions test/deserialization_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from unittest.mock import MagicMock

import pytest

from openfga_sdk.api_client import ApiClient
from openfga_sdk.configuration import Configuration
from openfga_sdk.exceptions import FgaValidationException
from openfga_sdk.rest import RESTResponse


def rest_response(data: bytes) -> RESTResponse:
response = MagicMock()
response.status = 200
response.reason = "OK"
return RESTResponse(response=response, data=data)


@pytest.mark.asyncio
@pytest.mark.parametrize(
"body,response_type",
[
pytest.param(b'{"allowed": "false"}', "CheckResponse", id="bool-as-string"),
pytest.param(b'{"allowed": 1}', "CheckResponse", id="bool-as-number"),
pytest.param(b"not json", "CheckResponse", id="non-json-object"),
pytest.param(
b'{"objects": "doc:1"}', "ListObjectsResponse", id="list-as-string"
),
pytest.param(b'{"objects": [1]}', "ListObjectsResponse", id="string-as-number"),
],
)
async def test_async_response_wrong_types_raise_validation_error(body, response_type):
async with ApiClient(Configuration(api_url="http://example.com")) as client:
with pytest.raises(FgaValidationException):
client.deserialize(rest_response(body), response_type)


@pytest.mark.asyncio
async def test_async_response_correct_types_still_deserialize():
async with ApiClient(Configuration(api_url="http://example.com")) as client:
check = client.deserialize(
rest_response(b'{"allowed": false}'), "CheckResponse"
)
objects = client.deserialize(
rest_response(b'{"objects": ["doc:1"]}'), "ListObjectsResponse"
)

assert check.allowed is False
assert objects.objects == ["doc:1"]
46 changes: 46 additions & 0 deletions test/sync/deserialization_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from unittest.mock import MagicMock

import pytest

from openfga_sdk.configuration import Configuration
from openfga_sdk.exceptions import FgaValidationException
from openfga_sdk.sync.api_client import ApiClient
from openfga_sdk.sync.rest import RESTResponse


def rest_response(data: bytes) -> RESTResponse:
response = MagicMock()
response.status = 200
response.reason = "OK"
return RESTResponse(response=response, data=data)


@pytest.mark.parametrize(
"body,response_type",
[
pytest.param(b'{"allowed": "false"}', "CheckResponse", id="bool-as-string"),
pytest.param(b'{"allowed": 1}', "CheckResponse", id="bool-as-number"),
pytest.param(b"not json", "CheckResponse", id="non-json-object"),
pytest.param(
b'{"objects": "doc:1"}', "ListObjectsResponse", id="list-as-string"
),
pytest.param(b'{"objects": [1]}', "ListObjectsResponse", id="string-as-number"),
],
)
def test_sync_response_wrong_types_raise_validation_error(body, response_type):
with ApiClient(Configuration(api_url="http://example.com")) as client:
with pytest.raises(FgaValidationException):
client.deserialize(rest_response(body), response_type)


def test_sync_response_correct_types_still_deserialize():
with ApiClient(Configuration(api_url="http://example.com")) as client:
check = client.deserialize(
rest_response(b'{"allowed": false}'), "CheckResponse"
)
objects = client.deserialize(
rest_response(b'{"objects": ["doc:1"]}'), "ListObjectsResponse"
)

assert check.allowed is False
assert objects.objects == ["doc:1"]