2016-01-09 51 views
2

我坐下來今天更好地學習py.test,發現網站的文檔已關閉(pytest.org),所以我很抱歉如果在這裏找到了這個問題的答案。pytest中參數的輸出

我想要做的是兩場比賽的輸出傳遞到參數多態,像這樣:

import pytest 

@pytest.fixture() 
def make_1(): 
    return 1 

@pytest.fixture() 
def make_2(): 
    return 2 

@pytest.mark.parametrize('arg', [make_1, make_2]) 
def test_main(arg): 
    assert isinstance(arg, int) 

但測試失敗,因爲,而不是分配燈具參數「ARG」的輸出燈具(功能)本身被傳遞。

如何以這種方式參數化各種燈具的輸出?

+0

是否有一個原因,你不能讓'make_1'成爲一個普通的函數 - 它需要是一個燈具,因爲它使用其他燈具或什麼? –

+0

在參數化中不能使用fixtue。 https://bitbucket.org/pytest-dev/pytest/issues/349/using-fixtures-in-pytestmarkparametrize –

+0

這也是一個非常有用的解決方法:https://github.com/pytest-dev/pytest/issues/ 349#issuecomment-189370273 – derchambers

回答

1

這個[醜陋/大規模黑客]會訣竅嗎?我很欣賞它遠非理想 - 我不知道是否有辦法創建一個懶惰評估的燈具,讓你做你想做的事情。

import pytest 

@pytest.fixture 
def make_1(): 
    return 1 

@pytest.fixture 
def make_2(): 
    return 2 

@pytest.fixture 
def all_makes(make_1, make_2): 
    return (make_1, make_2) 

def _test_thing(make): 
    # Run your test 
    pass 

def test_main(all_makes): 
    for make in all_makes: 
     try: 
      _test_thing(make) 
     except AssertionError: 
      print "Failed for make {}".format(make) 
      raise 

一個可能是更好的替代方法可能是參數燈具本身(如果可能的話) - 參考文檔:https://pytest.org/latest/fixture.html#parametrizing-a-fixture

@pytest.fixture(params=[1, 2]) 
def make(request): 
    return request.param 

def test_make(make): 
    # Run your test 
    pass 

如果你的不同「使」燈具超級不同,你可以有像這樣:

def build_make_1(): 
    return 1 

def build_make_2(): 
    return 2 

@pytest.fixture(params=[build_make_1, build_make_2]) 
def make(request): 
    return request.param() 

def test_make(make): 
    # Run your test 
    pass 
+0

是的,使用夾具來調用函數,就像在你的最後一個例子中一樣,應該可以正常工作,並且編寫一個額外的夾具來收集和調用函數並不是什麼大不了的事情。感謝你的回答!我也檢查過,即使有多個使用它們的測試,看起來make作用域上的scope =「module」仍然只會調用每個函數。 – derchambers