]> granicus.if.org Git - python/commitdiff
Issue #12451: Add support.create_empty_file()
authorVictor Stinner <victor.stinner@haypocalc.com>
Thu, 30 Jun 2011 21:25:47 +0000 (23:25 +0200)
committerVictor Stinner <victor.stinner@haypocalc.com>
Thu, 30 Jun 2011 21:25:47 +0000 (23:25 +0200)
We don't need to create a temporary buffered binary or text file object just to
create an empty file.

Replace also os.fdopen(handle).close() by os.close(handle).

17 files changed:
Lib/distutils/tests/test_build_py.py
Lib/test/support.py
Lib/test/test_dbm.py
Lib/test/test_glob.py
Lib/test/test_imp.py
Lib/test/test_import.py
Lib/test/test_mailbox.py
Lib/test/test_optparse.py
Lib/test/test_os.py
Lib/test/test_pkgimport.py
Lib/test/test_posix.py
Lib/test/test_reprlib.py
Lib/test/test_runpy.py
Lib/test/test_shutil.py
Lib/test/test_tarfile.py
Lib/test/test_unicode_file.py
Lib/test/test_zipimport.py

index 4e46339b43cf01f7c3e0bd304f711cf9cf8c9079..c7c36f3cc780067feb7e35044940a21663cebe60 100644 (file)
@@ -10,7 +10,7 @@ from distutils.core import Distribution
 from distutils.errors import DistutilsFileError
 
 from distutils.tests import support
