bpo-40275: Use new test.support helper submodules in tests (GH-21451)

This commit is contained in:
Hai Shi 2020-08-04 00:47:42 +08:00 committed by GitHub
parent a7f5d93bb6
commit bb0424b122
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 324 additions and 278 deletions

View File

@ -58,6 +58,9 @@ import linecache
from contextlib import contextmanager from contextlib import contextmanager
from itertools import islice, repeat from itertools import islice, repeat
import test.support import test.support
from test.support import import_helper
from test.support import os_helper
class BdbException(Exception): pass class BdbException(Exception): pass
class BdbError(BdbException): """Error raised by the Bdb instance.""" class BdbError(BdbException): """Error raised by the Bdb instance."""
@ -531,7 +534,7 @@ def run_test(modules, set_list, skip=None):
@contextmanager @contextmanager
def create_modules(modules): def create_modules(modules):
with test.support.temp_cwd(): with os_helper.temp_cwd():
sys.path.append(os.getcwd()) sys.path.append(os.getcwd())
try: try:
for m in modules: for m in modules:
@ -543,7 +546,7 @@ def create_modules(modules):
yield yield
finally: finally:
for m in modules: for m in modules:
test.support.forget(m) import_helper.forget(m)
sys.path.pop() sys.path.pop()
def break_in_func(funcname, fname=__file__, temporary=False, cond=None): def break_in_func(funcname, fname=__file__, temporary=False, cond=None):

View File

@ -4,9 +4,10 @@ import unittest
from textwrap import dedent from textwrap import dedent
from contextlib import ExitStack from contextlib import ExitStack
from unittest import mock from unittest import mock
from test import support from test.support import import_helper
code = support.import_module('code')
code = import_helper.import_module('code')
class TestInteractiveConsole(unittest.TestCase): class TestInteractiveConsole(unittest.TestCase):

View File

@ -1,5 +1,7 @@
# Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs) # Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs)
from test import support from test import support
from test.support import import_helper
from test.support import os_helper
import unittest import unittest
from collections import namedtuple from collections import namedtuple
@ -1339,8 +1341,8 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
# #
# The global path configuration (_Py_path_config) must be a copy # The global path configuration (_Py_path_config) must be a copy
# of the path configuration of PyInterpreter.config (PyConfig). # of the path configuration of PyInterpreter.config (PyConfig).
ctypes = support.import_module('ctypes') ctypes = import_helper.import_module('ctypes')
_testinternalcapi = support.import_module('_testinternalcapi') _testinternalcapi = import_helper.import_module('_testinternalcapi')
def get_func(name): def get_func(name):
func = getattr(ctypes.pythonapi, name) func = getattr(ctypes.pythonapi, name)
@ -1418,7 +1420,7 @@ class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
returncode=1) returncode=1)
def test_audit_run_interactivehook(self): def test_audit_run_interactivehook(self):
startup = os.path.join(self.oldcwd, support.TESTFN) + ".py" startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
with open(startup, "w", encoding="utf-8") as f: with open(startup, "w", encoding="utf-8") as f:
print("import sys", file=f) print("import sys", file=f)
print("sys.__interactivehook__ = lambda: None", file=f) print("sys.__interactivehook__ = lambda: None", file=f)
@ -1431,7 +1433,7 @@ class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
os.unlink(startup) os.unlink(startup)
def test_audit_run_startup(self): def test_audit_run_startup(self):
startup = os.path.join(self.oldcwd, support.TESTFN) + ".py" startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
with open(startup, "w", encoding="utf-8") as f: with open(startup, "w", encoding="utf-8") as f:
print("pass", file=f) print("pass", file=f)
try: try:

View File

