使用夹具跳过 pytest 中的测试 [英] Using fixtures to skip a test in pytest

查看:40
本文介绍了使用夹具跳过 pytest 中的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个巨大的对象,其中包含在夹具内启动的信息.我需要使用这些信息来运行我的测试,这里开始了棘手的部分.如果我在测试用例中使用的对象中没有属性,我必须跳过它.

So I have a huge object that holds information that is being initiated inside a fixture. I need to use this information to run my tests and here starts the tricky part. IF I do not have an attribute inside the object that is being used inside the test case I have to skip it.

在测试运行(一般情况下)之前,生成对象的夹具会被启动一次.在测试之前,我需要一个易于使用的装饰器/夹具/任何东西,以检查对象是否在对象内部具有所需的内容.

The fixture with the generation of the object is being initiated once before test runs (in general). I need an easy-to-use decorator/fixture/whatever before the test that will check if the object has what it is needed inside the object.

示例:

@pytest.fixture(scope="package")
def info(request):
    print("Setting up...")
    obj = Creator()
    obj.setup()
    obj.prepare() if hasattr(obj, "prepare") else ""
    def teardown():
        obj.teardown() if hasattr(obj, "teardown") else ""
    request.addfinalizer(teardown)
    return obj.call()

...

@has_attr("some_attr")
def test_sometest(info):
    assert info.some_attr == 42

推荐答案

我可以想到多种可能性来实现这一点,但没有一种看起来像您的示例那样清晰.

There are several possibilities I can think of to achieve this, none of which looks as clean as your example.

最简单的就是在测试中跳过:

The easiest one is just to do the skipping inside the test:

def test_something(info):
    if not hasattr(info, "some_attr"):
        pytest.skip("Missing attribute 'some_attr'")
    assert info.some_attr == 42

可能不是你想要的,但如果你没有很多测试,它可能是有意义的.如果您只想检查几个不同的属性,您可以为这些属性制作特定的装置:

Probably not what you want, but if you don't have many tests, it may make sense. If you have only a few different attributes you want to check, you can make specific fixtures for these attributes:

@pytest.fixture
def info_with_some_attr(info):
    if not hasattr(info, "some_attr"):
        pytest.skip("Missing attribute 'some_attr'")
    yield info

def test_something(info_with_some_attr):
    assert info_with_some_attr.some_attr == 42

如果你有更多的属性,你可以用属性名称来参数化夹具:

If you have more attributes, you can parametrize the fixture with the attribute names instead:

@pytest.fixture
def info_with_attr(request, info):
    if hasattr(request, "param"):
        for attr in request.param:
            if not hasattr(info, attr):
                pytest.skip(f"Missing attribute '{attr}'")
    yield info


@pytest.mark.parametrize("info_with_attr", [("some_attr", "another_attr")], indirect=True)
def test_something(info_with_attr):
    assert info_with_attr.some_attr == 42

这正是你想要的,虽然看起来有点尴尬.

This does exactly what you want, although it looks a bit awkward.

编辑:如评论中所述,更新了最后一个示例以使用元组而不是单个字符串.

Edit: Updated the last example to use a tuple instead of single string, as mentioned in the comments.

这篇关于使用夹具跳过 pytest 中的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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