如何参数化 Pytest 夹具 [英] How to parametrize a Pytest fixture

查看:53
本文介绍了如何参数化 Pytest 夹具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 Pytest:

Consider the following Pytest:

import pytest

class TimeLine(object):
    instances = [0, 1, 2]

@pytest.fixture
def timeline():
    return TimeLine()

def test_timeline(timeline):
    for instance in timeline.instances:
        assert instance % 2 == 0

if __name__ == "__main__":
    pytest.main([__file__])

测试test_timeline 使用Pytest 固定装置timeline,它本身具有属性instances.此属性在测试中迭代,因此只有当断言对 timeline.instances 中的每个 instance 成立时,测试才通过.

The test test_timeline uses a Pytest fixture, timeline, which itself has the attribute instances. This attribute is iterated over in the test, so that the test only passes if the assertion holds for every instance in timeline.instances.

然而,我实际上想要做的是生成 3 个测试,其中 2 个应该通过,其中 1 个将失败.我试过了

What I actually would like to do, however, is to generate 3 tests, 2 of which should pass and 1 of which would fail. I've tried

@pytest.mark.parametrize("instance", timeline.instances)
def test_timeline(timeline):
    assert instance % 2 == 0

但这导致

AttributeError: 'function' object has no attribute 'instances'

据我所知,在 Pytest 固定装置中,函数变成"了它的返回值,但这在测试参数化时似乎还没有发生.如何以所需的方式设置测试?

As I understand it, in Pytest fixtures the function 'becomes' its return value, but this seems to not have happened yet at the time the test is parametrized. How can I set up the test in the desired fashion?

推荐答案

来自 在 pytest.mark.parametrize pytest issue 中使用 fixtures,看来目前无法在 pytest.mark.parametrize 中使用 fixtures.

From Using fixtures in pytest.mark.parametrize pytest issue, it would appear that it is currently not possible to use fixtures in pytest.mark.parametrize.

这篇关于如何参数化 Pytest 夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