Skip to content

Commit bae0ba9

Browse files
[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 85fa295) Co-authored-by: Zang Peiyu <166481866+factnn@users.noreply.github.com>
1 parent de8d7bb commit bae0ba9

3 files changed

Lines changed: 11 additions & 1 deletion

File tree

Lib/test/test_unittest/testmock/testmock.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2101,6 +2101,15 @@ def test_mock_open_after_eof(self):
21012101
self.assertEqual([], h.readlines())
21022102
self.assertEqual([], h.readlines())
21032103

2104+
def test_mock_open_exit_with_contextlib_exit_stack(self):
2105+
# gh-150484: mock_open's __exit__ should work when called from
2106+
# contextlib.ExitStack, which passes (exctype, excinst, exctb).
2107+
from contextlib import ExitStack
2108+
with mock.patch('builtins.open', mock.mock_open()) as m:
2109+
with ExitStack() as exit_stack:
2110+
with exit_stack.enter_context(open('/tmp/test.txt', 'w')):
2111+
pass
2112+
21042113
def test_mock_parents(self):
21052114
for Klass in Mock, MagicMock:
21062115
m = Klass()

Lib/unittest/mock.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2991,7 +2991,7 @@ def _next_side_effect():
29912991
return handle.readline.return_value
29922992
return next(_state[0])
29932993

2994-
def _exit_side_effect(exctype, excinst, exctb):
2994+
def _exit_side_effect(*args):
29952995
handle.close()
29962996

29972997
global file_spec
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`unittest.mock.mock_open` ``__exit__`` raising ``TypeError`` when used with :class:`contextlib.ExitStack`.

0 commit comments

Comments
 (0)