Skip to content

Commit

Permalink
feat: add default values parameter to to_json (#164)
Browse files Browse the repository at this point in the history
* feat: add default values parameter to to_json

* fix: typing & stylecheck issues
  • Loading branch information
yon-mg committed Nov 20, 2020
1 parent fef7983 commit 691f1b2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
10 changes: 8 additions & 2 deletions proto/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,13 @@ def deserialize(cls, payload: bytes) -> "Message":
"""
return cls.wrap(cls.pb().FromString(payload))

def to_json(cls, instance, *, use_integers_for_enums=True) -> str:
def to_json(
cls,
instance,
*,
use_integers_for_enums=True,
including_default_value_fields=True
) -> str:
"""Given a message instance, serialize it to json
Args:
Expand All @@ -343,7 +349,7 @@ def to_json(cls, instance, *, use_integers_for_enums=True) -> str:
return MessageToJson(
cls.pb(instance),
use_integers_for_enums=use_integers_for_enums,
including_default_value_fields=True,
including_default_value_fields=including_default_value_fields,
)

def from_json(cls, payload, *, ignore_unknown_fields=False) -> "Message":
Expand Down
23 changes: 23 additions & 0 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,29 @@ class Zone(proto.Enum):
assert json2 == '{"zone":"EPIPELAGIC"}'


def test_json_default_values():
class Squid(proto.Message):
mass_kg = proto.Field(proto.INT32, number=1)
name = proto.Field(proto.STRING, number=2)

s = Squid(name="Steve")
json1 = (
Squid.to_json(s, including_default_value_fields=False)
.replace(" ", "")
.replace("\n", "")
)
assert json1 == '{"name":"Steve"}'

json2 = Squid.to_json(s).replace(" ", "").replace("\n", "")
assert (
json2 == '{"name":"Steve","massKg":0}' or json2 == '{"massKg":0,"name":"Steve"}'
)

s1 = Squid.from_json(json1)
s2 = Squid.from_json(json2)
assert s == s1 == s2


def test_json_unknown_field():
# Note that 'lengthCm' is unknown in the local definition.
# This could happen if the client is using an older proto definition
Expand Down

0 comments on commit 691f1b2

Please sign in to comment.