从protobufs检查有效的枚举类型

时间:2015-12-22 22:28:11

标签: python enums protocol-buffers pytest

在我名为skill.proto的protobuf文件中,我有:

message Cooking {
     enum VegeType {
         CAULIFLOWER = 0;
         CUCUMBER = 1;
         TOMATO = 2
     }

required VegeType type = 1;
}

在另一个文件中(例如:name.py)我想检查文件中的枚举是否为有效类型

#if (myCookingStyle.type != skill_pb2.Cooking.VegeTypes):
   print "Error: invalid cooking type"

如何检查myCookingStyle.type是否为有效的枚举类型?
即:我如何做那个评论行

注意:我想避免对枚举类型的检查进行硬编码,因为我稍后可能会添加更多的VegeTypes,例如:POTATO = 3,ONION = 4

1 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题,当你使用proto时,如果在分配时给出了错误的类型,那么就会出现错误。

将相关代码包装在try...except块中应该可以解决问题:

try:
    proto = skill_pb2.Cooking()
    proto.type = 6 # Incorrect type being assigned
except ValueError as e: # Above assignment throws a ValueError, caught here
    print 'Incorrect type assigned to Cooking proto'
    raise
else:
    # Use proto.type here freely - if it has been assigned to successfully, it contains a valid type
    print proto.type
    ...
相关问题