Skip to content

Commit

Permalink
[Python Client] Fixed reserved keys is not removed when encode (#15844)…
Browse files Browse the repository at this point in the history
… (#15947)
  • Loading branch information
boatrainlsz authored and merlimat committed Jun 7, 2022
1 parent 2cd29dc commit 6bf823e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
20 changes: 12 additions & 8 deletions pulsar-client-cpp/python/pulsar/schema/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ def __str__(self):
return 'StringSchema'


def remove_reserved_key(data):
if '_default' in data:
del data['_default']
if '_required' in data:
del data['_required']
if '_required_default' in data:
del data['_required_default']


class JsonSchema(Schema):

Expand All @@ -88,19 +96,15 @@ def _get_serialized_value(self, o):
if isinstance(o, enum.Enum):
return o.value
else:
return o.__dict__
data = o.__dict__.copy()
remove_reserved_key(data)
return data

def encode(self, obj):
self._validate_object_type(obj)
# Copy the dict of the object as to not modify the provided object via the reference provided
data = obj.__dict__.copy()
if '_default' in data:
del data['_default']
if '_required' in data:
del data['_required']
if '_required_default' in data:
del data['_required_default']

remove_reserved_key(data)
return json.dumps(data, default=self._get_serialized_value, indent=True).encode('utf-8')

def decode(self, data):
Expand Down
13 changes: 13 additions & 0 deletions pulsar-client-cpp/python/schema_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1266,5 +1266,18 @@ def produce_and_consume(topic, schema_definition):

client.close()

def test_json_schema_encode_remove_reserved_key(self):
class SchemaB(Record):
field = String(required=True)

class SchemaA(Record):
field = SchemaB()

a = SchemaA(field=SchemaB(field="something"))
b = JsonSchema(SchemaA).encode(a)
# reserved field should not be in the encoded json
self.assertTrue(b'_default' not in b)
self.assertTrue(b'_required' not in b)
self.assertTrue(b'_required_default' not in b)
if __name__ == '__main__':
main()

0 comments on commit 6bf823e

Please sign in to comment.