Configure Django to find all doctests in all modules?

后端 未结 5 1913
终归单人心
终归单人心 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 09:59

    I'm not up to speed on Djano's testing, but as I understand it uses automatic unittest discovery, just like python -m unittest discover and Nose.

    If so, just put the following file somewhere the discovery will find it (usually just a matter of naming it test_doctest.py or similar).

    Change your_package to the package to test. All modules (including subpackages) will be doctested.

    import doctest
    import pkgutil
    
    import your_package as root_package
    
    
    def load_tests(loader, tests, ignore):
        modules = pkgutil.walk_packages(root_package.__path__, root_package.__name__ + '.')
        for _, module_name, _ in modules:
            try:
                suite = doctest.DocTestSuite(module_name)
            except ValueError:
                # Presumably a "no docstrings" error. That's OK.
                pass
            else:
                tests.addTests(suite)
        return tests
    

提交回复
热议问题