homepage

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.

classification
Title: Add support of context managers in unittest
Type: enhancement Stage: patch review
Components: Library (Lib) Versions: Python 3.11
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: chris.jerdonek, ezio.melotti, michael.foord, r.david.murray, rbcollins, serhiy.storchaka
Priority: normal Keywords: patch

Created on 2021年08月29日 16:56 by serhiy.storchaka, last changed 2022年04月11日 14:59 by admin.

Pull Requests
URL Status Linked Edit
PR 28045 open serhiy.storchaka, 2021年08月29日 17:01
Messages (1)
msg400552 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2021年08月29日 16:56
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
2022年04月11日 14:59:49adminsetgithub: 89209
2021年08月29日 17:01:15serhiy.storchakasetkeywords: + patch
stage: patch review
pull_requests: + pull_request26490
2021年08月29日 16:56:08serhiy.storchakacreate

AltStyle によって変換されたページ (->オリジナル) /