Bhupesh Pant
Bhupesh Pant

Reputation: 4329

Fecthing unit test cases in python automatically

I am using Python's unittest with simple code like so:

suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module1))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module2))

I want my test suite to automatically parse all the modules and searches for all the unit test cases files that we have written? for e.g.

there are 5 files,

1). f1.py

2). f2.py

3). f3.py

4). f4.py

5). f5.py

we dont know which of this file is the unit test case file. I want a way through which each file will be parsed and only the name of the module that has unit test cases should be returned

NOTE:- I am using python 2.6.6 so could not really make use of unittest.TestLoaded.discover()

Upvotes: 0

Views: 493

Answers (2)

Joe Heffer
Joe Heffer

Reputation: 845

Use the discovery feature of the unittest library:

$ python -m unittest discover --start-directory my_project

Upvotes: 0

bereal
bereal

Reputation: 34252

Consider using the nose tool, it completely changes your unit-testing life. You just run it in the source folder root like:

> nosetests

then it automatically finds all the test cases.

If you want also run all the doctests, use:

> nosetests --with-doctest

In case if you only want to find a list of modules programmatically, nose provides some API (unfortunately, not as convenient as TestLoader.discover()).

UPDATE: I've just discovered (pun intended) that there is a library called unittest2 that backports all the later unittest features to the earlier versions of Python. I'll keep the code below for the archaeologists, but I think, unittest2 is a better way to go.

import nose.loader
import nose.suite
import types

def _iter_modules(tests):
    '''
    Recursively find all the modules containing tests.
    (Some may repeat)
    '''
    for item in tests:
        if isinstance(item, nose.suite.ContextSuite):
            for t in _iter_modules(item):
                yield t
        elif isinstance(item.context, types.ModuleType):
            yield item.context.__name__
        else:
            yield item.context.__module__

def find_test_modules(basedir):
   '''
   Get a list of all the modules that contain tests.
   '''
   loader = nose.loader.TestLoader()
   tests = loader.loadTestsFromDir(basedir)
   modules = list(set(_iter_modules(tests)))  # remove duplicates
   return modules

Upvotes: 2

Related Questions