Support JSON base64 bytes and enums as strings
This commit is contained in:
3
betterproto/tests/bytes.json
Normal file
3
betterproto/tests/bytes.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"data": "SGVsbG8sIFdvcmxkIQ=="
|
||||
}
|
||||
5
betterproto/tests/bytes.proto
Normal file
5
betterproto/tests/bytes.proto
Normal file
@@ -0,0 +1,5 @@
|
||||
syntax = "proto3";
|
||||
|
||||
message Test {
|
||||
bytes data = 1;
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"greeting": 1
|
||||
"greeting": "HEY"
|
||||
}
|
||||
|
||||
@@ -69,10 +69,15 @@ if __name__ == "__main__":
|
||||
print(f"Using {parts[0]}_pb2 to generate {os.path.basename(out)}")
|
||||
|
||||
imported = importlib.import_module(f"{parts[0]}_pb2")
|
||||
parsed = Parse(open(filename).read(), imported.Test())
|
||||
input_json = open(filename).read()
|
||||
parsed = Parse(input_json, imported.Test())
|
||||
serialized = parsed.SerializeToString()
|
||||
serialized_json = MessageToJson(
|
||||
parsed, preserving_proto_field_name=True, use_integers_for_enums=True
|
||||
)
|
||||
assert json.loads(serialized_json) == json.load(open(filename))
|
||||
serialized_json = MessageToJson(parsed, preserving_proto_field_name=True)
|
||||
|
||||
s_loaded = json.loads(serialized_json)
|
||||
in_loaded = json.loads(input_json)
|
||||
|
||||
if s_loaded != in_loaded:
|
||||
raise AssertionError("Expected JSON to be equal:", s_loaded, in_loaded)
|
||||
|
||||
open(out, "wb").write(serialized)
|
||||
|
||||
@@ -30,3 +30,21 @@ def test_has_field():
|
||||
# Can manually set it but defaults to false
|
||||
foo.bar = Bar()
|
||||
assert foo.bar.serialized_on_wire == False
|
||||
|
||||
|
||||
def test_enum_as_int_json():
|
||||
class TestEnum(betterproto.Enum):
|
||||
ZERO = 0
|
||||
ONE = 1
|
||||
|
||||
@dataclass
|
||||
class Foo(betterproto.Message):
|
||||
bar: TestEnum = betterproto.enum_field(1)
|
||||
|
||||
# JSON strings are supported, but ints should still be supported too.
|
||||
foo = Foo().from_dict({"bar": 1})
|
||||
assert foo.bar == TestEnum.ONE
|
||||
|
||||
# Plain-ol'-ints should serialize properly too.
|
||||
foo.bar = 1
|
||||
assert foo.to_dict() == {"bar": "ONE"}
|
||||
|
||||
Reference in New Issue
Block a user