Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
assignee=Noneclosed_at=Nonecreated_at=<Date2021-08-29.16:56:08.979>labels= ['type-feature', 'library', '3.11']
title='Add support of context managers in unittest'updated_at=<Date2021-08-29.17:01:15.427>user='https://github.com/serhiy-storchaka'
Methods setUp() and tearDown() of TestClass allow to add some code executed before and after every test method. In many cases addCleanup() is more convenient than tearDown() -- you do not need to keep data for cleaning up as TestCase attributes, addCleanup() doe it for you. You should not worry about partial cleaning up if setUp() fails in the middle. You can also use addCleanup() in test methods, and corresponding resources will be cleaned only for these tests which created them.
self.resource=resource# optional, if you need access to it in test methods
Some resources are managed by context managers. It is so easy to create a context manager with the contextlib.contextmanager decorator, that its __enter__ and __exit__ methods can be only way to create and destroy resource. So the code looks like the following:
# or self.resource = cm.__enter__()self.addCleanup(cm.__exit__, None, None, None)
It looks not so nice. You need to use dunder methods, and pass thee Nones as arguments for __exit__.
I propose to add helpers: methods enterContext(), enterClassContext(), enterAsyncContext() and function enterModuleContext() which wraps addCleanup/addClassCleanup/addAsyncCleanup/addModuleCleanup correspondently and allow to get rid of the boilerplate code. Example:
# or self.resource = self.enterContext(my_context_manager())
It solves the same problem as bpo-15351, but from different direction, so I opened a separate issue.