[英]How can I access a pytest fixture by a string?
pytest
固定裝置可以作為參數傳遞給其他固定裝置:
@pytest.fixture(scope='module')
def wrapper_fixture1(fixture1):
fixture1.do_something()
return fixture1
現在我有多個不同的燈具fixture1
, fixture2
和fixture3
它們是不同的,但有相似之處(如命名函數do_something()
我想申請到他們每個人。
但是,我沒有定義三個新的燈具(如示例中那樣),而是要定義一個通用的燈具/功能,該通用燈具/功能創建了三個燈具,可以傳遞給測試。 我在想這樣的事情:
def fixture_factory():
for index in range(3):
fixture = pytest.get_fixture('fixture%d'%(index+1))
fixture.do_something()
pytest.set_fixture('wrapper_fixture%d'%(index+1), fixture, scope='module')
能以某種方式做到嗎? 還是我必須為每個原始燈具編寫三個包裝器燈具,一遍又一遍地重復相同的代碼?
要通過字符串獲取燈具,可以在測試函數或其他燈具中使用request.getfuncargvalue()
。
您可以嘗試以下方法:
import pytest
@pytest.fixture
def fixture1():
return "I'm fixture 1"
@pytest.fixture(scope='module')
def fixture2():
return "I'm fixture 2"
@pytest.fixture(params=[1, 2])
def all_fixtures(request):
your_fixture = request.getfuncargvalue("fixture{}".format(request.param))
# here you can call your_fixture.do_something()
your_fixture += " with something"
return your_fixture
def test_all(all_fixtures):
assert 0, all_fixtures
您可能還需要查看pytest_generate_tests()
掛鈎( http://pytest.org/latest/plugins.html?highlight=generate_tests#_pytest.hookspec.pytest_generate_tests )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.