Configure Django to find all doctests in all modules?

后端 未结 5 1911
终归单人心
终归单人心 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:17

    Thanks to Alex and Paul. This is what I came up with:

    # tests.py
    import sys, settings, re, os, doctest, unittest, imp
    
    # import your base Django project
    import myapp
    
    # Django already runs these, don't include them again
    ALREADY_RUN = ['tests.py', 'models.py']
    
    def find_untested_modules(package):
        """ Gets all modules not already included in Django's test suite """
        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 ALREADY_RUN]
        return [imp.load_module(file, *imp.find_module(file, package.__path__))
                 for file in files]
    
    def modules_callables(module):
        return [m for m in dir(module) if callable(getattr(module, m))]
    
    def has_doctest(docstring):
        return ">>>" in docstring
    
    __test__ = {}
    for module in find_untested_modules(myapp.module1):
        for method in modules_callables(module):
            docstring = str(getattr(module, method).__doc__)
            if has_doctest(docstring):
    
                print "Found doctest(s) " + module.__name__ + "." + method
    
                # import the method itself, so doctest can find it
                _temp = __import__(module.__name__, globals(), locals(), [method])
                locals()[method] = getattr(_temp, method)
    
                # Django looks in __test__ for doctests to run
                __test__[method] = getattr(module, method)
    

提交回复
热议问题