bpo-38971: Open file in codecs.open() closes if exception raised. (GH-17666)


Open issue in the BPO indicated a desire to make the implementation of
codecs.open() at parity with io.open(), which implements a try/except to
assure file stream gets closed before an exception is raised.
(cherry picked from commit 2565edec2c974b2acca03b4cc5025e83f903ddd7)

Co-authored-by: Chris A <christopher.aporta@gmail.com>
diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py
index 8c10e94..0fd258c 100644
--- a/Lib/test/test_codecs.py
+++ b/Lib/test/test_codecs.py
@@ -1142,6 +1142,7 @@
             got = ostream.getvalue()
             self.assertEqual(got, unistring)
 
+
 class EscapeDecodeTest(unittest.TestCase):
     def test_empty(self):
         self.assertEqual(codecs.escape_decode(b""), (b"", 0))
@@ -1713,6 +1714,14 @@
             self.assertRaises(UnicodeError,
                 codecs.decode, b'abc', 'undefined', errors)
 
+    def test_file_closes_if_lookup_error_raised(self):
+        mock_open = mock.mock_open()
+        with mock.patch('builtins.open', mock_open) as file:
+            with self.assertRaises(LookupError):
+                codecs.open(support.TESTFN, 'wt', 'invalid-encoding')
+
+            file().close.assert_called()
+
 
 class StreamReaderTest(unittest.TestCase):