Skip to content

Commit a945246

Browse files
Fixes danielgtaylor#93 to_dict returns wrong enum fields when numbering is not consecutive
1 parent 42e197f commit a945246

File tree

7 files changed

+148
-57
lines changed

7 files changed

+148
-57
lines changed

src/betterproto/__init__.py

Lines changed: 59 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import json
55
import struct
66
import sys
7+
import warnings
78
from abc import ABC
89
from base64 import b64decode, b64encode
910
from datetime import datetime, timedelta, timezone
@@ -21,6 +22,8 @@
2122
get_type_hints,
2223
)
2324

25+
import typing
26+
2427
from ._types import T
2528
from .casing import camel_case, safe_snake_case, snake_case
2629
from .grpc.grpclib_client import ServiceStub
@@ -251,7 +254,7 @@ def map_field(
251254
)
252255

253256

254-
class Enum(int, enum.Enum):
257+
class Enum(enum.IntEnum):
255258
"""Protocol buffers enumeration base class. Acts like `enum.IntEnum`."""
256259

257260
@classmethod
@@ -635,9 +638,13 @@ def __bytes__(self) -> bytes:
635638

636639
@classmethod
637640
def _type_hint(cls, field_name: str) -> Type:
641+
return cls._type_hints()[field_name]
642+
643+
@classmethod
644+
def _type_hints(cls) -> Dict[str, Type]:
638645
module = inspect.getmodule(cls)
639646
type_hints = get_type_hints(cls, vars(module))
640-
return type_hints[field_name]
647+
return type_hints
641648

