Fix is_set for optional proto3 fields

This commit is contained in:
James Hilton-Balfe 2022-04-24 00:37:15 +01:00 committed by GitHub
parent 6f7d706a8e
commit 3ca092a724
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View File

@ -1319,7 +1319,12 @@ class Message(ABC):
:class:`bool`
`True` if field has been set, otherwise `False`.
"""
return self.__raw_get(name) is not PLACEHOLDER
default = (
PLACEHOLDER
if not self._betterproto.meta_by_field_name[name].optional
else None
)
return self.__raw_get(name) is not default
def serialized_on_wire(message: Message) -> bool:

View File

@ -517,3 +517,15 @@ def test_copyability():
assert spam == deepcopied
assert spam is not deepcopied
assert spam.baz is not deepcopied.baz
def test_is_set():
@dataclass
class Spam(betterproto.Message):
foo: bool = betterproto.bool_field(1)
bar: Optional[int] = betterproto.int32_field(2, optional=True)
assert not Spam().is_set("foo")
assert not Spam().is_set("bar")
assert Spam(foo=True).is_set("foo")
assert Spam(foo=True, bar=0).is_set("bar")