danielgtaylor / python-betterproto

Clean, modern, Python 3.6+ code generator & library for Protobuf 3 and async gRPC
MIT License
1.45k stars 196 forks source link

Enum dict-related methods broken #133

Closed upcFrost closed 3 years ago

upcFrost commented 3 years ago

Hi,

Enum to_dict doesn't seem to work if enum values are not sequential. Example:

message Msg {
  Test t = 1;
}

enum Test {
  DEFAULT = 0;
  OTHER = 8;
}

Trying to convert this message to dict will fail with list index out of range exception. It's caused by this code

enum_values = list(
    self._betterproto.cls_by_field[field.name]
)  # type: ignore
if isinstance(v, list):
    output[cased_name] = [enum_values[e].name for e in v]
else:
    output[cased_name] = enum_values[v].name

As v is both Enum and integer, it will try to take the 8th element of the enum_values list, while it should take the element with value 8. In case of IntEnum - just don't use the list, as Test(8) will give the correct value. Or it is possible to use a static dict for name-value mapping

For the from_dict method, the issue might arise when the value passed to it is invalid but is neither list nor string. For example, passing byte bypasses the type check and assigned value of the wrong type to the enum field.

upcFrost commented 3 years ago

Closing as it seems to be fixed in the upstream, didn't see it, sorry. Published version is still broken though