Cha*_*ert 10 django doctest django-testing
如果我运行以下命令:
>python manage.py test
Run Code Online (Sandbox Code Playgroud)
Django在我的应用程序中查看tests.py,并在该文件中运行任何doctests或单元测试.它还会查看__ test __字典以运行额外的测试.所以我可以链接来自其他模块的doctests:
#tests.py
from myapp.module1 import _function1, _function2
__test__ = {
"_function1": _function1,
"_function2": _function2
}
Run Code Online (Sandbox Code Playgroud)
如果我想要包含更多doctests,那么在这本字典中是否有比简单列举更简单的方法?理想情况下,我只想让Django在myapp应用程序中查找所有模块中的所有doctests.
是否有某种反射黑客会让我到达我想去的地方?
感谢亚历克斯和保罗。这就是我想出的:
# 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1685 次 |
| 最近记录: |