[New-bugs-announce] [issue45046] Add support of context managers in unittest

Serhiy Storchaka report at bugs.python.org
Sun Aug 29 12:56:09 EDT 2021


New submission from Serhiy Storchaka <storchaka+cpython at gmail.com>:

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.

----------
components: Library (Lib)
messages: 400552
nosy: chris.jerdonek, ezio.melotti, michael.foord, r.david.murray, rbcollins, serhiy.storchaka
priority: normal
severity: normal
status: open
title: Add support of context managers in unittest
type: enhancement
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45046>
_______________________________________


More information about the New-bugs-announce mailing list