这东西也是搞测试用的。同时,也需要明确一个问题,就是django的setting.py中是可以指定TEST_RUNNER的。这个东西很关键,只有指定了 TEST_RUNNER,是django_nose,然后最后在执行测试用例的时候,才用的是django_nose在跑测试用例。
在使用之前,肯定是下载django_nose包,完了肯定需要注册的:
INSTALLED_APPS = [
...
'django_nose'
]
然后在setting.py中设置一个参数:TEST_RUNNER
这个参数绑定的对象就是django-nose中的具体的执行类。下面是个例子,是属于包装了一下,对django_nose的runer进行了修饰,添加了其它的内容,这里就不完全展示了。
# machineweb models. See PR 612691.
SEARCH_ENGINE = 'postgresql'
TEST_RUNNER = 'webapps.testing.runner.Runner'
# Directory the scheduled build crontab files are stored in
SCHEDULES_CRON_D_DIR = '/build/apps/scheduler/cron.d'
from django.apps import apps
from django_nose.runner import NoseTestSuiteRunner
from webapps.testing import router
class Runner(NoseTestSuiteRunner):
'''
Custom test suite runner for the webapps testing needs.
First we reroute the models to their appropriate databases during the
creation of the test database. We drop the routing after that as it can
interfere with the database access during the actual tests.
当然也可以直接一些,让 TEST_RUNNER 直接绑定到位也行 :
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
然后,其他的用法就比较常规,这里补充一种用法。
在setting.py中,可以添加一个参数:NOSE_ARGS
这样一来,在执行测试的时候,nosetests 就会将这里的参数当作测试执行过程中的参数,一起执行,好处就是比较自动化一些。
NOSE_ARGS = [
'--with-coverage',
'--cover-package=webapps',
]
像这样添加以后,然后再执行测试命令时,命令中就会自动带上这几个参数。
def run_webapps_tests():
generate_global_config()
for test_module in ['build', 'build_scheduler', 'watchbuild']:
cmd = [
'python3', 'manage.py', 'test', test_module,
]
print(subprocess.check_output(cmd))
b'nosetests build_scheduler --with-coverage --cover-package=webapps --verbosity=1\n'
Creating test database for alias 'default'...
Creating test database for alias 'sb'...
Creating test database for alias 'machine'...
Creating test database for alias 'components'...
..
Coverage.py warning: Module webapps was previously imported, but not measured (module-not-measured)
Name Stmts Miss Cover
------------------------------------------------------------------------
webapps/__init__.py 5 2 60%
webapps/api/__init__.py 0 0 100%
webapps/apidocs/__init__.py 0 0 100%
webapps/apidocs/management/__init__.py 0 0 100%
webapps/build/__init__.py 1 0 100%
webapps/build/apps.py 6 0 100%
这样就可以在测试结果中自带coverage报告