比如我有这个测试数据:
PARAMS = {'pic1': [1, 2, 3], 'pic2': [14, 15], 'pic3': [100, 200, 300]}
我需要从这个 PARAMS
下载每个关键图片并生成单独的测试 [1, 2, 3]
,它将使用这个图片。之后,当 'pic1': [1, 2, 3]
对的每次测试结束时,删除图片,然后下载下一张,依此类推......
粗略地说,生成的测试应如下所示:
test_pic[pic1-1]
test_pic[pic1-2]
test_pic[pic1-3]
test_pic[pic2-14]
test_pic[pic2-15]
test_pic[pic3-100]
test_pic[pic3-200]
test_pic[pic3-300]
但里面会有下载图片的逻辑。
我没有找到在 pytest 中如何做的方法。
请帮忙。
最佳答案
对我来说,这看起来像是间接参数化的任务。
准备参数
首先要做的事情:pytest.mark.parametrize
期望参数作为元组列表传递,数据按参数名称排序,例如:
@pytest.mark.parametrize('spam,eggs', [(1, 2), (3, 4), (5, 6)])
将生成三个测试:
spam=1, eggs=2
,spam=3, eggs=4
,spam=5, eggs=6
。
因此您必须将 PARAMS
字典转换为元组列表,每个字典键一个数字。有很多方法可以做到这一点,一种解决方案是:
PARAMS = {'pic1': [1, 2, 3],
'pic2': [14, 15],
'pic3': [100, 200, 300]}
test_pic_params = [(key, el) for key, nums in PARAMS.items()
for el in nums]
@pytest.mark.parametrize('file,num', test_pic_params)
def test_pic(file, num):
assert True
检查测试是否正确生成:
$ pytest --collect-only --quiet test_spam.py
test_spam.py::test_pic[pic1-1]
test_spam.py::test_pic[pic1-2]
test_spam.py::test_pic[pic1-3]
test_spam.py::test_pic[pic2-14]
test_spam.py::test_pic[pic2-15]
test_spam.py::test_pic[pic3-100]
test_spam.py::test_pic[pic3-200]
test_spam.py::test_pic[pic3-300]
no tests ran in 0.07 seconds
间接参数化
现在你想在测试前处理file
参数,所以测试得到的是pic1
而不是pic1
的下载文件。这可以通过间接参数化来完成。你需要做的是:
- 实现一个名为
file
的 fixture(重要的是 fixture 与测试参数同名,否则pytest
将无法识别和应用它); - 将
indirect=['file']
添加到参数化标记。
这样,pic1
首先传递给 file()
fixture,然后 fixture 的结果传递给测试。扩展示例:
import pathlib
import pytest
PARAMS = {'pic1': [1, 2, 3],
'pic2': [14, 15],
'pic3': [100, 200, 300]}
test_pic_params = [(key, el) for key, nums in PARAMS.items()
for el in nums]
@pytest.fixture
def file(request):
pic = request.param
# this will just create an empty file named 'pic1' etc;
# replace it with file download logic
filename = pathlib.Path(pic)
filename.touch()
# pass filename instead of pic to test
yield filename
# after test finishes, we remove downloaded file
filename.unlink()
@pytest.mark.parametrize('file,num', test_pic_params, indirect=['file'])
def test_pic(file, num):
assert file.is_file()
编辑:
What I need is remove file
'pic1'
after teststest_pic[pic1-1] , test_pic[pic1-2], test_pic[pic1-3]
. Then download new filepic2
.
虽然这肯定是可能的,但请记住,这将违反单个测试运行的原子性,例如,您将失去并行运行测试的能力。
如果要跟踪测试运行的当前状态,只需在 fixture 中进行即可。当数字为对应列表的第一个时,下载文件;删除最后一个数字的文件:
@pytest.fixture
def file(request):
pic = request.param
num = request.node.callspec.params['num']
filename = pathlib.Path(pic)
if num == PARAMS[pic][0]: # download here
filename.touch()
yield filename
if num == PARAMS[pic][-1]: # remove here
filename.unlink()
IMO 的更好方法是使用 disk cache , 第一次下载时缓存文件;这将使测试再次原子运行。
关于python - 如何在pytest中进行依赖参数化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51337165/