class TestHandler:

    def __enter__(self):
        pass

def __exit__(self, exc_type, exc_val, exc_tb):
    if isinstance(exc_val, AssertionError):
        get_screenshot()
with TestHandler():
    Assert.fail('failed test')
How to detect when pytest test case failed?