gpt4 book ai didi

python - 如何使用可调用作为 pytest parametrize() 参数?

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:55 24 4
gpt4 key购买 nike

有没有办法将可调用指定为pytest.mark.parametrize()参数,以便仅在测试时动态生成参数选择运行?

为了生成参数,我需要执行一些昂贵的操作,并且我只想在选择运行测试时执行这些操作。

例如,

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

最佳答案

我认为这符合您的要求 - 昂贵的计算位于 fixture 内部,仅在调用测试时才会调用,并且昂贵的计算仅执行一次:

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

关于python - 如何使用可调用作为 pytest parametrize() 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45578662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com