如何设置pytest.参数自动id ?



我有一个参数化测试:

import pytest
@pytest.mark.parametrize('args', [
[1,2,3],
['a'],
[[],[1],['a']],
])
def test_bla(args):
assert all(args)

运行时,我得到以下输出:

platform linux -- Python 3.6.12, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 -- /home/bla/venv/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.6.12', 'Platform': 'Linux-4.15.0-132-generic-x86_64-with-Ubuntu-16.04-xenial', 'Packages': {'pytest': '6.0.2', 'py': '1.9.0', 'pluggy': '0.13.1'}, 'Plugins': {'metadata': '1.10.0'}}
rootdir: ...
plugins: metadata-1.10.0
collected 3 items                                                                                                                                                                                              
my_test.py::test_bla[args0] PASSED
my_test.py::test_bla[args1] PASSED
my_test.py::test_bla[args2] FAILED    <---------- Note that this is not very descriptive :(
=================================================================================================== FAILURES ===================================================================================================
_______________________________________________________________________________________________ test_bla[args2] ________________________________________________________________________________________________
args = [[], [1], ['a']]
@pytest.mark.parametrize('args', [
[1,2,3],
['a'],
[[],[1],['a']],
])
def test_bla(args):
>       assert all(args)
E       AssertionError: assert False
E        +  where False = all([[], [1], ['a']])
my_test.py:8: AssertionError
=========================================================================================== short test summary info ============================================================================================
FAILED my_test.py::test_bla[args2] - AssertionError: assert False
========================================================================================= 1 failed, 2 passed in 0.11s ==========================================================================================

我想要的是在输出中获得实际使用的参数,例如:

my_test.py::test_bla[args0] PASSED
my_test.py::test_bla[args1] PASSED
my_test.py::test_bla[[], [1], ["a"]] FAILED    <---------- Note the change here

这是我通过编辑parameterization:

得到的
pytest.param([[],[1],['a']], id='[], [1], ["a"]'),

是否有一种方法可以让pytest只是接受参数并使其成为id = str(param)?(基本上自动化了我刚刚在测试中编辑的内容)

可以将ID函数传递给@pytest.mark的ids参数。用参数表示修饰符:

import pytest
@pytest.mark.parametrize('args', [
[1,2,3],
['a'],
[[],[1],['a']],
], ids=str)
def test_bla(args):
assert all(args)

最新更新