在测试中初始化pytest测试对象,而不是在`参数化`/集合阶段

问题描述 投票:0回答:1

我运行了许多 pytest 测试

import pytest

from mymodule import fun1, fun2, fun3, fun4


@pytest.mark.parametrize(
    "arg",
    [
        fun1(),
        fun2(),
    ]
    + [fun3(n) for n in range(10)]
    + [fun4(n, model) for n in range(3, 7) for model in ["explicit", "implicit"]],
)
def test_foobar(arg):
    # lots of testing
    pass

有些

fun*
需要很长时间才能初始化,但我不知道是哪一个,因为初始化发生在 pytest collection 阶段。我宁愿将初始化移至函数本身而不添加太多样板代码

我如何实现这一目标?请注意,不同的

fun
方法具有不同的签名。

python pytest
1个回答
0
投票

将“thunk”(包装对其他函数的调用的零参数函数)作为参数而不是函数的结果传递,然后在测试中调用 thunk。

from functools import partial

@pytest.mark.parametrize(
    "arg",
    [
        partial(fun1),
        partial(fun2),
    ]
    + [partial(fun3, n) for n in range(10)]
    + [partial(fun4, n, model) for n in range(3, 7) for model in ["explicit", "implicit"]],
)
def test_foobar(arg):
    arg = [f() for f in arg]
    # lots of testing
    pass
© www.soinside.com 2019 - 2024. All rights reserved.