Serialize default values in oneofs when calling to_dict() or to_json() (#110)

* Serialize default values in oneofs when calling to_dict() or to_json()

This change is consistent with the official protobuf implementation. If
a default value is set when using a oneof, and then a message is
translated from message -> JSON -> message, the default value is kept in
tact. Also, if no default value is set, they remain null.

* Some cleanup + testing for nested messages with oneofs

* Cleanup oneof_enum test cases, they should be fixed

This _should_ address:
https://github.com/danielgtaylor/python-betterproto/issues/63

* Include default value oneof fields when serializing to bytes

This will cause oneof fields with default values to explicitly be sent
to clients. Note that does not mean that all fields are serialized and
sent to clients, just those that _could_ be null and are not.

* Remove assignment when populating a sub-message within a proto

Also, move setattr out one indentation level

* Properly transform proto with empty string in oneof to bytes

Also, updated tests to ensure that which_one_of picks up the set field

* Formatting betterproto/__init__.py

* Adding test cases demonstrating equivalent behaviour with google impl

* Removing a temporary file I made locally

* Adding some clarifying comments

* Fixing tests for python38
This commit is contained in:
Brady Kieffer
2020-07-25 13:51:40 -04:00
committed by GitHub
parent 2745953a8e
commit c1a76a5f5e
7 changed files with 277 additions and 27 deletions

View File

@@ -282,3 +282,38 @@ def test_to_dict_default_values():
"someDouble": 1.2,
"someMessage": {"someOtherInt": 0},
}
def test_oneof_default_value_set_causes_writes_wire():
@dataclass
class Foo(betterproto.Message):
bar: int = betterproto.int32_field(1, group="group1")
baz: str = betterproto.string_field(2, group="group1")
def _round_trip_serialization(foo: Foo) -> Foo:
return Foo().parse(bytes(foo))
foo1 = Foo(bar=0)
foo2 = Foo(baz="")
foo3 = Foo()
assert bytes(foo1) == b"\x08\x00"
assert (
betterproto.which_one_of(foo1, "group1")
== betterproto.which_one_of(_round_trip_serialization(foo1), "group1")
== ("bar", 0)
)
assert bytes(foo2) == b"\x12\x00" # Baz is just an empty string
assert (
betterproto.which_one_of(foo2, "group1")
== betterproto.which_one_of(_round_trip_serialization(foo2), "group1")
== ("baz", "")
)
assert bytes(foo3) == b""
assert (
betterproto.which_one_of(foo3, "group1")
== betterproto.which_one_of(_round_trip_serialization(foo3), "group1")
== ("", None)
)