[Python-checkins] bpo-44185: Added close() to mock_open __exit__ (#26902)
cjw296
webhook-mailer at python.org
Sun Jun 11 14:51:29 EDT 2023
https://github.com/python/cpython/commit/3f7c0810f6158a7ff37be432f8d7f9511427489f
commit: 3f7c0810f6158a7ff37be432f8d7f9511427489f
branch: main
author: Samet YASLAN <sametyaslan at gmail.com>
committer: cjw296 <chris at withers.org>
date: 2023年06月11日T19:51:21+01:00
summary:
bpo-44185: Added close() to mock_open __exit__ (#26902)
files:
A Misc/NEWS.d/next/Library/2021-06-24-20-45-03.bpo-44185.ZHb8yJ.rst
M Lib/test/test_unittest/testmock/testwith.py
M Lib/unittest/mock.py
diff --git a/Lib/test/test_unittest/testmock/testwith.py b/Lib/test/test_unittest/testmock/testwith.py
index 8dc8eb1137691..56cb16394fac4 100644
--- a/Lib/test/test_unittest/testmock/testwith.py
+++ b/Lib/test/test_unittest/testmock/testwith.py
@@ -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)
@@ -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):
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 4ca7062961a6b..f10f9b04a5ab1 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -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
@@ -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)
diff --git a/Misc/NEWS.d/next/Library/2021-06-24-20-45-03.bpo-44185.ZHb8yJ.rst b/Misc/NEWS.d/next/Library/2021-06-24-20-45-03.bpo-44185.ZHb8yJ.rst
new file mode 100644
index 0000000000000..056ab8d93515f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-06-24-20-45-03.bpo-44185.ZHb8yJ.rst
@@ -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.
More information about the Python-checkins
mailing list