2017-08-25 134 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了解详情。