From bf816223dfe8f1d36a020b4bc02060b8d1ce7d26 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Thu, 30 Jun 2011 23:25:47 +0200 Subject: [PATCH] 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). --- 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 index 4e46339b43c..c7c36f3cc78 100644 --- a/Lib/distutils/tests/test_build_py.py +++ b/Lib/distutils/tests/test_build_py.py @@ -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 diff --git a/Lib/test/support.py b/Lib/test/support.py index d4010f4832a..2ce013fcdd0 100644 --- a/Lib/test/support.py +++ b/Lib/test/support.py @@ -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()) diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py index 26d4c146238..02df7e3cab3 100644 --- a/Lib/test/test_dbm.py +++ b/Lib/test/test_dbm.py @@ -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) diff --git a/Lib/test/test_glob.py b/Lib/test/test_glob.py index 1560a6bbf0b..6ee08db0b6b 100644 --- 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 @@ 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" diff --git a/Lib/test/test_imp.py b/Lib/test/test_imp.py index 83fcf2259f6..3041218083b 100644 --- a/Lib/test/test_imp.py +++ b/Lib/test/test_imp.py @@ -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') diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py index 0332fdd826c..a1cebf91e57 100644 --- a/Lib/test/test_import.py +++ b/Lib/test/test_import.py @@ -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) diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py index 18aeec72b5a..8c8920a6c2a 100644 --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -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()) diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py index 61f44ee06db..d1ae7574b74 100644 --- a/Lib/test/test_optparse.py +++ b/Lib/test/test_optparse.py @@ -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'}, []) diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index 0f2aedfa9ef..5f39f64340d 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -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") diff --git a/Lib/test/test_pkgimport.py b/Lib/test/test_pkgimport.py index c37e9362b00..a8426b5c9ad 100644 --- a/Lib/test/test_pkgimport.py +++ b/Lib/test/test_pkgimport.py @@ -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): diff --git a/Lib/test/test_posix.py b/Lib/test/test_posix.py index c5dbd56504f..14bd356a0e1 100644 --- a/Lib/test/test_posix.py +++ b/Lib/test/test_posix.py @@ -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') diff --git a/Lib/test/test_reprlib.py b/Lib/test/test_reprlib.py index e476941d356..439fa337947 100644 --- a/Lib/test/test_reprlib.py +++ b/Lib/test/test_reprlib.py @@ -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), "" % (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), "" % 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 ''') diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py index 00f34b18248..c1f96c09628 100644 --- a/Lib/test/test_runpy.py +++ b/Lib/test/test_runpy.py @@ -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): diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index 839f7428142..ad31f470a03 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -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) diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index ddde01ccc97..d65e1b5187e 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -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) diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py index 6c2011ace8e..68bd658a754 100644 --- a/Lib/test/test_unicode_file.py +++ b/Lib/test/test_unicode_file.py @@ -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: diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py index ab669cf199a..56141efbfb7 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -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):