I am trying to implement a validation for protobuf files in Python. I don't want to use an external package.
I tried:
desc_set = descriptor_pb2.FileDescriptorSet()
descriptor_bytes = str.encode(descriptor)
desc_set.ParseFromString(descriptor_bytes)
pool = descriptor_pool.DescriptorPool()
desc = descriptor_pb2.FileDescriptorProto()
descriptor_bytes = str.encode(descriptor)
desc.ParseFromString(descriptor_bytes)
for fd in desc_set.file:
pool.Add(fd)
proto_msg = MessageFactory(pool).GetPrototype(pool.FindMessageTypeByName(desc_set.file[0].package))
proto_msg.FromString(bytearray(b'\n\x05Adnan'))
in the last line I defined proto file:
syntax = "proto2";
package employees;
message Employees {
required string Name = 1;
required int32 age = 2;
}
I sent bytearray(<msg>)
to FromString()
method
I expect to get parse error since the age field is missing in the and in the proto file the field is required.
How can I get parse error in this case?
Your code was non-reproducible and didn't work for me as-was:
However:
Renaming (!) the field to
name
(per the style guide):And:
And:
Yields:
NOTE
ParseFromString
throws no error here (either)I'm unfamiliar with using Python to work with Descriptors:
Yields:
NOTE
ParseFromString
throws no error here (either)It seems that
ParseFromString
doesn't validate.