温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to parametrize a Pytest fixture
pytest python

python - 如何参数化Pytest灯具

发布于 2020-03-27 10:45:36

考虑以下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在测试中迭代该属性,以便仅在每个instancein 的断言均成立的情况下测试才通过timeline.instances

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

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

但这导致

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

据我了解,在Pytest固定装置中,函数“成为”其返回值,但是在对参数进行参数设置时,这似乎尚未发生。如何以所需的方式设置测试?

查看更多

查看更多

提问者
Kurt Peek
被浏览
15
35.3k 2020-01-20 23:32

pytest.mark.parametrize pytest中的使用固定装置问题来看,目前似乎无法在中使用固定装置pytest.mark.parametrize