[英]PyTest : dynamically generating test name during runtime
當我使用@pytest.mark.parametrize("value",values_list)
夾具運行測試時,我想在運行時動態命名測試。 例如:
values_list=['apple','tomatoes','potatoes']
@pytest.mark.parametrize("value",values_list)
def test_xxx(self,value):
assert value==value
我想看到的最終結果是 3 個具有以下名稱的測試:
測試蘋果
test_tomatoes
test_potatoes
我嘗試查看 pytest 文檔,但我沒有找到任何可能闡明此問題的內容。
您可以通過重寫測試項的_nodeid
屬性來更改測試執行中顯示的名稱。 示例:在您的項目/測試根目錄中創建一個名為conftest.py
的文件,其內容如下:
def pytest_collection_modifyitems(items):
for item in items:
# check that we are altering a test named `test_xxx`
# and it accepts the `value` arg
if item.originalname == 'test_xxx' and 'value' in item.fixturenames:
item._nodeid = item.nodeid.replace(']', '').replace('xxx[', '')
運行您的測試現在將產生
test_fruits.py::test_apple PASSED
test_fruits.py::test_tomatoes PASSED
test_fruits.py::test_potatoes PASSED
請注意,覆蓋_nodeid
應謹慎使用,因為每個 nodeid 應保持唯一。 否則, pytest
會默默地放棄執行一些測試,很難找出原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.