Skip to content

Commit 0bd94e6

Browse files
sametycjw296
authored andcommitted
bpo-44185: Added close() to mock_open __exit__ (#26902)
Backports: 3f7c0810f6158a7ff37be432f8d7f9511427489f Signed-off-by: Chris Withers <chris@simplistix.co.uk>
1 parent 6f79656 commit 0bd94e6

3 files changed

Lines changed: 10 additions & 3 deletions

File tree

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.

mock/mock.py

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

2997+
def _exit_side_effect(exctype, excinst, exctb):
2998+
handle.close()
2999+
29973000
global file_spec
29983001
if file_spec is None:
29993002
import _io
@@ -3020,6 +3023,7 @@ def _next_side_effect():
30203023
handle.readlines.side_effect = _readlines_side_effect
30213024
handle.__iter__.side_effect = _iter_side_effect
30223025
handle.__next__.side_effect = _next_side_effect
3026+
handle.__exit__.side_effect = _exit_side_effect
30233027

30243028
def reset_data(*args, **kwargs):
30253029
_state[0] = _to_stream(read_data)

mock/tests/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):

0 commit comments

Comments
 (0)