为了账号安全,请及时绑定邮箱和手机立即绑定

proto.Unmarshal 测试不一致地失败

proto.Unmarshal 测试不一致地失败

Go
www说 2022-12-19 10:41:38
我有一些 Redis 代码依赖于 Proto 标准来编组/解组数据。我使用gomega编写了以下测试来测试proto.Unmarshal:b64Decoded, err := base64.StdEncoding.DecodeString("derp")Expect(err).ShouldNot(HaveOccurred())var item testRecorderr = proto.Unmarshal(b64Decoded, &item)Expect(err).Should(HaveOccurred())Expect(err.Error()).Should(Equal("proto:\u00a0cannot parse invalid wire-format data"))但是,最终断言失败,因为预期的错误字符串是proto: cannot parse invalid wire-format data。这里显而易见的解决方案是更改它,当我这样做时,错误就会消失。直到我修改测试并重新运行它,在这种情况下,测试再次失败,告诉我字符串应该是proto:\u00a0cannot parse invalid wire-format data。这个循环无限继续下去。那么,我在这里做错了什么以及如何解决这个问题?
查看完整描述

1 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

这个问题跟你想的不太一样;该protobuf包随机选择一个空格或\u00a0在输出错误时(我相信它基于二进制的哈希)。你可以在这里看到这个:

// Deliberately introduce instability into the error message string to

// discourage users from performing error string comparisons.

if detrand.Bool() {

   return "proto: " // use non-breaking spaces (U+00a0)

} else {

   return "proto: " // use regular spaces (U+0020)

}

所以你遇到的问题是故意的,旨在防止用户做你正在尝试的事情(依赖于保持不变的错误)。你只有在更改测试时才会看到它(我猜,不是每次更改它时)的原因是它Go会缓存测试结果(默认情况下,测试仅在发生更改时运行)。

关于你能做些什么,我首先建议考虑这个测试是否真的有必要。软件包作者特别指出错误不稳定,因此在google.golang.org/protobuf/proto发布新版本时,以这种方式进行比较可能会中断。

包测试通过调用(例如这里protobuf)来解决这个问题。您不能这样做,因为is under and, as such, not accessibledetrand.Disable()google.golang.org/protobuf/internal/detrandinternal

如果您真的想解决这个问题,最简单的方法可能是strings.Contains


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 829 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号