我创建了一个“动态”参数列表,并将其传递给参数化。
OPTIONS = ['a', 'b', 'c']
def get_unique_pairs():
unique_list = []
for first in OPTIONS:
for second OPTIONS:
if first == second:
continue
unique_list.append({'first':first, 'second':second))
return unique_list
def some_func()
unique_pairs = get_unique_pairs()
result = []
for pair in unique_pair:
if test(pair):
continue
else:
result.append(pair)
return pair
@pytest.mark.parametrize('param', some_fnc())
def test_fnc(param):
first = param['first']
second = param['second']
我希望传递给 test_fnc
的输入是 [('a','b'),('a','c')...('c', 'b')]
其中第一个和第二个元素永远不会相同。我正在使用一些额外的逻辑来进一步删除特定的对。
当我运行测试时,我得到了输出:
::test_fnc[param0] PASSED
::test_fnc[param1] PASSED
::test_fnc[param2] PASSED
我有两个问题:
- 我不完全确定如何描述我正在做什么以查找更多文档/帮助。
- 我想要更具描述性的输出(即不是
param0
),并且我想继续使用字典将数据传递给测试。
最佳答案
我会这样写:
import pytest
import itertools
OPTIONS = ['a', 'b', 'c']
@pytest.mark.parametrize(
'param',
itertools.permutations(OPTIONS, 2),
ids=lambda pair: "first={}, second={}".format(*pair)
)
def test_fn(param):
first, second = param
assert first != second
结果:
> pytest --verbose
================================ test session starts =================================
platform linux2 -- Python 2.7.12, pytest-3.6.1, py-1.5.3, pluggy-0.6.0 -- /usr/bin/python
cachedir: .pytest_cache
rootdir: /home/paulos/work/lixo/tests, inifile:
collected 6 items
test_foo.py::test_fn[first=a, second=b] PASSED [ 16%]
test_foo.py::test_fn[first=a, second=c] PASSED [ 33%]
test_foo.py::test_fn[first=b, second=a] PASSED [ 50%]
test_foo.py::test_fn[first=b, second=c] PASSED [ 66%]
test_foo.py::test_fn[first=c, second=a] PASSED [ 83%]
test_foo.py::test_fn[first=c, second=b] PASSED [100%]
================================ 6 passed in 0.03 seconds ================================
[更新]
I think this answer is the solution I will use. Every day is a school day! (Out of curiosity is there a way I could be the 'param' into something like 'first, second' so to have test_foo(param) be test_foo(first, second). I'm not sure that actually helps anything... but I am curious – F. Elliot
如果您不介意使用 test_fn[a-b]
而不是 test_fn[a, b]
:
@pytest.mark.parametrize(
'first,second',
itertools.permutations(OPTIONS, 2),
)
def test_fn(first, second):
assert first != second
在实践中,我们并没有真正使用 --verbose
运行测试,所以大多数时候每个测试的输出只是一个点。
关于python - pytest动态参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817905/