Skip to content

Commit

Permalink
Pack booleans correctly when packing to JSON (#129)
Browse files Browse the repository at this point in the history
  • Loading branch information
JSCU-CNI authored Aug 1, 2024
1 parent b2eaf44 commit beabaa6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion flow/record/jsonpacker.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,20 @@ def pack_obj(self, obj):
if obj._desc.identifier not in self.descriptors:
self.register(obj._desc, True)
serial = obj._asdict()

if self.pack_descriptors:
serial["_type"] = "record"
serial["_recorddescriptor"] = obj._desc.identifier

# PYTHON2: Because "bytes" are also "str" we have to handle this here
for field_type, field_name in obj._desc.get_field_tuples():
# PYTHON2: Because "bytes" are also "str" we have to handle this here
if field_type == "bytes" and isinstance(serial[field_name], str):
serial[field_name] = base64.b64encode(serial[field_name]).decode()

# Boolean field types should be cast to a bool instead of staying ints
elif field_type == "boolean" and isinstance(serial[field_name], int):
serial[field_name] = bool(serial[field_name])

return serial
if isinstance(obj, RecordDescriptor):
serial = {
Expand Down
21 changes: 21 additions & 0 deletions tests/test_json_packer.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,24 @@ def test_record_descriptor_not_found():
packer = JsonRecordPacker()
with pytest.raises(RecordDescriptorNotFound, match="No RecordDescriptor found for: .*test/descriptor_not_found"):
packer.unpack(data)


def test_record_pack_bool_regression() -> None:
TestRecord = RecordDescriptor(
"test/record_pack_bool",
[
("varint", "some_varint"),
("uint16", "some_uint"),
("boolean", "some_boolean"),
],
)

record = TestRecord(some_varint=1, some_uint=0, some_boolean=False)
packer = JsonRecordPacker()

# pack to json string and check if some_boolean is false instead of 0
data = packer.pack(record)
assert data.startswith('{"some_varint": 1, "some_uint": 0, "some_boolean": false, ')

# pack the json string back to a record and make sure it is the same as before
assert packer.unpack(data) == record

0 comments on commit beabaa6

Please sign in to comment.