Unit Test in Python with Two Lists

I am doing a Unit Test in Python, where I am trying to check if elements are inside two lists in a specific range from each other. The two lists that I am considering are yields and list_of_yields and are considering doing self.assertEqual(round(yields-list_of_yields, 7), 0) . However, it - an unsupported type for lists, so my two problems are: checking if the elements are in a certain range and how to perform an assert for several elements, since I was told that with multiple asserts this is bad practice. I saw this answer , but my question is a little different.

thanks

+4
source share
2 answers

If the elements must be matched in the order in which they appear, you can create a utility function that accepts parameters and checks that they satisfy some condition:

 def close_round(item1, item2, rounding_param): """Determines closeness for our test purposes""" return round(item1, rounding_param) == round(item2, rounding_param) 

Then you can use this in a test case as follows:

 assert len(yields1) == len(list_of_yields) index = 0 for result, expected in zip(yields, list_of_yields): self.assertTrue(close_round(result, expected, 7), msg="Test failed: got {0} expected {1} at index {2}".format(result, expected, index)) index+=1 

You may find this type of template useful, in which case you could create a function that does this:

 def test_lists_close(self, lst1, lst2, comp_function): """Tests if lst1 and lst2 are equal by applying comp_function to every element of both lists""" assert len(lst1) == len(lst2) index = 0 for result, expected in zip(yields, list_of_yields): self.assertTrue(comp_function(result, expected), msg="Test failed: got {0} expected {1} at index {2}".format(result, expected, index)) index+=1 

If you have used it a lot, you probably want to check this feature as well.

+1
source

Here's a functional approach

 assert(0 == (reduce(lambda a,b:a+b, map(lambda c:round(c[0]-c[1], 7), zip(yields, list_of_yeilds)))) 

Violation of this: take the zip from yields and list_of_yields to get a list of pairs:

 [(yields[0], list_of_yields[0]), (yields[1], list_of_yields[1]), ...] 

Then map function lambda c:round(c[0]-c[1], 7) for each pair to get the yields and list_of_yields difference in pairs rounded to 7 decimal places.

 [round(yields[0] - list_of_yields[0], 7), round(yields[1] - list_of_yields[1], 7), ...] 

The last step is to check if any of the elements of this list is nonzero (in this case, the lists are not close enough). Just reduce with the addition and check against 0, and you're done.

 0 == round(yields[0] - list_of_yields[0], 7) + round(yields[1] - list_of_yields[1], 7) + ... 
0
source

All Articles