Skip to main content
 首页 » 编程设计

python之如何将 Django TestCases 收集到 TestSuites 中并运行它们

2025年05月04日24mfryf

与 this question我想出了如何打破对多个文件的测试。所以现在在每个文件/模块中我都有一系列的 TestCase 类。

我仍然可以通过从命令行显式命名它们来调用单个测试用例,例如:

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

与其单独调用相关的测试用例,现在我认为将相关的测试用例分组到套件中,然后从命令行调用整个套件会更好;希望不会失去一次调用应用程序中所有套件的能力。

我看过 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 测试用例安排到套件中并且可以告诉我如何做?

请您参考如下方法:

一种可能的方法是编写一个自定义运行器来扩展 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 的标签将导致所有模块中的测试/套件被添加到最终套件。

请注意,“模块:”标签不是应用程序标签,因此它必须是模块的完整 Python 路径。

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