2017-08-25 33 views
0

我有一個參數化測試,它需要strdict作爲參數,所以如果我允許pytest生成id,名稱看起來很奇怪。pytest參數化測試用自定義id函數

所以我雖然使用函數生成自定義ID,但它看起來沒有按預期工作。

def id_func(param): 
    if isinstance(param, str): 
     return param 


@pytest.mark.parametrize(argnames=('date', 'category_value'), 
         argvalues=[("2017.01", {"bills": "0,10", "shopping": "100,90", "Summe": "101,00"}), 
            ("2017.02", {"bills": "20,00", "shopping": "10,00", "Summe": "30,00"})], 
         ids=id_func) 
def test_demo(date, category_value): 
    pass 

我想它會返回這樣的事情

test_file.py::test_demo[2017.01] PASSED 
test_file.py::test_demo[2017.02] PASSED 

但它返回這一點。

test_file.py::test_demo[2017.01-category_value0] PASSED 
test_file.py::test_demo[2017.02-category_value1] PASSED 

有人可以告訴我這有什麼問題,或者有什麼辦法可以實現嗎?

更新: 我意識到有什麼問題,if_func將要求每個參數,如果我不會爲任何參數的默認功能回到str將被調用。我已修好,但那也很難看。

def id_func(param): 
    if isinstance(param, str): 
     return param 
    return " " 

現在它返回這樣的事情,

test_file.py::test_demo[2017.01- ] PASSED 
test_file.py::test_demo[2017.02- ] PASSED 

的問題是,即使我返回空字符串(即return "")所花費的默認表示。有人能告訴我爲什麼嗎?

回答

2

一種方法是將您的argvalues另一個變量,寫你的測試是這樣的:

import pytest 


my_args = [ 
     ("2017.01", {"bills": "0,10", "shopping": "100,90", "Summe": "101,00"}), 
     ("2017.02", {"bills": "20,00", "shopping": "10,00", "Summe": "30,00"}) 
] 


@pytest.mark.parametrize(
    argnames=('date', 'category_value'), argvalues=my_args, 
    ids=[i[0] for i in my_args] 
) 
def test_demo(date, category_value): 
    pass 

測試執行:

$ pytest -v tests.py 
================= test session starts ================= 
platform linux2 -- Python 2.7.12, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/kris/.virtualenvs/2/bin/python2 
cachedir: .cache 
rootdir: /home/kris/projects/tmp, inifile: 
collected 2 items          

tests.py::test_demo[2017.01] PASSED 
tests.py::test_demo[2017.02] PASSED 

============== 2 passed in 0.00 seconds =============== 

我認爲這是無法實現的功能( idfn),因爲如果它沒有爲對象生成標籤,則使用默認的pytest表示。
查看pytest site瞭解詳情。