首页 > 解决方案 > 是否可以为参数化生成输入?

问题描述

我有一组相当大的参数来运行几个测试用例。如果可能的话,我宁愿将集合放在其他地方而不是在参数化语句中,填充参数化。这种方式参数化几个测试用例不会有重复的大块测试用例参数。

如果那不可能,是否有另一种方法可以“共享”这个参数化?为了避免重复装饰受影响的测试用例?

import pytest

# this data structure has about 20 of these
@pytest.mark.parametrize("a, b, c" [('hello' [(1,1), ('abc','abc')],[(1, 2)]....)
def test_case_a(a, b, c):

# the same data and arguments as test_case_a
@pytest.mark.parametrize("a, b, c" [('hello' [(1,1), ('abc','abc')],[(1, 2)]....)
def test_case_b(a, b, c):

标签: pythonpytest

解决方案


只需将您的共享参数放在全局变量中:

测试.py

import pytest

SHARED_PARAMS = "a, b, c", [['hello', [(1, 1), ('abc', 'abc')], [(1, 2)]]]

@pytest.mark.parametrize(*SHARED_PARAMS)
def test_case_a(a, b, c):
    pass

@pytest.mark.parametrize(*SHARED_PARAMS)
def test_case_b(a, b, c):
    pass

执行结果:

$ pytest -v
=========================== test session starts =========================
platform linux -- Python 3.7.0, pytest-3.6.2, py-1.5.4, pluggy-0.6.0 
-- /home/user/.virtualenvs/test3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /home/user/projects/so, inifile:
collected 2 items

so/test_api.py::test_case_a[hello-b0-c0] PASSED
so/test_api.py::test_case_b[hello-b0-c0] PASSED

======================== 2 passed in 0.01 seconds =======================

推荐阅读