pytest:xfail 给定异常,否则通过

pytest: xfail on given exception, pass otherwise

我有一个测试使用 requests 并且需要活动连接。

如果连接断开,我希望它xfail,否则可以正常通过。

这是我尝试过的:

from requests import ConnectionError

@pytest.mark.xfail(raises=ConnectionError)
class TestStuff():
    def test_stuff():
        do stuff

如果连接断开,这确实会 xfail,但在一般情况下会 xpass

有什么方法可以实现我想要的吗?

我可以使用 try/except:

from requests import ConnectionError

class TestStuff():

    def test_stuff():
        try:
            do stuff
        except ConnectionError:
            pass

但我没有 xfail。测试总是通过,但我没有收到无法正常执行的通知。

我猜 xfail 是针对有朝一日可能会修复的系统错误(损坏的库等),而不是针对连接错误等暂时性错误。

pytest 在测试或设置函数中支持命令式 xfail。

使用您拥有的 try/except 代码,并在 except 正文中包含 pytest.xfail('some message')

参见: http://doc.pytest.org/en/latest/skipping.html#imperative-xfail-from-within-a-test-or-setup-function

ConnectionError 被捕获时调用 xfail 是一个解决方案。

最好检查夹具中的连接(同样的方式 - try-except pytest.xfail)并在所有需要连接的测试中使用该夹具。

这样的话,这样的夹具将导致所有依赖测试失败,甚至没有 运行 它们。