Skip to content

bpo-44185: Added close() to mock_open __exit__ #26902

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jun 11, 2023
6 changes: 3 additions & 3 deletions Lib/test/test_unittest/testmock/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
4 changes: 4 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2941,6 +2941,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 @@ -2967,6 +2970,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
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.