-from test.support import run_unittest
+from test.support import run_unittest, create_empty_file
 
 
 class BuildPyTestCase(support.TempdirManager,
@@ -71,11 +71,11 @@ class BuildPyTestCase(support.TempdirManager,
 
         # create the distribution files.
         sources = self.mkdtemp()
-        open(os.path.join(sources, "__init__.py"), "w").close()
+        create_empty_file(os.path.join(sources, "__init__.py"))
 
         testdir = os.path.join(sources, "doc")
         os.mkdir(testdir)
-        open(os.path.join(testdir, "testfile"), "w").close()
+        create_empty_file(os.path.join(testdir, "testfile"))
 
         os.chdir(sources)
         old_stdout = sys.stdout
index d4010f4832a6c3a8b8a7aa4e3fcb2441c62cf67e..2ce013fcdd061ce7202c373db64d6ee9f9c5f060 100644 (file)
@@ -40,7 +40,7 @@ __all__ = [
     "is_resource_enabled", "requires", "requires_linux_version",
     "requires_mac_ver", "find_unused_port", "bind_port",
     "IPV6_ENABLED", "is_jython", "TESTFN", "HOST", "SAVEDCWD", "temp_cwd",
-    "findfile", "sortdict", "check_syntax_error", "open_urlresource",
+    "findfile", "create_empty_file", "sortdict", "check_syntax_error", "open_urlresource",
     "check_warnings", "CleanImport", "EnvironmentVarGuard", "TransientResource",
     "captured_stdout", "captured_stdin", "captured_stderr", "time_out",
     "socket_peer_reset", "ioerror_peer_reset", "run_with_locale", 'temp_umask',
@@ -596,6 +596,11 @@ def findfile(file, here=__file__, subdir=None):
         if os.path.exists(fn): return fn
     return file
 
+def create_empty_file(filename):
+    """Create an empty file. If the file already exists, truncate it."""
+    fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
+    os.close(fd)
+
 def sortdict(dict):
     "Like repr(dict), but in sorted order."
     items = sorted(dict.items())
index 26d4c146238a8ab25146c753664f5d2bf93313cb..02df7e3cab3c1a1224d05052427197a873bc74bc 100644 (file)
@@ -71,8 +71,8 @@ class AnyDBMTestCase(unittest.TestCase):
         f.close()
 
     def test_anydbm_creation_n_file_exists_with_invalid_contents(self):
-        with open(_fname, "w") as w:
-            pass # create an empty file
+        # create an empty file
+        test.support.create_empty_file(_fname)
 
         f = dbm.open(_fname, 'n')
         self.addCleanup(f.close)
index 1560a6bbf0b1b45895f006caf428a5ceb9a441fa..6ee08db0b6b01aa0e5d76511419670a86aa9e583 100644 (file)
@@ -1,5 +1,6 @@
 import unittest
-from test.support import run_unittest, TESTFN, skip_unless_symlink, can_symlink
+from test.support import (run_unittest, TESTFN, skip_unless_symlink,
+    can_symlink, create_empty_file)
 import glob
 import os
 import shutil
@@ -14,8 +15,7 @@ class GlobTests(unittest.TestCase):
         base, file = os.path.split(filename)
         if not os.path.exists(base):
             os.makedirs(base)
-        f = open(filename, 'w')
-        f.close()
+        create_empty_file(filename)
 
     def setUp(self):
         self.tempdir = TESTFN+"_dir"
index 83fcf2259f60b03c584bd67d24f3bd44e3e0ba8c..3041218083b4273b6d0d35491b4cfc0401a394e9 100644 (file)
@@ -324,8 +324,7 @@ class PEP3147Tests(unittest.TestCase):
             shutil.rmtree('pep3147')
         self.addCleanup(cleanup)
         # Touch the __init__.py file.
-        with open('pep3147/__init__.py', 'w'):
-            pass
+        support.create_empty_file('pep3147/__init__.py')
         m = __import__('pep3147')
         # Ensure we load the pyc file.
         support.forget('pep3147')
index 0332fdd826c8045a1baf02a30ca8bfc551c8a94e..a1cebf91e57974e11bd0dee18c118512963e5506 100644 (file)
@@ -14,7 +14,7 @@ import textwrap
 from test.support import (
     EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
     make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
-    unlink, unload)
+    unlink, unload, create_empty_file)
 from test import script_helper
 
 
@@ -103,7 +103,7 @@ class ImportTests(unittest.TestCase):
             sys.path.insert(0, os.curdir)
             try:
                 fname = TESTFN + os.extsep + "py"
-                open(fname, 'w').close()
+                create_empty_file(fname)
                 os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                                  stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
                 __import__(TESTFN)
index 18aeec72b5a236a09775d404775ffd21830d565d..8c8920a6c2aea7812fb7b7e2ee857bc7e2a4784c 100644 (file)
@@ -902,8 +902,7 @@ class TestMaildir(TestMailbox):
         # Now, write something into cur and remove it.  This changes
         # the mtime and should cause a re-read.
         filename = os.path.join(self._path, 'cur', 'stray-file')
-        f = open(filename, 'w')
-        f.close()
+        support.create_empty_file(filename)
         os.unlink(filename)
         self._box._refresh()
         self.assertTrue(refreshed())
index 61f44ee06db5436238d97cf9375f6c25507064a9..d1ae7574b74fc8d85a397a197582c3faa03cf0a3 100644 (file)
@@ -1023,7 +1023,7 @@ class TestExtendAddTypes(BaseTest):
         TYPE_CHECKER["file"] = check_file
 
     def test_filetype_ok(self):
-        open(support.TESTFN, "w").close()
+        support.create_empty_file(support.TESTFN)
         self.assertParseOK(["--file", support.TESTFN, "-afoo"],
                            {'file': support.TESTFN, 'a': 'foo'},
                            [])
index 0f2aedfa9ef86f5327234484ea3907df97c7c8ac..5f39f64340de1f6c30828f36626e4c4f533099b2 100644 (file)
@@ -1028,8 +1028,7 @@ if sys.platform != 'win32':
             os.mkdir(self.dir)
             try:
                 for fn in bytesfn:
-                    f = open(os.path.join(self.bdir, fn), "w")
-                    f.close()
+                    support.create_empty_file(os.path.join(self.bdir, fn))
                     fn = os.fsdecode(fn)
                     if fn in self.unicodefn:
                         raise ValueError("duplicate filename")
index c37e9362b00d0195e6def2d50418059d6ac87ac4..a8426b5c9adc54d1c1159712bcb0c4a9a50f6057 100644 (file)
@@ -7,7 +7,7 @@ import tempfile
 import unittest
 
 from imp import cache_from_source
-from test.support import run_unittest
+from test.support import run_unittest, create_empty_file
 
 class TestImport(unittest.TestCase):
 
@@ -29,7 +29,7 @@ class TestImport(unittest.TestCase):
         self.package_dir = os.path.join(self.test_dir,
                                         self.package_name)
         os.mkdir(self.package_dir)
-        open(os.path.join(self.package_dir, '__init__.py'), 'w').close()
+        create_empty_file(os.path.join(self.package_dir, '__init__.py'))
         self.module_path = os.path.join(self.package_dir, 'foo.py')
 
     def tearDown(self):
index c5dbd56504f779816675ce6e9616474bd50a577e..14bd356a0e11c314f8e0efab479c910569cecfc8 100644 (file)
@@ -410,7 +410,7 @@ class PosixTester(unittest.TestCase):
         self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
 
         # re-create the file
-        open(support.TESTFN, 'w').close()
+        support.create_empty_file(support.TESTFN)
         self._test_all_chown_common(posix.chown, support.TESTFN)
 
     @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
@@ -661,7 +661,7 @@ class PosixTester(unittest.TestCase):
     @unittest.skipUnless(hasattr(posix, 'fchownat'), "test needs posix.fchownat()")
     def test_fchownat(self):
         support.unlink(support.TESTFN)
-        open(support.TESTFN, 'w').close()
+        support.create_empty_file(support.TESTFN)
 
         f = posix.open(posix.getcwd(), posix.O_RDONLY)
         try:
@@ -766,7 +766,7 @@ class PosixTester(unittest.TestCase):
     @unittest.skipUnless(hasattr(posix, 'renameat'), "test needs posix.renameat()")
     def test_renameat(self):
         support.unlink(support.TESTFN)
-        open(support.TESTFN + 'ren', 'w').close()
+        support.create_empty_file(support.TESTFN + 'ren')
         f = posix.open(posix.getcwd(), posix.O_RDONLY)
         try:
             posix.renameat(f, support.TESTFN + 'ren', f, support.TESTFN)
@@ -791,7 +791,7 @@ class PosixTester(unittest.TestCase):
     @unittest.skipUnless(hasattr(posix, 'unlinkat'), "test needs posix.unlinkat()")
     def test_unlinkat(self):
         f = posix.open(posix.getcwd(), posix.O_RDONLY)
-        open(support.TESTFN + 'del', 'w').close()
+        support.create_empty_file(support.TESTFN + 'del')
         posix.stat(support.TESTFN + 'del') # should not throw exception
         try:
             posix.unlinkat(f, support.TESTFN + 'del')
index e476941d356c7b6417d5bc5021d674b1ab5c0418..439fa337947abd4078612299585a9fb35a4a413e 100644 (file)
@@ -8,7 +8,7 @@ import os
 import shutil
 import unittest
 
-from test.support import run_unittest
+from test.support import run_unittest, create_empty_file
 from reprlib import repr as r # Don't shadow builtin repr
 from reprlib import Repr
 from reprlib import recursive_repr
@@ -193,10 +193,9 @@ class ReprTests(unittest.TestCase):
         r(y)
         r(z)
 
-def touch(path, text=''):
-    fp = open(path, 'w')
-    fp.write(text)
-    fp.close()
+def write_file(path, text):
+    with open(path, 'w', encoding='ASCII') as fp:
+        fp.write(text)
 
 class LongReprTest(unittest.TestCase):
     def setUp(self):
@@ -206,10 +205,10 @@ class LongReprTest(unittest.TestCase):
         # Make the package and subpackage
         shutil.rmtree(self.pkgname, ignore_errors=True)
         os.mkdir(self.pkgname)
-        touch(os.path.join(self.pkgname, '__init__.py'))
+        create_empty_file(os.path.join(self.pkgname, '__init__.py'))
         shutil.rmtree(self.subpkgname, ignore_errors=True)
         os.mkdir(self.subpkgname)
-        touch(os.path.join(self.subpkgname, '__init__.py'))
+        create_empty_file(os.path.join(self.subpkgname, '__init__.py'))
         # Remember where we are
         self.here = os.getcwd()
         sys.path.insert(0, self.here)
@@ -231,7 +230,7 @@ class LongReprTest(unittest.TestCase):
 
     def test_module(self):
         eq = self.assertEqual
-        touch(os.path.join(self.subpkgname, self.pkgname + '.py'))
+        create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py'))
         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
         eq(repr(areallylongpackageandmodulenametotestreprtruncation),
            "<module %r from %r>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
@@ -239,7 +238,7 @@ class LongReprTest(unittest.TestCase):
 
     def test_type(self):
         eq = self.assertEqual
-        touch(os.path.join(self.subpkgname, 'foo.py'), '''\
+        write_file(os.path.join(self.subpkgname, 'foo.py'), '''\
 class foo(object):
     pass
 ''')
@@ -253,7 +252,7 @@ class foo(object):
         pass
 
     def test_class(self):
-        touch(os.path.join(self.subpkgname, 'bar.py'), '''\
+        write_file(os.path.join(self.subpkgname, 'bar.py'), '''\
 class bar:
     pass
 ''')
@@ -262,7 +261,7 @@ class bar:
         self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__)
 
     def test_instance(self):
-        touch(os.path.join(self.subpkgname, 'baz.py'), '''\
+        write_file(os.path.join(self.subpkgname, 'baz.py'), '''\
 class baz:
     pass
 ''')
@@ -273,7 +272,7 @@ class baz:
 
     def test_method(self):
         eq = self.assertEqual
-        touch(os.path.join(self.subpkgname, 'qux.py'), '''\
+        write_file(os.path.join(self.subpkgname, 'qux.py'), '''\
 class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
     def amethod(self): pass
 ''')
index 00f34b182489997fb82689c3f35b1ea1aefecfce..c1f96c096280b20267cf1fc2bc17e5e296952e2f 100644 (file)
@@ -7,7 +7,8 @@ import re
 import tempfile
 import py_compile
 from test.support import (
-    forget, make_legacy_pyc, run_unittest, unload, verbose, no_tracing)
+    forget, make_legacy_pyc, run_unittest, unload, verbose, no_tracing,
+    create_empty_file)
 from test.script_helper import (
     make_pkg, make_script, make_zip_pkg, make_zip_script, temp_dir)
 
@@ -113,8 +114,7 @@ class RunModuleTest(unittest.TestCase):
     def _add_pkg_dir(self, pkg_dir):
         os.mkdir(pkg_dir)
         pkg_fname = os.path.join(pkg_dir, "__init__.py")
-        pkg_file = open(pkg_fname, "w")
-        pkg_file.close()
+        create_empty_file(pkg_fname)
         return pkg_fname
 
     def _make_pkg(self, source, depth, mod_base="runpy_test"):
@@ -219,8 +219,7 @@ class RunModuleTest(unittest.TestCase):
             module_dir = os.path.join(module_dir, pkg_name)
         # Add sibling module
         sibling_fname = os.path.join(module_dir, "sibling.py")
-        sibling_file = open(sibling_fname, "w")
-        sibling_file.close()
+        create_empty_file(sibling_fname)
         if verbose: print("  Added sibling module:", sibling_fname)
         # Add nephew module
         uncle_dir = os.path.join(parent_dir, "uncle")
@@ -230,8 +229,7 @@ class RunModuleTest(unittest.TestCase):
         self._add_pkg_dir(cousin_dir)
         if verbose: print("  Added cousin package:", cousin_dir)
         nephew_fname = os.path.join(cousin_dir, "nephew.py")
-        nephew_file = open(nephew_fname, "w")
-        nephew_file.close()
+        create_empty_file(nephew_fname)
         if verbose: print("  Added nephew module:", nephew_fname)
 
     def _check_relative_imports(self, depth, run_name=None):
index 839f7428142b7745fb21ed50e56231e269652a49..ad31f470a033ea703fe9abddcc77d75c46b1a323 100644 (file)
@@ -107,8 +107,7 @@ class TestShutil(unittest.TestCase):
             self.errorState = 0
             os.mkdir(TESTFN)
             self.childpath = os.path.join(TESTFN, 'a')
-            f = open(self.childpath, 'w')
-            f.close()
+            support.create_empty_file(self.childpath)
             old_dir_mode = os.stat(TESTFN).st_mode
             old_child_mode = os.stat(self.childpath).st_mode
             # Make unwritable.
@@ -156,7 +155,7 @@ class TestShutil(unittest.TestCase):
     def test_rmtree_dont_delete_file(self):
         # When called on a file instead of a directory, don't delete it.
         handle, path = tempfile.mkstemp()
-        os.fdopen(handle).close()
+        os.close(handle)
         self.assertRaises(OSError, shutil.rmtree, path)
         os.remove(path)
 
index ddde01ccc9766f61646908afd38047ca47f20da2..d65e1b5187e84e3bea705dcf6e47b3b08e320750 100644 (file)
@@ -893,7 +893,7 @@ class WriteTest(WriteTestBase):
         try:
             for name in ("foo", "bar", "baz"):
                 name = os.path.join(tempdir, name)
-                open(name, "wb").close()
+                support.create_empty_file(name)
 
             exclude = os.path.isfile
 
@@ -920,7 +920,7 @@ class WriteTest(WriteTestBase):
         try:
             for name in ("foo", "bar", "baz"):
                 name = os.path.join(tempdir, name)
-                open(name, "wb").close()
+                support.create_empty_file(name)
 
             def filter(tarinfo):
                 if os.path.basename(tarinfo.name) == "bar":
@@ -959,7 +959,7 @@ class WriteTest(WriteTestBase):
         # and compare the stored name with the original.
         foo = os.path.join(TEMPDIR, "foo")
         if not dir:
-            open(foo, "w").close()
+            support.create_empty_file(foo)
         else:
             os.mkdir(foo)
 
index 6c2011ace8e1370bf36129a34bffa6f9fc57b4ed..68bd658a754a41d17e5dafa02f1fa1079ddc71a9 100644 (file)
@@ -6,7 +6,7 @@ import unicodedata
 
 import unittest
 from test.support import (run_unittest, rmtree,
-    TESTFN_ENCODING, TESTFN_UNICODE, TESTFN_UNENCODABLE)
+    TESTFN_ENCODING, TESTFN_UNICODE, TESTFN_UNENCODABLE, create_empty_file)
 
 if not os.path.supports_unicode_filenames:
     try:
@@ -99,8 +99,7 @@ class TestUnicodeFiles(unittest.TestCase):
     # top-level 'test' functions would be if they could take params
     def _test_single(self, filename):
         remove_if_exists(filename)
-        f = open(filename, "w")
-        f.close()
+        create_empty_file(filename)
         try:
             self._do_single(filename)
         finally:
index ab669cf199abaafe0a617ce86fc11ce203b0539f..56141efbfb75e544cb6b53f6056b2859b4026876 100644 (file)
@@ -411,7 +411,7 @@ class BadFileZipImportTestCase(unittest.TestCase):
 
     def testEmptyFile(self):
         support.unlink(TESTMOD)
-        open(TESTMOD, 'w+').close()
+        support.create_empty_file(TESTMOD)
         self.assertZipFailure(TESTMOD)
 
     def testFileUnreadable(self):