pytest: xfail on given exception, pass otherwise
<p>I have a test that uses <code>requests</code> and needs an active connection.</p>

<p>I would like it to <code>xfail</code> if the connection is down but pass normally otherwise.</p>

<p>Here is what I tried:</p>

<pre><code>from requests import ConnectionError

@pytest.mark.xfail(raises=ConnectionError)
class TestStuff():
    def test_stuff():
        do stuff
</code></pre>

<p>This will indeed <code>xfail</code> if connection is down but it <code>xpass</code>es in the general case.</p>

<p>Is there any way to achieve what I want?</p>

<p>I can use a try/except:</p>

<pre><code>from requests import ConnectionError

class TestStuff():

    def test_stuff():
        try:
            do stuff
        except ConnectionError:
            pass
</code></pre>

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

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

<p>pytest supports imperative xfail from within a test or setup function.</p>

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

<p>See:
<a href="http://doc.pytest.org/en/latest/skipping.html#imperative-xfail-from-within-a-test-or-setup-function" rel="nofollow">http://doc.pytest.org/en/latest/skipping.html#imperative-xfail-from-within-a-test-or-setup-function</a></p>

python py.test