642649
@classmethod
643650
def _cls_for(cls, field: dataclasses.Field, index: int = 0) -> Type:
@@ -789,55 +796,68 @@ def to_dict(
789796
`False`.
790797
"""
791798
output: Dict[str, Any] = {}
799+
field_types = self._type_hints()
792800
for field_name, meta in self._betterproto.meta_by_field_name.items():
793-
v = getattr(self, field_name)
801+
field_type = field_types[field_name]
802+
field_is_repeated = type(field_type) is type(typing.List)
803+
value = getattr(self, field_name)
794804
cased_name = casing(field_name).rstrip("_") # type: ignore
795-
if meta.proto_type == "message":
796-
if isinstance(v, datetime):
797-
if v != DATETIME_ZERO or include_default_values:
798-
output[cased_name] = _Timestamp.timestamp_to_json(v)
799-
elif isinstance(v, timedelta):
800-
if v != timedelta(0) or include_default_values:
801-
output[cased_name] = _Duration.delta_to_json(v)
805+
if meta.proto_type == TYPE_MESSAGE:
806+
if isinstance(value, datetime):
807+
if value != DATETIME_ZERO or include_default_values:
808+
output[cased_name] = _Timestamp.timestamp_to_json(value)
809+
elif isinstance(value, timedelta):
810+
if value != timedelta(0) or include_default_values:
811+
output[cased_name] = _Duration.delta_to_json(value)
802812
elif meta.wraps:
803-
if v is not None or include_default_values:
804-
output[cased_name] = v
805-
elif isinstance(v, list):
813+
if value is not None or include_default_values:
814+
output[cased_name] = value
815+
elif field_is_repeated:
806816
# Convert each item.
807-
v = [i.to_dict(casing, include_default_values) for i in v]
808-
if v or include_default_values:
809-
output[cased_name] = v
817+
value = [i.to_dict(casing, include_default_values) for i in value]
818+
if value or include_default_values:
819+
output[cased_name] = value
810820
else:
811-
if v._serialized_on_wire or include_default_values:
812-
output[cased_name] = v.to_dict(casing, include_default_values)
813-
elif meta.proto_type == "map":
814-
for k in v:
815-
if hasattr(v[k], "to_dict"):
816-
v[k] = v[k].to_dict(casing, include_default_values)
817-
818-
if v or include_default_values:
819-
output[cased_name] = v
820-
elif v != self._get_field_default(field_name) or include_default_values:
821+
if value._serialized_on_wire or include_default_values:
822+
output[cased_name] = value.to_dict(
823+
casing, include_default_values
824+
)
825+
elif meta.proto_type == TYPE_MAP:
826+
for k in value:
827+
if hasattr(value[k], "to_dict"):
828+
value[k] = value[k].to_dict(casing, include_default_values)
829+
830+
if value or include_default_values:
831+
output[cased_name] = value
832+
elif value != self._get_field_default(field_name) or include_default_values:
821833
if meta.proto_type in INT_64_TYPES:
822-
if isinstance(v, list):
823-
output[cased_name] = [str(n) for n in v]
834+
if field_is_repeated:
835+
output[cased_name] = [str(n) for n in value]
824836
else:
825-
output[cased_name] = str(v)
837+
output[cased_name] = str(value)
826838
elif meta.proto_type == TYPE_BYTES:
827-
if isinstance(v, list):
828-
output[cased_name] = [b64encode(b).decode("utf8") for b in v]
839+
if field_is_repeated:
840+
output[cased_name] = [
841+
b64encode(b).decode("utf8") for b in value
842+
]
829843
else:
830-
output[cased_name] = b64encode(v).decode("utf8")
844+
output[cased_name] = b64encode(value).decode("utf8")
831845
elif meta.proto_type == TYPE_ENUM:
832-
enum_values = list(
833-
self._betterproto.cls_by_field[field_name]
834-
) # type: ignore
835-
if isinstance(v, list):
836-
output[cased_name] = [enum_values[e].name for e in v]
846+
if field_is_repeated:
847+
enum_class = field_type.__args__[0]
848+
if isinstance(value, typing.Iterable):
849+
output[cased_name] = [
850+
enum_class(element).name for element in value
851+
]
852+
else:
853+
warnings.warn(
854+
f"Non-iterable value for repeated enum field {field_name}"
855+
)
837856
else:
838-
output[cased_name] = enum_values[v].name
857+
enum_class = field_type
858+
output[cased_name] = enum_class(value).name
839859
else:
840-
output[cased_name] = v
860+
output[cased_name] = value
841861
return output
842862

843863
def from_dict(self: T, value: dict) -> T:

tests/inputs/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"namespace_keywords", # 70
66
"namespace_builtin_types", # 53
77
"googletypes_struct", # 9
8-
"googletypes_value", # 9,
8+
"googletypes_value", # 9
99
"import_capitalized_package",
1010
"example", # This is the example in the readme. Not a test.
1111
}

tests/inputs/enum/enum.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"choice": "FOUR",
3+
"choices": [
4+
"ZERO",
5+
"ONE",
6+
"THREE",
7+
"FOUR"
8+
]
9+
}

tests/inputs/enum/enum.proto

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
syntax = "proto3";
2+
3+
// Tests that enums are correctly serialized and that it correctly handles skipped and out-of-order enum values
4+
message Test {
5+
Choice choice = 1;
6+
repeated Choice choices = 2;
7+
}
8+
9+
enum Choice {
10+
ZERO = 0;
11+
ONE = 1;
12+
// TWO = 2;
13+
FOUR = 4;
14+
THREE = 3;
15+
}

tests/inputs/enum/test_enum.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from tests.output_betterproto.enum import (
2+
Test,
3+
Choice,
4+
)
5+
6+
7+
def test_enum_set_and_get():
8+
assert Test(choice=Choice.ZERO).choice == Choice.ZERO
9+
assert Test(choice=Choice.ONE).choice == Choice.ONE
10+
assert Test(choice=Choice.THREE).choice == Choice.THREE
11+
assert Test(choice=Choice.FOUR).choice == Choice.FOUR
12+
13+
14+
def test_enum_set_with_int():
15+
assert Test(choice=0).choice == Choice.ZERO
16+
assert Test(choice=1).choice == Choice.ONE
17+
assert Test(choice=3).choice == Choice.THREE
18+
assert Test(choice=4).choice == Choice.FOUR
19+
20+
21+
def test_enum_is_comparable_with_int():
22+
assert Test(choice=Choice.ZERO).choice == 0
23+
assert Test(choice=Choice.ONE).choice == 1
24+
assert Test(choice=Choice.THREE).choice == 3
25+
assert Test(choice=Choice.FOUR).choice == 4
26+
27+
28+
def test_enum_to_dict():
29+
assert (
30+
"choice" not in Test(choice=Choice.ZERO).to_dict()
31+
), "Default enum value is not serialized"
32+
assert (
33+
Test(choice=Choice.ZERO).to_dict(include_default_values=True)["choice"]
34+
== "ZERO"
35+
)
36+
assert Test(choice=Choice.ONE).to_dict()["choice"] == "ONE"
37+
assert Test(choice=Choice.THREE).to_dict()["choice"] == "THREE"
38+
assert Test(choice=Choice.FOUR).to_dict()["choice"] == "FOUR"
39+
40+
41+
def test_repeated_enum_is_comparable_with_int():
42+
assert Test(choices=[Choice.ZERO]).choices == [0]
43+
assert Test(choices=[Choice.ONE]).choices == [1]
44+
assert Test(choices=[Choice.THREE]).choices == [3]
45+
assert Test(choices=[Choice.FOUR]).choices == [4]
46+
47+
48+
def test_repeated_enum_set_and_get():
49+
assert Test(choices=[Choice.ZERO]).choices == [Choice.ZERO]
50+
assert Test(choices=[Choice.ONE]).choices == [Choice.ONE]
51+
assert Test(choices=[Choice.THREE]).choices == [Choice.THREE]
52+
assert Test(choices=[Choice.FOUR]).choices == [Choice.FOUR]
53+
54+
55+
def test_repeated_enum_to_dict():
56+
assert Test(choices=[Choice.ZERO]).to_dict()["choices"] == ["ZERO"]
57+
assert Test(choices=[Choice.ONE]).to_dict()["choices"] == ["ONE"]
58+
assert Test(choices=[Choice.THREE]).to_dict()["choices"] == ["THREE"]
59+
assert Test(choices=[Choice.FOUR]).to_dict()["choices"] == ["FOUR"]
60+
61+
all_enums_dict = Test(
62+
choices=[Choice.ZERO, Choice.ONE, Choice.THREE, Choice.FOUR]
63+
).to_dict()
64+
assert (all_enums_dict["choices"]) == ["ZERO", "ONE", "THREE", "FOUR"]

tests/inputs/enums/enums.json

Lines changed: 0 additions & 3 deletions
This file was deleted.

tests/inputs/enums/enums.proto

Lines changed: 0 additions & 14 deletions
This file was deleted.

0 commit comments

Comments
 (0)