【问题标题】:Using fixtures to skip a test in pytest使用fixtures跳过pytest中的测试
【发布时间】:2020-10-02 16:30:56
【问题描述】:

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

在测试运行之前(通常),生成对象的夹具被启动一次。 在测试之前,我需要一个易于使用的装饰器/夹具/任何东西来检查对象是否在对象内部具有所需的东西。

例子:

@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

【问题讨论】:

  • 嘿!我想知道您是否将一个夹具用于各种测试,这些测试可以划分为使用多个专门定制的夹具的测试。有什么想法吗?
  • 这个想法是夹具可以灵活地跨测试重用。因此,一般来说,当测试人员编写新测试时,他可以确保 info 对象具有所需的一切。在某些情况下,info 对象会丢失一个 attr,这是正常的。测试基于对象中的值,而不是对象是否有这个和那个。

标签: python-3.x testing pytest python-3.8


【解决方案1】:

我可以想到几种可能性来实现这一点,但没有一个看起来像你的例子那样干净。

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

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

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

@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

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

@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

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

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

【讨论】:

  • 感谢您的回答,但这不是我想要的。我正在寻找另一种方法 - 我们可以访问夹具测试中的变量吗?在测试开始时,我们可以使用所有需要的属性来 sepcify 一个元组,然后检查夹具是否存在。你怎么看?
  • 这就是该方法的作用——除了传递单个属性名称,您还可以传递一个元组(我将相应地更新答案)。但正如我所写,这看起来有点复杂 - 但这是我知道将测试参数传回夹具的唯一方法(例如,通过 request 夹具)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2019-02-14
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2019-01-16
  • 2018-01-22
相关资源
最近更新 更多