Django:使用覆盖率运行测试

8

我正在尝试使用coverage运行Django测试。虽然它可以正常工作,但它无法检测到类定义,因为它们是在启动覆盖率之前定义的。我有以下测试运行器,我在计算覆盖率时使用:

import sys
import os
import logging

from django.conf import settings

MAIN_TEST_RUNNER = 'django.test.simple.run_tests'

if settings.COMPUTE_COVERAGE:
    try:
        import coverage
    except ImportError:
        print "Warning: coverage module not found: test code coverage will not be computed"
    else:
        coverage.exclude('def __unicode__')
        coverage.exclude('if DEBUG')
        coverage.exclude('if settings.DEBUG')
        coverage.exclude('raise')
        coverage.erase()
        coverage.start()
        MAIN_TEST_RUNNER = 'django-test-coverage.runner.run_tests'

def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    # start coverage - jeśli włączmy już tutaj, a wyłączymy w django-test-coverage,
    # to dostaniemy dobrze wyliczone pokrycie dla instrukcji wykonywanych przy
    # imporcie modułów
    test_path = MAIN_TEST_RUNNER.split('.')
    # Allow for Python 2.5 relative paths
    if len(test_path) > 1:
        test_module_name = '.'.join(test_path[:-1])
    else:
        test_module_name = '.'
    test_module = __import__(test_module_name, {}, {}, test_path[-1])
    test_runner = getattr(test_module, test_path[-1])
    failures = test_runner(test_labels, verbosity=verbosity, interactive=interactive)
    if failures:
        sys.exit(failures)

我该怎么做,才能将类也包含在覆盖率中?否则我的覆盖率会很低,我无法轻易地检测到真正需要覆盖的地方。

1个回答

9

最简单的方法是使用覆盖率执行测试运行器。如果你的运行器名称为“runner.py”,那么请使用以下命令:

coverage run runner.py

你可以将四个排除项放入一个 .coveragerc 文件中,这样你就可以享受到覆盖率代码的所有好处,而不必保留任何覆盖率代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接