2012-09-11 28 views
3

通過py.test,我經常生成測試,其中一些測試用例預計會失敗。我如何將它們標記爲xfail?如果我將@py.test.mark.xfail放在測試函數上,則意味着它的所有實例都是xfail。如果我在測試中做py.test.xfail()它實際上不通過測試,不只是將它標記爲xfail。有什麼我可以用metafunc來添加這個標記嗎?如何將一些生成的測試標記爲xfail/skip?

例如

# code - function with a bug :) 

def evenHigherThanSquare(n): 
    return n**2 


# test file 

def pytest_generate_tests(metafunc): 
    data = [ 
     (2, 4), 
     (3, 10), # should be xfail 
     (4, 16), 
     (5, 26), # should be xfail 
     ] 
    for input, expected in data: 
     if metafunc.function is test_evenHigherThanSquare: 
      metafunc.addcall(funcargs=dict(input=input, expected=expected)) 


def test_evenHigherThanSquare(input, expected): 
    assert evenHigherThanSquare(input) == expected 
+0

看起來很複雜。它可以用更簡單的方法重寫嗎?就像使用應該傳遞的值列表和應該失敗的值列表創建一個測試。 – demalexx

+0

@demalexx這個例子確實是過度工程,但它只是一個最小的工作示例。在我的實際測試中,測試數據和測試本身還有很多事情要做。 – pfctdayelise

回答

3

當然,你可以使用一個funcarg factoryapply an xfail marker(since 1.3.2)

def pytest_generate_tests(metafunc): 
    data = [ 
     # input # output # is expected to fail? 
     (2, 4, False), 
     (3, 10, True), 
     (4, 16, False), 
     (5, 26, True), 
     ] 
    for input, expected, xfail in data: 
     if metafunc.function is test_evenHigherThanSquare: 
      metafunc.addcall(funcargs=dict(input=input, expected=expected), 
          param=xfail) 


def pytest_funcarg__xfail(request): 
    if request.param: 
     request.applymarker(py.test.mark.xfail) 


def test_evenHigherThanSquare(input, expected, xfail): 
    assert evenHigherThanSquare(input) == expected 

這裏我們使用未使用xfail參數test_evenHigherThanSquare觸發的pytest_funcarg__xfail每個測試項目的調用;它使用提供給metafunc.addcallparam來決定是否對測試進行xfail。

Funcarg工廠更常用於生成在收集時創建昂貴的參數,但應用標記也是完全支持的用法。

+0

非常感謝你!這太棒了。 – pfctdayelise

相關問題