Skip to content
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

Fix JsonRecordPacker boolean packing #129

Merged
merged 3 commits into from
Aug 1, 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
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
Loading