`self.doCleanups()` cannot be called from a test method of a `unittest.IsolatedAsyncioTestCase` subclass

Open
#101,018 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
50/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
python
Domain
testing

Research direction

Run the supplied reproducer with unittest.IsolatedAsyncioTestCase, then inspect Lib/unittest/async_case.py, especially _callCleanup and _callMaybeAsync. Trace the regression identified by gh-91150/GH-31837 and add coverage for calling doCleanups() from a test method. Done means the example and the relevant unittest tests pass without the Context already-entered error.

Written by the indexing model from the issue text.

Description

3.13 3.14 3.15 docs stdlib

Example:

import unittest


events = []

class Test(unittest.IsolatedAsyncioTestCase):

    def test(self):
        events.append('started')
        self.addCleanup(events.append, 'cleanup')
        self.doCleanups()
        events.append('end')

unittest.main(exit=False)

assert events == ['started', 'cleanup', 'end'], events

The above passes in 3.9 and 3.10, but fails in 3.11 with

E
======================================================================
ERROR: test (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/.../cpython/Lib/unittest/async_case.py", line 75, in _callCleanup
    self._callMaybeAsync(function, *args, **kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.../cpython/Lib/unittest/async_case.py", line 95, in _callMaybeAsync
    return self._asyncioTestContext.run(func, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: cannot enter context: <_contextvars.Context object at 0x7fb2f93a9900> is already entered

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)
Traceback (most recent call last):
  File "<stdin>", line 16, in <module>
AssertionError: ['started', 'end']

git bisect found the culprit to be gh-91150/GH-31837.

Dominant language
Python
Stars
77.2k
Forks
36k
Avg merge
1d 9h
Merged PRs (30d)
558

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/cpython

All issues in python/cpython

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.