]> granicus.if.org Git - python/commitdiff
Merged revisions 85503 via svnmerge from
authorAntoine Pitrou <solipsis@pitrou.net>
Thu, 14 Oct 2010 22:22:30 +0000 (22:22 +0000)
committerAntoine Pitrou <solipsis@pitrou.net>
Thu, 14 Oct 2010 22:22:30 +0000 (22:22 +0000)
svn+ssh://pythondev@svn.python.org/python/branches/py3k

........
  r85503 | antoine.pitrou | 2010-10-15 00:11:44 +0200 (ven., 15 oct. 2010) | 2 lines

  More proper closing of files
........

Lib/doctest.py
Lib/test/test_decimal.py
Lib/test/test_modulefinder.py
Lib/test/test_multibytecodec.py
Lib/test/test_multibytecodec_support.py
Lib/test/test_pipes.py
Lib/test/test_shutil.py

index c37ff9e651ea82f355337afe9c3788cca04d0894..5565aab57f7c7d5a32324a6bd6190362fb22187b 100644 (file)
@@ -216,7 +216,8 @@ def _load_testfile(filename, package, module_relative):
                 # get_data() opens files as 'rb', so one must do the equivalent
                 # conversion as universal newlines would do.
                 return file_contents.replace(os.linesep, '\n'), filename
-    return open(filename).read(), filename
+    with open(filename) as f:
+        return f.read(), filename
 
 # Use sys.stdout encoding for ouput.
 _encoding = getattr(sys.__stdout__, 'encoding', None) or 'utf-8'
index f8d8dec5ade73c3bf0b6f92261602ce402cfa0e7..dc217779eefbe39fad0848045ef7308f17f46b96 100644 (file)
@@ -224,14 +224,15 @@ class DecimalTest(unittest.TestCase):
         if skip_expected:
             raise unittest.SkipTest
             return
-        for line in open(file):
-            line = line.replace('\r\n', '').replace('\n', '')
-            #print line
-            try:
-                t = self.eval_line(line)
-            except DecimalException, exception:
-                #Exception raised where there shoudn't have been one.
-                self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
+        with open(file) as f:
+            for line in f:
+                line = line.replace('\r\n', '').replace('\n', '')
+                #print line
+                try:
+                    t = self.eval_line(line)
+                except DecimalException as exception:
+                    #Exception raised where there shoudn't have been one.
+                    self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
 
         return
 
index 8c76977e3b186664639ec710a6a7d252162f818c..e71d1e0aeb66080ffec2f73484663768d4d1d329 100644 (file)
@@ -211,11 +211,17 @@ def open_file(path):
 
 def create_package(source):
     ofi = None
-    for line in source.splitlines():
-        if line.startswith(" ") or line.startswith("\t"):
-            ofi.write(line.strip() + "\n")
-        else:
-            ofi = open_file(os.path.join(TEST_DIR, line.strip()))
+    try:
+        for line in source.splitlines():
+            if line.startswith(" ") or line.startswith("\t"):
+                ofi.write(line.strip() + "\n")
+            else:
+                if ofi:
+                    ofi.close()
+                ofi = open_file(os.path.join(TEST_DIR, line.strip()))
+    finally:
+        if ofi:
+            ofi.close()
 
 class ModuleFinderTest(unittest.TestCase):
     def _do_test(self, info, report=False):
index 95ca0ab288cacd95ebe15086a326fe50c6a17616..63c1e620b5935eabf3798517674b619fa8233e12 100644 (file)
@@ -46,12 +46,9 @@ class Test_MultibyteCodec(unittest.TestCase):
                           'apple\x92ham\x93spam', 'test.cjktest')
 
     def test_codingspec(self):
-        try:
-            for enc in ALL_CJKENCODINGS:
-                print >> open(TESTFN, 'w'), '# coding:', enc
-                exec open(TESTFN)
-        finally:
-            os.unlink(TESTFN)
+        for enc in ALL_CJKENCODINGS:
+            code = '# coding: {}\n'.format(enc)
+            exec code
 
     def test_init_segfault(self):
         # bug #3305: this used to segfault
index 9aa764a44853aac6f34fbf11f2ed9e428ba812be..0639032a2dd475efb7522e89a3633e81173e40a5 100644 (file)
@@ -252,7 +252,7 @@ class TestBase_Mapping(unittest.TestCase):
     def __init__(self, *args, **kw):
         unittest.TestCase.__init__(self, *args, **kw)
         try:
-            self.open_mapping_file() # test it to report the error early
+            self.open_mapping_file().close() # test it to report the error early
         except (IOError, HTTPException):
             self.skipTest("Could not retrieve "+self.mapfileurl)
 
@@ -270,36 +270,38 @@ class TestBase_Mapping(unittest.TestCase):
         unichrs = lambda s: u''.join(_unichr(c) for c in s.split('+'))
         urt_wa = {}
 
-        for line in self.open_mapping_file():
-            if not line:
-                break
-            data = line.split('#')[0].strip().split()
-            if len(data) != 2:
-                continue
-
-            csetval = eval(data[0])
-            if csetval <= 0x7F:
-                csetch = chr(csetval & 0xff)
-            elif csetval >= 0x1000000:
-                csetch = chr(csetval >> 24) + chr((csetval >> 16) & 0xff) + \
-                         chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
-            elif csetval >= 0x10000:
-                csetch = chr(csetval >> 16) + \
-                         chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
-            elif csetval >= 0x100:
-                csetch = chr(csetval >> 8) + chr(csetval & 0xff)
-            else:
-                continue
+        with self.open_mapping_file() as f:
+            for line in f:
+                if not line:
+                    break
+                data = line.split('#')[0].strip().split()
+                if len(data) != 2:
+                    continue
+
+                csetval = eval(data[0])
+                if csetval <= 0x7F:
+                    csetch = chr(csetval & 0xff)
+                elif csetval >= 0x1000000:
+                    csetch = chr(csetval >> 24) + chr((csetval >> 16) & 0xff) + \
+                             chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
+                elif csetval >= 0x10000:
+                    csetch = chr(csetval >> 16) + \
+                             chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
+                elif csetval >= 0x100:
+                    csetch = chr(csetval >> 8) + chr(csetval & 0xff)
+                else:
+                    continue
 
