2012-03-08 49 views
8

鼻子插件有一個現有的插件,它可以像使用:的預期,失敗

@nose.plugins.expectedfailure 
def not_done_yet(): 
    a = Thingamajig().fancynewthing() 
    assert a == "example" 

如果測試失敗,它會看起來像一個跳過測試:

$ nosetests 
...S.. 

..但如果意外通過,這將同樣出現了故障,也許像:

like SkipTest
================================= 
UNEXPECTED PASS: not_done_yet 
--------------------------------- 
-- >> begin captured stdout << -- 
Things and etc 
... 

,但不imple作爲阻止測試運行的例外。

我能找到的唯一的事情是this ticket關於支持unittest2 expectedFailure裝飾(雖然我寧可不使用unittest2,即使鼻子支持它)

回答

11

我不知道鼻子插件,但你可以輕鬆編寫你自己的裝飾器來做到這一點。這裏有一個簡單的實現:

import functools 
import nose 

def expected_failure(test): 
    @functools.wraps(test) 
    def inner(*args, **kwargs): 
     try: 
      test(*args, **kwargs) 
     except Exception: 
      raise nose.SkipTest 
     else: 
      raise AssertionError('Failure expected') 
    return inner 

如果我運行這些測試:

@expected_failure 
def test_not_implemented(): 
    assert False 

@expected_failure 
def test_unexpected_success(): 
    assert True 

我從鼻子以下的輸出:

tests.test.test_not_implemented ... SKIP 
tests.test.test_unexpected_success ... FAIL 

====================================================================== 
FAIL: tests.test.test_unexpected_success 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "C:\Python32\lib\site-packages\nose-1.1.2-py3.2.egg\nose\case.py", line 198, in runTest 
    self.test(*self.arg) 
    File "G:\Projects\Programming\dt-tools\new-sanbi\tests\test.py", line 16, in inner 
    raise AssertionError('Failure expected') 
AssertionError: Failure expected 

---------------------------------------------------------------------- 
Ran 2 tests in 0.016s 

FAILED (failures=1) 
+0

哦,當然了!如果測試失敗,它會提高SkipTest,這是完美的 - 謝謝\ o/ – dbr 2012-03-08 12:08:17

3

原諒我,如果我誤解了,但是,這不是「T你想要通過Python核心的unittest庫與expectedFailure裝飾提供的行爲,這是 - 通過擴展兼容nose

對於使用的一個例子見docspost about its implementation

+0

是的,這是真的,但我喜歡的一個關於鼻子的東西是能夠將測試編寫爲函數,而不是將子類的方法編寫爲通過內置的單元測試模塊所需(如:'高清test_exampleblah():pass') – dbr 2014-08-13 13:37:39

+2

如果是這樣的問題,那麼也許你想['pytest'(http://pytest.org/latest/contents.html)它是[兼容'nose'](http://pytest.org/latest/nose.html),也支持[測試作爲功能](http://pytest.org/latest/assert.html#asserting-with -the-斷言語句),並具有['xfail'](http://pytest.org/latest/skipping.html#mark-a-test-function-as-expected-to-fail)裝飾。 – 2014-08-16 14:55:53

+2

根據我的經驗,'unittest.expectedFailure'是*不*用鼻子兼容。 [鼻子錯誤33](https:// github。com/nose-devs/nose/issues/33)同意。 – 2014-11-14 21:35:25

-2

您可以通過以下兩種方法之一做到這一點:

  1. nose.tools.raises裝飾

    from nose.tools import raises 
    
    @raises(TypeError) 
    def test_raises_type_error(): 
        raise TypeError("This test passes") 
    
  2. nose.tools.assert_raises

    from nose.tools import assert_raises 
    
    def test_raises_type_error(): 
        with assert_raises(TypeError): 
         raise TypeError("This test passes") 
    

測試將失敗,如果異常沒有提出。我知道,3年前問:) :)

相關問題