Mark Mark - 4 months ago 8
Python Question

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)

Answer

In another post I stumbled accross Nose Tests It is more suited to data driven testing.


class Test_data():
    def testNumbers():
        numbers = [0,11,222,33,44,555,6,77,8,9999]
        for i in numbers:
            yield checkNumber, num

def checkNumber(num):
    assert num == 33

The above code does the exact same thing as my first post. No imports are needed, just write a python class.

You execute the tests by typing:

nosetests filename