@ -11,10 +11,12 @@ import sys
import unittest import unittest
from subprocess import PIPE, Popen from subprocess import PIPE, Popen
from test import support from test import support
from test.support import import_helper
from test.support import os_helper
from test.support import _4G, bigmemtest from test.support import _4G, bigmemtest
from test.support.script_helper import assert_python_ok, assert_python_failure from test.support.script_helper import assert_python_ok, assert_python_failure
gzip = support.import_module('gzip') gzip = import_helper.import_module('gzip')
data1 = b""" int length=DEFAULTALLOC, err = Z_OK; data1 = b""" int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal; PyObject *RetVal;
@ -29,7 +31,7 @@ data2 = b"""/* zlibmodule.c -- gzip-compatible data compression */
""" """
TEMPDIR = os.path.abspath(support.TESTFN) + '-gzdir' TEMPDIR = os.path.abspath(os_helper.TESTFN) + '-gzdir'
class UnseekableIO(io.BytesIO): class UnseekableIO(io.BytesIO):
@ -44,13 +46,13 @@ class UnseekableIO(io.BytesIO):
class BaseTest(unittest.TestCase): class BaseTest(unittest.TestCase):
filename = support.TESTFN filename = os_helper.TESTFN
def setUp(self): def setUp(self):
support.unlink(self.filename) os_helper.unlink(self.filename)
def tearDown(self): def tearDown(self):
support.unlink(self.filename) os_helper.unlink(self.filename)
class TestGzip(BaseTest): class TestGzip(BaseTest):
@ -286,7 +288,7 @@ class TestGzip(BaseTest):
self.test_write() self.test_write()
with gzip.GzipFile(self.filename, 'r') as f: with gzip.GzipFile(self.filename, 'r') as f:
self.assertEqual(f.myfileobj.mode, 'rb') self.assertEqual(f.myfileobj.mode, 'rb')
support.unlink(self.filename) os_helper.unlink(self.filename)
with gzip.GzipFile(self.filename, 'x') as f: with gzip.GzipFile(self.filename, 'x') as f:
self.assertEqual(f.myfileobj.mode, 'xb') self.assertEqual(f.myfileobj.mode, 'xb')
@ -365,7 +367,7 @@ class TestGzip(BaseTest):
self.assertEqual(isizeBytes, struct.pack('<i', len(data1))) self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
def test_metadata_ascii_name(self): def test_metadata_ascii_name(self):
self.filename = support.TESTFN_ASCII self.filename = os_helper.TESTFN_ASCII
self.test_metadata() self.test_metadata()
def test_compresslevel_metadata(self): def test_compresslevel_metadata(self):
@ -497,7 +499,7 @@ class TestGzip(BaseTest):
self.assertEqual(g.mode, gzip.READ) self.assertEqual(g.mode, gzip.READ)
for mode in "wb", "ab", "xb": for mode in "wb", "ab", "xb":
if "x" in mode: if "x" in mode:
support.unlink(self.filename) os_helper.unlink(self.filename)
with open(self.filename, mode) as f: with open(self.filename, mode) as f:
with self.assertWarns(FutureWarning): with self.assertWarns(FutureWarning):
g = gzip.GzipFile(fileobj=f) g = gzip.GzipFile(fileobj=f)
@ -611,7 +613,7 @@ class TestOpen(BaseTest):
with self.assertRaises(FileExistsError): with self.assertRaises(FileExistsError):
gzip.open(self.filename, "xb") gzip.open(self.filename, "xb")
support.unlink(self.filename) os_helper.unlink(self.filename)
with gzip.open(self.filename, "xb") as f: with gzip.open(self.filename, "xb") as f:
f.write(uncompressed) f.write(uncompressed)
with open(self.filename, "rb") as f: with open(self.filename, "rb") as f:
@ -648,7 +650,7 @@ class TestOpen(BaseTest):
with self.assertRaises(FileExistsError): with self.assertRaises(FileExistsError):
gzip.open(self.filename, "x") gzip.open(self.filename, "x")
support.unlink(self.filename) os_helper.unlink(self.filename)
with gzip.open(self.filename, "x") as f: with gzip.open(self.filename, "x") as f:
f.write(uncompressed) f.write(uncompressed)
with open(self.filename, "rb") as f: with open(self.filename, "rb") as f:
@ -734,7 +736,7 @@ def create_and_remove_directory(directory):
try: try:
return function(*args, **kwargs) return function(*args, **kwargs)
finally: finally:
support.rmtree(directory) os_helper.rmtree(directory)
return wrapper return wrapper
return decorator return decorator

View File

@ -8,9 +8,10 @@ import unittest
import socket import socket
import shutil import shutil
import threading import threading
from test.support import TESTFN, requires, unlink, bigmemtest from test.support import requires, bigmemtest
from test.support import SHORT_TIMEOUT from test.support import SHORT_TIMEOUT
from test.support import socket_helper from test.support import socket_helper
from test.support.os_helper import TESTFN, unlink
import io # C implementation of io import io # C implementation of io
import _pyio as pyio # Python implementation of io import _pyio as pyio # Python implementation of io

View File

@ -2,7 +2,7 @@ import os
import textwrap import textwrap
import unittest import unittest
from test import support from test.support import os_helper
from test.support.script_helper import assert_python_ok from test.support.script_helper import assert_python_ok
@ -13,8 +13,8 @@ class TestLLTrace(unittest.TestCase):
# bpo-34113. The crash happened at the command line console of # bpo-34113. The crash happened at the command line console of
# debug Python builds with __ltrace__ enabled (only possible in console), # debug Python builds with __ltrace__ enabled (only possible in console),
# when the interal Python stack was negatively adjusted # when the interal Python stack was negatively adjusted
with open(support.TESTFN, 'w') as fd: with open(os_helper.TESTFN, 'w') as fd:
self.addCleanup(os.unlink, support.TESTFN) self.addCleanup(os_helper.unlink, os_helper.TESTFN)
fd.write(textwrap.dedent("""\ fd.write(textwrap.dedent("""\
import code import code
@ -25,7 +25,7 @@ class TestLLTrace(unittest.TestCase):
print('unreachable if bug exists') print('unreachable if bug exists')
""")) """))
assert_python_ok(support.TESTFN) assert_python_ok(os_helper.TESTFN)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -10,10 +10,13 @@ import unittest
import weakref import weakref
from collections.abc import MutableMapping from collections.abc import MutableMapping
from test import mapping_tests, support from test import mapping_tests, support
from test.support import import_helper
py_coll = support.import_fresh_module('collections', blocked=['_collections']) py_coll = import_helper.import_fresh_module('collections',
c_coll = support.import_fresh_module('collections', fresh=['_collections']) blocked=['_collections'])
c_coll = import_helper.import_fresh_module('collections',
fresh=['_collections'])
@contextlib.contextmanager @contextlib.contextmanager

View File

@ -11,8 +11,9 @@ import tempfile
import unittest import unittest
from unittest import mock from unittest import mock
from test import support from test.support import import_helper
from test.support import TESTFN, FakePath from test.support import os_helper
from test.support.os_helper import TESTFN, FakePath
try: try:
import grp, pwd import grp, pwd
@ -1346,7 +1347,7 @@ class _BasePathTest(object):
def setUp(self): def setUp(self):
def cleanup(): def cleanup():
os.chmod(join('dirE'), 0o777) os.chmod(join('dirE'), 0o777)
support.rmtree(BASE) os_helper.rmtree(BASE)
self.addCleanup(cleanup) self.addCleanup(cleanup)
os.mkdir(BASE) os.mkdir(BASE)
os.mkdir(join('dirA')) os.mkdir(join('dirA'))
@ -1363,7 +1364,7 @@ class _BasePathTest(object):
with open(join('dirC', 'dirD', 'fileD'), 'wb') as f: with open(join('dirC', 'dirD', 'fileD'), 'wb') as f:
f.write(b"this is file D\n") f.write(b"this is file D\n")
os.chmod(join('dirE'), 0) os.chmod(join('dirE'), 0)
if support.can_symlink(): if os_helper.can_symlink():
# Relative symlinks. # Relative symlinks.
os.symlink('fileA', join('linkA')) os.symlink('fileA', join('linkA'))
os.symlink('non-existing', join('brokenLink')) os.symlink('non-existing', join('brokenLink'))
@ -1414,7 +1415,7 @@ class _BasePathTest(object):
self.assertTrue(p.is_absolute()) self.assertTrue(p.is_absolute())
def test_home(self): def test_home(self):
with support.EnvironmentVarGuard() as env: with os_helper.EnvironmentVarGuard() as env:
self._test_home(self.cls.home()) self._test_home(self.cls.home())
env.clear() env.clear()
@ -1470,7 +1471,7 @@ class _BasePathTest(object):
self.assertIs(True, (p / 'dirA').exists()) self.assertIs(True, (p / 'dirA').exists())
self.assertIs(True, (p / 'fileA').exists()) self.assertIs(True, (p / 'fileA').exists())
self.assertIs(False, (p / 'fileA' / 'bah').exists()) self.assertIs(False, (p / 'fileA' / 'bah').exists())
if support.can_symlink(): if os_helper.can_symlink():
self.assertIs(True, (p / 'linkA').exists()) self.assertIs(True, (p / 'linkA').exists())
self.assertIs(True, (p / 'linkB').exists()) self.assertIs(True, (p / 'linkB').exists())
self.assertIs(True, (p / 'linkB' / 'fileB').exists()) self.assertIs(True, (p / 'linkB' / 'fileB').exists())
@ -1515,11 +1516,11 @@ class _BasePathTest(object):
it = p.iterdir() it = p.iterdir()
paths = set(it) paths = set(it)
expected = ['dirA', 'dirB', 'dirC', 'dirE', 'fileA'] expected = ['dirA', 'dirB', 'dirC', 'dirE', 'fileA']
if support.can_symlink(): if os_helper.can_symlink():
expected += ['linkA', 'linkB', 'brokenLink', 'brokenLinkLoop'] expected += ['linkA', 'linkB', 'brokenLink', 'brokenLinkLoop']
self.assertEqual(paths, { P(BASE, q) for q in expected }) self.assertEqual(paths, { P(BASE, q) for q in expected })
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_iterdir_symlink(self): def test_iterdir_symlink(self):
# __iter__ on a symlink to a directory. # __iter__ on a symlink to a directory.
P = self.cls P = self.cls
@ -1548,16 +1549,16 @@ class _BasePathTest(object):
_check(it, ["fileA"]) _check(it, ["fileA"])
_check(p.glob("fileB"), []) _check(p.glob("fileB"), [])
_check(p.glob("dir*/file*"), ["dirB/fileB", "dirC/fileC"]) _check(p.glob("dir*/file*"), ["dirB/fileB", "dirC/fileC"])
if not support.can_symlink(): if not os_helper.can_symlink():
_check(p.glob("*A"), ['dirA', 'fileA']) _check(p.glob("*A"), ['dirA', 'fileA'])
else: else:
_check(p.glob("*A"), ['dirA', 'fileA', 'linkA']) _check(p.glob("*A"), ['dirA', 'fileA', 'linkA'])
if not support.can_symlink(): if not os_helper.can_symlink():
_check(p.glob("*B/*"), ['dirB/fileB']) _check(p.glob("*B/*"), ['dirB/fileB'])
else: else:
_check(p.glob("*B/*"), ['dirB/fileB', 'dirB/linkD', _check(p.glob("*B/*"), ['dirB/fileB', 'dirB/linkD',
'linkB/fileB', 'linkB/linkD']) 'linkB/fileB', 'linkB/linkD'])
if not support.can_symlink(): if not os_helper.can_symlink():
_check(p.glob("*/fileB"), ['dirB/fileB']) _check(p.glob("*/fileB"), ['dirB/fileB'])
else: else:
_check(p.glob("*/fileB"), ['dirB/fileB', 'linkB/fileB']) _check(p.glob("*/fileB"), ['dirB/fileB', 'linkB/fileB'])
@ -1572,7 +1573,7 @@ class _BasePathTest(object):
_check(it, ["fileA"]) _check(it, ["fileA"])
_check(p.rglob("fileB"), ["dirB/fileB"]) _check(p.rglob("fileB"), ["dirB/fileB"])
_check(p.rglob("*/fileA"), []) _check(p.rglob("*/fileA"), [])
if not support.can_symlink(): if not os_helper.can_symlink():
_check(p.rglob("*/fileB"), ["dirB/fileB"]) _check(p.rglob("*/fileB"), ["dirB/fileB"])
else: else:
_check(p.rglob("*/fileB"), ["dirB/fileB", "dirB/linkD/fileB", _check(p.rglob("*/fileB"), ["dirB/fileB", "dirB/linkD/fileB",
@ -1583,7 +1584,7 @@ class _BasePathTest(object):
_check(p.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"]) _check(p.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"])
_check(p.rglob("*/*"), ["dirC/dirD/fileD"]) _check(p.rglob("*/*"), ["dirC/dirD/fileD"])
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_rglob_symlink_loop(self): def test_rglob_symlink_loop(self):
# Don't get fooled by symlink loops (Issue #26012). # Don't get fooled by symlink loops (Issue #26012).
P = self.cls P = self.cls
@ -1626,7 +1627,7 @@ class _BasePathTest(object):
self.assertEqual(set(p.glob("dirA/../file*")), { P(BASE, "dirA/../fileA") }) self.assertEqual(set(p.glob("dirA/../file*")), { P(BASE, "dirA/../fileA") })
self.assertEqual(set(p.glob("../xyzzy")), set()) self.assertEqual(set(p.glob("../xyzzy")), set())
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_glob_permissions(self): def test_glob_permissions(self):
# See bpo-38894 # See bpo-38894
P = self.cls P = self.cls
@ -1670,7 +1671,7 @@ class _BasePathTest(object):
# This can be used to check both relative and absolute resolutions. # This can be used to check both relative and absolute resolutions.
_check_resolve_relative = _check_resolve_absolute = _check_resolve _check_resolve_relative = _check_resolve_absolute = _check_resolve
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_resolve_common(self): def test_resolve_common(self):
P = self.cls P = self.cls
p = P(BASE, 'foo') p = P(BASE, 'foo')
@ -1710,8 +1711,9 @@ class _BasePathTest(object):
# resolves to 'dirB/..' first before resolving to parent of dirB. # resolves to 'dirB/..' first before resolving to parent of dirB.
self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False) self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
# Now create absolute symlinks. # Now create absolute symlinks.
d = support._longpath(tempfile.mkdtemp(suffix='-dirD', dir=os.getcwd())) d = os_helper._longpath(tempfile.mkdtemp(suffix='-dirD',
self.addCleanup(support.rmtree, d) dir=os.getcwd()))
self.addCleanup(os_helper.rmtree, d)
os.symlink(os.path.join(d), join('dirA', 'linkX')) os.symlink(os.path.join(d), join('dirA', 'linkX'))
os.symlink(join('dirB'), os.path.join(d, 'linkY')) os.symlink(join('dirB'), os.path.join(d, 'linkY'))
p = P(BASE, 'dirA', 'linkX', 'linkY', 'fileB') p = P(BASE, 'dirA', 'linkX', 'linkY', 'fileB')
@ -1730,7 +1732,7 @@ class _BasePathTest(object):
# resolves to 'dirB/..' first before resolving to parent of dirB. # resolves to 'dirB/..' first before resolving to parent of dirB.
self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False) self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_resolve_dot(self): def test_resolve_dot(self):
# See https://bitbucket.org/pitrou/pathlib/issue/9/pathresolve-fails-on-complex-symlinks # See https://bitbucket.org/pitrou/pathlib/issue/9/pathresolve-fails-on-complex-symlinks
p = self.cls(BASE) p = self.cls(BASE)
@ -1784,7 +1786,7 @@ class _BasePathTest(object):
self.addCleanup(p.chmod, st.st_mode) self.addCleanup(p.chmod, st.st_mode)
self.assertNotEqual(p.stat(), st) self.assertNotEqual(p.stat(), st)
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_lstat(self): def test_lstat(self):
p = self.cls(BASE)/ 'linkA' p = self.cls(BASE)/ 'linkA'
st = p.stat() st = p.stat()
@ -1899,7 +1901,7 @@ class _BasePathTest(object):
self.assertEqual(os.stat(r).st_size, size) self.assertEqual(os.stat(r).st_size, size)
self.assertFileNotFound(q.stat) self.assertFileNotFound(q.stat)
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_readlink(self): def test_readlink(self):
P = self.cls(BASE) P = self.cls(BASE)
self.assertEqual((P / 'linkA').readlink(), self.cls('fileA')) self.assertEqual((P / 'linkA').readlink(), self.cls('fileA'))
@ -2074,7 +2076,7 @@ class _BasePathTest(object):
self.assertNotIn(str(p12), concurrently_created) self.assertNotIn(str(p12), concurrently_created)
self.assertTrue(p.exists()) self.assertTrue(p.exists())
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_symlink_to(self): def test_symlink_to(self):
P = self.cls(BASE) P = self.cls(BASE)
target = P / 'fileA' target = P / 'fileA'
@ -2104,7 +2106,7 @@ class _BasePathTest(object):
self.assertFalse((P / 'fileA').is_dir()) self.assertFalse((P / 'fileA').is_dir())
self.assertFalse((P / 'non-existing').is_dir()) self.assertFalse((P / 'non-existing').is_dir())
self.assertFalse((P / 'fileA' / 'bah').is_dir()) self.assertFalse((P / 'fileA' / 'bah').is_dir())
if support.can_symlink(): if os_helper.can_symlink():
self.assertFalse((P / 'linkA').is_dir()) self.assertFalse((P / 'linkA').is_dir())
self.assertTrue((P / 'linkB').is_dir()) self.assertTrue((P / 'linkB').is_dir())
self.assertFalse((P/ 'brokenLink').is_dir(), False) self.assertFalse((P/ 'brokenLink').is_dir(), False)
@ -2117,7 +2119,7 @@ class _BasePathTest(object):
self.assertFalse((P / 'dirA').is_file()) self.assertFalse((P / 'dirA').is_file())
self.assertFalse((P / 'non-existing').is_file()) self.assertFalse((P / 'non-existing').is_file())
self.assertFalse((P / 'fileA' / 'bah').is_file()) self.assertFalse((P / 'fileA' / 'bah').is_file())
if support.can_symlink(): if os_helper.can_symlink():
self.assertTrue((P / 'linkA').is_file()) self.assertTrue((P / 'linkA').is_file())
self.assertFalse((P / 'linkB').is_file()) self.assertFalse((P / 'linkB').is_file())
self.assertFalse((P/ 'brokenLink').is_file()) self.assertFalse((P/ 'brokenLink').is_file())
@ -2133,7 +2135,7 @@ class _BasePathTest(object):
self.assertFalse((P / 'non-existing').is_mount()) self.assertFalse((P / 'non-existing').is_mount())
self.assertFalse((P / 'fileA' / 'bah').is_mount()) self.assertFalse((P / 'fileA' / 'bah').is_mount())
self.assertTrue(R.is_mount()) self.assertTrue(R.is_mount())
if support.can_symlink(): if os_helper.can_symlink():
self.assertFalse((P / 'linkA').is_mount()) self.assertFalse((P / 'linkA').is_mount())
self.assertIs(self.cls('/\udfff').is_mount(), False) self.assertIs(self.cls('/\udfff').is_mount(), False)
self.assertIs(self.cls('/\x00').is_mount(), False) self.assertIs(self.cls('/\x00').is_mount(), False)
@ -2144,13 +2146,13 @@ class _BasePathTest(object):
self.assertFalse((P / 'dirA').is_symlink()) self.assertFalse((P / 'dirA').is_symlink())
self.assertFalse((P / 'non-existing').is_symlink()) self.assertFalse((P / 'non-existing').is_symlink())
self.assertFalse((P / 'fileA' / 'bah').is_symlink()) self.assertFalse((P / 'fileA' / 'bah').is_symlink())
if support.can_symlink(): if os_helper.can_symlink():
self.assertTrue((P / 'linkA').is_symlink()) self.assertTrue((P / 'linkA').is_symlink())
self.assertTrue((P / 'linkB').is_symlink()) self.assertTrue((P / 'linkB').is_symlink())
self.assertTrue((P/ 'brokenLink').is_symlink()) self.assertTrue((P/ 'brokenLink').is_symlink())
self.assertIs((P / 'fileA\udfff').is_file(), False) self.assertIs((P / 'fileA\udfff').is_file(), False)
self.assertIs((P / 'fileA\x00').is_file(), False) self.assertIs((P / 'fileA\x00').is_file(), False)
if support.can_symlink(): if os_helper.can_symlink():
self.assertIs((P / 'linkA\udfff').is_file(), False) self.assertIs((P / 'linkA\udfff').is_file(), False)
self.assertIs((P / 'linkA\x00').is_file(), False) self.assertIs((P / 'linkA\x00').is_file(), False)
@ -2288,15 +2290,15 @@ class _BasePathTest(object):
finally: finally:
os.chdir(old_path) os.chdir(old_path)
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_complex_symlinks_absolute(self): def test_complex_symlinks_absolute(self):
self._check_complex_symlinks(BASE) self._check_complex_symlinks(BASE)
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_complex_symlinks_relative(self): def test_complex_symlinks_relative(self):
self._check_complex_symlinks('.') self._check_complex_symlinks('.')
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_complex_symlinks_relative_dot_dot(self): def test_complex_symlinks_relative_dot_dot(self):
self._check_complex_symlinks(os.path.join('dirA', '..')) self._check_complex_symlinks(os.path.join('dirA', '..'))
@ -2362,7 +2364,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
st = os.stat(join('masked_new_file')) st = os.stat(join('masked_new_file'))
self.assertEqual(stat.S_IMODE(st.st_mode), 0o750) self.assertEqual(stat.S_IMODE(st.st_mode), 0o750)
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_resolve_loop(self): def test_resolve_loop(self):
# Loops with relative symlinks. # Loops with relative symlinks.
os.symlink('linkX/inside', join('linkX')) os.symlink('linkX/inside', join('linkX'))
@ -2387,7 +2389,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
P = self.cls P = self.cls
p = P(BASE) p = P(BASE)
given = set(p.glob("FILEa")) given = set(p.glob("FILEa"))
expect = set() if not support.fs_is_case_insensitive(BASE) else given expect = set() if not os_helper.fs_is_case_insensitive(BASE) else given
self.assertEqual(given, expect) self.assertEqual(given, expect)
self.assertEqual(set(p.glob("FILEa*")), set()) self.assertEqual(set(p.glob("FILEa*")), set())
@ -2395,7 +2397,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
P = self.cls P = self.cls
p = P(BASE, "dirC") p = P(BASE, "dirC")
given = set(p.rglob("FILEd")) given = set(p.rglob("FILEd"))
expect = set() if not support.fs_is_case_insensitive(BASE) else given expect = set() if not os_helper.fs_is_case_insensitive(BASE) else given
self.assertEqual(given, expect) self.assertEqual(given, expect)
self.assertEqual(set(p.rglob("FILEd*")), set()) self.assertEqual(set(p.rglob("FILEd*")), set())
@ -2403,7 +2405,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
'pwd module does not expose getpwall()') 'pwd module does not expose getpwall()')
def test_expanduser(self): def test_expanduser(self):
P = self.cls P = self.cls
support.import_module('pwd') import_helper.import_module('pwd')
import pwd import pwd
pwdent = pwd.getpwuid(os.getuid()) pwdent = pwd.getpwuid(os.getuid())
username = pwdent.pw_name username = pwdent.pw_name
@ -2426,7 +2428,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
p6 = P('') p6 = P('')
p7 = P('~fakeuser/Documents') p7 = P('~fakeuser/Documents')
with support.EnvironmentVarGuard() as env: with os_helper.EnvironmentVarGuard() as env:
env.pop('HOME', None) env.pop('HOME', None)
self.assertEqual(p1.expanduser(), P(userhome) / 'Documents') self.assertEqual(p1.expanduser(), P(userhome) / 'Documents')
@ -2490,7 +2492,7 @@ class WindowsPathTest(_BasePathTest, unittest.TestCase):
def test_expanduser(self): def test_expanduser(self):
P = self.cls P = self.cls
with support.EnvironmentVarGuard() as env: with os_helper.EnvironmentVarGuard() as env:
env.pop('HOME', None) env.pop('HOME', None)
env.pop('USERPROFILE', None) env.pop('USERPROFILE', None)
env.pop('HOMEPATH', None) env.pop('HOMEPATH', None)

View File

@ -3,7 +3,9 @@ import os
import string import string
import unittest import unittest
import shutil import shutil
from test.support import TESTFN, run_unittest, unlink, reap_children from test.support import run_unittest, reap_children
from test.support.os_helper import TESTFN, unlink
if os.name != 'posix': if os.name != 'posix':
raise unittest.SkipTest('pipes module only works on posix') raise unittest.SkipTest('pipes module only works on posix')

View File

@ -1,10 +1,13 @@
"Test posix functions" "Test posix functions"
from test import support from test import support
from test.support import import_helper
from test.support import os_helper
from test.support import warnings_helper
from test.support.script_helper import assert_python_ok from test.support.script_helper import assert_python_ok
# Skip these tests if there is no posix module. # Skip these tests if there is no posix module.
posix = support.import_module('posix') posix = import_helper.import_module('posix')
import errno import errno
import sys import sys
@ -20,7 +23,7 @@ import warnings
import textwrap import textwrap
_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(), _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
support.TESTFN + '-dummy-symlink') os_helper.TESTFN + '-dummy-symlink')
requires_32b = unittest.skipUnless(sys.maxsize < 2**32, requires_32b = unittest.skipUnless(sys.maxsize < 2**32,
'test is only meaningful on 32-bit builds') 'test is only meaningful on 32-bit builds')
@ -42,17 +45,17 @@ class PosixTester(unittest.TestCase):
def setUp(self): def setUp(self):
# create empty file # create empty file
fp = open(support.TESTFN, 'w+') fp = open(os_helper.TESTFN, 'w+')
fp.close() fp.close()
self.teardown_files = [ support.TESTFN ] self.teardown_files = [ os_helper.TESTFN ]
self._warnings_manager = support.check_warnings() self._warnings_manager = warnings_helper.check_warnings()
self._warnings_manager.__enter__() self._warnings_manager.__enter__()
warnings.filterwarnings('ignore', '.* potential security risk .*', warnings.filterwarnings('ignore', '.* potential security risk .*',
RuntimeWarning) RuntimeWarning)
def tearDown(self): def tearDown(self):
for teardown_file in self.teardown_files: for teardown_file in self.teardown_files:
support.unlink(teardown_file) os_helper.unlink(teardown_file)
self._warnings_manager.__exit__(None, None, None) self._warnings_manager.__exit__(None, None, None)
def testNoArgFunctions(self): def testNoArgFunctions(self):
@ -153,7 +156,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'fstatvfs'), @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
'test needs posix.fstatvfs()') 'test needs posix.fstatvfs()')
def test_fstatvfs(self): def test_fstatvfs(self):
fp = open(support.TESTFN) fp = open(os_helper.TESTFN)
try: try:
self.assertTrue(posix.fstatvfs(fp.fileno())) self.assertTrue(posix.fstatvfs(fp.fileno()))
self.assertTrue(posix.statvfs(fp.fileno())) self.assertTrue(posix.statvfs(fp.fileno()))
@ -163,7 +166,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'ftruncate'), @unittest.skipUnless(hasattr(posix, 'ftruncate'),
'test needs posix.ftruncate()') 'test needs posix.ftruncate()')
def test_ftruncate(self): def test_ftruncate(self):
fp = open(support.TESTFN, 'w+') fp = open(os_helper.TESTFN, 'w+')
try: try:
# we need to have some data to truncate # we need to have some data to truncate
fp.write('test') fp.write('test')
@ -174,10 +177,10 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()") @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
def test_truncate(self): def test_truncate(self):
with open(support.TESTFN, 'w') as fp: with open(os_helper.TESTFN, 'w') as fp:
fp.write('test') fp.write('test')
fp.flush() fp.flush()
posix.truncate(support.TESTFN, 0) posix.truncate(os_helper.TESTFN, 0)
@unittest.skipUnless(getattr(os, 'execve', None) in os.supports_fd, "test needs execve() to support the fd parameter") @unittest.skipUnless(getattr(os, 'execve', None) in os.supports_fd, "test needs execve() to support the fd parameter")
@unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
@ -268,7 +271,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()") @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
def test_lockf(self): def test_lockf(self):
fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_WRONLY | os.O_CREAT)
try: try:
os.write(fd, b'test') os.write(fd, b'test')
os.lseek(fd, 0, os.SEEK_SET) os.lseek(fd, 0, os.SEEK_SET)
@ -280,7 +283,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()") @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
def test_pread(self): def test_pread(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
os.write(fd, b'test') os.write(fd, b'test')
os.lseek(fd, 0, os.SEEK_SET) os.lseek(fd, 0, os.SEEK_SET)
@ -292,7 +295,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()") @unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()")
def test_preadv(self): def test_preadv(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
os.write(fd, b'test1tt2t3t5t6t6t8') os.write(fd, b'test1tt2t3t5t6t6t8')
buf = [bytearray(i) for i in [5, 3, 2]] buf = [bytearray(i) for i in [5, 3, 2]]
@ -304,7 +307,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()") @unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()")
@unittest.skipUnless(hasattr(posix, 'RWF_HIPRI'), "test needs posix.RWF_HIPRI") @unittest.skipUnless(hasattr(posix, 'RWF_HIPRI'), "test needs posix.RWF_HIPRI")
def test_preadv_flags(self): def test_preadv_flags(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
os.write(fd, b'test1tt2t3t5t6t6t8') os.write(fd, b'test1tt2t3t5t6t6t8')
buf = [bytearray(i) for i in [5, 3, 2]] buf = [bytearray(i) for i in [5, 3, 2]]
@ -326,7 +329,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()") @unittest.skipUnless(hasattr(posix, 'preadv'), "test needs posix.preadv()")
@requires_32b @requires_32b
def test_preadv_overflow_32bits(self): def test_preadv_overflow_32bits(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
buf = [bytearray(2**16)] * 2**15 buf = [bytearray(2**16)] * 2**15
with self.assertRaises(OSError) as cm: with self.assertRaises(OSError) as cm:
@ -338,7 +341,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()") @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
def test_pwrite(self): def test_pwrite(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
os.write(fd, b'test') os.write(fd, b'test')
os.lseek(fd, 0, os.SEEK_SET) os.lseek(fd, 0, os.SEEK_SET)
@ -349,7 +352,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()") @unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()")
def test_pwritev(self): def test_pwritev(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
os.write(fd, b"xx") os.write(fd, b"xx")
os.lseek(fd, 0, os.SEEK_SET) os.lseek(fd, 0, os.SEEK_SET)
@ -364,7 +367,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()") @unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()")
@unittest.skipUnless(hasattr(posix, 'os.RWF_SYNC'), "test needs os.RWF_SYNC") @unittest.skipUnless(hasattr(posix, 'os.RWF_SYNC'), "test needs os.RWF_SYNC")
def test_pwritev_flags(self): def test_pwritev_flags(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
os.write(fd,b"xx") os.write(fd,b"xx")
os.lseek(fd, 0, os.SEEK_SET) os.lseek(fd, 0, os.SEEK_SET)
@ -379,7 +382,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()") @unittest.skipUnless(hasattr(posix, 'pwritev'), "test needs posix.pwritev()")
@requires_32b @requires_32b
def test_pwritev_overflow_32bits(self): def test_pwritev_overflow_32bits(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
with self.assertRaises(OSError) as cm: with self.assertRaises(OSError) as cm:
os.pwritev(fd, [b"x" * 2**16] * 2**15, 0) os.pwritev(fd, [b"x" * 2**16] * 2**15, 0)
@ -390,7 +393,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'posix_fallocate'), @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
"test needs posix.posix_fallocate()") "test needs posix.posix_fallocate()")
def test_posix_fallocate(self): def test_posix_fallocate(self):
fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_WRONLY | os.O_CREAT)
try: try:
posix.posix_fallocate(fd, 0, 10) posix.posix_fallocate(fd, 0, 10)
except OSError as inst: except OSError as inst:
@ -419,7 +422,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'posix_fadvise'), @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
"test needs posix.posix_fadvise()") "test needs posix.posix_fadvise()")
def test_posix_fadvise(self): def test_posix_fadvise(self):
fd = os.open(support.TESTFN, os.O_RDONLY) fd = os.open(os_helper.TESTFN, os.O_RDONLY)
try: try:
posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED) posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
finally: finally:
@ -437,7 +440,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime") @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
def test_utime_with_fd(self): def test_utime_with_fd(self):
now = time.time() now = time.time()
fd = os.open(support.TESTFN, os.O_RDONLY) fd = os.open(os_helper.TESTFN, os.O_RDONLY)
try: try:
posix.utime(fd) posix.utime(fd)
posix.utime(fd, None) posix.utime(fd, None)
@ -458,17 +461,21 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime") @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
def test_utime_nofollow_symlinks(self): def test_utime_nofollow_symlinks(self):
now = time.time() now = time.time()
posix.utime(support.TESTFN, None, follow_symlinks=False) posix.utime(os_helper.TESTFN, None, follow_symlinks=False)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), follow_symlinks=False) self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), follow_symlinks=False) (None, None), follow_symlinks=False)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), follow_symlinks=False) self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False) (now, None), follow_symlinks=False)
posix.utime(support.TESTFN, (now, now), follow_symlinks=False) self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
posix.utime(support.TESTFN, follow_symlinks=False) (None, now), follow_symlinks=False)
posix.utime(os_helper.TESTFN, (int(now), int(now)),
follow_symlinks=False)
posix.utime(os_helper.TESTFN, (now, now), follow_symlinks=False)
posix.utime(os_helper.TESTFN, follow_symlinks=False)
@unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()") @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
def test_writev(self): def test_writev(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
n = os.writev(fd, (b'test1', b'tt2', b't3')) n = os.writev(fd, (b'test1', b'tt2', b't3'))
self.assertEqual(n, 10) self.assertEqual(n, 10)
@ -491,7 +498,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()") @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
@requires_32b @requires_32b
def test_writev_overflow_32bits(self): def test_writev_overflow_32bits(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
with self.assertRaises(OSError) as cm: with self.assertRaises(OSError) as cm:
os.writev(fd, [b"x" * 2**16] * 2**15) os.writev(fd, [b"x" * 2**16] * 2**15)
@ -501,7 +508,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()") @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
def test_readv(self): def test_readv(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
os.write(fd, b'test1tt2t3') os.write(fd, b'test1tt2t3')
os.lseek(fd, 0, os.SEEK_SET) os.lseek(fd, 0, os.SEEK_SET)
@ -524,7 +531,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()") @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
@requires_32b @requires_32b
def test_readv_overflow_32bits(self): def test_readv_overflow_32bits(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) fd = os.open(os_helper.TESTFN, os.O_RDWR | os.O_CREAT)
try: try:
buf = [bytearray(2**16)] * 2**15 buf = [bytearray(2**16)] * 2**15
with self.assertRaises(OSError) as cm: with self.assertRaises(OSError) as cm:
@ -537,7 +544,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'dup'), @unittest.skipUnless(hasattr(posix, 'dup'),
'test needs posix.dup()') 'test needs posix.dup()')
def test_dup(self): def test_dup(self):
fp = open(support.TESTFN) fp = open(os_helper.TESTFN)
try: try:
fd = posix.dup(fp.fileno()) fd = posix.dup(fp.fileno())
self.assertIsInstance(fd, int) self.assertIsInstance(fd, int)
@ -554,8 +561,8 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'dup2'), @unittest.skipUnless(hasattr(posix, 'dup2'),
'test needs posix.dup2()') 'test needs posix.dup2()')
def test_dup2(self): def test_dup2(self):
fp1 = open(support.TESTFN) fp1 = open(os_helper.TESTFN)
fp2 = open(support.TESTFN) fp2 = open(os_helper.TESTFN)
try: try:
posix.dup2(fp1.fileno(), fp2.fileno()) posix.dup2(fp1.fileno(), fp2.fileno())
finally: finally:
@ -565,47 +572,47 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC") @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
@support.requires_linux_version(2, 6, 23) @support.requires_linux_version(2, 6, 23)
def test_oscloexec(self): def test_oscloexec(self):
fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC) fd = os.open(os_helper.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
self.addCleanup(os.close, fd) self.addCleanup(os.close, fd)
self.assertFalse(os.get_inheritable(fd)) self.assertFalse(os.get_inheritable(fd))
@unittest.skipUnless(hasattr(posix, 'O_EXLOCK'), @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
'test needs posix.O_EXLOCK') 'test needs posix.O_EXLOCK')
def test_osexlock(self): def test_osexlock(self):
fd = os.open(support.TESTFN, fd = os.open(os_helper.TESTFN,
os.O_WRONLY|os.O_EXLOCK|os.O_CREAT) os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
self.assertRaises(OSError, os.open, support.TESTFN, self.assertRaises(OSError, os.open, os_helper.TESTFN,
os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK) os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
os.close(fd) os.close(fd)
if hasattr(posix, "O_SHLOCK"): if hasattr(posix, "O_SHLOCK"):
fd = os.open(support.TESTFN, fd = os.open(os_helper.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
self.assertRaises(OSError, os.open, support.TESTFN, self.assertRaises(OSError, os.open, os_helper.TESTFN,
os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK) os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
os.close(fd) os.close(fd)
@unittest.skipUnless(hasattr(posix, 'O_SHLOCK'), @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
'test needs posix.O_SHLOCK') 'test needs posix.O_SHLOCK')
def test_osshlock(self): def test_osshlock(self):
fd1 = os.open(support.TESTFN, fd1 = os.open(os_helper.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
fd2 = os.open(support.TESTFN, fd2 = os.open(os_helper.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
os.close(fd2) os.close(fd2)
os.close(fd1) os.close(fd1)
if hasattr(posix, "O_EXLOCK"): if hasattr(posix, "O_EXLOCK"):
fd = os.open(support.TESTFN, fd = os.open(os_helper.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
self.assertRaises(OSError, os.open, support.TESTFN, self.assertRaises(OSError, os.open, os_helper.TESTFN,
os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK) os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
os.close(fd) os.close(fd)
@unittest.skipUnless(hasattr(posix, 'fstat'), @unittest.skipUnless(hasattr(posix, 'fstat'),
'test needs posix.fstat()') 'test needs posix.fstat()')
def test_fstat(self): def test_fstat(self):
fp = open(support.TESTFN) fp = open(os_helper.TESTFN)
try: try:
self.assertTrue(posix.fstat(fp.fileno())) self.assertTrue(posix.fstat(fp.fileno()))
self.assertTrue(posix.stat(fp.fileno())) self.assertTrue(posix.stat(fp.fileno()))
@ -617,58 +624,58 @@ class PosixTester(unittest.TestCase):
fp.close() fp.close()
def test_stat(self): def test_stat(self):
self.assertTrue(posix.stat(support.TESTFN)) self.assertTrue(posix.stat(os_helper.TESTFN))
self.assertTrue(posix.stat(os.fsencode(support.TESTFN))) self.assertTrue(posix.stat(os.fsencode(os_helper.TESTFN)))
self.assertWarnsRegex(DeprecationWarning, self.assertWarnsRegex(DeprecationWarning,
'should be string, bytes, os.PathLike or integer, not', 'should be string, bytes, os.PathLike or integer, not',
posix.stat, bytearray(os.fsencode(support.TESTFN))) posix.stat, bytearray(os.fsencode(os_helper.TESTFN)))
self.assertRaisesRegex(TypeError, self.assertRaisesRegex(TypeError,
'should be string, bytes, os.PathLike or integer, not', 'should be string, bytes, os.PathLike or integer, not',
posix.stat, None) posix.stat, None)
self.assertRaisesRegex(TypeError, self.assertRaisesRegex(TypeError,
'should be string, bytes, os.PathLike or integer, not', 'should be string, bytes, os.PathLike or integer, not',
posix.stat, list(support.TESTFN)) posix.stat, list(os_helper.TESTFN))
self.assertRaisesRegex(TypeError, self.assertRaisesRegex(TypeError,
'should be string, bytes, os.PathLike or integer, not', 'should be string, bytes, os.PathLike or integer, not',
posix.stat, list(os.fsencode(support.TESTFN))) posix.stat, list(os.fsencode(os_helper.TESTFN)))
@unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()") @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
def test_mkfifo(self): def test_mkfifo(self):
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
try: try:
posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR) posix.mkfifo(os_helper.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
except PermissionError as e: except PermissionError as e:
self.skipTest('posix.mkfifo(): %s' % e) self.skipTest('posix.mkfifo(): %s' % e)
self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode)) self.assertTrue(stat.S_ISFIFO(posix.stat(os_helper.TESTFN).st_mode))
@unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'), @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
"don't have mknod()/S_IFIFO") "don't have mknod()/S_IFIFO")
def test_mknod(self): def test_mknod(self):
# Test using mknod() to create a FIFO (the only use specified # Test using mknod() to create a FIFO (the only use specified
# by POSIX). # by POSIX).
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
try: try:
posix.mknod(support.TESTFN, mode, 0) posix.mknod(os_helper.TESTFN, mode, 0)
except OSError as e: except OSError as e:
# Some old systems don't allow unprivileged users to use # Some old systems don't allow unprivileged users to use
# mknod(), or only support creating device nodes. # mknod(), or only support creating device nodes.
self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES)) self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES))
else: else:
self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode)) self.assertTrue(stat.S_ISFIFO(posix.stat(os_helper.TESTFN).st_mode))
# Keyword arguments are also supported # Keyword arguments are also supported
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
try: try:
posix.mknod(path=support.TESTFN, mode=mode, device=0, posix.mknod(path=os_helper.TESTFN, mode=mode, device=0,
dir_fd=None) dir_fd=None)
except OSError as e: except OSError as e:
self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES)) self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES))
@unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()') @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
def test_makedev(self): def test_makedev(self):
st = posix.stat(support.TESTFN) st = posix.stat(os_helper.TESTFN)
dev = st.st_dev dev = st.st_dev
self.assertIsInstance(dev, int) self.assertIsInstance(dev, int)
self.assertGreaterEqual(dev, 0) self.assertGreaterEqual(dev, 0)
@ -757,19 +764,19 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()") @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
def test_chown(self): def test_chown(self):
# raise an OSError if the file does not exist # raise an OSError if the file does not exist
os.unlink(support.TESTFN) os.unlink(os_helper.TESTFN)
self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1) self.assertRaises(OSError, posix.chown, os_helper.TESTFN, -1, -1)
# re-create the file # re-create the file
support.create_empty_file(support.TESTFN) os_helper.create_empty_file(os_helper.TESTFN)
self._test_all_chown_common(posix.chown, support.TESTFN, posix.stat) self._test_all_chown_common(posix.chown, os_helper.TESTFN, posix.stat)
@unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()") @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
def test_fchown(self): def test_fchown(self):
os.unlink(support.TESTFN) os.unlink(os_helper.TESTFN)
# re-create the file # re-create the file
test_file = open(support.TESTFN, 'w') test_file = open(os_helper.TESTFN, 'w')
try: try:
fd = test_file.fileno() fd = test_file.fileno()
self._test_all_chown_common(posix.fchown, fd, self._test_all_chown_common(posix.fchown, fd,
@ -779,35 +786,35 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()") @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
def test_lchown(self): def test_lchown(self):
os.unlink(support.TESTFN) os.unlink(os_helper.TESTFN)
# create a symlink # create a symlink
os.symlink(_DUMMY_SYMLINK, support.TESTFN) os.symlink(_DUMMY_SYMLINK, os_helper.TESTFN)
self._test_all_chown_common(posix.lchown, support.TESTFN, self._test_all_chown_common(posix.lchown, os_helper.TESTFN,
getattr(posix, 'lstat', None)) getattr(posix, 'lstat', None))
@unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()') @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
def test_chdir(self): def test_chdir(self):
posix.chdir(os.curdir) posix.chdir(os.curdir)
self.assertRaises(OSError, posix.chdir, support.TESTFN) self.assertRaises(OSError, posix.chdir, os_helper.TESTFN)
def test_listdir(self): def test_listdir(self):
self.assertIn(support.TESTFN, posix.listdir(os.curdir)) self.assertIn(os_helper.TESTFN, posix.listdir(os.curdir))
def test_listdir_default(self): def test_listdir_default(self):
# When listdir is called without argument, # When listdir is called without argument,
# it's the same as listdir(os.curdir). # it's the same as listdir(os.curdir).
self.assertIn(support.TESTFN, posix.listdir()) self.assertIn(os_helper.TESTFN, posix.listdir())
def test_listdir_bytes(self): def test_listdir_bytes(self):
# When listdir is called with a bytes object, # When listdir is called with a bytes object,
# the returned strings are of type bytes. # the returned strings are of type bytes.
self.assertIn(os.fsencode(support.TESTFN), posix.listdir(b'.')) self.assertIn(os.fsencode(os_helper.TESTFN), posix.listdir(b'.'))
def test_listdir_bytes_like(self): def test_listdir_bytes_like(self):
for cls in bytearray, memoryview: for cls in bytearray, memoryview:
with self.assertWarns(DeprecationWarning): with self.assertWarns(DeprecationWarning):
names = posix.listdir(cls(b'.')) names = posix.listdir(cls(b'.'))
self.assertIn(os.fsencode(support.TESTFN), names) self.assertIn(os.fsencode(os_helper.TESTFN), names)
for name in names: for name in names:
self.assertIs(type(name), bytes) self.assertIs(type(name), bytes)
@ -828,7 +835,7 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()') @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
def test_access(self): def test_access(self):
self.assertTrue(posix.access(support.TESTFN, os.R_OK)) self.assertTrue(posix.access(os_helper.TESTFN, os.R_OK))
@unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()') @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
def test_umask(self): def test_umask(self):
@ -887,12 +894,15 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()') @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
def test_utime(self): def test_utime(self):
now = time.time() now = time.time()
posix.utime(support.TESTFN, None) posix.utime(os_helper.TESTFN, None)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None)) self.assertRaises(TypeError, posix.utime,
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None)) os_helper.TESTFN, (None, None))
self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now)) self.assertRaises(TypeError, posix.utime,
posix.utime(support.TESTFN, (int(now), int(now))) os_helper.TESTFN, (now, None))
posix.utime(support.TESTFN, (now, now)) self.assertRaises(TypeError, posix.utime,
os_helper.TESTFN, (None, now))
posix.utime(os_helper.TESTFN, (int(now), int(now)))
posix.utime(os_helper.TESTFN, (now, now))
def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs): def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
st = os.stat(target_file) st = os.stat(target_file)
@ -920,20 +930,21 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()') @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
def test_chflags(self): def test_chflags(self):
self._test_chflags_regular_file(posix.chflags, support.TESTFN) self._test_chflags_regular_file(posix.chflags, os_helper.TESTFN)
@unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()') @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
def test_lchflags_regular_file(self): def test_lchflags_regular_file(self):
self._test_chflags_regular_file(posix.lchflags, support.TESTFN) self._test_chflags_regular_file(posix.lchflags, os_helper.TESTFN)
self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False) self._test_chflags_regular_file(posix.chflags, os_helper.TESTFN,
follow_symlinks=False)
@unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()') @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
def test_lchflags_symlink(self): def test_lchflags_symlink(self):
testfn_st = os.stat(support.TESTFN) testfn_st = os.stat(os_helper.TESTFN)
self.assertTrue(hasattr(testfn_st, 'st_flags')) self.assertTrue(hasattr(testfn_st, 'st_flags'))
os.symlink(support.TESTFN, _DUMMY_SYMLINK) os.symlink(os_helper.TESTFN, _DUMMY_SYMLINK)
self.teardown_files.append(_DUMMY_SYMLINK) self.teardown_files.append(_DUMMY_SYMLINK)
dummy_symlink_st = os.lstat(_DUMMY_SYMLINK) dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
@ -951,7 +962,7 @@ class PosixTester(unittest.TestCase):
msg = 'chflag UF_IMMUTABLE not supported by underlying fs' msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
self.skipTest(msg) self.skipTest(msg)
try: try:
new_testfn_st = os.stat(support.TESTFN) new_testfn_st = os.stat(os_helper.TESTFN)
new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK) new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags) self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
@ -987,7 +998,7 @@ class PosixTester(unittest.TestCase):
def test_getcwd_long_pathnames(self): def test_getcwd_long_pathnames(self):
dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef' dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
curdir = os.getcwd() curdir = os.getcwd()
base_path = os.path.abspath(support.TESTFN) + '.getcwd' base_path = os.path.abspath(os_helper.TESTFN) + '.getcwd'
try: try:
os.mkdir(base_path) os.mkdir(base_path)
@ -1017,7 +1028,7 @@ class PosixTester(unittest.TestCase):
finally: finally:
os.chdir(curdir) os.chdir(curdir)
support.rmtree(base_path) os_helper.rmtree(base_path)
@unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()") @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
@unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()") @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
@ -1061,53 +1072,53 @@ class PosixTester(unittest.TestCase):
def test_access_dir_fd(self): def test_access_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f)) self.assertTrue(posix.access(os_helper.TESTFN, os.R_OK, dir_fd=f))
finally: finally:
posix.close(f) posix.close(f)
@unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()") @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
def test_chmod_dir_fd(self): def test_chmod_dir_fd(self):
os.chmod(support.TESTFN, stat.S_IRUSR) os.chmod(os_helper.TESTFN, stat.S_IRUSR)
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f) posix.chmod(os_helper.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
s = posix.stat(support.TESTFN) s = posix.stat(os_helper.TESTFN)
self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR) self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
finally: finally:
posix.close(f) posix.close(f)
@unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()") @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
def test_chown_dir_fd(self): def test_chown_dir_fd(self):
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
support.create_empty_file(support.TESTFN) os_helper.create_empty_file(os_helper.TESTFN)
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f) posix.chown(os_helper.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
finally: finally:
posix.close(f) posix.close(f)
@unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()") @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
def test_stat_dir_fd(self): def test_stat_dir_fd(self):
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
with open(support.TESTFN, 'w') as outfile: with open(os_helper.TESTFN, 'w') as outfile:
outfile.write("testline\n") outfile.write("testline\n")
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
s1 = posix.stat(support.TESTFN) s1 = posix.stat(os_helper.TESTFN)
s2 = posix.stat(support.TESTFN, dir_fd=f) s2 = posix.stat(os_helper.TESTFN, dir_fd=f)
self.assertEqual(s1, s2) self.assertEqual(s1, s2)
s2 = posix.stat(support.TESTFN, dir_fd=None) s2 = posix.stat(os_helper.TESTFN, dir_fd=None)
self.assertEqual(s1, s2) self.assertEqual(s1, s2)
self.assertRaisesRegex(TypeError, 'should be integer or None, not', self.assertRaisesRegex(TypeError, 'should be integer or None, not',
posix.stat, support.TESTFN, dir_fd=posix.getcwd()) posix.stat, os_helper.TESTFN, dir_fd=posix.getcwd())
self.assertRaisesRegex(TypeError, 'should be integer or None, not', self.assertRaisesRegex(TypeError, 'should be integer or None, not',
posix.stat, support.TESTFN, dir_fd=float(f)) posix.stat, os_helper.TESTFN, dir_fd=float(f))
self.assertRaises(OverflowError, self.assertRaises(OverflowError,
posix.stat, support.TESTFN, dir_fd=10**20) posix.stat, os_helper.TESTFN, dir_fd=10**20)
finally: finally:
posix.close(f) posix.close(f)
@ -1116,24 +1127,30 @@ class PosixTester(unittest.TestCase):
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
now = time.time() now = time.time()
posix.utime(support.TESTFN, None, dir_fd=f) posix.utime(os_helper.TESTFN, None, dir_fd=f)
posix.utime(support.TESTFN, dir_fd=f) posix.utime(os_helper.TESTFN, dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f) self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f) now, dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f) self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f) (None, None), dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f) self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f) (now, None), dir_fd=f)
posix.utime(support.TESTFN, (now, now), dir_fd=f) self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
posix.utime(support.TESTFN, (None, now), dir_fd=f)
self.assertRaises(TypeError, posix.utime, os_helper.TESTFN,
(now, "x"), dir_fd=f)
posix.utime(os_helper.TESTFN, (int(now), int(now)), dir_fd=f)
posix.utime(os_helper.TESTFN, (now, now), dir_fd=f)
posix.utime(os_helper.TESTFN,
(int(now), int((now - int(now)) * 1e9)), dir_fd=f) (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
posix.utime(support.TESTFN, dir_fd=f, posix.utime(os_helper.TESTFN, dir_fd=f,
times=(int(now), int((now - int(now)) * 1e9))) times=(int(now), int((now - int(now)) * 1e9)))
# try dir_fd and follow_symlinks together # try dir_fd and follow_symlinks together
if os.utime in os.supports_follow_symlinks: if os.utime in os.supports_follow_symlinks:
try: try:
posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f) posix.utime(os_helper.TESTFN, follow_symlinks=False,
dir_fd=f)
except ValueError: except ValueError:
# whoops! using both together not supported on this platform. # whoops! using both together not supported on this platform.
pass pass
@ -1145,53 +1162,54 @@ class PosixTester(unittest.TestCase):
def test_link_dir_fd(self): def test_link_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f) posix.link(os_helper.TESTFN, os_helper.TESTFN + 'link',
src_dir_fd=f, dst_dir_fd=f)
except PermissionError as e: except PermissionError as e:
self.skipTest('posix.link(): %s' % e) self.skipTest('posix.link(): %s' % e)
else: else:
# should have same inodes # should have same inodes
self.assertEqual(posix.stat(support.TESTFN)[1], self.assertEqual(posix.stat(os_helper.TESTFN)[1],
posix.stat(support.TESTFN + 'link')[1]) posix.stat(os_helper.TESTFN + 'link')[1])
finally: finally:
posix.close(f) posix.close(f)
support.unlink(support.TESTFN + 'link') os_helper.unlink(os_helper.TESTFN + 'link')
@unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()") @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
def test_mkdir_dir_fd(self): def test_mkdir_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
posix.mkdir(support.TESTFN + 'dir', dir_fd=f) posix.mkdir(os_helper.TESTFN + 'dir', dir_fd=f)
posix.stat(support.TESTFN + 'dir') # should not raise exception posix.stat(os_helper.TESTFN + 'dir') # should not raise exception
finally: finally:
posix.close(f) posix.close(f)
support.rmtree(support.TESTFN + 'dir') os_helper.rmtree(os_helper.TESTFN + 'dir')
@unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'), @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
"test requires both stat.S_IFIFO and dir_fd support for os.mknod()") "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
def test_mknod_dir_fd(self): def test_mknod_dir_fd(self):
# Test using mknodat() to create a FIFO (the only use specified # Test using mknodat() to create a FIFO (the only use specified
# by POSIX). # by POSIX).
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
posix.mknod(support.TESTFN, mode, 0, dir_fd=f) posix.mknod(os_helper.TESTFN, mode, 0, dir_fd=f)
except OSError as e: except OSError as e:
# Some old systems don't allow unprivileged users to use # Some old systems don't allow unprivileged users to use
# mknod(), or only support creating device nodes. # mknod(), or only support creating device nodes.
self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES)) self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES))
else: else:
self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode)) self.assertTrue(stat.S_ISFIFO(posix.stat(os_helper.TESTFN).st_mode))
finally: finally:
posix.close(f) posix.close(f)
@unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()") @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
def test_open_dir_fd(self): def test_open_dir_fd(self):
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
with open(support.TESTFN, 'w') as outfile: with open(os_helper.TESTFN, 'w') as outfile:
outfile.write("testline\n") outfile.write("testline\n")
a = posix.open(posix.getcwd(), posix.O_RDONLY) a = posix.open(posix.getcwd(), posix.O_RDONLY)
b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a) b = posix.open(os_helper.TESTFN, posix.O_RDONLY, dir_fd=a)
try: try:
res = posix.read(b, 9).decode(encoding="utf-8") res = posix.read(b, 9).decode(encoding="utf-8")
self.assertEqual("testline\n", res) self.assertEqual("testline\n", res)
@ -1201,27 +1219,27 @@ class PosixTester(unittest.TestCase):
@unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()") @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
def test_readlink_dir_fd(self): def test_readlink_dir_fd(self):
os.symlink(support.TESTFN, support.TESTFN + 'link') os.symlink(os_helper.TESTFN, os_helper.TESTFN + 'link')
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
self.assertEqual(posix.readlink(support.TESTFN + 'link'), self.assertEqual(posix.readlink(os_helper.TESTFN + 'link'),
posix.readlink(support.TESTFN + 'link', dir_fd=f)) posix.readlink(os_helper.TESTFN + 'link', dir_fd=f))
finally: finally:
support.unlink(support.TESTFN + 'link') os_helper.unlink(os_helper.TESTFN + 'link')
posix.close(f) posix.close(f)
@unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()") @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
def test_rename_dir_fd(self): def test_rename_dir_fd(self):
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
support.create_empty_file(support.TESTFN + 'ren') os_helper.create_empty_file(os_helper.TESTFN + 'ren')
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f) posix.rename(os_helper.TESTFN + 'ren', os_helper.TESTFN, src_dir_fd=f, dst_dir_fd=f)
except: except:
posix.rename(support.TESTFN + 'ren', support.TESTFN) posix.rename(os_helper.TESTFN + 'ren', os_helper.TESTFN)
raise raise
else: else:
posix.stat(support.TESTFN) # should not raise exception posix.stat(os_helper.TESTFN) # should not raise exception
finally: finally:
posix.close(f) posix.close(f)
@ -1239,38 +1257,40 @@ class PosixTester(unittest.TestCase):
def test_symlink_dir_fd(self): def test_symlink_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f) posix.symlink(os_helper.TESTFN, os_helper.TESTFN + 'link',
self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN) dir_fd=f)
self.assertEqual(posix.readlink(os_helper.TESTFN + 'link'),
os_helper.TESTFN)
finally: finally:
posix.close(f) posix.close(f)
support.unlink(support.TESTFN + 'link') os_helper.unlink(os_helper.TESTFN + 'link')
@unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()") @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
def test_unlink_dir_fd(self): def test_unlink_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
support.create_empty_file(support.TESTFN + 'del') os_helper.create_empty_file(os_helper.TESTFN + 'del')
posix.stat(support.TESTFN + 'del') # should not raise exception posix.stat(os_helper.TESTFN + 'del') # should not raise exception
try: try:
posix.unlink(support.TESTFN + 'del', dir_fd=f) posix.unlink(os_helper.TESTFN + 'del', dir_fd=f)
except: except:
support.unlink(support.TESTFN + 'del') os_helper.unlink(os_helper.TESTFN + 'del')
raise raise
else: else:
self.assertRaises(OSError, posix.stat, support.TESTFN + 'link') self.assertRaises(OSError, posix.stat, os_helper.TESTFN + 'link')
finally: finally:
posix.close(f) posix.close(f)
@unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()") @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
def test_mkfifo_dir_fd(self): def test_mkfifo_dir_fd(self):
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
f = posix.open(posix.getcwd(), posix.O_RDONLY) f = posix.open(posix.getcwd(), posix.O_RDONLY)
try: try:
try: try:
posix.mkfifo(support.TESTFN, posix.mkfifo(os_helper.TESTFN,
stat.S_IRUSR | stat.S_IWUSR, dir_fd=f) stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
except PermissionError as e: except PermissionError as e:
self.skipTest('posix.mkfifo(): %s' % e) self.skipTest('posix.mkfifo(): %s' % e)
self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode)) self.assertTrue(stat.S_ISFIFO(posix.stat(os_helper.TESTFN).st_mode))
finally: finally:
posix.close(f) posix.close(f)
@ -1397,7 +1417,7 @@ class PosixTester(unittest.TestCase):
# behaviour: # behaviour:
# os.SEEK_DATA = current position # os.SEEK_DATA = current position
# os.SEEK_HOLE = end of file position # os.SEEK_HOLE = end of file position
with open(support.TESTFN, 'r+b') as fp: with open(os_helper.TESTFN, 'r+b') as fp:
fp.write(b"hello") fp.write(b"hello")
fp.flush() fp.flush()
size = fp.tell() size = fp.tell()
@ -1424,7 +1444,7 @@ class PosixTester(unittest.TestCase):
if function is None: if function is None:
continue continue
for dst in ("noodly2", support.TESTFN): for dst in ("noodly2", os_helper.TESTFN):
try: try:
function('doesnotexistfilename', dst) function('doesnotexistfilename', dst)
except OSError as e: except OSError as e:
@ -1434,10 +1454,10 @@ class PosixTester(unittest.TestCase):
self.fail("No valid path_error2() test for os." + name) self.fail("No valid path_error2() test for os." + name)
def test_path_with_null_character(self): def test_path_with_null_character(self):
fn = support.TESTFN fn = os_helper.TESTFN
fn_with_NUL = fn + '\0' fn_with_NUL = fn + '\0'
self.addCleanup(support.unlink, fn) self.addCleanup(os_helper.unlink, fn)
support.unlink(fn) os_helper.unlink(fn)
fd = None fd = None
try: try:
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@ -1452,10 +1472,10 @@ class PosixTester(unittest.TestCase):
self.assertRaises(ValueError, os.stat, fn_with_NUL) self.assertRaises(ValueError, os.stat, fn_with_NUL)
def test_path_with_null_byte(self): def test_path_with_null_byte(self):
fn = os.fsencode(support.TESTFN) fn = os.fsencode(os_helper.TESTFN)
fn_with_NUL = fn + b'\0' fn_with_NUL = fn + b'\0'
self.addCleanup(support.unlink, fn) self.addCleanup(os_helper.unlink, fn)
support.unlink(fn) os_helper.unlink(fn)
fd = None fd = None
try: try:
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@ -1530,8 +1550,8 @@ class _PosixSpawnMixin:
return (sys.executable, '-I', '-S', *args) return (sys.executable, '-I', '-S', *args)
def test_returns_pid(self): def test_returns_pid(self):
pidfile = support.TESTFN pidfile = os_helper.TESTFN
self.addCleanup(support.unlink, pidfile) self.addCleanup(os_helper.unlink, pidfile)
script = f"""if 1: script = f"""if 1:
import os import os
with open({pidfile!r}, "w") as pidfile: with open({pidfile!r}, "w") as pidfile:
@ -1559,8 +1579,8 @@ class _PosixSpawnMixin:
self.assertNotEqual(status, 0) self.assertNotEqual(status, 0)
def test_specify_environment(self): def test_specify_environment(self):
envfile = support.TESTFN envfile = os_helper.TESTFN
self.addCleanup(support.unlink, envfile) self.addCleanup(os_helper.unlink, envfile)
script = f"""if 1: script = f"""if 1:
import os import os
with open({envfile!r}, "w") as envfile: with open({envfile!r}, "w") as envfile:
@ -1806,8 +1826,8 @@ class _PosixSpawnMixin:
os.O_RDONLY, 0)]) os.O_RDONLY, 0)])
def test_open_file(self): def test_open_file(self):
outfile = support.TESTFN outfile = os_helper.TESTFN
self.addCleanup(support.unlink, outfile) self.addCleanup(os_helper.unlink, outfile)
script = """if 1: script = """if 1:
import sys import sys
sys.stdout.write("hello") sys.stdout.write("hello")
@ -1826,8 +1846,8 @@ class _PosixSpawnMixin:
self.assertEqual(f.read(), 'hello') self.assertEqual(f.read(), 'hello')
def test_close_file(self): def test_close_file(self):
closefile = support.TESTFN closefile = os_helper.TESTFN
self.addCleanup(support.unlink, closefile) self.addCleanup(os_helper.unlink, closefile)
script = f"""if 1: script = f"""if 1:
import os import os
try: try:
@ -1845,8 +1865,8 @@ class _PosixSpawnMixin:
self.assertEqual(f.read(), 'is closed %d' % errno.EBADF) self.assertEqual(f.read(), 'is closed %d' % errno.EBADF)
def test_dup2(self): def test_dup2(self):
dupfile = support.TESTFN dupfile = os_helper.TESTFN
self.addCleanup(support.unlink, dupfile) self.addCleanup(os_helper.unlink, dupfile)
script = """if 1: script = """if 1:
import sys import sys
sys.stdout.write("hello") sys.stdout.write("hello")
@ -1872,11 +1892,11 @@ class TestPosixSpawn(unittest.TestCase, _PosixSpawnMixin):
class TestPosixSpawnP(unittest.TestCase, _PosixSpawnMixin): class TestPosixSpawnP(unittest.TestCase, _PosixSpawnMixin):
spawn_func = getattr(posix, 'posix_spawnp', None) spawn_func = getattr(posix, 'posix_spawnp', None)
@support.skip_unless_symlink @os_helper.skip_unless_symlink
def test_posix_spawnp(self): def test_posix_spawnp(self):
# Use a symlink to create a program in its own temporary directory # Use a symlink to create a program in its own temporary directory
temp_dir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
self.addCleanup(support.rmtree, temp_dir) self.addCleanup(os_helper.rmtree, temp_dir)
program = 'posix_spawnp_test_program.exe' program = 'posix_spawnp_test_program.exe'
program_fullpath = os.path.join(temp_dir, program) program_fullpath = os.path.join(temp_dir, program)

View File

@ -23,13 +23,12 @@ import xml.etree.ElementTree
import textwrap import textwrap
from io import StringIO from io import StringIO
from collections import namedtuple from collections import namedtuple
from test.support import os_helper
from test.support.script_helper import assert_python_ok from test.support.script_helper import assert_python_ok
from test.support import threading_helper from test.support import threading_helper
from test.support import ( from test.support import (reap_children, captured_output, captured_stdout,
TESTFN, rmtree, captured_stderr, requires_docstrings)
reap_children, captured_output, captured_stdout, from test.support.os_helper import (TESTFN, rmtree, unlink)
captured_stderr, unlink, requires_docstrings
)
from test import pydoc_mod from test import pydoc_mod
@ -728,7 +727,7 @@ class PydocDocTest(unittest.TestCase):
self.assertEqual(synopsis, expected) self.assertEqual(synopsis, expected)
def test_synopsis_sourceless_empty_doc(self): def test_synopsis_sourceless_empty_doc(self):
with test.support.temp_cwd() as test_dir: with os_helper.temp_cwd() as test_dir:
init_path = os.path.join(test_dir, 'foomod42.py') init_path = os.path.join(test_dir, 'foomod42.py')
cached_path = importlib.util.cache_from_source(init_path) cached_path = importlib.util.cache_from_source(init_path)
with open(init_path, 'w') as fobj: with open(init_path, 'w') as fobj:
@ -745,11 +744,11 @@ class PydocDocTest(unittest.TestCase):
('I Am A Doc', '\nHere is my description')) ('I Am A Doc', '\nHere is my description'))
def test_is_package_when_not_package(self): def test_is_package_when_not_package(self):
with test.support.temp_cwd() as test_dir: with os_helper.temp_cwd() as test_dir:
self.assertFalse(pydoc.ispackage(test_dir)) self.assertFalse(pydoc.ispackage(test_dir))
def test_is_package_when_is_package(self): def test_is_package_when_is_package(self):
with test.support.temp_cwd() as test_dir: with os_helper.temp_cwd() as test_dir:
init_path = os.path.join(test_dir, '__init__.py') init_path = os.path.join(test_dir, '__init__.py')
open(init_path, 'w').close() open(init_path, 'w').close()
self.assertTrue(pydoc.ispackage(test_dir)) self.assertTrue(pydoc.ispackage(test_dir))

View File

@ -2,9 +2,11 @@ import contextlib
import sys import sys
import unittest import unittest
from test import support from test import support
from test.support import import_helper
from test.support import os_helper
import time import time
resource = support.import_module('resource') resource = import_helper.import_module('resource')
# This test is checking a few specific problem spots with the resource module. # This test is checking a few specific problem spots with the resource module.
@ -51,7 +53,7 @@ class ResourceTest(unittest.TestCase):
limit_set = True limit_set = True
except ValueError: except ValueError:
limit_set = False limit_set = False
f = open(support.TESTFN, "wb") f = open(os_helper.TESTFN, "wb")
try: try:
f.write(b"X" * 1024) f.write(b"X" * 1024)
try: try:
@ -77,7 +79,7 @@ class ResourceTest(unittest.TestCase):
finally: finally:
if limit_set: if limit_set:
resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
support.unlink(support.TESTFN) os_helper.unlink(os_helper.TESTFN)
def test_fsize_toobig(self): def test_fsize_toobig(self):
# Be sure that setrlimit is checking for really large values # Be sure that setrlimit is checking for really large values

View File

@ -9,9 +9,9 @@ import importlib, importlib.machinery, importlib.util
import py_compile import py_compile
import warnings import warnings
import pathlib import pathlib
from test.support import ( from test.support import verbose, no_tracing
forget, make_legacy_pyc, unload, verbose, no_tracing, from test.support.import_helper import forget, make_legacy_pyc, unload
create_empty_file, temp_dir) from test.support.os_helper import create_empty_file, temp_dir
from test.support.script_helper import make_script, make_zip_script from test.support.script_helper import make_script, make_zip_script

View File

@ -22,8 +22,10 @@ import shutil
import sys import sys
from urllib.error import URLError from urllib.error import URLError
import urllib.request import urllib.request
from test import support from test.support import os_helper
from test.support import findfile, run_unittest, FakePath, TESTFN from test.support import findfile, run_unittest
from test.support.os_helper import FakePath, TESTFN
TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata") TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata")
TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata") TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata")
@ -36,7 +38,7 @@ except UnicodeEncodeError:
supports_nonascii_filenames = True supports_nonascii_filenames = True
if not os.path.supports_unicode_filenames: if not os.path.supports_unicode_filenames:
try: try:
support.TESTFN_UNICODE.encode(sys.getfilesystemencoding()) os_helper.TESTFN_UNICODE.encode(sys.getfilesystemencoding())
except (UnicodeError, TypeError): except (UnicodeError, TypeError):
# Either the file system encoding is None, or the file name # Either the file system encoding is None, or the file name
# cannot be encoded in the file system encoding. # cannot be encoded in the file system encoding.
@ -121,7 +123,7 @@ class ParseTest(unittest.TestCase):
data = '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>' data = '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>'
def tearDown(self): def tearDown(self):
support.unlink(TESTFN) os_helper.unlink(TESTFN)
def check_parse(self, f): def check_parse(self, f):
from xml.sax import parse from xml.sax import parse
@ -349,12 +351,12 @@ class SaxutilsTest(unittest.TestCase):
class PrepareInputSourceTest(unittest.TestCase): class PrepareInputSourceTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.file = support.TESTFN self.file = os_helper.TESTFN
with open(self.file, "w") as tmp: with open(self.file, "w") as tmp:
tmp.write("This was read from a file.") tmp.write("This was read from a file.")
def tearDown(self): def tearDown(self):
support.unlink(self.file) os_helper.unlink(self.file)
def make_byte_stream(self): def make_byte_stream(self):
return BytesIO(b"This is a byte stream.") return BytesIO(b"This is a byte stream.")
@ -824,14 +826,14 @@ class StreamWriterXmlgenTest(XmlgenTest, unittest.TestCase):
(encoding, doc)).encode('ascii', 'xmlcharrefreplace') (encoding, doc)).encode('ascii', 'xmlcharrefreplace')
class StreamReaderWriterXmlgenTest(XmlgenTest, unittest.TestCase): class StreamReaderWriterXmlgenTest(XmlgenTest, unittest.TestCase):
fname = support.TESTFN + '-codecs' fname = os_helper.TESTFN + '-codecs'
def ioclass(self): def ioclass(self):
writer = codecs.open(self.fname, 'w', encoding='ascii', writer = codecs.open(self.fname, 'w', encoding='ascii',
errors='xmlcharrefreplace', buffering=0) errors='xmlcharrefreplace', buffering=0)
def cleanup(): def cleanup():
writer.close() writer.close()
support.unlink(self.fname) os_helper.unlink(self.fname)
self.addCleanup(cleanup) self.addCleanup(cleanup)
def getvalue(): def getvalue():
# Windows will not let use reopen without first closing # Windows will not let use reopen without first closing
@ -901,9 +903,9 @@ class ExpatReaderTest(XmlTestBase):
@requires_nonascii_filenames @requires_nonascii_filenames
def test_expat_binary_file_nonascii(self): def test_expat_binary_file_nonascii(self):
fname = support.TESTFN_UNICODE fname = os_helper.TESTFN_UNICODE
shutil.copyfile(TEST_XMLFILE, fname) shutil.copyfile(TEST_XMLFILE, fname)
self.addCleanup(support.unlink, fname) self.addCleanup(os_helper.unlink, fname)
parser = create_parser() parser = create_parser()
result = BytesIO() result = BytesIO()
@ -1137,9 +1139,9 @@ class ExpatReaderTest(XmlTestBase):
@requires_nonascii_filenames @requires_nonascii_filenames
def test_expat_inpsource_sysid_nonascii(self): def test_expat_inpsource_sysid_nonascii(self):
fname = support.TESTFN_UNICODE fname = os_helper.TESTFN_UNICODE
shutil.copyfile(TEST_XMLFILE, fname) shutil.copyfile(TEST_XMLFILE, fname)
self.addCleanup(support.unlink, fname) self.addCleanup(os_helper.unlink, fname)
parser = create_parser() parser = create_parser()
result = BytesIO() result = BytesIO()
@ -1239,9 +1241,9 @@ class ExpatReaderTest(XmlTestBase):
@requires_nonascii_filenames @requires_nonascii_filenames
def test_expat_locator_withinfo_nonascii(self): def test_expat_locator_withinfo_nonascii(self):
fname = support.TESTFN_UNICODE fname = os_helper.TESTFN_UNICODE
shutil.copyfile(TEST_XMLFILE, fname) shutil.copyfile(TEST_XMLFILE, fname)
self.addCleanup(support.unlink, fname) self.addCleanup(os_helper.unlink, fname)
result = BytesIO() result = BytesIO()
xmlgen = XMLGenerator(result) xmlgen = XMLGenerator(result)

View File

@ -10,6 +10,7 @@ import sys
import sysconfig import sysconfig
import test.support import test.support
from test import support from test import support
from test.support import os_helper
from test.support.script_helper import assert_python_ok, assert_python_failure from test.support.script_helper import assert_python_ok, assert_python_failure
from test.support import threading_helper from test.support import threading_helper
import textwrap import textwrap
@ -632,7 +633,7 @@ class SysModuleTest(unittest.TestCase):
out = p.communicate()[0].strip() out = p.communicate()[0].strip()
self.assertEqual(out, b'\xbd') self.assertEqual(out, b'\xbd')
@unittest.skipUnless(test.support.FS_NONASCII, @unittest.skipUnless(os_helper.FS_NONASCII,
'requires OS support of non-ASCII encodings') 'requires OS support of non-ASCII encodings')
@unittest.skipUnless(sys.getfilesystemencoding() == locale.getpreferredencoding(False), @unittest.skipUnless(sys.getfilesystemencoding() == locale.getpreferredencoding(False),
'requires FS encoding to match locale') 'requires FS encoding to match locale')
@ -641,10 +642,10 @@ class SysModuleTest(unittest.TestCase):
env["PYTHONIOENCODING"] = "" env["PYTHONIOENCODING"] = ""
p = subprocess.Popen([sys.executable, "-c", p = subprocess.Popen([sys.executable, "-c",
'print(%a)' % test.support.FS_NONASCII], 'print(%a)' % os_helper.FS_NONASCII],
stdout=subprocess.PIPE, env=env) stdout=subprocess.PIPE, env=env)
out = p.communicate()[0].strip() out = p.communicate()[0].strip()
self.assertEqual(out, os.fsencode(test.support.FS_NONASCII)) self.assertEqual(out, os.fsencode(os_helper.FS_NONASCII))
@unittest.skipIf(sys.base_prefix != sys.prefix, @unittest.skipIf(sys.base_prefix != sys.prefix,
'Test is not venv-compatible') 'Test is not venv-compatible')

View File

@ -1,6 +1,5 @@
from test.support import import_helper
from test import support syslog = import_helper.import_module("syslog") #skip if not supported
syslog = support.import_module("syslog") #skip if not supported
import unittest import unittest
# XXX(nnorwitz): This test sucks. I don't know of a platform independent way # XXX(nnorwitz): This test sucks. I don't know of a platform independent way

View File

@ -1,7 +1,9 @@
from test import support from test import support
from test.support import import_helper
# Skip this test if _tkinter does not exist. # Skip this test if _tkinter does not exist.
support.import_module('_tkinter') import_helper.import_module('_tkinter')
from tkinter.test import runtktests from tkinter.test import runtktests

View File

@ -6,6 +6,8 @@ import unittest
import warnings import warnings
from unicodedata import normalize from unicodedata import normalize
from test import support from test import support
from test.support import os_helper
filenames = [ filenames = [
'1_abc', '1_abc',
@ -62,14 +64,14 @@ class UnicodeFileTests(unittest.TestCase):
def setUp(self): def setUp(self):
try: try:
os.mkdir(support.TESTFN) os.mkdir(os_helper.TESTFN)
except FileExistsError: except FileExistsError:
pass pass
self.addCleanup(support.rmtree, support.TESTFN) self.addCleanup(os_helper.rmtree, os_helper.TESTFN)
files = set() files = set()
for name in self.files: for name in self.files:
name = os.path.join(support.TESTFN, self.norm(name)) name = os.path.join(os_helper.TESTFN, self.norm(name))
with open(name, 'wb') as f: with open(name, 'wb') as f:
f.write((name+'\n').encode("utf-8")) f.write((name+'\n').encode("utf-8"))
os.stat(name) os.stat(name)
@ -144,9 +146,10 @@ class UnicodeFileTests(unittest.TestCase):
sf0 = set(self.files) sf0 = set(self.files)
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning) warnings.simplefilter("ignore", DeprecationWarning)
f1 = os.listdir(support.TESTFN.encode(sys.getfilesystemencoding())) f1 = os.listdir(os_helper.TESTFN.encode(
f2 = os.listdir(support.TESTFN) sys.getfilesystemencoding()))
sf2 = set(os.path.join(support.TESTFN, f) for f in f2) f2 = os.listdir(os_helper.TESTFN)
sf2 = set(os.path.join(os_helper.TESTFN, f) for f in f2)
self.assertEqual(sf0, sf2, "%a != %a" % (sf0, sf2)) self.assertEqual(sf0, sf2, "%a != %a" % (sf0, sf2))
self.assertEqual(len(f1), len(f2)) self.assertEqual(len(f1), len(f2))
@ -156,9 +159,10 @@ class UnicodeFileTests(unittest.TestCase):
os.rename("tmp", name) os.rename("tmp", name)
def test_directory(self): def test_directory(self):
dirname = os.path.join(support.TESTFN, 'Gr\xfc\xdf-\u66e8\u66e9\u66eb') dirname = os.path.join(os_helper.TESTFN,
'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
filename = '\xdf-\u66e8\u66e9\u66eb' filename = '\xdf-\u66e8\u66e9\u66eb'
with support.temp_cwd(dirname): with os_helper.temp_cwd(dirname):
with open(filename, 'wb') as f: with open(filename, 'wb') as f:
f.write((filename + '\n').encode("utf-8")) f.write((filename + '\n').encode("utf-8"))
os.access(filename,os.R_OK) os.access(filename,os.R_OK)

View File

@ -1,6 +1,8 @@
import unittest import unittest
from test import support from test import support
from test.support import os_helper
from test.support import socket_helper from test.support import socket_helper
from test.support import warnings_helper
from test import test_urllib from test import test_urllib
import os import os
@ -765,7 +767,7 @@ class HandlerTests(unittest.TestCase):
h = urllib.request.FileHandler() h = urllib.request.FileHandler()
o = h.parent = MockOpener() o = h.parent = MockOpener()
TESTFN = support.TESTFN TESTFN = os_helper.TESTFN
urlpath = sanepathname2url(os.path.abspath(TESTFN)) urlpath = sanepathname2url(os.path.abspath(TESTFN))
towrite = b"hello, world\n" towrite = b"hello, world\n"
urls = [ urls = [
@ -1490,7 +1492,7 @@ class HandlerTests(unittest.TestCase):
self.check_basic_auth(headers, realm) self.check_basic_auth(headers, realm)
# no quote: expect a warning # no quote: expect a warning
with support.check_warnings(("Basic Auth Realm was unquoted", with warnings_helper.check_warnings(("Basic Auth Realm was unquoted",
UserWarning)): UserWarning)):
headers = [f'WWW-Authenticate: Basic realm={realm}'] headers = [f'WWW-Authenticate: Basic realm={realm}']
self.check_basic_auth(headers, realm) self.check_basic_auth(headers, realm)

View File

@ -15,9 +15,8 @@ import subprocess
import sys import sys
import tempfile import tempfile
from test.support import (captured_stdout, captured_stderr, requires_zlib, from test.support import (captured_stdout, captured_stderr, requires_zlib,
can_symlink, EnvironmentVarGuard, rmtree,
import_module,
skip_if_broken_multiprocessing_synchronize) skip_if_broken_multiprocessing_synchronize)
from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree)
import unittest import unittest
import venv import venv
from unittest.mock import patch from unittest.mock import patch