Skip to content

Commit

Permalink
bpo-44185: Added close() to mock_open __exit__ (#26902)
Browse files Browse the repository at this point in the history
Backports: 3f7c0810f6158a7ff37be432f8d7f9511427489f
Signed-off-by: Chris Withers <[email protected]>
  • Loading branch information
samety authored and cjw296 committed Jul 11, 2023
1 parent 6f79656 commit 0bd94e6
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
3 changes: 3 additions & 0 deletions NEWS.d/2021-06-24-20-45-03.bpo-44185.ZHb8yJ.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:func:`unittest.mock.mock_open` will call the :func:`close` method of the file
handle mock when it is exiting from the context manager.
Patch by Samet Yaslan.
4 changes: 4 additions & 0 deletions mock/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2994,6 +2994,9 @@ def _next_side_effect():
return handle.readline.return_value
return next(_state[0])

def _exit_side_effect(exctype, excinst, exctb):
handle.close()

global file_spec
if file_spec is None:
import _io
Expand All @@ -3020,6 +3023,7 @@ def _next_side_effect():
handle.readlines.side_effect = _readlines_side_effect
handle.__iter__.side_effect = _iter_side_effect
handle.__next__.side_effect = _next_side_effect
handle.__exit__.side_effect = _exit_side_effect

def reset_data(*args, **kwargs):
_state[0] = _to_stream(read_data)
Expand Down
6 changes: 3 additions & 3 deletions mock/tests/testwith.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def test_mock_open_context_manager(self):
f.read()

expected_calls = [call('foo'), call().__enter__(), call().read(),
call().__exit__(None, None, None)]
call().__exit__(None, None, None), call().close()]
self.assertEqual(mock.mock_calls, expected_calls)
self.assertIs(f, handle)

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

expected_calls = [
call('foo'), call().__enter__(), call().read(),
call().__exit__(None, None, None),
call().__exit__(None, None, None), call().close(),
call('bar'), call().__enter__(), call().read(),
call().__exit__(None, None, None)]
call().__exit__(None, None, None), call().close()]
self.assertEqual(mock.mock_calls, expected_calls)

def test_explicit_mock(self):
Expand Down

0 comments on commit 0bd94e6

Please sign in to comment.