unittest:assertIn的更好替代品

时间:2014-12-14 14:11:14

标签: python unit-testing tdd python-unittest

假设我有一个巨大的列表作为我要测试的输出。我创建了一个列表,其中包含一些我认为应该在输出列表中的随机元素。这是我在阅读文档后想出来的:

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,则expectedelements将无法检查,并且会引发AssertionError并且python将继续到下一个测试。我想知道哪些元素['some', 'expected', 'elements']不在,而不仅仅是第一个无法找到的元素。

  2. 它完全污染了stdout的巨大列表,不得不将其管道到日志中进行检查

1 个答案:

答案 0 :(得分:1)

如何使用sets(假设需要检查不同的元素):

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)