Django自定义测试运行器删除了一些默认的测试参数

时间:2016-11-11 06:25:17

标签: python django testing

我在Django中编写了一个自定义测试运行器来添加自定义参数'--headless',但副作用是我不能使用一些默认参数。我正在使用Django 1.9.11。我的测试运行代码是:

from django.test.runner import DiscoverRunner        
class IbesTestRunner(DiscoverRunner):
    @classmethod                                    
    def add_arguments(cls, parser):
        parser.add_argument(
            '--headless',
            action='store_true', default=False, dest='headless',
            help='This is custom optional arguments for IBES.'
            'Use this option to do browser testing without GUI')

使用此测试运行器时./manage.py test -h的结果是:

usage: manage.py test [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
                  [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                  [--noinput] [--failfast] [--testrunner TESTRUNNER]
                  [--liveserver LIVESERVER] [--headless]
                  [test_label [test_label ...]]
. . .

使用默认测试运行器时,./manage.py test -h的结果为:

usage: manage.py test [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
                  [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                  [--noinput] [--failfast] [--testrunner TESTRUNNER]
                  [--liveserver LIVESERVER] [-t TOP_LEVEL] [-p PATTERN]
                  [-k] [-r] [-d] [--parallel [N]]
                  [test_label [test_label ...]]
...

请注意,我不能使用某些参数,例如-k,-p,-r等。 如何添加自定义测试参数但不丢失默认测试参数?

1 个答案:

答案 0 :(得分:0)

测试运行器加载到 django / core / management / commands / test.py

class Command(BaseCommand):
    help = 'Discover and run tests in the specified modules or the current directory.'
    # ... more code goes here
    def add_arguments(self, parser):
        test_runner_class = get_runner(settings, self.test_runner)

        if hasattr(test_runner_class, 'add_arguments'):
            test_runner_class.add_arguments(parser)
    # ... more code goes here

Django将附加测试运行器中定义的参数,但add_argumentsclass method,除非您明确执行DiscoverRunner.add_arguments方法,否则将省略默认行为。

因此解决方法是拨打您父母add_arguments课程的IbesTestRunner,如下所示:

from django.test.runner import DiscoverRunner        
class IbesTestRunner(DiscoverRunner):
    @classmethod                                    
    def add_arguments(cls, parser):
        parser.add_argument(
            '--headless',
            action='store_true', default=False, dest='headless',
            help='This is custom optional arguments for IBES.'
                 'Use this option to do browser testing without GUI')
        # Adding default test runner arguments.
        # Remember python takes care of passing the cls argument.
        DiscoverRunner.add_arguments(parser)