Skip to content

Serialize JSONObject in MappedObject #399

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

Merged
merged 4 commits into from
Apr 18, 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
4 changes: 3 additions & 1 deletion linode_api4/objects/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def dict(self):
result[k] = [
(
item.dict
if isinstance(item, cls)
if isinstance(item, (cls, JSONObject))
else (
self._flatten_base_subclass(item)
if isinstance(item, Base)
Expand All @@ -135,6 +135,8 @@ def dict(self):
]
elif isinstance(v, Base):
result[k] = self._flatten_base_subclass(v)
elif isinstance(v, JSONObject):
result[k] = v.dict

return result

Expand Down
24 changes: 22 additions & 2 deletions test/unit/objects/mapped_object_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from dataclasses import dataclass
from test.unit.base import ClientBaseCase

from linode_api4.objects import Base, MappedObject, Property
from linode_api4.objects import Base, JSONObject, MappedObject, Property


class MappedObjectCase(ClientBaseCase):
Expand All @@ -20,7 +21,7 @@ def test_mapped_object_dict(self):
mapped_obj = MappedObject(**test_dict)
self.assertEqual(mapped_obj.dict, test_dict)

def test_mapped_object_dict(self):
def test_serialize_base_objects(self):
test_property_name = "bar"
test_property_value = "bar"

Expand All @@ -42,3 +43,22 @@ class Foo(Base):

mapped_obj = MappedObject(foo=foo)
self.assertEqual(mapped_obj.dict, expected_dict)

def test_serialize_json_objects(self):
test_property_name = "bar"
test_property_value = "bar"

@dataclass
class Foo(JSONObject):
bar: str = ""

foo = Foo.from_json({test_property_name: test_property_value})

expected_dict = {
"foo": {
test_property_name: test_property_value,
}
}

mapped_obj = MappedObject(foo=foo)
self.assertEqual(mapped_obj.dict, expected_dict)