unittest:断言的更好选择

2024-04-19 04:31:08 发布

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

假设我有一个巨大的列表作为输出,我想测试。我用一些随机元素创建一个列表,我觉得这些元素应该在我的输出列表中。这是我在阅读文档后想到的:

def TestMyList(unittest.TestCase):
    def setUp(self):
        self.mylist = #get my list from program output file

    def test_list(self):
        list_to_test_against = ['some', 'expected', 'elements']
        for el in list_to_test_against:
             self.assertIn(el, self.mylist)

上述代码存在许多问题:

  1. 如果'some'不在self.mylist中,那么expected和{}将不会被检查,并引发AssertionError,python将继续进行下一个测试。我想知道['some', 'expected', 'elements']中的哪一个元素不在,而不仅仅是第一个找不到的元素。

  2. 它用巨大的列表完全污染了stdout,必须通过管道将其传输到日志中进行检查


Tags: to文档testself元素列表defsome
1条回答
网友
1楼 · 发布于 2024-04-19 04:31:08

使用sets如何(假设需要检查oly distinct元素):

def TestMyList(unittest.TestCase):
    def setUp(self):
        # testing for existence we only need a set...
        self.myset = set(<#get my list from program output file>)

    def test_list(self):
        # work with sets to compare
        set_to_test_against = set(['some', 'expected', 'elements'])
        # set of tested elements that are found in program output
        common_set = set_to_test_against & self.myset
        # report back difference between sets if different (using difference)
        assert set_to_test_against == common_set, "missing %s" % (set_to_test_against - common_set)

相关问题 更多 >