Search code examples
pythonnosetests

python nosetests equivalent of unittest Testsuite in the test file


In nosetests, I know that you can specify which tests you want to run via a nosetests config file as such:

[nosetests]
tests=testIWT_AVW.py:testIWT_AVW.tst_bynd1,testIWT_AVW.py:testIWT_AVW.tst_bynd3

However, the above just looks messy and becomes harder to maintain when a lot of tests are added, especially without being able to use linebreaks. I found it a lot more convenient to be able to specify which tests I want to run using unittests TestSuite feature. e.g.

def custom_suite():

    suite = unittest.TestSuite()
    suite.addTest(testIWT_AVW('tst_bynd1'))
    suite.addTest(testIWT_AVW('tst_bynd3'))
    return suite
if __name__=="__main__":

    runner = unittest.TextTestRunner()
    runner.run(custom_suite())

Question: How do I specify which tests should be run by nosetests within my .py file?
Thanks.
P.S. If there is a way to specify tests via a nosetest config file that doesn't force all tests to be written on one line I would be open to it as well, as a second alternative


Solution

  • I'm not entirely sure whether you want to run the tests programmatically or from the command line. Either way this should cover both:

    import itertools
    
    from nose.loader import TestLoader
    from nose import run
    from nose.suite import LazySuite
    
    paths = ("/path/to/my/project/module_a",
             "/path/to/my/project/module_b",
             "/path/to/my/project/module_c")
    
    def run_my_tests():
        all_tests = ()
        for path in paths:
            all_tests = itertools.chain(all_tests, TestLoader().loadTestsFromDir(path))
        suite = LazySuite(all_tests)
        run(suite=suite)
    
    if __name__ == '__main__':
        run_my_tests()
    

    Note that the nose.suite.TestLoader object has a number of different methods available for loading tests.

    You can call the run_my_tests method from other code or you can run this from the command line with a python interpreter, rather than through nose. If you have other nose configuration, you may need to pass that in programmatically as well.