As of the 0.2 release, context_tools includes three tools:
As of the 0.2 release, context_tools includes three tools:
decorate_with() allows you to use a context manager as a function decorator
(though not a class decorator or a
generator decorator. That is,
@context_tools.decorate_with(my_manager()) def foo(context, y, z): ...
is equivalent to
def foo(y, z):
with my_manager() as context:
...
Note that new first parameter in the decorate_with() example; the context
value is passed into the function as the first parameter.
test_with() allows you to use transform a context manager into setUp() and tearDown()
function pairs for unittest- and
test_harness-based test suites. That is,
from context_tools import test_with
class Test(unittest.TestCase):
setUp, tearDown = test_with(foo_bar=my_manager(),
bar_baz=other_mgr())
def test_foo(self):
frobnicate(self.foo_bar)
frobnicate(self.bar_baz, with_baz=True)
self.assertEqual(frob_count, 2)
The context manager's __enter__() will be called in setUp()
method, and the manager's __exit__() method will be called in tearDown().
__exit__() will always be called with (None, None, None) as arguments,
even if the test raised an exception.
Note that the names of the keyword arguments supplied to test_with() will
be used as the names of the instance attributes used to store the context values (foo_bar
and bar_baz in the above).
yield_with() is like decorate_with(), except for generators.
@context_tools.yield_with(my_manager()) def foo(context, x, y): ... yield something ... yield something_else
The context manager's __enter__() will be called when the generator
function is called, and __exit__() will be called when the generator
raises an exception (StopIteration or otherwise).
Like decorate_with(), the context value will be passed in as the
generator function's first parameter.
Having the context manager's __exit__() method return True
will not cause StopIteration to be swallowed as it would other exceptions.