]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-44185: Added close() to mock_open __exit__ (#26902)
authorSamet YASLAN <sametyaslan@gmail.com>
Sun, 11 Jun 2023 18:51:21 +0000 (20:51 +0200)
committerGitHub <noreply@github.com>
Sun, 11 Jun 2023 18:51:21 +0000 (19:51 +0100)
Lib/test/test_unittest/testmock/testwith.py
Lib/unittest/mock.py
Misc/NEWS.d/next/Library/2021-06-24-20-45-03.bpo-44185.ZHb8yJ.rst [new file with mode: 0644]

index 8dc8eb1137691fa0efef7aea721ad6a802514582..56cb16394fac40858c26fff84ddf544300da9114 100644 (file)
@@ -158,7 +158,7 @@ class TestMockOpen(unittest.TestCase):
                 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 @@ class TestMockOpen(unittest.TestCase):
 
         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):
index 4ca7062961a6ba2a54e91071b4f4f0aab5c8b6f9..f10f9b04a5ab182d053fad1c9f8465d83f0e389d 100644 (file)
@@ -2941,6 +2941,9 @@ def mock_open(mock=None, read_data=''):
             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 mock_open(mock=None, read_data=''):
     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 (file)
index 0000000..056ab8d
--- /dev/null
@@ -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.