I am using python unittest module to do a number of tests; however, it is very repetitive.
I have a lot of data that I want to run through the same test over and over, checking if correct. However, I have to define a test for every one.
For instance I want to do something similar to this. I know I could do it using a generator (found it in a previous thread here). But are there alternatives, maybe even using a different testing module?
Any suggestions would be great.
import unittest
class TestData(unittest.TestCase):
def testNumbers(self):
numbers = [0,11,222,33,44,555,6,77,8,9999]
for i in numbers:
self.assertEqual(i, 33)
you can have multiple asserts on the same object. they will usually be the same concept being tested.
“One assertion per test” is a wise rule to keep in mind, because it helps you have tests that fail for a specific reason, and drives you to focus on a specific behavior at a time.
Yes it is possible to have more than one assertEquals in one unittest. The unit test fails if one of the assertEquals returns false.
I should definitely use only one assert in test method!
As of Python 3.4 you can use unittest.TestCase.subTest(msg=None, **params)
context manager (documentation). This will allow you to achieve what you want by adding just one statement.
Here is your example modified to use subTest()
import unittest
class TestData(unittest.TestCase):
def testNumbers(self):
numbers = [0, 11, 222, 33, 44, 555, 6, 77, 8, 9999]
for i in numbers:
with self.subTest(i=i): # added statement
self.assertEqual(i, 33)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With