[英]How to apply fixture from conftest.py to inner folders only
我有一個位於 conftest.py 中的夾具。
@pytest.fixture(scope='module', autouse=True)
def my_fixture():
"""
Some useful code
"""
結構如下:
tests
|
|--first_folder
| |--__init__.py
| |--test_first_1.py
| |--test_first_2.py
|
|--second_folder
| |--__init__.py
| |--test_second_1.py
|
|--__init__.py
|--conftest.py
|--test_common_1.py
我希望該夾具僅在內部文件夾測試腳本中自動使用:在test_first_1.py 、 test_first_2.py 、 test_second_1.py中,但不在 test_common_1.py中。
我可以在每個內部文件夾中使用該夾具創建 conftest,但我不想復制代碼
有什么方法可以將 conftest 中的夾具應用到內部文件夾中的測試腳本並在公共文件夾測試腳本中忽略它?
一種可能的解決方案是您不想更改文件夾的結構,即您在夾具中使用request
object 來檢查測試中使用的標記,因此如果設置了特定標記,您可以執行任何操作:
@pytest.fixture(scope='module', autouse=True)
def my_fixture(request):
"""
Some useful code
"""
if 'noautofixt' in request.keywords:
return
# more code
然后將您的測試標記如下:
@pytest.mark.noautofixt
def test_no_running_my_fixture():
pass
您可以通過將文件夾“第一個文件夾”和“第二個文件夾”移動到一個新文件夾並在該新文件夾中有一個 conftest.py 文件來實現此目的。 像這樣 -
tests
|
|--new folder
| |--first_folder
| | |--__init__.py
| | |--test_first_1.py
| | |--test_first_2.py
| |
| |--second_folder
| | |--__init__.py
| | |--test_second_1.py
| |--conftest.py
|
|--__init__.py
|--conftest.py
|--test_common_1.py
如果您只想為測試模塊的子集自動使用頂級 conftest 固定裝置,則指導是使用全局變量pytestmark
(參考: pytestmark ;教程: 標記整個類或模塊)。
在您的情況下,您需要為在tests/conftest.py
autouse
定義的夾具禁用自動使用:
# tests/conftest.py
import pytest
@pytest.fixture(scope='module')
def my_fixture():
"""
Some useful code
"""
然后在您想要啟用自動使用的任何模塊中,設置全局變量pytestmark
例如
# tests/first_folder/test_first_1.py
import pytest
pytestmark = pytest.mark.usefixtures('my_fixture')
def test_first_feature():
result = something(my_fixture) # autouse of my_fixture
assert result == expected
@lmiuelvargasf 回答(+1)為我指明了正確的方向,並使用request
解決了以下問題:
@pytest.fixture(scope='module', autouse=True)
def my_fixture(request):
if request.config.invocation_dir.basename != 'tests':
"""
Some useful code
"""
此夾具僅適用於內部文件夾中的測試腳本,因為調用文件夾名稱不等於“測試”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.