Skip to content

Commit

Permalink
feat(converters)!: Implement converter for single-attribute objects (…
Browse files Browse the repository at this point in the history
…#11)
  • Loading branch information
c0r0n3r committed Sep 3, 2023
1 parent fef67df commit 70150b6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
25 changes: 25 additions & 0 deletions cryptodatahub/common/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,31 @@ def convert_dict_to_object(object_type):
return _DictObjectConverter(object_type)


@attr.s(repr=False, slots=True, hash=True)
class _ValueToObjectConverter(_ConverterBase):
object_type = attr.ib(validator=attr.validators.instance_of(type))
value_converter = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(_ConverterBase)))

def __call__(self, value):
if value is None:
return None

if isinstance(value, self.object_type):
return value

if self.value_converter is not None:
value = self.value_converter(value)

return self.object_type(value)

def __repr__(self):
return '<value to object converter>'


def convert_value_to_object(object_type, value_converter=None):
return _ValueToObjectConverter(object_type, value_converter)


@attr.s(repr=False, slots=True, hash=True)
class _EnumConverter(_ConverterBase):
enum_type = attr.ib(validator=attr.validators.instance_of(type))
Expand Down
20 changes: 20 additions & 0 deletions test/common/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
convert_mapping,
convert_url,
convert_variadic,
convert_value_to_object,
)


Expand Down Expand Up @@ -194,6 +195,25 @@ def test_repr(self):
self.assertEqual(repr(convert_dict_to_object(str)), '<dict to object converter>')


class TestValueToObjectConverter(unittest.TestCase):
def test_none(self):
converted_value = convert_value_to_object(TestJsonObjectComplex)(None)
self.assertEqual(converted_value, None)

def test_convert_object_class(self):
original_value = TestJsonObjectComplex('value')
converted_value = convert_value_to_object(TestJsonObjectComplex)(original_value)
self.assertEqual(original_value, converted_value)

def test_convert_converter(self):
original_value = '1970-01-01'
converted_value = convert_value_to_object(TestJsonObjectComplex, convert_datetime())(original_value)
self.assertEqual(converted_value.attr, datetime.datetime(1970, 1, 1, 0, 0))

def test_repr(self):
self.assertEqual(repr(convert_value_to_object(str)), '<value to object converter>')


class TestBigNumberConverter(unittest.TestCase):
def test_error_invalid_type(self):
original_value = 1234
Expand Down

0 comments on commit 70150b6

Please sign in to comment.