pytest:未引发上下文管理器内的 AssertionError

pytest: AssertionError inside Context Manager not raised

还有一些类似的问题,例如Pytests with context manager. Still I don't get it. Why is this assertion inside a context manager没有提出来?

class foo:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        return self

def test_context_manager():
    with foo():
        assert False  # <- works outside the with statement but not here

使用:python3.9 和 pytest6.2.5

更新: 当上下文管理器的 __exit__ 方法不是 return 时它起作用。这有效:

class foo:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        pass  # <- this fixes it

但问题依然存在。为什么第一种情况会失败。这是一个错误吗?我要举报吗?

上下文管理器旨在捕获此类异常并将其传递给 __exit__。如果要抛出异常,需要自己处理:

class foo:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_value:
            raise exc_value # AssertionError raised here
        return self

def test_context_manager():
    with foo():
        assert False

test_context_manager()