This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author serhiy.storchaka
Recipients chris.jerdonek, ezio.melotti, michael.foord, r.david.murray, rbcollins, serhiy.storchaka
Date 2021-08-29.16:56:08
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1630256169.0.0.0736015144313.issue45046@roundup.psfhosted.org>
In-reply-to
Content
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.

    resource = open_resource()
    self.addCleanup(close_resource, resource)
    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:

    cm = my_context_manager()
    cm.__enter__()
    # 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:

    self.enterContext(my_context_manager())
    # or self.resource = self.enterContext(my_context_manager())

It solves the same problem as issue15351, but from different direction, so I opened a separate issue.
History
Date User Action Args
2021-08-29 16:56:09serhiy.storchakasetrecipients: + serhiy.storchaka, rbcollins, ezio.melotti, r.david.murray, michael.foord, chris.jerdonek
2021-08-29 16:56:09serhiy.storchakasetmessageid: <1630256169.0.0.0736015144313.issue45046@roundup.psfhosted.org>
2021-08-29 16:56:08serhiy.storchakalinkissue45046 messages
2021-08-29 16:56:08serhiy.storchakacreate