summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorBerker Peksag <berker.peksag@gmail.com>2015-02-06 08:21:37 (GMT)
committerBerker Peksag <berker.peksag@gmail.com>2015-02-06 08:21:37 (GMT)
commitbf5e9604cc5a5ae61181b093193286f06a502ad6 (patch)
treec20966ea695e430b9dddae88196def7aca84f309 /Lib
parent088ca8b9470e51b932b73d6b39d970b0292f2ba3 (diff)
downloadcpython-bf5e9604cc5a5ae61181b093193286f06a502ad6.zip
cpython-bf5e9604cc5a5ae61181b093193286f06a502ad6.tar.gz
cpython-bf5e9604cc5a5ae61181b093193286f06a502ad6.tar.bz2
Issue #20289: cgi.FieldStorage() now supports the context management protocol.
Diffstat (limited to 'Lib')
-rwxr-xr-xLib/cgi.py6
-rw-r--r--Lib/test/test_cgi.py19
2 files changed, 19 insertions, 6 deletions
diff --git a/Lib/cgi.py b/Lib/cgi.py
index 1ef780c..a55232e 100755
--- a/Lib/cgi.py
+++ b/Lib/cgi.py
@@ -566,6 +566,12 @@ class FieldStorage:
except AttributeError:
pass
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ self.file.close()
+
def __repr__(self):
"""Return a printable representation."""
return "FieldStorage(%r, %r, %r)" % (
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py
index 86e1f3a..89a6e84 100644
--- a/Lib/test/test_cgi.py
+++ b/Lib/test/test_cgi.py
@@ -1,4 +1,4 @@
-from test.support import run_unittest, check_warnings
+from test.support import check_warnings
import cgi
import os
import sys
@@ -307,6 +307,17 @@ Content-Type: text/plain
got = getattr(files[x], k)
self.assertEqual(got, exp)
+ def test_fieldstorage_as_context_manager(self):
+ fp = BytesIO(b'x' * 10)
+ env = {'REQUEST_METHOD': 'PUT'}
+ with cgi.FieldStorage(fp=fp, environ=env) as fs:
+ content = fs.file.read()
+ self.assertFalse(fs.file.closed)
+ self.assertTrue(fs.file.closed)
+ self.assertEqual(content, 'x' * 10)
+ with self.assertRaisesRegex(ValueError, 'I/O operation on closed file'):
+ fs.file.read()
+
_qs_result = {
'key1': 'value1',
'key2': ['value2x', 'value2y'],
@@ -481,9 +492,5 @@ Content-Transfer-Encoding: binary
--AaB03x--
"""
-
-def test_main():
- run_unittest(CgiTests)
-
if __name__ == '__main__':
- test_main()
+ unittest.main()