mirror of https://github.com/python/cpython
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).
This commit is contained in:
parent
61600cb0c3
commit
bf816223df
|
@ -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
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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"
|
||||
|
|
|
@ -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')
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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'},
|
||||
[])
|
||||
|
|
|
@ -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")
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -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')
|
||||
|
|
|
@ -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
|
||||
''')
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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):
|
||||
|
|
Loading…
Reference in New Issue