单元测试两个列表,如果有差异,打印/显示i

2024-04-26 20:52:19 发布

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

我昨天开始用Python进行单元测试。我在网上看到了使用assertEqual测试的例子,assertEqual会自动打印出两个列表之间的差异。然而,这似乎没有发生在我的脚本。我怎样才能得到那个?你知道吗

下面的代码包含在从unittest.TestCase测试用例地址:

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')

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

测试比较两个列表是否应该失败(main.TestCase)。。。好 啊 测试比较两个列表,如果失败(main.TestCase)。。。失败

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

失败:测试比较两个列表,如果失败(main.TestCase)

回溯(最近一次呼叫): 文件“C:/u目录/测试用例.py“,第34行,在测试\u中比较\u两个\u列表\u是否失败 self.assertListEqual公司(a,b,'列表不相等') 断言错误:列表是不相等的


在0.001秒内进行了2次测试

失败(失败=1)


Tags: intestself列表maindef测试用例testcase
2条回答

如果您是从Python中的单元测试开始的,我建议您使用pytest。因此,它比xUnit更易于使用,失败消息也更聪明。你知道吗

pytest你会得到这样的结果:

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

因此:

================================== 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 ===========================

写起来很简单,信息也很明显。试试看!你知道吗

问题是您在对assertListEqual的两个调用中指定的消息。你知道吗

these docs

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.

因此,如果您希望看到列表之间的差异,请避免传递以下信息:

self.assertListEqual(a ,b)

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

相关问题 更多 >