Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test same assertion for large amount of data

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)
like image 690
Mark Avatar asked Oct 12 '10 13:10

Mark


People also ask

Can a test case have multiple assertions?

you can have multiple asserts on the same object. they will usually be the same concept being tested.

Why is it recommended to have only one assert statement per test?

“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.

Can you have multiple assertEquals?

Yes it is possible to have more than one assertEquals in one unittest. The unit test fails if one of the assertEquals returns false.

How many assertions should be included in a Junit test?

I should definitely use only one assert in test method!


1 Answers

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)
like image 156
Mr. Deathless Avatar answered Oct 15 '22 18:10

Mr. Deathless