This rule raises an issue when assertion statements, assertion methods, or fluent assertions are placed within a try block whose except clause catches AssertionError, one of its parent classes, or every exception, and does not re-raise it.

Why is this an issue?

Assertions in Python raise an AssertionError when they fail. This includes built-in assert statements, unittest assertion helpers such as assertEqual, and fluent assertions from libraries such as assertpy. This is the mechanism testing frameworks use to detect test failures.

Such an except clause swallows the AssertionError instead of letting it reach the test framework. The assertion can still fail, but nothing reports it, so the test passes when it should have failed.

This defeats the entire purpose of writing assertions in tests. The test appears to pass, giving false confidence that the code works correctly, when in reality the assertion failed and detected a problem.

The root cause of this anti-pattern is usually a misunderstanding of exception handling in tests. Developers might add try-except blocks around assertions thinking they need to "handle" exceptions, but assertions are meant to propagate upward to the test framework.

This issue commonly occurs when:

What is the potential impact?

When assertions are silently caught and ignored, tests provide false confidence in the codebase. Code that should fail tests will appear to pass, allowing bugs to reach production.

This can lead to:

Exceptions

No issue is raised when the except clause re-raises the exception, or when it catches only types that cannot match an AssertionError. Assertions guarded by an except* clause are not reported either.

Some test helpers catch AssertionError deliberately. A soft-assertion helper, for instance, records several failures and re-raises them once every check has run. Review such code instead of rewriting it: the pattern is sound as long as the failures still reach the test framework, and removing the try-except would change how the helper reports them.

An issue is still raised when a nested except clause re-raises the AssertionError but an enclosing one swallows it, because the failure never reaches the test framework.

Before changing a test, check where the caught AssertionError can come from. If it can only be raised by the code under test, and never by the assertion itself, the rule does not apply and the issue is a false positive worth reporting. If the assertion really can be swallowed but your team accepts it, for example in a legacy test that is already scheduled for deletion, the issue is a deliberate trade-off rather than a false positive.

How to fix it in unittest

Code examples

Noncompliant code example

The try-except block is there to skip the test when the configuration cannot be read, but except Exception also catches the AssertionError raised by assertEqual. As a result, the test is reported as skipped instead of failed when the timeout has the wrong value.

import unittest

class MyTest(unittest.TestCase):
    def test_timeout_is_configured(self):
        try:
            self.assertEqual(load_config()["timeout"], 30)  # Noncompliant: this AssertionError is caught by the except clause below
        except Exception:
            self.skipTest("no configuration file available")

Compliant solution

Catch only the exception you actually want to tolerate. Once except Exception is narrowed down to except OSError, an assertion failure propagates to the test framework and the test fails as expected.

import unittest

class MyTest(unittest.TestCase):
    def test_timeout_is_configured(self):
        try:
            self.assertEqual(load_config()["timeout"], 30)  # Compliant: an AssertionError is no longer caught here
        except OSError:
            self.skipTest("no configuration file available")

Noncompliant code example

Catching AssertionError to report additional context has the same effect: the failure is visible in the test output, but the test itself still passes.

import unittest

class MyTest(unittest.TestCase):
    def test_user_is_active(self):
        try:
            self.assertTrue(fetch_user().is_active)  # Noncompliant
        except AssertionError as error:
            print(f"the user is not active: {error}")

Compliant solution

If you do need to react to an assertion failure, re-raise the exception so the test framework still sees it.

import unittest

class MyTest(unittest.TestCase):
    def test_user_is_active(self):
        try:
            self.assertTrue(fetch_user().is_active)  # Compliant: the AssertionError is re-raised
        except AssertionError as error:
            print(f"the user is not active: {error}")
            raise

How to fix it in pytest

Code examples

Noncompliant code example

The assert False statement guards against do_something() not raising anything, but it raises an AssertionError that the surrounding except AssertionError block swallows. The test can therefore never fail.

import pytest

def test_should_raise_error():
    try:
        do_something()
        assert False, "Expected an AssertionError!"  # Noncompliant
    except AssertionError:
        pass

def do_something():
    raise AssertionError("Something went wrong")

Compliant solution

Use the pytest.raises context manager to test for exceptions. It fails the test when the expected exception is not raised, without catching assertion failures.

import pytest

def test_should_raise_error():
    with pytest.raises(AssertionError):
        do_something()

def do_something():
    raise AssertionError("Something went wrong")

Noncompliant code example

Logging the caught exception does not help either. Both the error raised by do_something() and the failure of the assert False guard end up in the same except block, so nothing is ever validated.

import pytest

def test_error_details():
    try:
        do_something()
        assert False, "Expected an AssertionError!"  # Noncompliant
    except AssertionError as error:
        print(f"caught: {error}")

def do_something():
    raise AssertionError("Something went wrong")

Compliant solution

To validate specific exception properties, access the exception info exposed by pytest.raises and assert on it once the context manager exits.

import pytest

def test_error_details():
    with pytest.raises(AssertionError) as exc_info:
        do_something()

    assert str(exc_info.value) == "Something went wrong"

def do_something():
    raise AssertionError("Something went wrong")

How to fix it in assertpy

Code examples

Noncompliant code example

With assertpy, fluent assertions still raise AssertionError. The try-except block serves no purpose other than hiding a failing test.

from assertpy import assert_that

def test_result():
    try:
        result = get_result()
        assert_that(result).is_equal_to("expected")  # Noncompliant
    except AssertionError:
        pass

Compliant solution

Remove the try-except block so that test failures are reported normally.

from assertpy import assert_that

def test_result():
    result = get_result()
    assert_that(result).is_equal_to("expected")

Resources

Documentation