From bae0ba9ec71e5433c2c634644cefa093f43cc056 Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Sun, 21 Jun 2026 19:02:30 +0200 Subject: [PATCH] [3.13] gh-150484: Fix mock_open __exit__ with contextlib.ExitStack (GH-151829) (GH-151861) mock_open's _exit_side_effect had a fixed 3-arg signature, but contextlib.ExitStack calls __exit__ with 4 args (self + 3 exc info). Use *args to accept any number of arguments. (cherry picked from commit 85fa295073a0291e517ae6bd24a26e03b5925b75) Co-authored-by: Zang Peiyu <166481866+factnn@users.noreply.github.com> --- Lib/test/test_unittest/testmock/testmock.py | 9 +++++++++ Lib/unittest/mock.py | 2 +- .../2026-05-28-00-00-00.gh-issue-150484.XxYyZz.rst | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-05-28-00-00-00.gh-issue-150484.XxYyZz.rst diff --git a/Lib/test/test_unittest/testmock/testmock.py b/Lib/test/test_unittest/testmock/testmock.py index e1b108f81e51..ca4d80862070 100644 --- a/Lib/test/test_unittest/testmock/testmock.py +++ b/Lib/test/test_unittest/testmock/testmock.py @@ -2101,6 +2101,15 @@ class MockTest(unittest.TestCase): self.assertEqual([], h.readlines()) self.assertEqual([], h.readlines()) + def test_mock_open_exit_with_contextlib_exit_stack(self): + # gh-150484: mock_open's __exit__ should work when called from + # contextlib.ExitStack, which passes (exctype, excinst, exctb). + from contextlib import ExitStack + with mock.patch('builtins.open', mock.mock_open()) as m: + with ExitStack() as exit_stack: + with exit_stack.enter_context(open('/tmp/test.txt', 'w')): + pass + def test_mock_parents(self): for Klass in Mock, MagicMock: m = Klass() diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index bf32ff6dd3cd..84f629ee1f76 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -2991,7 +2991,7 @@ def mock_open(mock=None, read_data=''): return handle.readline.return_value return next(_state[0]) - def _exit_side_effect(exctype, excinst, exctb): + def _exit_side_effect(*args): handle.close() global file_spec diff --git a/Misc/NEWS.d/next/Library/2026-05-28-00-00-00.gh-issue-150484.XxYyZz.rst b/Misc/NEWS.d/next/Library/2026-05-28-00-00-00.gh-issue-150484.XxYyZz.rst new file mode 100644 index 000000000000..522c70058ed2 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-05-28-00-00-00.gh-issue-150484.XxYyZz.rst @@ -0,0 +1 @@ +Fix :func:`unittest.mock.mock_open` ``__exit__`` raising ``TypeError`` when used with :class:`contextlib.ExitStack`. -- 2.47.3