
ExitStack: many patch() calls without a pyramid of with
A test that has to isolate a function from its dependencies often ends up stacking patch() calls. Three dependencies, three nested with blocks. Five dependencies, a pyramid that pushes the useful code ten levels deep. The test becomes unreadable even though its intent is simple: verify a single behavior at a precise boundary. contextlib.ExitStack solves exactly this problem. It is a context manager that aggregates any number of others and closes them all cleanly on exit. Here is how I use it to keep a test focused on its boundary, with a concrete example on authentication. ...








