繁体   English   中英

格式化python unittests的测试失败

[英]Formatting test failures for python unittests

我正在运行许多单元测试来测试二进制协议:

失败消息示例如下:

AssertionError: Items in the first set but not the second:
b'\x00\x02@=\x00'
Items in the second set but not the first:
b'\x00\x02@N\x00'

这很麻烦,因为我需要手动将ascii字符转换为十六进制以检查发生了什么。

如果有可能导致unittest将所有bytes对象格式化为十六进制,那就太好了,例如

AssertionError: Items in the first set but not the second:
b'\x00\x02\x40\x3d\x00'
Items in the second set but not the first:
b'\x00\x02\x40\x4e\x00'

关于如何通过租赁努力实现这一目标的任何建议?

注意:我不仅有两个集合之间的特定比较,而且还有列表和字典之间的比较...因此,我需要一个省力的解决方案。

好的,我自己研究了unittest的代码。

在内部,它使用repr(obj)格式化测试失败的输出。 缺少重写列表,集合,字典等的所有比较例程的方法。没有容易解决的方法。

我发现的最佳解决方案是将bytes对象子类化,并使其__repr__方法重载,如下所示:

class st_frame(bytes):
    def __repr__(self):
        return "b'{}'".format(
            ''.join(['\\x%02x' % c for c in self])
        )

然后,可以在测试用例中使用该对象包装结果:

ret = func_to_test(data)      # lets assume this returns list of bytes objects
ret = [st_frame(value) for value in ret]
self.assertEqual(ret, target)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM