关于python:单元测试两个列表,如果有差异,打印/显示它

Unit testing two lists and if there is a difference, print/show it

我昨天开始用Python进行单元测试。 我在网上看到了一个用assertEqual测试的例子,他自动打印出两个列表之间的差异。 但是,似乎不会在我的脚本中发生。 我怎么能得到它?

下面的代码包含在从unittest.TestCase派生的类中:

1
2
3
4
5
6
7
8
9
10
11
def test_compare_two_lists_should_fail(self):
    a = [1,2,3] # In my actual code this is generated by a module's function
    b = [1,2,4]

    self.assertListEqual(a, b, 'lists are inequal')

def test_compare_two_lists_should_not_fail(self):
    a = [1,2,3] # In my actual code this is generated by a module's function
    b = [1,2,3]

    self.assertListEqual(a ,b, 'lists are inequal')

运行此测试时,会产生以下输出:

test_compare_two_lists_should_not_fail(main.TestCase)......好的
test_compare_two_lists_should_fail(main.TestCase)......失败

======================================================================

失败:test_compare_two_lists_should_fail(main.TestCase)

Traceback(最近一次调用最后一次):
test_compare_two_lists_should_fail中的文件"C:/some_dir/TestCase.py",第34行
self.assertListEqual(a,b,'lists is inequal')
AssertionError:列表不等

在0.001s中进行2次测试

失败(失败= 1)


问题是您在两次调用assertListEqual时指定的消息。

从这些文档

Args:

list1: The first list to compare.

list2: The second list to compare.

msg: Optional message to use on failure instead of a list of differences.

因此,如果您想查看列表之间的差异,请避免传递消息:

1
self.assertListEqual(a ,b)

顺便说一下,在两个测试中都有相同的lists are inequal消息。


如果您从Python开始进行单元测试,我建议您使用pytest。 恕我直言,它更容易使用,失败消息比xUnit更聪明。

使用pytest,你会得到这样的东西:

1
2
def testFoo():
    assert [1, 2, 3] == [1, 2, 4], 'lists are inequal'

结果是:

1
2
3
4
5
6
7
8
9
10
11
12
13
================================== FAILURES ===================================
___________________________________ testFoo ___________________________________

    def testFoo():
>       assert [1, 2, 3] == [1, 2, 4]
E       AssertionError: lists are inequal
E       assert [1, 2, 3] == [1, 2, 4]
E         At index 2 diff: 3 != 4
E         Use -v to get the full diff

File"foo.py", line 2
AssertionError
========================== 1 failed in 0.07 seconds ===========================

写它很容易,而且很明显。 试试看!