如何将django测试用例收集到测试套件中并运行它们?

时间:2011-06-10 00:56:11

标签: python django unit-testing

使用this question我研究了如何在多个文件上打破我的测试。所以现在在每个文件/模块中我都有一系列的TestCase类。

我仍然可以通过从命令行显式命名它们来调用各个TestCase,如:

./manage.py test api.TokenGeneratorTestCase api.ViewsTestCase

现在我认为将相关的TestCase分组到套件中,然后从命令行调用整个套件,而不是单独调用相关的TestCase。希望不会失去同时调用应用程序中所有套件的能力。

我见过关于套房的this python stuff,还有关于套房的this django stuff,但是弄清楚如何做我想做的事情是难以捉摸的。我想我希望能够说出这样的话:

./manage.py test api.NewSeedsImportTestCase api.NewSeedsExportTestCase
./manage.py test api.NewSeedsSuite
./manage.py test api.NewRoomsSuite
./manage.py test api

有没有人安排他们的Django TestCases进入套房,可以告诉我怎么做?

1 个答案:

答案 0 :(得分:1)

一种可能的方法是编写一个自定义运行器,它将扩展django.test.simple.DjangoTestSuiteRunner并覆盖build_suite方法。这就是Django生成test命令使用的套件的地方。

它获得一个参数test_labels,它对应于传递给命令的命令行参数。您可以通过允许从应加载测试的位置传递额外的模块路径来扩展其功能。像这样的东西应该做的伎俩(这只是为了演示方法,我没有测试代码):

from django.test.simple import DjangoTestSuiteRunner
from django.utils import unittest
from django.utils.importlib import import_module


class MyTestSuiteRunner(DjangoTestSuiteRunner):

    def build_suite(self, test_labels, extra_tests=None, *args, **kwargs):
        if test_labels:
            extra_test_modules = [label.lstrip('module:')
                                  for label in test_labels
                                  if label.startswith('module:')]
            extra_tests = extra_tests or []
            for module_path in extra_test_modules:
                # Better way to load the tests here would probably be to use
                # `django.test.siple.build_suite` as it does some extra stuff like looking for doctests.
                extra_tests += unittest.defaultTestLoader.loadTestsFromModule(import_module(module_path))

            # Remove the 'module:*' labels
            test_labels = [label for label in test_labels if not label.startswith('module:')]

        # Let Django do the rest
        return super(MyTestSuiteRunner, self).build_suite(test_labels, extra_tests, *args, **kwargs)

现在您应该能够像以前一样运行test命令,除了任何看起来像这个module:api.test.extra的标签将导致模块中的所有测试/套件被添加到最终套件。

请注意,'module:'标签不是app标签,因此它必须是模块的完整python路径。

您还需要将TEST_RUNNER设置指向新的测试运行员。