From fad4205479354bf46c74794223900db6b3873c57 Mon Sep 17 00:00:00 2001 From: Andrew Omondi Date: Tue, 8 Oct 2024 18:22:05 +0300 Subject: [PATCH] sync sources. --- .../json_serialization_writer.py | 61 +++++++++-------- .../unit/test_json_parse_node_factory.py | 2 +- .../unit/test_json_serialization_writer.py | 68 +++++++++---------- 3 files changed, 68 insertions(+), 63 deletions(-) diff --git a/packages/serialization/json/kiota_serialization_json/json_serialization_writer.py b/packages/serialization/json/kiota_serialization_json/json_serialization_writer.py index 41f9f50c..330c6fa4 100644 --- a/packages/serialization/json/kiota_serialization_json/json_serialization_writer.py +++ b/packages/serialization/json/kiota_serialization_json/json_serialization_writer.py @@ -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: @@ -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) @@ -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 = [] @@ -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(): @@ -390,17 +390,17 @@ 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 @@ -408,17 +408,17 @@ def on_before_object_serialization(self, value: Optional[Callable[[Parsable], No 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 @@ -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 @@ -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 @@ -460,14 +460,11 @@ 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): @@ -475,24 +472,32 @@ def write_any_value(self, key: Optional[str], value: Any) -> Any: 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: diff --git a/packages/serialization/json/tests/unit/test_json_parse_node_factory.py b/packages/serialization/json/tests/unit/test_json_parse_node_factory.py index 174875a4..2975f37c 100644 --- a/packages/serialization/json/tests/unit/test_json_parse_node_factory.py +++ b/packages/serialization/json/tests/unit/test_json_parse_node_factory.py @@ -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() diff --git a/packages/serialization/json/tests/unit/test_json_serialization_writer.py b/packages/serialization/json/tests/unit/test_json_serialization_writer.py index 02ce3f6d..9f3fd4cf 100644 --- a/packages/serialization/json/tests/unit/test_json_serialization_writer.py +++ b/packages/serialization/json/tests/unit/test_json_serialization_writer.py @@ -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( @@ -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() @@ -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( @@ -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(