Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix pydict serialization for optional fields #495

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1373,6 +1373,9 @@ def to_pydict(
value = [i.to_pydict(casing, include_default_values) for i in value]
if value or include_default_values:
output[cased_name] = value
elif value is None:
if include_default_values:
output[cased_name] = None
elif (
value._serialized_on_wire
or include_default_values
Expand Down
26 changes: 26 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,32 @@ class Request(betterproto.Message):
assert Request().parse(b"\n\x00").flag is False


def test_optional_datetime_to_dict():
@dataclass
class Request(betterproto.Message):
date: Optional[datetime] = betterproto.message_field(1, optional=True)

# Check dict serialization
assert Request().to_dict() == {}
assert Request().to_dict(include_default_values=True) == {"date": None}
assert Request(date=datetime(2020, 1, 1)).to_dict() == {
"date": "2020-01-01T00:00:00Z"
}
assert Request(date=datetime(2020, 1, 1)).to_dict(include_default_values=True) == {
"date": "2020-01-01T00:00:00Z"
}

# Check pydict serialization
assert Request().to_pydict() == {}
assert Request().to_pydict(include_default_values=True) == {"date": None}
assert Request(date=datetime(2020, 1, 1)).to_pydict() == {
"date": datetime(2020, 1, 1)
}
assert Request(date=datetime(2020, 1, 1)).to_pydict(
include_default_values=True
) == {"date": datetime(2020, 1, 1)}


def test_to_json_default_values():
@dataclass
class TestMessage(betterproto.Message):
Expand Down