-            unich = unichrs(data[1])
-            if unich == u'\ufffd' or unich in urt_wa:
-                continue
-            urt_wa[unich] = csetch
+                unich = unichrs(data[1])
+                if unich == u'\ufffd' or unich in urt_wa:
+                    continue
+                urt_wa[unich] = csetch
 
-            self._testpoint(csetch, unich)
+                self._testpoint(csetch, unich)
 
     def _test_mapping_file_ucm(self):
-        ucmdata = self.open_mapping_file().read()
+        with self.open_mapping_file() as f:
+            ucmdata = f.read()
         uc = re.findall('<a u="([A-F0-9]{4})" b="([0-9A-F ]+)"/>', ucmdata)
         for uni, coded in uc:
             unich = unichr(int(uni, 16))
index 476bd7c6440a9cedc14e322a52ed1bfc79fc8cb4..c8b8be106c2fb4da76c28da3c2a2aef5e5d19374 100644 (file)
@@ -23,17 +23,21 @@ class SimplePipeTests(unittest.TestCase):
         f = t.open(TESTFN, 'w')
         f.write('hello world #1')
         f.close()
-        self.assertEqual(open(TESTFN).read(), 'HELLO WORLD #1')
+        with open(TESTFN) as f:
+            self.assertEqual(f.read(), 'HELLO WORLD #1')
 
     def testSimplePipe2(self):
-        file(TESTFN, 'w').write('hello world #2')
+        with open(TESTFN, 'w') as f:
+            f.write('hello world #2')
         t = pipes.Template()
         t.append(s_command + ' < $IN > $OUT', pipes.FILEIN_FILEOUT)
         t.copy(TESTFN, TESTFN2)
-        self.assertEqual(open(TESTFN2).read(), 'HELLO WORLD #2')
+        with open(TESTFN2) as f:
+            self.assertEqual(f.read(), 'HELLO WORLD #2')
 
     def testSimplePipe3(self):
-        file(TESTFN, 'w').write('hello world #2')
+        with open(TESTFN, 'w') as f:
+            f.write('hello world #2')
         t = pipes.Template()
         t.append(s_command + ' < $IN', pipes.FILEIN_STDOUT)
         with t.open(TESTFN, 'r') as f:
@@ -42,16 +46,20 @@ class SimplePipeTests(unittest.TestCase):
     def testEmptyPipeline1(self):
         # copy through empty pipe
         d = 'empty pipeline test COPY'
-        file(TESTFN, 'w').write(d)
-        file(TESTFN2, 'w').write('')
+        with open(TESTFN, 'w') as f:
+            f.write(d)
+        with open(TESTFN2, 'w') as f:
+            f.write('')
         t=pipes.Template()
         t.copy(TESTFN, TESTFN2)
-        self.assertEqual(open(TESTFN2).read(), d)
+        with open(TESTFN2) as f:
+            self.assertEqual(f.read(), d)
 
     def testEmptyPipeline2(self):
         # read through empty pipe
         d = 'empty pipeline test READ'
-        file(TESTFN, 'w').write(d)
+        with open(TESTFN, 'w') as f:
+            f.write(d)
         t=pipes.Template()
         with t.open(TESTFN, 'r') as f:
             self.assertEqual(f.read(), d)
@@ -60,8 +68,10 @@ class SimplePipeTests(unittest.TestCase):
         # write through empty pipe
         d = 'empty pipeline test WRITE'
         t = pipes.Template()
-        t.open(TESTFN, 'w').write(d)
-        self.assertEqual(open(TESTFN).read(), d)
+        with t.open(TESTFN, 'w') as f:
+            f.write(d)
+        with open(TESTFN) as f:
+            self.assertEqual(f.read(), d)
 
     def testQuoting(self):
         safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
index d6839359bd712d0105223a632a682f8072368c78..648a2cda43f421e5add21f71fe21cc9aad4e49d8 100644 (file)
@@ -277,7 +277,8 @@ class TestShutil(unittest.TestCase):
 
                 os.link(src, dst)
                 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
-                self.assertEqual(open(src,'r').read(), 'cheddar')
+                with open(src, 'r') as f:
+                    self.assertEqual(f.read(), 'cheddar')
                 os.remove(dst)
 
                 # Using `src` here would mean we end up with a symlink pointing
@@ -285,7 +286,8 @@ class TestShutil(unittest.TestCase):
                 # TESTFN/cheese.
                 os.symlink('cheese', dst)
                 self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
-                self.assertEqual(open(src,'r').read(), 'cheddar')
+                with open(src, 'r') as f:
+                    self.assertEqual(f.read(), 'cheddar')
                 os.remove(dst)
             finally:
                 try:
@@ -588,9 +590,11 @@ class TestMove(unittest.TestCase):
                 pass
 
     def _check_move_file(self, src, dst, real_dst):
-        contents = open(src, "rb").read()
+        with open(src, "rb") as f:
+            contents = f.read()
         shutil.move(src, dst)
-        self.assertEqual(contents, open(real_dst, "rb").read())
+        with open(real_dst, "rb") as f:
+            self.assertEqual(contents, f.read())
         self.assertFalse(os.path.exists(src))
 
     def _check_move_dir(self, src, dst, real_dst):