python - 带有自定义 id 函数的 pytest 参数化测试

标签 python python-2.7 pytest fixtures

我有一个参数化测试,它需要 str , 和 dict作为参数,所以如果我允许 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 "" ),它也会采用默认表示。有人可以让我知道为什么吗?

最佳答案

一种方法是移动您的 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详情。

关于python - 带有自定义 id 函数的 pytest 参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45879028/

相关文章:

python - 简单的 Numpy 向量化

python - 为什么RotatingFileHandler不继承日志格式?

python - 使用 Python 检查任意用户是否在管理员组中

python-2.7 - 在测试中 mock sleep

python - 如何用自定义字符串完全替换 pytest 输出以进行测试?

python - 从 pandas 中特定列的 DF 中提取最大值、最小值或标准差

python - 为什么我的程序停止响应?

python - 如何在Python中打印没有每三个字符的字符串?

python-2.7 - Pandas 将列表附加到列名列表

Django channel pytest 测试。 django.core.exceptions.ImproperlyConfigured。 .