[英]How to conditionally skip instantiation of fixture in pytest?
問題:
我有一個需要大約 5 分鍾來實例化的夾具。 這個夾具依賴於我無法觸摸的另一個 package 的夾具。 取決於不同(必須更快實例化)夾具的 state,夾具的時間可以大大加快。 例如,這是我想要做的偽代碼:
@pytest.fixture()
def everyday_fixture(slow_fixture, fast_fixture):
if fast_fixture.is_usable():
yield fast_fixture
else:
slow_fixture.instantiate()
yield slow_fixture
這是 pytest 的特性嗎? 我曾嘗試直接調用固定裝置,但這也是不允許的。
您可以使用“工廠作為夾具”模式:
@pytest.fixture()
def fast_fixture():
def _fast_fixture():
return fast_fixture_data
return _fast_fixture
@pytest.fixture()
def slow_fixture():
def _slow_fixture():
return slow_fixture_data
return _slow_fixture
@pytest.fixture()
def everyday_fixture(slow_fixture, fast_fixture):
if fast_fixture():
yield fast_fixture()
else:
yield slow_fixture()
我會為此使用request
夾具。
@pytest.fixture
def everyday_fixture(request, fast_fixture):
if fast_fixture.is_usable():
yield fast_fixture
else:
slow_fixture = request.getfixturevalue("slow_fixture")
slow_fixture.instantiate()
yield slow_fixture
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.