为python单元测试格式化测试失败

2024-05-16 21:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

故障消息示例如下:

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'

关于如何用租赁费来完成这项工作有什么建议吗

注:我不仅有两个集合之间的特殊比较,还有列表和dicts之间的比较。。。因此,我要求一个低努力的解决方案


Tags: thein协议二进制notitems单元测试but
1条回答
网友
1楼 · 发布于 2024-05-16 21:28:52

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

在内部,它使用repr(obj)格式化测试失败的输出。除了重写list、set、dict等的所有比较例程之外,没有简单的解决方法

我找到的最佳解决方案是对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)

相关问题 更多 >