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

Sync sources for changes in https://github.com/microsoft/kiota-serialization-json-python/pull/369 #345

Merged
merged 1 commit into from
Oct 8, 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
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def write_uuid_value(self, key: Optional[str], value: Optional[UUID]) -> None:
"""Writes the specified uuid value to the stream with an optional given key.
Args:
key (Optional[str]): The key to be used for the written value. May be null.
value (Optional[UUId]): The uuid value to be written.
value (Optional[UUID]): The uuid value to be written.
"""
if isinstance(value, UUID):
if key:
Expand All @@ -107,9 +107,9 @@ def write_datetime_value(self, key: Optional[str], value: Optional[datetime]) ->
"""
if isinstance(value, datetime):
if key:
self.writer[key] = str(value.isoformat())
self.writer[key] = value.isoformat()
else:
self.value = str(value.isoformat())
self.value = value.isoformat()
elif isinstance(value, str):
try:
pendulum.parse(value)
Expand Down Expand Up @@ -239,7 +239,7 @@ def write_collection_of_enum_values(
"""Writes the specified collection of enum values to the stream with an optional given key.
Args:
key (Optional[str]): The key to be used for the written value. May be null.
values Optional[List[Enum]): The enum values to be written.
values (Optional[List[Enum]]): The enum values to be written.
"""
if isinstance(values, list):
result = []
Expand Down Expand Up @@ -360,7 +360,7 @@ def __write_dict_value(self, key: Optional[str], value: Dict[str, Any]) -> None:
def write_additional_data_value(self, value: Dict[str, Any]) -> None:
"""Writes the specified additional data to the stream.
Args:
value (Dict[str, Any]): he additional data to be written.
value (Dict[str, Any]): The additional data to be written.
"""
if isinstance(value, dict):
for key, val in value.items():
Expand Down Expand Up @@ -390,35 +390,35 @@ def get_serialized_content(self) -> bytes:
def on_before_object_serialization(self) -> Optional[Callable[[Parsable], None]]:
"""Gets the callback called before the object gets serialized.
Returns:
Optional[Callable[[Parsable], None]]:the callback called before the object
Optional[Callable[[Parsable], None]]: The callback called before the object
gets serialized.
"""
return self._on_before_object_serialization

@on_before_object_serialization.setter
def on_before_object_serialization(self, value: Optional[Callable[[Parsable], None]]) -> None:
"""Sets the callback called before the objects gets serialized.
"""Sets the callback called before the objects get serialized.
Args:
value (Optional[Callable[[Parsable], None]]): the callback called before the objects
gets serialized.
value (Optional[Callable[[Parsable], None]]): The callback called before the objects
get serialized.
"""
self._on_before_object_serialization = value

@property
def on_after_object_serialization(self) -> Optional[Callable[[Parsable], None]]:
"""Gets the callback called after the object gets serialized.
Returns:
Optional[Optional[Callable[[Parsable], None]]]: the callback called after the object
Optional[Optional[Callable[[Parsable], None]]]: The callback called after the object
gets serialized.
"""
return self._on_after_object_serialization

