测试protobuff消息中是否存在重复字段

时间:2016-10-03 13:13:31

标签: python unit-testing protocol-buffers

我有一条谷歌protobuf消息:

message Foo {
  required int bar = 1;
}

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

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

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

message Foo {
  repeated int bar = 1;
}

2 个答案:

答案 0 :(得分:2)

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

Thread: 13 is writing
Thread: 13 has stopped writing
Thread: 14 is reading a string: 0
Thread: 14 has stopped reading
Thread: 12 is writing
Thread: 12 has stopped writing
Thread: 16 is reading a string: 01
Thread: 18 is reading a string: 01
Thread: 17 is reading a string: 01
Thread: 15 is reading a string: 01
Thread: 20 is reading a string: 01
Thread: 21 is reading a string: 01
Thread: 19 is reading a string: 01
Thread: 23 is reading a string: 01
Thread: 22 is reading a string: 01
Thread: 25 is reading a string: 01
Thread: 26 is reading a string: 01
Thread: 27 is reading a string: 01
Thread: 24 is reading a string: 01
Thread: 30 is reading a string: 01
Thread: 31 is reading a string: 01
Thread: 29 is reading a string: 01
Thread: 28 is reading a string: 01
Thread: 33 is reading a string: 01
Thread: 32 is reading a string: 01
Thread: 28 has stopped reading
Thread: 29 has stopped reading
Thread: 18 has stopped reading
Thread: 17 has stopped reading
Thread: 21 has stopped reading
Thread: 19 has stopped reading
Thread: 23 has stopped reading
Thread: 24 has stopped reading
Thread: 27 has stopped reading
Thread: 33 has stopped reading
Thread: 26 has stopped reading
Thread: 32 has stopped reading
Thread: 16 has stopped reading
Thread: 22 has stopped reading
Thread: 25 has stopped reading
Thread: 20 has stopped reading
Thread: 15 has stopped reading
Thread: 30 has stopped reading
Thread: 31 has stopped reading

然后测试

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

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

答案 1 :(得分:1)

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

assert len(foo.bar) == 0