Skip to content

Commit 85fa295

Browse files
authored
[3.14] gh-150484: Fix mock_open __exit__ with contextlib.ExitStack (GH-151829)
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.
1 parent 2027088 commit 85fa295

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
@@ -2108,6 +2108,15 @@ def test_mock_open_after_eof(self):
21082108
self.assertEqual([], h.readlines())
21092109
self.assertEqual([], h.readlines())
21102110

2111+
def test_mock_open_exit_with_contextlib_exit_stack(self):
2112+
# gh-150484: mock_open's __exit__ should work when called from
2113+
# contextlib.ExitStack, which passes (exctype, excinst, exctb).
2114+
from contextlib import ExitStack
2115+
with mock.patch('builtins.open', mock.mock_open()) as m:
2116+
with ExitStack() as exit_stack:
2117+
with exit_stack.enter_context(open('/tmp/test.txt', 'w')):
2118+
pass
2119+
21112120
def test_mock_parents(self):
21122121
for Klass in Mock, MagicMock:
21132122
m = Klass()

Lib/unittest/mock.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3010,7 +3010,7 @@ def _next_side_effect():
30103010
return handle.readline.return_value
30113011
return next(_state[0])
30123012

3013-
def _exit_side_effect(exctype, excinst, exctb):
3013+
def _exit_side_effect(*args):
30143014
handle.close()
30153015

30163016
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)