JavaSa
JavaSa

Reputation: 6242

Handling exception in pytest fixture and pytest.fail vs assert in general

Consider you have something like the following:

import pytest

@pytest.fixture
def foo_fixture():
    assert x == 1, "X is not 1"
    if x != 1:
        pytest.fail("X is not 1")


def test_foo():
    assert x == 1, "X is not 1"
    if x != 1:
        pytest.fail("X is not 1")

Can someone please shed light on differences between raising errors via pytest.fail vs assert,
in both contexts - inside pytest.fixture or inside regular test function.

What is the difference, what is more right\common to do in each case?

Thank in advance

Upvotes: 4

Views: 4180

Answers (1)

Tomer Cohen
Tomer Cohen

Reputation: 332

The biggest difference is that pytest.fail() can't be caught and assert can:

for example - this test is going to pass:

def test_assert():
    try:
        assert False
    except:
        pass

and this test is going to fail:

def test_pytest_fail():
    try:
        pytest.fail('failed')
    except Exception:
        pass

Other than that I don't think there are more major differences because they both raise an AssertionError.

Anyway, I would suggest you use this library https://pypi.org/project/assertpy/ for more cleaner and readable assertions.

**** EDIT: ****

Guess I was wrong:

pytest.fail() can be caught by catching the specific exception Failed or just 'BaseException.

So - they both are ways to raise exceptions but from some reason Failed does not inherit from the generic Exception type. so pytest.fail() raises Failed exception and not AssertionError

Upvotes: 5

Related Questions