Django單元測試案例程式碼涵蓋範圍統計 – 自訂test runner

來源:互聯網
上載者:User

如何在Django中編寫單元測試案例,以及使用測試用的test_setting和test runner,見:django單元測試曆險記

代碼很好懂,不做什麼解釋了。如果需要拷過去,根據自己的需要修改一下,不是什麼難事。

test_settings.py

COVERAGE_MODULES = ['testapp.models', 'testapp.lib', 'testapp.common']

TEST_RUNNER  = 'testapp.testrunner.test_runner_with_coverage'

testrunner.py

代碼import os, shutil, sys, unittest

# Look for coverage.py in __file__/lib as well as sys.path
sys.path = [os.path.join(os.path.dirname(__file__), "lib")] + sys.path

from coverage import coverage
from inspect import getmembers, ismodule

from django.test.simple import run_tests as django_test_runner

from django.conf import settings

def get_all_coverage_modules(module_path):
    """
    Returns all possible modules to report coverage on, even if they
    aren't loaded.
    """
    app_path = module_path.split('.')
    app_package = __import__(module_path, {}, {}, app_path[-1])
    app_dirpath = app_package.__path__[-1]

    mod_list = []
    for root, dirs, files in os.walk(app_dirpath):
        root_path = app_path + root[len(app_dirpath):].split(os.path.sep)[1:]
        for file in files:
            if file.lower().endswith('.py'):
                mod_name = file[:-3].lower()
                try:
                    mod = __import__('.'.join(root_path + [mod_name]), {}, {},
                        mod_name)
                except ImportError:
                    pass
                else:
                    mod_list.append(mod)

    return mod_list

def test_runner_with_coverage(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """Custom test runner.  Follows the django.test.simple.run_tests() interface."""
    # Start code coverage before anything else if necessary
    cov = None
    if hasattr(settings, 'COVERAGE_MODULES'):
        cov = coverage()
        cov.use_cache(1) # Do not cache any of the coverage.py stuff
        #cov.exclude('if __name__ == .__main__.:')
        cov.start()

    test_results = django_test_runner(test_labels, verbosity, interactive, extra_tests)

    # Stop code coverage after tests have completed
    if hasattr(settings, 'COVERAGE_MODULES'):
        cov.stop()

        # Print code metrics header
        print ''
        print '----------------------------------------------------------------------'
        print ' Unit Test Code Coverage Results'
        print '----------------------------------------------------------------------'

    # Report code coverage metrics
    if hasattr(settings, 'COVERAGE_MODULES'):
        coverage_modules = []
        for module in settings.COVERAGE_MODULES:
            coverage_modules.extend(get_all_coverage_modules(module))

        cov.report(coverage_modules, show_missing=1)
        #cov.html_report(directory='covhtml')
        #cov.combine()
        cov.save()

        # Print code metrics footer
        print '----------------------------------------------------------------------'

    return test_results

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.