Skip to content
Open
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
41 changes: 17 additions & 24 deletions pulsar/schema/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,30 +75,8 @@ def __init__(self, default=None, required_default=False, required=False, *args,

for k, value in self._fields.items():
if k in kwargs:
if isinstance(value, Record) and isinstance(kwargs[k], dict):
# Use dict init Record object
copied = copy.copy(value)
copied.__init__(**kwargs[k])
self.__setattr__(k, copied)
elif isinstance(value, Array) and isinstance(kwargs[k], list) and len(kwargs[k]) > 0 \
and isinstance(value.array_type, Record) and isinstance(kwargs[k][0], dict):
arr = []
for item in kwargs[k]:
copied = copy.copy(value.array_type)
copied.__init__(**item)
arr.append(copied)
self.__setattr__(k, arr)
elif isinstance(value, Map) and isinstance(kwargs[k], dict) and len(kwargs[k]) > 0 \
and isinstance(value.value_type, Record) and isinstance(list(kwargs[k].values())[0], dict):
dic = {}
for mapKey, mapValue in kwargs[k].items():
copied = copy.copy(value.value_type)
copied.__init__(**mapValue)
dic[mapKey] = copied
self.__setattr__(k, dic)
else:
# Value was overridden at constructor
self.__setattr__(k, kwargs[k])
# Value was overridden at constructor
self.__setattr__(k, _hydrate_field(value, kwargs[k]))
elif isinstance(value, Record):
# Value is a subrecord
self.__setattr__(k, value)
Expand Down Expand Up @@ -523,6 +501,21 @@ def default(self):
return None


def _hydrate_field(field, value):
# Rebuild Record instances from dicts produced by JSON/Avro decode,
# including nested Array and Map fields.
if isinstance(field, Record) and isinstance(value, dict):
copied = copy.copy(field)
copied.__init__(**value)
return copied
if isinstance(field, Array) and isinstance(value, list):
return [_hydrate_field(field.array_type, item) for item in value]
if isinstance(field, Map) and isinstance(value, dict):
return {map_key: _hydrate_field(field.value_type, map_value)
for map_key, map_value in value.items()}
return value


# Python3 has no `unicode` type, so here we use a tricky way to check if the type of `x` is `unicode` in Python2
# and also make it work well with Python3.
def is_unicode(x):
Expand Down
48 changes: 48 additions & 0 deletions tests/schema_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,54 @@ class Example(Record):
self.assertEqual(r2.__class__.__name__, 'Example')
self.assertEqual(r2, r)

def test_serialize_json_nested_array_of_records(self):
# Expected values come from issue 172: JsonSchema.decode of
# Array(Array(Record)) should rebuild the inner dict as a Record,
# so nested_objects.a is readable. One-level Array(Record) already
# worked; deeper nesting previously left dicts in place.
class A(Record):
a = String()

class B(Record):
b = Array(Array(A()))

s = JsonSchema(B)
decoded = s.decode('{"b": [[{"a": "hello world"}]]}')
self.assertIsInstance(decoded.b[0][0], A)
self.assertEqual(decoded.b[0][0].a, 'hello world')

original = B(b=[[A(a='hello world')]])
roundtrip = s.decode(s.encode(original))
self.assertEqual(roundtrip, original)
self.assertIsInstance(roundtrip.b[0][0], A)

def test_serialize_json_nested_map_of_records(self):
# Same Record.__init__ hydration path as issue 172, for nested
# Map/Array combinations of Record that were also left as dicts.
class A(Record):
a = String()

class MapMap(Record):
values = Map(Map(A()))

class ArrayMap(Record):
values = Array(Map(A()))

class MapArray(Record):
values = Map(Array(A()))

decoded = JsonSchema(MapMap).decode('{"values": {"k": {"n": {"a": "hello"}}}}')
self.assertIsInstance(decoded.values['k']['n'], A)
self.assertEqual(decoded.values['k']['n'].a, 'hello')

decoded = JsonSchema(ArrayMap).decode('{"values": [{"n": {"a": "hello"}}]}')
self.assertIsInstance(decoded.values[0]['n'], A)
self.assertEqual(decoded.values[0]['n'].a, 'hello')

decoded = JsonSchema(MapArray).decode('{"values": {"k": [{"a": "hello"}]}}')
self.assertIsInstance(decoded.values['k'][0], A)
self.assertEqual(decoded.values['k'][0].a, 'hello')

def test_serialize_avro(self):
class Example(Record):
a = Integer()
Expand Down