2012-07-24 35 views
2

我想縮小pytest xfail標記的範圍。正如我目前使用它,它標誌着整個測試功能,任何失敗的功能都很酷。在py.test中,如何縮小xfail標記的範圍?

我想縮小到一個較小的範圍,也許與上下文管理器類似於「pytest.raises(module.Error)」。例如:

@pytest.mark.xfail 
def test_12345(): 
    first_step() 
    second_step() 
    third_step() 

如果我在我調用的三種方法中的任何一種中聲明,則此測試將xfail。我希望只有當它在second_step()中聲明時,xfail纔會進行測試,而不是其他地方。這樣的事情:

def test_12345(): 
    first_step() 
    with pytest.something.xfail: 
     second_step() 
    third_step() 

這可能與py.test?

謝謝。

回答

3

您可以定義做它一個上下文管理自己,是這樣的:

import pytest 

class XFailContext: 
    def __enter__(self): 
     pass 
    def __exit__(self, type, val, traceback): 
     if type is not None: 
      pytest.xfail(str(val)) 
xfail = XFailContext() 

def step1(): 
    pass 

def step2(): 
    0/0 

def step3(): 
    pass 

def test_hello(): 
    step1() 
    with xfail: 
     step2() 
    step3() 

當然,你也可以修改contextmanager尋找特定的異常。 唯一需要注意的是,你不能導致「xpass」結果,即(測試的一部分)意外通過的特殊結果。

+1

這與您所描述的完全相同。由於xpass漏洞,它並不完美,但它比我所處理的要好得多。謝謝! – 2012-07-26 10:58:51