[英]How to override a pytest fixture calling the original in pytest 4
我正在定義一個覆蓋django_db_setup
fixture的django_db_setup
fixture 。
為了安全起見,我已經設置了額外的拆卸,因為有使用此夾具的集成測試可能會產生進程並且有時需要進行清理以防止所有事情發生破壞。
這似乎是合理的,並且也在pytest docs中提出。 但是,我不想復制粘貼django_db_setup
的相同邏輯,因為我對已經存在的內容感到滿意。 但是,將其作為函數運行會引發棄用警告:
/usr/local/lib/python3.6/dist-packages/_pytest/fixtures.py:799:
RemovedInPytest4Warning: Fixture "django_db_setup" called directly.
Fixtures are not meant to be called directly, are created automatically
when test functions request them as parameters. See
https://docs.pytest.org/en/latest/fixture.html for more information.
在pytest 4中處理這種情況的推薦方法是什么? 我們是否鼓勵從我們想要覆蓋的燈具中復制粘貼代碼,或者是否有另一種“繼承”燈具的方法,並在調用之前和之后注入自定義行為?
要在調用初始夾具之前注入自定義行為,您可以使用此行為創建單獨的夾具,並在夾具的參數列表中的初始夾具之前使用它,該夾具覆蓋先前定義的:
@pytest.fixture(scope='session')
def inject_before():
print('inject_before')
@pytest.fixture(scope='session')
def django_db_setup(inject_before, django_db_setup):
print('inject_after')
使用自定義impl重新定義夾具有一個簡單的技巧。 只需在本地測試代碼中聲明一個具有相同名稱和簽名的fixture(我通常在項目根目錄中的conftest.py
中進行)。 例子:
# conftest.py
import pytest
@pytest.fixture(scope='session')
def django_db_setup(
request,
django_db_setup,
django_test_environment,
django_db_blocker,
django_db_use_migrations,
django_db_keepdb,
django_db_createdb,
django_db_modify_db_settings,
):
# do custom stuff here
print('my custom django_db_setup executing')
請注意,我在自定義django_db_setup
fixture中有django_db_setup
參數 - 這可以確保在自定義夾具之前調用原始夾具。
如果省略參數,自定義夾具將替換原始夾具,因此不會執行:
@pytest.fixture(scope='session')
def django_db_setup(
request,
django_test_environment,
django_db_blocker,
django_db_use_migrations,
django_db_keepdb,
django_db_createdb,
django_db_modify_db_settings,
):
print((
'my custom django_db_setup executing - '
'original django_db_setup will not run at all'
))
順便說一句,這是另一個方便的技巧,當你想要關閉其他地方定義的燈具時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.