当我在Python单元测试中比较两个Unicode字符串时,它会给出一个很好的失败信息,突出显示不同的行和字符。然而,比较两个8位字符串只显示两个字符串,没有突出显示。
如何才能让Unicode和8位字符串都有突出显示?
下面是一个示例单元测试,展示了这两种比较:
这个测试的结果显示了差异:
如何才能让Unicode和8位字符串都有突出显示?
下面是一个示例单元测试,展示了这两种比较:
import unittest
class TestAssertEqual(unittest.TestCase):
def testString(self):
a = 'xax\nzzz'
b = 'xbx\nzzz'
self.assertEqual(a, b)
def testUnicode(self):
a = u'xax\nzzz'
b = u'xbx\nzzz'
self.assertEqual(a, b)
if __name__ == '__main__':
unittest.main()
这个测试的结果显示了差异:
FF
======================================================================
FAIL: testString (__main__.TestAssertEqual)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/data/don/workspace/scratch/scratch.py", line 7, in testString
self.assertEqual(a, b)
AssertionError: 'xax\nzzz' != 'xbx\nzzz'
======================================================================
FAIL: testUnicode (__main__.TestAssertEqual)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/data/don/workspace/scratch/scratch.py", line 12, in testUnicode
self.assertEqual(a, b)
AssertionError: u'xax\nzzz' != u'xbx\nzzz'
- xax
? ^
+ xbx
? ^
zzz
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=2)
Python 3更新
在Python 3中,默认情况下,字符串字面量是Unicode编码的,因此这基本上是无关紧要的。assertMultiLineEqual()
不再支持字节字符串,所以你只能使用常规的assertEqual()
,除非你愿意将字节字符串解码为Unicode。
f-string
和标准的多行字符串。它会给其中一个添加大量的\n
字符,而另一个则不会。然后我将标准字符串转换为f-string
,比较就可以工作了(但我必须忽略使用没有插入变量的f-string
的lint警告)。 - Zephaniah Grunschlag