有没有办法跳过pytest夹具?

问题描述:

问题是我给定的fixture函数有一个外部依赖关系,导致一个“错误”(如无法访问的网络/资源不足等)。有没有办法跳过pytest夹具?

我想跳过夹具,然后跳过依赖此夹具的任何测试。

做这样的事情不会工作:

import pytest 

@pytest.mark.skip(reason="Something.") 
@pytest.fixture(scope="module") 
def parametrized_username(): 
    raise Exception("foobar") 
    return 'overridden-username' 

这将导致

_______________________________ ERROR at setup of test_username _______________________________ 

    @pytest.mark.skip(reason="Something.") 
    @pytest.fixture(scope="module") 
    def parametrized_username(): 
>  raise Exception("foobar") 
E  Exception: foobar 

a2.py:6: Exception 

什么是客场跳过pytest夹具的权利?

+0

你可以在'try/except'块中填入定义吗? –

+0

@PaulH - 测试将失败。那么我该如何跳过测试? –

+0

我想你将不得不单独标记测试或者测试类里面的东西,并且一举跳过 –

是的,你可以很容易地做到这一点:

import pytest 

@pytest.fixture 
def myfixture(): 
    pytest.skip('Because I want so') 

def test_me(myfixture): 
    pass 

$ pytest -v -s -ra r.py 
r.py::test_me SKIPPED 
=========== short test summary info =========== 
SKIP [1] .../r.py:6: Because I want so 

=========== 1 skipped in 0.01 seconds =========== 

内部,pytest.skip()函数抛出一个异常Skipped,这是从OutcomeException继承。这些例外情况专门用于模拟测试结果,但不能通过测试(类似于pytest.fail())。

+1

谢谢你的教育,@Sergey。 –