mock.mock_open __exit__ called as instance method from contextlib.ExitStack context
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
In Python 3.13 onwards:
from contextlib import ExitStack
from unittest import mock
with mock.patch("__main__.open", mock.mock_open()) as m:
with ExitStack() as exit_stack:
with exit_stack.enter_context(open("/tmp/test.txt", "w")):
pass
raises
TypeError: mock_open.<locals>._exit_side_effect() takes 3 positional arguments but 4 were given
The issue seems to come from https://github.com/python/cpython/commit/3f7c0810f6158a7ff37be432f8d7f9511427489f
It appears that in Python versions 3.12 and earlier, mock_open().__exit__ was always called with 4 args (self, exctype, excinst, exctb) when used with contextlib.ExitStack but that used to be a no-op before the exit handler was added.
I'm not sure whether this should be fixed by:
- changing the way
ExitStackcalls its stack of__exit__callbacks - making
mock_openandopenmore similar, or - making
mock_open's exit handler take*args, **kwargssame as the enter handler??
Thanks
CPython versions tested on:
3.12, 3.13, 3.14
Operating systems tested on:
Linux
Linked PRs
- gh-150521
- gh-150535
- gh-151829
- gh-151861
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Begin with the reproducer using contextlib.ExitStack and unittest.mock.mock_open, then inspect the callback behavior described in the issue. Done means resolving the Python 3.13+ TypeError while preserving the expected context-manager behavior and adding coverage for the reported case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100