如何检测 pytest 测试用例何时出现 AssertionError?

How to detect when pytest test case got AssertionError?

我正在使用 pytest 来自动化项目测试。我想仅在测试用例失败时才采取一些独特的操作,例如 "save_snapshot()"。

我们在 pytest 中有类似的东西吗?

我曾尝试使用 teardown_method() 来实现此目的,但是当测试用例失败时,此方法不会被执行。

我通过对 class 中的每个测试使用 python 装饰器找到了解决此问题的方法:

def is_failed_decorator(func):
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except AssertionError:
            cls_obj = args[0]
            cur_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
            func_name = func.__name__
            # Save_snapshot().
            raise
    return wrapper

# Tests class
@is_failed_decorator
def test_fail(self):
    assert False

对我有用 :D