Skip to content

Commit 31c63b3

Browse files
committed
Fix serialization of repeated fields with empty messages
Extend test config and utils to support exclusion of certain json samples from testing for symetry.
1 parent 7c5ee47 commit 31c63b3

File tree

4 files changed

+31
-2
lines changed

4 files changed

+31
-2
lines changed

src/betterproto/__init__.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,7 @@ def encode_varint(value: int) -> bytes:
307307

308308
def _preprocess_single(proto_type: str, wraps: str, value: Any) -> bytes:
309309
"""Adjusts values before serialization."""
310+
310311
if proto_type in [
311312
TYPE_ENUM,
312313
TYPE_BOOL,
@@ -738,9 +739,18 @@ def __bytes__(self) -> bytes:
738739
output += _serialize_single(meta.number, TYPE_BYTES, buf)
739740
else:
740741
for item in value:
741-
output += _serialize_single(
742-
meta.number, meta.proto_type, item, wraps=meta.wraps or ""
742+
output += (
743+
_serialize_single(
744+
meta.number,
745+
meta.proto_type,
746+
item,
747+
wraps=meta.wraps or "",
748+
)
749+
# if it's an empty message it still needs to be represented
750+
# as an item in the repeated list
751+
or b"\n\x00"
743752
)
753+
744754
elif isinstance(value, dict):
745755
for k, v in value.items():
746756
assert meta.map_types

tests/inputs/config.py

+7
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,10 @@
2121
"example_service",
2222
"empty_service",
2323
}
24+
25+
26+
# Indicate json sample messages to skip when testing that json (de)serialization
27+
# is symmetrical becuase some cases legitimately are not symmetrical.
28+
# For tuple in the set, the first value is the name of the test and the second is
29+
# the name of the json file.
30+
non_symmetrical_json = {("empty_repeated", "empty_repeated")}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"msg": [{"values":[]}]
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
syntax = "proto3";
2+
3+
message MessageA {
4+
repeated float values = 1;
5+
}
6+
7+
message Test {
8+
repeated MessageA msg = 1;
9+
}

0 commit comments

Comments
 (0)