Reputation: 3582
I have the unittest that may run over some sequence, where I check results of some processing over the sequence. I don't care if there are individual failures - as long as I can pinpoint on which element of sequence the processing did not yield good result. So, instead of writing
class MyTectClass(unittest.TestCase):
.....
def TestOverSequence(self):
for elem in sequence:
<run a bunch of asserts>
I would like to have something like
class MyTectClass(unittest.TestCase):
def __init__(self):
super().__init__()
self.sequence_iter = iter(sequence)
def TestOverElem(self):
elem = next(self.sequence_iter)
<run a bunch of asserts>
Is it doable, and if it is - how?
Thanks in advance
PS I may issue warnings - but I would rather have failed test cases.
Upvotes: 2
Views: 541
Reputation: 3582
Thanks to all who've tried to help, but after looking at the documentation again, I've found exactly what I need - unittest.subTest() context manager.
I should have seen it in the first place
class MyTectClass(unittest.TestCase):
def _some_test(**kwargs):
.......
def TestOverSequence(self):
for elem in sequence:
with self.subTest(elem=elem)
self._some_test(elem=elem)
Thanks for looking over my shoulder LOL (you know, sometimes to find the answer you need someone to look over your shoulder)
Upvotes: 0
Reputation: 23
That, what you are talking about, is called parametric testing. You add some annotational parameters to your tests, and test system repeats test with accordance to your parameters. In your example it would be a list of values, and test system would repeat test for each of them.
Looks like python still has not such feature in it's testing system: https://bugs.python.org/issue7897
But I found some self help solution here https://gist.github.com/mfazekas/1710455
I also found that separate testing framework pytest has some support for parametric testing https://docs.pytest.org/en/latest/example/parametrize.html
Upvotes: 2
Reputation: 16733
If you want to assert separately, then why use a loop in first place?
So either mention all asserts
separately or try to add the message to assert statements to identify which one has failed.
# ...
def testOverSequence(self):
for elem in sequence:
self.assertEqual(elem, 3, "{} is not equal to 3".format(elem)) # for instance
# Something on these lines
Upvotes: 0