yayu
yayu

Reputation: 8088

unittest: better alternative to assertIn

Suppose I have a huge list as output that I want to test. I create a list with some random elements that I feel should be in my output list. This is what I come up with after reading the documentation:

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)

There are many problems with the above code:

  1. if 'some' is not in self.mylist then expected and elements won't be checked and the AssertionError would be raised and python will move on to the next test. I want to know which of the elements ['some', 'expected', 'elements'] is not in, not just the first element that couldn't be found.

  2. It totally pollutes the stdout with the huge list, having to pipe it to a log to inspect it

Upvotes: 0

Views: 749

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

How about using sets (assuming oly distinct elements need to be checked):

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)

Upvotes: 1

Related Questions