From db846c6ba308330466481ebfe20500c83c7c0a9d Mon Sep 17 00:00:00 2001 From: Silvano Cerza <3314350+silvanocerza@users.noreply.github.com> Date: Fri, 18 Aug 2023 16:24:40 +0200 Subject: [PATCH] Add AddFixedValue to_dict and from_dict (#88) Co-authored-by: Massimiliano Pippi --- sample_components/add_value.py | 13 ++++++++++--- test/sample_components/test_add_value.py | 23 +++++++++++++++++++++-- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/sample_components/add_value.py b/sample_components/add_value.py index 3db9d866f9..59819f470f 100644 --- a/sample_components/add_value.py +++ b/sample_components/add_value.py @@ -1,20 +1,27 @@ # SPDX-FileCopyrightText: 2022-present deepset GmbH # # SPDX-License-Identifier: Apache-2.0 -from typing import Optional +from typing import Optional, Dict, Any from canals import component +from canals.serialization import default_to_dict, default_from_dict @component -class AddFixedValue: # pylint: disable=too-few-public-methods +class AddFixedValue: """ Adds two values together. """ def __init__(self, add: int = 1): self.add = add - self.init_parameters = {"add": add} + + def to_dict(self) -> Dict[str, Any]: # pylint: disable=missing-function-docstring + return default_to_dict(self, add=self.add) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AddFixedValue": # pylint: disable=missing-function-docstring + return default_from_dict(cls, data) @component.output_types(result=int) def run(self, value: int, add: Optional[int] = None): diff --git a/test/sample_components/test_add_value.py b/test/sample_components/test_add_value.py index 04557a21f8..08b5b39e54 100644 --- a/test/sample_components/test_add_value.py +++ b/test/sample_components/test_add_value.py @@ -12,8 +12,27 @@ def test_saveload_default(self, tmp_path): def test_saveload_add(self, tmp_path): self.assert_can_be_saved_and_loaded_in_pipeline(AddFixedValue(add=2), tmp_path) - def test_addvalue(self): + def test_to_dict(self): + component = AddFixedValue() + res = component.to_dict() + assert res == {"hash": id(component), "type": "AddFixedValue", "init_parameters": {"add": 1}} + + def test_to_dict_with_custom_add_value(self): + component = AddFixedValue(add=100) + res = component.to_dict() + assert res == {"hash": id(component), "type": "AddFixedValue", "init_parameters": {"add": 100}} + + def test_from_dict(self): + data = {"hash": 1234, "type": "AddFixedValue"} + component = AddFixedValue.from_dict(data) + assert component.add == 1 + + def test_from_dict_with_custom_add_value(self): + data = {"hash": 1234, "type": "AddFixedValue", "init_parameters": {"add": 100}} + component = AddFixedValue.from_dict(data) + assert component.add == 100 + + def test_run(self): component = AddFixedValue() results = component.run(value=50, add=10) assert results == {"result": 60} - assert component.init_parameters == {"add": 1}