There are some similar questions, e.g Pytests with context manager. Still I don't get it. Why is this assertion inside a context manager not raised?
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
Using: python3.9 and pytest6.2.5
Update: it works when the __exit__
method of the context manager does not return self. This works:
class foo:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass # <- this fixes it
But still the question remains. Why does the 1st case fail. Is this a bug? Shall I report it?
CodePudding user response:
A context manager is designed to catch exceptions like this and pass it to __exit__
. If you want to raise the exception, you need to take care of it yourself:
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()