2009-07-13 41 views
41

當使用Python的nosetests時,可以通過將測試函數的__test__屬性設置爲false來禁用單元測試。我已經使用以下裝飾器實現了這一點:禁用Python nosetests

def unit_test_disabled(): 
    def wrapper(func): 
     func.__test__ = False 
     return func 

    return wrapper 

@unit_test_disabled 
def test_my_sample_test() 
    #code here ... 

但是,這具有將包裝調用爲單元測試的副作用。包裝將始終通過,但它包含在鼻子測試輸出中。是否還有另一種構造裝飾器的方法,以便測試不會運行,並且不會出現在鼻子測試輸出中。

回答

-17

我認爲你還需要將你的裝飾器重命名爲未經測試的東西。下面僅對第二次測試失敗,第一次測試不會顯示在測試套件中。

def unit_disabled(func): 
    def wrapper(func): 
     func.__test__ = False 
     return func 

    return wrapper 

@unit_disabled 
def test_my_sample_test(): 
    assert 1 <> 1 

def test2_my_sample_test(): 
    assert 1 <> 1 
+6

這些downvotes變得愚蠢。 – 2014-12-26 03:33:19

+7

爲什麼不刪除這個帖子並贏得你的'同伴壓力'徽章? – 2015-04-02 02:45:37

+1

這爲什麼這麼嚴重downvoted?推理不清楚。 – CaffeineConnoisseur 2015-10-02 00:44:46

30

還存在對nosetest一個skiptest插件,這將導致測試顯示在測試輸出中被跳過。下面是一個裝飾:

輸出示例:

$ nosetests tests 
.......................................................................... 
..................................S............. 
---------------------------------------------------------------------- 
Ran 122 tests in 2.160s 

OK (SKIP=1) 
54

您還可以使用unittest.skip裝飾:

import unittest 


@unittest.skip("temporarily disabled") 
class MyTestCase(unittest.TestCase): 
    ... 
4

你可以只啓動類,方法或函數的名稱用下劃線和鼻子會忽略它。

@nottest有它的用途,但我發現它不能很好地工作,當類相互派生和一些基類必須被鼻子忽略。這經常發生在我有一系列類似的Django視圖要測試時。他們經常分享需要測試的特徵。例如,只有具有特定權限的用戶才能訪問它們。我並沒有爲它們寫出相同的權限檢查,而是將這樣的共享測試放在其他類從其派生的初始類中。但問題是,基類只能由後面的類派生,並不意味着要自行運行。這裏的問題的一個例子:

from unittest import TestCase 

class Base(TestCase): 

    def test_something(self): 
     print "Testing something in " + self.__class__.__name__ 

class Derived(Base): 

    def test_something_else(self): 
     print "Testing something else in " + self.__class__.__name__ 

而且從流鼻水它的輸出:

$ nosetests test.py -s 
Testing something in Base 
.Testing something in Derived 
.Testing something else in Derived 
. 
---------------------------------------------------------------------- 
Ran 3 tests in 0.000s 

OK 

Base類包含在測試中。

我不能在Base上啪啪@nottest,因爲它會標記整個層次結構。事實上,如果您只需將@nottest添加到class Base前面的代碼中,那麼鼻子將不會運行任何測試。

我要做的就是在基類的前面加上一個下劃線:

from unittest import TestCase 

class _Base(TestCase): 

    def test_something(self): 
     print "Testing something in " + self.__class__.__name__ 

class Derived(_Base): 

    def test_something_else(self): 
     print "Testing something else in " + self.__class__.__name__ 

並運行它_Base時被忽略:

$ nosetests test3.py -s 
Testing something in Derived 
.Testing something else in Derived 
. 
---------------------------------------------------------------------- 
Ran 2 tests in 0.000s 

OK 

這種行爲是不是有據可查的,但代碼選擇測試explicitly checks for an underscore at the start of class names

類似的測試是通過在函數和方法名稱上進行的,所以可以通過在名稱的開頭添加下劃線來排除它們。