有没有办法使用多返回值夹具运行测试函数?

发布于 2025-01-09 01:29:24 字数 853 浏览 1 评论 0原文

我有一个想要参数化的测试:

@pytest.mark.parametrize("param", [1,2])
def test(param):
    assert param==1

现在,如果我想让“param”具有复杂的逻辑,我可以这样做:

def f():
    return 1

def g(): # something dumb just to make a point
    for _ in range(100):
        pass
    return 1

@pytest.mark.parametrize("param", [f(), g()])
def test(param):
    assert param==1

但是,这将在测试运行之前运行“setup”函数,即

  1. f()
  2. g ()
  3. f() 的测试值
  4. g() 的测试值

我尝试将其作为多返回值固定装置:

@pytest.fixture
def param():
    for i in "12":
        yield i

def test(param):
    assert param==1

但这是非法的(拆卸时中断),所以现在我想象类似我展示的参数化的东西,但是与步骤2 & 3 交换顺序,这样我就有了 2 个独立的测试。

是否可以?

I have a test that I want to parametrize:

@pytest.mark.parametrize("param", [1,2])
def test(param):
    assert param==1

Now, if I want to have the "param" to have complex logic, I can do:

def f():
    return 1

def g(): # something dumb just to make a point
    for _ in range(100):
        pass
    return 1

@pytest.mark.parametrize("param", [f(), g()])
def test(param):
    assert param==1

However, this would run the "setup" functions before the test runs, i.e.

  1. f()
  2. g()
  3. test value of f()
  4. test value of g()

I tried to have it as a multi-return-value fixture:

@pytest.fixture
def param():
    for i in "12":
        yield i

def test(param):
    assert param==1

but this is illegal (breaks on teardown), so now I imagine something like the parametrize I showed, but with steps 2 & 3 swap the order so I have 2 stand-alone tests.

Is it possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叹倦 2025-01-16 01:29:24

一种可能性是使用间接参数化来推迟对运行时调用的固定装置的实际函数调用(与加载时评估的参数相反)。在您的情况下,您可以使用可调用对象作为参数:

@pytest.fixture
def param(request):
    fct = request.param  # f or g
    yield fct()


@pytest.mark.parametrize("param", [f, g], indirect=True)
def test(param):
    assert param == 1

在这种情况下,每个函数将在执行相应的测试之前被调用。

One possibility is to use indirect parametrization to defer the actual function call to a fixture called at runtime (as opposed to the parameters that are evaluated at load time). In your case, you could use the callables as parameters:

@pytest.fixture
def param(request):
    fct = request.param  # f or g
    yield fct()


@pytest.mark.parametrize("param", [f, g], indirect=True)
def test(param):
    assert param == 1

In this case, each function would be called just before the respective test is executed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文