Search code examples
python-2.7nosetest-suiteunit-testing

How to write a test suite for nose


If i want to write an unit test, I just drop a file in my test/ subdirectory with my test class heriting from unittest.TestCase.

Now i want to use such pattern for a test suite: I have a python file in test/ with a class (extending unittest.TestSuite) which reads a file and generate test from it. I've already the code for parsing the file and generate the TestCase from them.

But nose does not detect this class. How can I make nose aware of this file and generate the tests from it ?


Solution

  • You don't specify the version of python you are using. With Python 2.7+ you can define a load_tests function in your module which will be called to create the TestSuite for the module.

    However, nose ignores the load_tests protocol. If you have nose2 then it features a plugin for the load tests protocol.

    Otherwise, you create a blank TestCase and populate with generated test functions. For instance:

    import unittest
    
    data = ["a", "b", "c"] # or from whatever source you want
    
    class GeneratedTests(unittest.TestCase):
    
        def setUp(self):
            self.correct = "b"
    
    def setup_module():
        for i, d in enumerate(data):
            test_driver = create_driver(d)
            name ="test_generated{}".format(i)
            setattr(GeneratedTests, name, test_driver)
    
    def create_driver(d):
        def test_driver(self):
            self.assertEqual(d, self.correct)
        return test_driver
    
    setup_module()
    

    One final way you can do this is to use the subtest context manager. This is only available in 3.4+. However, you can find a poor man's replacement here. Hopefully, it should help you structure your generated tests in a more readable fashion.