2010-01-14 42 views

回答

95

使用裝飾器unittest.skip可以禁用單獨的測試方法或類。

@unittest.skip("reason for skipping") 
def test_foo(): 
    print('This is foo test case.') 


@unittest.skip # no reason needed 
def test_bar(): 
    print('This is bar test case.') 

有關其他選項,請參閱文檔Skipping tests and expected failures

+5

在Python 3中,Akif的答案在'@ unittest.SkipTest'下面起作用,而不是'@ unittest.skip' – lifebalance 2017-05-13 18:48:22

+1

我使用Python 3.6.1和'@ unittest.skip'也很好。 – Pete 2017-06-13 13:15:01

+1

@Pete,在Python 3.4.0中,'@ unittest.skip'不起作用。 – lifebalance 2017-07-09 06:17:26

2

2.1的docs沒有指定忽略或跳過方法。

雖然我通常會在需要時阻止評論。

+0

Noufal提出了一個很好的觀點,即將該名稱起作用。 – Finglas 2010-01-14 18:33:20

9

The latest version (2.7 - unreleased) supports test skipping/disabling like so。你可以獲得這個模塊並在現有的Python安裝中使用它。它可能會工作。

在此之前,我曾經將我想要的測試重新命名爲xtest_testname,從test_testname


這是一個快速的elisp腳本來做到這一點。我的elisp有點生疏,所以我提前爲任何問題道歉。未經測試。

(defun disable_enable_test() 
    (interactive "") 
    (save-excursion 
    (beginning-of-line) 
    (search-forward "def") 
    (forward-char) 
    (if (looking-at "disable_") 
    (zap-to-char 1 ?_) 
     (insert "disable_")))) 
+0

+1,但在我工作的整個項目中,大家都在使用python v2.6.2,我不認爲這會改變:/,但這是一個解決方案,謝謝 – coelhudo 2010-01-14 18:36:42

+0

現在正在重命名。謝謝 – coelhudo 2010-01-14 18:37:30

+0

你可以稍微調整一下你的編輯器給你一個宏來啓用/禁用一個測試用例,但是我作爲一個Emacs用戶說話,所以...... :) – 2010-01-14 18:42:45

22

你可以用裝飾來禁用它可以包含的功能和防止googletest或Python單元測試運行測試用例的測試。

def disabled(f): 
    def _decorator(): 
     print f.__name__ + ' has been disabled' 
    return _decorator 

@disabled 
def testFoo(): 
    '''Foo test case''' 
    print 'this is foo test case' 

testFoo() 

輸出:

testFoo has been disabled 
4

我剛重命名測試用例方法以下劃線:test_myfunc變得_test_myfunc。

5

簡單地將@unittest.SkipTest裝飾器放在測試上面就足夠了。

+0

我不知道是誰做的。但是,我正在閱讀文檔,它說SkipTest是一個例外。無論如何,它與unittest.skip的不同之處在於skip從不執行測試(使其被禁用),而如果在測試執行期間不期望發生某些事情時會引發SkipTest目的,則它將被引發。我對嗎?有趣的強硬。 – coelhudo 2017-02-24 08:20:13

+0

'unittest.skip'(無理由)在Python 2中給我錯誤,但在Python 3中沒有。 – Akif 2017-02-27 09:35:35