Configure Django to find all doctests in all modules?

后端 未结 5 1889
终归单人心
终归单人心 2021-02-14 09:27

If I run the following command:

>python manage.py test

Django looks at tests.py in my application, and runs any doctests or unit tests in th

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-14 10:01

    Here're key elements of solution:

    tests.py:

    def find_modules(package):
        """Return list of imported modules from given package"""
        files = [re.sub('\.py$', '', f) for f in os.listdir(os.path.dirname(package.__file__))
                 if f.endswith(".py") and os.path.basename(f) not in ('__init__.py', 'test.py')]
        return [imp.load_module(file, *imp.find_module(file, package.__path__)) for file in files]
    
    def suite(package=None):
        """Assemble test suite for Django default test loader"""
        if not package: package = myapp.tests # Default argument required for Django test runner
        return unittest.TestSuite([doctest.DocTestSuite(m) for m in find_modules(package)])
    

    To add recursion use os.walk() to traverse module tree and find python packages.

提交回复
热议问题