【问题标题】:Testing of existence of a repeated field in a protobuff message测试 protobuf 消息中是否存在重复字段
【发布时间】:2016-10-03 13:13:30
【问题描述】:

我有一条 google protobuf 消息:

message Foo {
  required int bar = 1;
}

我知道为了测试消息的字段,我们可以使用:

foo.bar = 1
assert foo.HasField("bar")

但是,“HasField”不适用于重复的字段类型。 如何测试“重复类型”字段是否存在?

message Foo {
  repeated int bar = 1;
}

【问题讨论】:

  • 似乎没有人真正理解您的问题。您想知道是否未提供重复字段,以及是否明确设置为空。我正在努力实现同样的目标……您找到解决方案了吗?

标签: python unit-testing protocol-buffers


【解决方案1】:

您可以尝试测试重复字段的长度:

assert len(foo.bar) == 0

【讨论】:

  • 但这只是让我知道添加了一个字段而不是它是什么字段。
  • 是的,你必须知道你的原型中有什么字段。杰
  • hasfield 方法主要用于测试字段是否设置了某个值
  • 但是 hasfield 不适用于重复类型的字段
  • 是的,这就是为什么您可以改为测试长度
【解决方案2】:

解决这个问题的方法是将重复的字段包含在自己的消息中。

message Foo {
  message Bars {
    repeated int bar = 1;
  }
  Bars bars = 1;
}

然后测试

foo.bars.SetInParent()
assert foo.HasField("bars")

这样您就可以判断是否没有设置重复字段,因为没有理由将 bar 消息添加到 foo,除非意图是添加 bar。

【讨论】:

    【解决方案3】:

    给定带有消息的msg 变量,您只能打印这样的重复字段。 from C# docs

    for descr in msg.DESCRIPTOR.fields:
        if descr.label == descr.LABEL_REPEATED:
            print(f'{descr.name} is repeated')
            for i, v_i in enumerate(getattr(msg, descr.name)):
                print(f'{i}:{v_i}')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多