2016-11-11 41 views
0

我在Django中編寫自定義測試運行器來添加自定義參數'--headless',但副作用是我不能使用一些默認參數。我正在使用Django 1.9.11。我的測試運行的代碼是:Django自定義測試運行器刪除一些默認的測試參數

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等一些參數。 如何添加自定義測試參數但不丟失默認測試參數?

回答

0

測試運行在的Django /核心/管理/命令/ 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方法。

所以解決的辦法是打電話給你父母的IbesTestRunner類的add_arguments,像這樣:

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) 
+0

感謝您的回答,它的工作。我想我需要學習更多關於python中的類。這是一個常見的python類的特性還是特定於django?爲什麼只有一些論點缺失? – pupil

+1

這是一個python的功能。當定義一個方法並用'classmethod'裝飾器對其進行裝飾時,正確的方法定義必須包含第一個參數(按照約定'cls'),那麼當你需要顯式地調用它時,python會將該類作爲'cls'參數,因此您只需發送其餘參數(如果方法定義需要)。有關詳細信息,請參閱文檔https://docs.python.org/2/library/functions.html?highlight=classmethod#classmethod – slackmart

相關問題