Sub topic 13
Pitfalls and how to test context managers
This chapter assumes you can write class-based and @contextmanager managers and know how __exit__ receives exception details. It covers the mistakes that cause the most bugs, then shows how to test a manager.
Pitfall 1: Reusing a single-use manager
A manager made with @contextmanager wraps one generator, and a generator runs only once. Entering the same object a second time fails.
from contextlib import contextmanager
@contextmanager
def managed():
print("enter")
try:
yield
finally:
print("exit")
cm = managed()
with cm:
pass
try:
with cm:
pass
except RuntimeError as error:
print("second use failed:", error)The second with raises RuntimeError: generator didn't yield. Call managed() again for each with block. Files behave the same way, since a closed file cannot be reopened by entering it again.
Pitfall 2: Skipping try/finally around yield
If the body of a with block raises, Python throws that exception into the generator at the yield. Code after the yield runs only if the yield is inside try/finally.
from contextlib import contextmanager
@contextmanager
def broken(log):
log.append("open")
yield
log.append("close") # never runs if the body raises
log = []
try:
with broken(log):
raise ValueError("boom")
except ValueError:
pass
print(log) # ['open'] - the cleanup was skippedWrap the yield in try/finally whenever cleanup must always happen.
Pitfall 3: Suppressing exceptions by accident
Python treats any true return value from __exit__ as "the exception was handled". A method that happens to return a truthy value can hide errors without anyone noticing.
class Leaky:
def release(self):
return True # "success" flag
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return self.release() # bug: hides every exception
with Leaky():
raise RuntimeError("this vanishes")
print("no error was reported")Return False or None explicitly unless you mean to suppress. When you do suppress, check the exception type first, as the Ignore class earlier in this tutorial does.
Other mistakes to watch for
- Forgetting
return selfin__enter__. Thenwith Manager() as mbindsmtoNone. - Raising inside
__exit__. A new exception replaces the original one. Python keeps the original as__context__, but the traceback is harder to read. Keep cleanup code simple. - Yielding twice in a
@contextmanagerfunction. The generator must yield exactly once, or you get aRuntimeError. - Catching an exception around
yieldand not re-raising it. Thewithblock then looks successful. This is the same as suppression, so do it only on purpose.
Testing a context manager
Test three things: setup and cleanup happen, cleanup also happens on error, and exceptions propagate (or are suppressed) as designed. Use a list as a log so the tests can check the order of events. This example uses pytest.
import pytest
class Transaction:
def __init__(self, log):
self.log = log
def __enter__(self):
self.log.append("begin")
return self
def __exit__(self, exc_type, exc_value, traceback):
self.log.append("rollback" if exc_type else "commit")
return False
def test_commit_on_success():
log = []
with Transaction(log):
pass
assert log == ["begin", "commit"]
def test_rollback_and_propagation_on_error():
log = []
with pytest.raises(ValueError):
with Transaction(log):
raise ValueError("boom")
assert log == ["begin", "rollback"]
def test_exit_does_not_suppress():
result = Transaction([]).__exit__(ValueError, ValueError("x"), None)
assert result is FalseThe pytest.raises block fails the test if the ValueError is swallowed, so it checks the propagation rule. Calling __exit__ directly is a quick way to test its return value without a with block.
For a suppressing manager, test the opposite: the listed exception type disappears, and a different type still escapes. For a @contextmanager function, also test that cleanup runs when the body raises, since that catches Pitfall 2.
Exercise
A teammate's @contextmanager function opens a connection, yields it, then calls conn.close() on the next line. Tests pass, but connections leak in production when queries fail. What is the bug, and how would you write a test that catches it?
Show answer
The close() call is not inside try/finally, so it is skipped when the body raises. Fix it by wrapping the yield in try: and putting conn.close() in finally:. To catch it, write a test that uses a fake connection which records close(), runs the manager with a body that raises inside pytest.raises, and asserts that close() was recorded.