mardi 26 juillet 2022

How to read a RepeatedField (or at least its lenght) using Google.Protobuf.Reflection?

I am writing tests for a C# application supporting several Protobuf definitions of the same objects... which are unfortunately not very compatible to each other.

So I have written the following utility methods using Google.Protobuf.Reflection:

namespace ProtobufUtils
{
    using Google.Protobuf;
    using Google.Protobuf.Collections;
    using Google.Protobuf.Reflection;
    ...

    public static uint ReadUint(this IMessage msg, string fieldName)
    {
        FieldDescriptor field = msg.Descriptor.FindFieldByName(fieldName);
        return (uint)field.Accessor.GetValue(msg);
    }

    public static string ReadString(this IMessage msg, string fieldName)
    {
        FieldDescriptor field = msg.Descriptor.FindFieldByName(fieldName);
        return (string)field.Accessor.GetValue(msg);
    }

Using the above methods I am able to read out some common fields from IMessage objects in my tests:

    [DataTestMethod]
    [DynamicData(nameof(GetAllVersionsToTest), typeof(BaseUnitTest), DynamicDataSourceType.Method)]
    public async Task GetConfigurationShouldContainSessionToken(uint version)
    {
        IMessage cfgReq = ProtobufUtils.GenerateConfigRequest(version);

        uint reqVersion = ProtobufUtils.ReadUint(cfgReq, "version");
        string reqId = ProtobufUtils.ReadString(cfgReq, "id");
        string reqEtag = ProtobufUtils.ReadString(cfgReq, "etag");

My question is:

Sometimes I also need to assert, that a RepeatedField has no elements.

How to do it please, by using reflection?

For example, in the .proto file I have:

message ConfigurationResponse {
    uint32 version = 1;
    string id= 2;
    string etag = 3;
    repeated ContainerConfiguration configuration = 4;
    reserved 5, 6;
}

How can I read out the ContainerConfiguration field using reflection and verify, that it is empty?

(and I do have to use reflection, because there are 4 not very compatible versions of ContainerConfiguration to be supported by our application... and more are coming).





Aucun commentaire:

Enregistrer un commentaire