from faker import Faker from google.protobuf.pyext._message import FieldDescriptor, Message class ResponseFaker: # pragma: no cover @staticmethod def populate_protobuf_models(message: Message) -> Message: """This function will populate protobuf model classes with **FAKE** data, including for use with nested protobuf models (recursive). """ fake = Faker() field: FieldDescriptor for field in message.DESCRIPTOR.fields: int_types = ( field.TYPE_FIXED32, field.TYPE_FIXED64, field.TYPE_INT32, field.TYPE_INT64, field.TYPE_UINT32, field.TYPE_UINT64, ) # Set a random integer value for tests (nearly all fields are int64) if field.type in int_types: setattr(message, field.name, fake.random_int(min=1000, max=9999999, step=1)) # Set (the same) integer value for tests (nearly all fields are int64) elif field.type == field.TYPE_STRING: setattr(message, field.name, fake.name()) elif field.type == field.TYPE_MESSAGE: child = ResponseFaker.populate_protobuf_models(getattr(message, field.name)) parent = getattr(message, field.name) # akin to setattr(message, field.name, child) which is not allowed by protobuf parent.CopyFrom(child) return message