@on_after_object_serialization.setter
def on_after_object_serialization(self, value: Optional[Callable[[Parsable], None]]) -> None:
"""Sets the callback called after the objects gets serialized.
"""Sets the callback called after the objects get serialized.
Args:
value (Optional[Callable[[Parsable], None]]): the callback called after the objects
gets serialized.
value (Optional[Callable[[Parsable], None]]): The callback called after the objects
get serialized.
"""
self._on_after_object_serialization = value

Expand All @@ -428,7 +428,7 @@ def on_start_object_serialization(
) -> Optional[Callable[[Parsable, SerializationWriter], None]]:
"""Gets the callback called right after the serialization process starts.
Returns:
Optional[Callable[[Parsable, SerializationWriter], None]]: the callback called
Optional[Callable[[Parsable, SerializationWriter], None]]: The callback called
right after the serialization process starts.
"""
return self._on_start_object_serialization
Expand All @@ -439,7 +439,7 @@ def on_start_object_serialization(
) -> None:
"""Sets the callback called right after the serialization process starts.
Args:
value (Optional[Callable[[Parsable, SerializationWriter], None]]): the callback
value (Optional[Callable[[Parsable, SerializationWriter], None]]): The callback
called right after the serialization process starts.
"""
self._on_start_object_serialization = value
Expand All @@ -460,39 +460,44 @@ def write_any_value(self, key: Optional[str], value: Any) -> Any:
"""Writes the specified value to the stream with an optional given key.
Args:
key (Optional[str]): The key to be used for the written value. May be null.
value Any): The value to be written.
value (Any): The value to be written.
"""
value_type = type(value)
if value is None:
self.write_null_value(key)
elif value_type in PRIMITIVE_TYPES:
method = getattr(self, f'write_{value_type.__name__.lower()}_value')
method(key, value)
elif isinstance(value, Parsable):
self.write_object_value(key, value)
elif isinstance(value, list):
if all(isinstance(x, Parsable) for x in value):
self.write_collection_of_object_values(key, value)
elif all(isinstance(x, Enum) for x in value):
self.write_collection_of_enum_values(key, value)
elif all((type(x) in PRIMITIVE_TYPES) for x in value):
elif all(
any(isinstance(x, primitive_type) for primitive_type in PRIMITIVE_TYPES)
for x in value
):
self.write_collection_of_primitive_values(key, value)
elif all(isinstance(x, dict) for x in value):
self.__write_collection_of_dict_values(key, value)
else:
raise TypeError(
f"Encountered an unknown collection type during serialization \
{value_type} with key {key}"
f"Encountered an unknown collection type during serialization {type(value)}\
with key {key}"
)
elif isinstance(value, dict):
self.__write_dict_value(key, value)
elif hasattr(value, '__dict__'):
self.write_non_parsable_object_value(key, value)
else:
raise TypeError(
f"Encountered an unknown type during serialization {value_type} \
with key {key}"
)
for primitive_type in PRIMITIVE_TYPES:
if isinstance(value, primitive_type):
method = getattr(self, f"write_{primitive_type.__name__.lower()}_value")
method(key, value)
return
if hasattr(value, "__dict__"):
self.write_non_parsable_object_value(key, value)
else:
raise TypeError(
f"Encountered an unknown type during serialization {type(value)} with key {key}"
)

def _serialize_value(self, temp_writer: JsonSerializationWriter, value: U):
if on_before := self.on_before_object_serialization:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def test_get_root_parse_node(sample_json_string):
assert isinstance(root, JsonParseNode)
assert root._json_node == json.loads(sample_json_string)


def test_get_root_parse_node_no_content_type(sample_json_string):
with pytest.raises(Exception) as e_info:
factory = JsonParseNodeFactory()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,20 +72,23 @@ def test_write_uuid_value():
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"id": "8f841f30-e6e3-439a-a812-ebd369559c36"}'



def test_write_uuid_value_with_valid_string():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_uuid_value("id", "8f841f30-e6e3-439a-a812-ebd369559c36")
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"id": "8f841f30-e6e3-439a-a812-ebd369559c36"}'



def test_write_uuid_value_with_invalid_string():
with pytest.raises(ValueError) as excinfo:
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_uuid_value("id", "invalid-uuid-string")
assert "Invalid UUID string value found for property id" in str(excinfo.value)



def test_write_datetime_value():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_datetime_value(
Expand All @@ -94,53 +97,50 @@ def test_write_datetime_value():
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"updatedAt": "2022-01-27T12:59:45.596117+00:00"}'



def test_write_datetime_value_valid_string():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_datetime_value(
"updatedAt", "2022-01-27T12:59:45.596117"
)
json_serialization_writer.write_datetime_value("updatedAt", "2022-01-27T12:59:45.596117")
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"updatedAt": "2022-01-27T12:59:45.596117+00:00"}'



def test_write_datetime_value_valid_string():
with pytest.raises(ValueError) as excinfo:
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_datetime_value(
"updatedAt", "invalid-datetime-string"
)
json_serialization_writer.write_datetime_value("updatedAt", "invalid-datetime-string")
assert "Invalid datetime string value found for property updatedAt" in str(excinfo.value)


def test_write_timedelta_value():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_timedelta_value(
"diff",
(pendulum.parse('2022-01-27T12:59:45.596117') - pendulum.parse('2022-01-27T10:59:45.596117')).as_timedelta()
"diff", (
pendulum.parse('2022-01-27T12:59:45.596117') -
pendulum.parse('2022-01-27T10:59:45.596117')
).as_timedelta()
)
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"diff": "2:00:00"}'



def test_write_timedelta_value_valid_string():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_timedelta_value(
"diff",
"2:00:00"
)
json_serialization_writer.write_timedelta_value("diff", "2:00:00")
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"diff": "2:00:00"}'



def test_write_timedelta_value_invalid_string():
with pytest.raises(ValueError) as excinfo:
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_timedelta_value(
"diff",
"invalid-timedelta-string"
)
json_serialization_writer.write_timedelta_value("diff", "invalid-timedelta-string")
assert "Invalid timedelta string value found for property diff" in str(excinfo.value)


def test_write_date_value():
json_serialization_writer = JsonSerializationWriter()
Expand All @@ -149,19 +149,22 @@ def test_write_date_value():
content_string = content.decode('utf-8')
assert content_string == '{"birthday": "2000-09-04"}'


def test_write_date_value_valid_string():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_date_value("birthday", "2000-09-04")
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"birthday": "2000-09-04"}'



def test_write_date_value_invalid_string():
with pytest.raises(ValueError) as excinfo:
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_date_value("birthday", "invalid-date-string")
assert "Invalid date string value found for property birthday" in str(excinfo.value)


def test_write_time_value():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_time_value(
Expand All @@ -172,25 +175,22 @@ def test_write_time_value():
content_string = content.decode('utf-8')
assert content_string == '{"time": "12:59:45.596117"}'


def test_write_time_value_valid_string():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_time_value(
"time",
"12:59:45.596117"
)
json_serialization_writer.write_time_value("time", "12:59:45.596117")
content = json_serialization_writer.get_serialized_content()
content_string = content.decode('utf-8')
assert content_string == '{"time": "12:59:45.596117"}'



def test_write_time_value_invalid_string():
with pytest.raises(ValueError) as excinfo:
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_time_value(
"time",
"invalid-time-string"
)
json_serialization_writer.write_time_value("time", "invalid-time-string")
assert "Invalid time string value found for property time" in str(excinfo.value)


def test_write_collection_of_primitive_values():
json_serialization_writer = JsonSerializationWriter()
json_serialization_writer.write_collection_of_primitive_values(
Expand Down