I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", name
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
Just use metaclasses, as seen here;
Output:
Following is my solution. I find this useful when: 1. Should work for unittest.Testcase and unittest discover 2. Have a set of tests to be run for different parameter settings. 3. Very simple no dependency on other packages import unittest
You can use
TestSuite
and customTestCase
classes.There's also Hypothesis which adds fuzz or property based testing: https://pypi.python.org/pypi/hypothesis
This is a very powerful testing method.
i use something like this:
The
parameterized
package can be used to automate this process:Which will generate the tests:
You can use nose-ittr plugin (
pip install nose-ittr
).It's very easy to integrate with existing tests, minimal changes (if any) are required. It also supports nose multiprocessing plugin.
Not that you can also have a customize
setup
function per test.It is also possible to pass
nosetest
parameters like with their build-in pluginattrib
, this way you can run only a specific test with specific parameter: