有没有办法跳过 pytest 固定装置?

Sen*_*ran 7 pytest

问题是我给定的固定功能具有外部依赖性,这会导致“错误”(例如无法访问网络/资源不足等)。

我想跳过该夹具,并跳过任何依赖于该夹具的测试。

做这样的事情是行不通的:

import pytest

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

这将导致

_______________________________ 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
Run Code Online (Sandbox Code Playgroud)

跳过 pytest 固定装置的正确方法是什么?

Ser*_*yev 9

是的,您可以轻松做到这一点:

import pytest

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

def test_me(myfixture):
    pass
Run Code Online (Sandbox Code Playgroud)
$ 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 ===========
Run Code Online (Sandbox Code Playgroud)

在内部,pytest.skip()函数引发异常Skipped,该异常继承自OutcomeException. 这些异常经过特殊处理以模拟测试结果,但不会导致测试失败(类似于pytest.fail())。