[Python-checkins] cpython: Issue #12451: Add support.create_empty_file()

victor.stinner python-checkins at python.org
Thu Jun 30 23:25:59 CEST 2011


http://hg.python.org/cpython/rev/0c49260e85a0
changeset:   71103:0c49260e85a0
user:        Victor Stinner <victor.stinner at haypocalc.com>
date:        Thu Jun 30 23:25:47 2011 +0200
summary:
  Issue #12451: Add support.create_empty_file()

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).

files:
  Lib/distutils/tests/test_build_py.py |   6 ++--
  Lib/test/support.py                  |   7 ++++-
  Lib/test/test_dbm.py                 |   4 +-
  Lib/test/test_glob.py                |   6 ++--
  Lib/test/test_imp.py                 |   3 +-
  Lib/test/test_import.py              |   4 +-
  Lib/test/test_mailbox.py             |   3 +-
  Lib/test/test_optparse.py            |   2 +-
  Lib/test/test_os.py                  |   3 +-
  Lib/test/test_pkgimport.py           |   4 +-
  Lib/test/test_posix.py               |   8 ++--
  Lib/test/test_reprlib.py             |  23 +++++++--------
  Lib/test/test_runpy.py               |  12 +++----
  Lib/test/test_shutil.py              |   5 +--
  Lib/test/test_tarfile.py             |   6 ++--
  Lib/test/test_unicode_file.py        |   5 +--
  Lib/test/test_zipimport.py           |   2 +-
  17 files changed, 50 insertions(+), 53 deletions(-)


diff --git a/Lib/distutils/tests/test_build_py.py b/Lib/distutils/tests/test_build_py.py
--- a/Lib/distutils/tests/test_build_py.py
+++ b/Lib/distutils/tests/test_build_py.py
@@ -10,7 +10,7 @@
 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 @@
 
         # 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
diff --git a/Lib/test/support.py b/Lib/test/support.py
--- a/Lib/test/support.py
+++ b/Lib/test/support.py
@@ -40,7 +40,7 @@
     "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 @@
         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())
diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py
--- a/Lib/test/test_dbm.py
+++ b/Lib/test/test_dbm.py
@@ -71,8 +71,8 @@
         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)
diff --git a/Lib/test/test_glob.py b/Lib/test/test_glob.py
--- a/Lib/test/test_glob.py
+++ b/Lib/test/test_glob.py
@@ -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 @@
         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"
diff --git a/Lib/test/test_imp.py b/Lib/test/test_imp.py
--- a/Lib/test/test_imp.py
+++ b/Lib/test/test_imp.py
@@ -324,8 +324,7 @@
             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')
diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py
--- a/Lib/test/test_import.py
+++ b/Lib/test/test_import.py
@@ -14,7 +14,7 @@
 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 @@
             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)
diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py
--- a/Lib/test/test_mailbox.py
+++ b/Lib/test/test_mailbox.py
@@ -902,8 +902,7 @@
         # 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())
diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py
--- a/Lib/test/test_optparse.py
+++ b/Lib/test/test_optparse.py
@@ -1023,7 +1023,7 @@
         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'},
                            [])
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
--- a/Lib/test/test_os.py
+++ b/Lib/test/test_os.py
@@ -1028,8 +1028,7 @@
             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")
diff --git a/Lib/test/test_pkgimport.py b/Lib/test/test_pkgimport.py
--- a/Lib/test/test_pkgimport.py
+++ b/Lib/test/test_pkgimport.py
@@ -7,7 +7,7 @@
 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 @@
         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):
diff --git a/Lib/test/test_posix.py b/Lib/test/test_posix.py
--- a/Lib/test/test_posix.py
+++ b/Lib/test/test_posix.py
@@ -410,7 +410,7 @@
         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 @@
     @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 @@
     @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 @@
     @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')
diff --git a/Lib/test/test_reprlib.py b/Lib/test/test_reprlib.py
--- a/Lib/test/test_reprlib.py
+++ b/Lib/test/test_reprlib.py
@@ -8,7 +8,7 @@
 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 @@
         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 @@
         # 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 @@
 
     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 @@
 
     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 @@
         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 @@
         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 @@
 
     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
 ''')
diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py
--- a/Lib/test/test_runpy.py
+++ b/Lib/test/test_runpy.py
@@ -7,7 +7,8 @@
 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 @@
     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 @@
             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 @@
         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):
diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py
--- a/Lib/test/test_shutil.py
+++ b/Lib/test/test_shutil.py
@@ -107,8 +107,7 @@
             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 @@
     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)
 
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -893,7 +893,7 @@
         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 @@
         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 @@
         # 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)
 
diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py
--- a/Lib/test/test_unicode_file.py
+++ b/Lib/test/test_unicode_file.py
@@ -6,7 +6,7 @@
 
 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 @@
     # 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:
diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py
--- a/Lib/test/test_zipimport.py
+++ b/Lib/test/test_zipimport.py
@@ -411,7 +411,7 @@
 
     def testEmptyFile(self):
         support.unlink(TESTMOD)
-        open(TESTMOD, 'w+').close()
+        support.create_empty_file(TESTMOD)
         self.assertZipFailure(TESTMOD)
 
     def testFileUnreadable(self):

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list