简体   繁体   English

格式化python unittests的测试失败

[英]Formatting test failures for python unittests

I am running a number of unittests to test a binary protocol: 我正在运行许多单元测试来测试二进制协议:

An example failure messages is as follows: 失败消息示例如下:

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'

This is unwieldy as I need to convert the ascii chars into hex manually to check what is happening. 这很麻烦,因为我需要手动将ascii字符转换为十六进制以检查发生了什么。

It would be nice, if it was possible to cause unittest to format all bytes objects as hex, eg 如果有可能导致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'

Any advice on how to accomplish this with the lease amount of effort? 关于如何通过租赁努力实现这一目标的任何建议?

Note: I have not only this particular comparison between two set, but also comparisons between lists and dicts... Hence my request for a low-effort solution. 注意:我不仅有两个集合之间的特定比较,而且还有列表和字典之间的比较...因此,我需要一个省力的解决方案。

Ok, I dug into the code of unittest myself. 好的,我自己研究了unittest的代码。

Internally, it uses repr(obj) to format the output of test failures. 在内部,它使用repr(obj)格式化测试失败的输出。 Short of rewriting all the comparison routines for list, set, dict, etc. there is no easy fix. 缺少重写列表,集合,字典等的所有比较例程的方法。没有容易解决的方法。

The best solution I found is subclassing the bytes object and overloading its __repr__ method like so: 我发现的最佳解决方案是将bytes对象子类化,并使其__repr__方法重载,如下所示:

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

Then one can wrap the results with this object within the test cases: 然后,可以在测试用例中使用该对象包装结果:

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