有没有办法为pytest.mark.parametrize()
指定一个可调用的pytest
参数,以便只有在选择运行测试时动态生成参数?
为了生成参数,我要执行一些昂贵的操作,如果选择运行测试,我只想执行它们。
如,
import pytest
def my_callable():
# do expensive operations here
return [(1, 2), (3, 6)]
# I want my_callable to be called only if test_something
# has been selected to be run
@pytest.mark.parametrize("my_parm_1,my_parm_2", my_callable)
def test_something(my_parm_1, my_parm_2):
assert my_parm_1 * 2 == my_parm_2
答案 0 :(得分:1)
我认为这样做你想要的 - 昂贵的计算是在夹具内部,只有在调用测试并且昂贵的计算只进行一次时才会调用:
class TestSomething:
_result = None
@pytest.fixture()
def my_callable(self):
if TestSomething._result is None:
# do expensive operations here
TestSomething._result = [(1, 2), (3, 6)]
def _my_callable(run_number):
return TestSomething._result[run_number]
return _my_callable
@pytest.mark.parametrize("run_number", [0, 1])
def test_something(self, run_number, my_callable):
my_param_1, my_param_2 = my_callable(run_number)
assert my_param_1 * 2 == my_param_2
答案 1 :(得分:0)
您可以创建代理,而不是直接在mycallable
中使用@pytest.mark.parametrize
:
def my_callable():
# do expensive operations here
return [(1, 2), (3, 6)]
expensive_params = [paramset for paramset in my_callable()]
@pytest.mark.parametrize("my_parm_1,my_parm_2", expensive_params)
...