Jérôme Jérôme - 1 month ago 13
Python Question

pytest: xfail on given exception, pass otherwise

I have a test that uses

requests
and needs an active connection.

I would like it to
xfail
if the connection is down but pass normally otherwise.

Here is what I tried:

from requests import ConnectionError

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


This will indeed
xfail
if connection is down but it
xpass
es in the general case.

Is there any way to achieve what I want?

I can use a try/except:

from requests import ConnectionError

class TestStuff():

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


but I get no xfail. The test always passes, but I'm not notified that it couldn't be performed properly.

I guess xfail is meant for systematic errors that may be fixed someday (broken lib,...), not for transient errors like connection errors.

Answer

pytest supports imperative xfail from within a test or setup function.

Use the try/except code you have, and include pytest.xfail('some message') in the except body.

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

Comments