Skip to content

Commit 3f7c081

Browse files
authored
bpo-44185: Added close() to mock_open __exit__ (python#26902)
1 parent 18d16e9 commit 3f7c081

File tree

3 files changed

+10
-3
lines changed

3 files changed

+10
-3
lines changed

Lib/test/test_unittest/testmock/testwith.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def test_mock_open_context_manager(self):
158158
f.read()
159159

160160
expected_calls = [call('foo'), call().__enter__(), call().read(),
161-
call().__exit__(None, None, None)]
161+
call().__exit__(None, None, None), call().close()]
162162
self.assertEqual(mock.mock_calls, expected_calls)
163163
self.assertIs(f, handle)
164164

@@ -172,9 +172,9 @@ def test_mock_open_context_manager_multiple_times(self):
172172

173173
expected_calls = [
174174
call('foo'), call().__enter__(), call().read(),
175-
call().__exit__(None, None, None),
175+
call().__exit__(None, None, None), call().close(),
176176
call('bar'), call().__enter__(), call().read(),
177-
call().__exit__(None, None, None)]
177+
call().__exit__(None, None, None), call().close()]
178178
self.assertEqual(mock.mock_calls, expected_calls)
179179

180180
def test_explicit_mock(self):

Lib/unittest/mock.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2941,6 +2941,9 @@ def _next_side_effect():
29412941
return handle.readline.return_value
29422942
return next(_state[0])
29432943

2944+
def _exit_side_effect(exctype, excinst, exctb):
2945+
handle.close()
2946+
29442947
global file_spec
29452948
if file_spec is None:
29462949
import _io
@@ -2967,6 +2970,7 @@ def _next_side_effect():
29672970
handle.readlines.side_effect = _readlines_side_effect
29682971
handle.__iter__.side_effect = _iter_side_effect
29692972
handle.__next__.side_effect = _next_side_effect
2973+
handle.__exit__.side_effect = _exit_side_effect
29702974

29712975
def reset_data(*args, **kwargs):
29722976
_state[0] = _to_stream(read_data)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`unittest.mock.mock_open` will call the :func:`close` method of the file
2+
handle mock when it is exiting from the context manager.
3+
Patch by Samet Yaslan.

0 commit comments

Comments
 (0)