2012-03-08 51 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年前问:) :)

相关问题