Skip to content

Commit

Permalink
Add AddFixedValue to_dict and from_dict (#88)
Browse files Browse the repository at this point in the history
Co-authored-by: Massimiliano Pippi <[email protected]>
  • Loading branch information
silvanocerza and masci authored Aug 18, 2023
1 parent f2e1aee commit db846c6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
13 changes: 10 additions & 3 deletions sample_components/add_value.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
# SPDX-FileCopyrightText: 2022-present deepset GmbH <[email protected]>
#
# 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):
Expand Down
23 changes: 21 additions & 2 deletions test/sample_components/test_add_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}

0 comments on commit db846c6

Please sign in to comment.