diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index 5f65d966d62..6b4679f82da 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -27,12 +27,13 @@ import test.support import test.support.script_helper from test import support from test.support import hashlib_helper +from test.support import import_helper from test.support import socket_helper from test.support import threading_helper # Skip tests if _multiprocessing wasn't built. -_multiprocessing = test.support.import_module('_multiprocessing') +_multiprocessing = import_helper.import_module('_multiprocessing') # Skip tests if sem_open implementation is broken. support.skip_if_broken_multiprocessing_synchronize() import threading diff --git a/Lib/test/test_base64.py b/Lib/test/test_base64.py index 1dbeac41dc0..1f67e46cd22 100644 --- a/Lib/test/test_base64.py +++ b/Lib/test/test_base64.py @@ -1,9 +1,9 @@ import unittest -from test import support import base64 import binascii import os from array import array +from test.support import os_helper from test.support import script_helper @@ -647,8 +647,8 @@ class BaseXYTestCase(unittest.TestCase): class TestMain(unittest.TestCase): def tearDown(self): - if os.path.exists(support.TESTFN): - os.unlink(support.TESTFN) + if os.path.exists(os_helper.TESTFN): + os.unlink(os_helper.TESTFN) def get_output(self, *args): return script_helper.assert_python_ok('-m', 'base64', *args).out @@ -662,9 +662,9 @@ class TestMain(unittest.TestCase): )) def test_encode_file(self): - with open(support.TESTFN, 'wb') as fp: + with open(os_helper.TESTFN, 'wb') as fp: fp.write(b'a\xffb\n') - output = self.get_output('-e', support.TESTFN) + output = self.get_output('-e', os_helper.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_encode_from_stdin(self): @@ -674,9 +674,9 @@ class TestMain(unittest.TestCase): self.assertIsNone(err) def test_decode(self): - with open(support.TESTFN, 'wb') as fp: + with open(os_helper.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') - output = self.get_output('-d', support.TESTFN) + output = self.get_output('-d', os_helper.TESTFN) self.assertEqual(output.rstrip(), b'a\xffb') if __name__ == '__main__': diff --git a/Lib/test/test_bool.py b/Lib/test/test_bool.py index 4c6fba42c0c..7b3a3859e08 100644 --- a/Lib/test/test_bool.py +++ b/Lib/test/test_bool.py @@ -2,6 +2,7 @@ import unittest from test import support +from test.support import os_helper import os @@ -234,11 +235,11 @@ class BoolTest(unittest.TestCase): def test_fileclosed(self): try: - with open(support.TESTFN, "w") as f: + with open(os_helper.TESTFN, "w") as f: self.assertIs(f.closed, False) self.assertIs(f.closed, True) finally: - os.remove(support.TESTFN) + os.remove(os_helper.TESTFN) def test_types(self): # types are always true. diff --git a/Lib/test/test_dict_version.py b/Lib/test/test_dict_version.py index b23786514f8..8cdccad0d79 100644 --- a/Lib/test/test_dict_version.py +++ b/Lib/test/test_dict_version.py @@ -2,11 +2,11 @@ Test implementation of the PEP 509: dictionary versionning. """ import unittest -from test import support +from test.support import import_helper # PEP 509 is implemented in CPython but other Python implementations # don't require to implement it -_testcapi = support.import_module('_testcapi') +_testcapi = import_helper.import_module('_testcapi') class DictVersionTests(unittest.TestCase): diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index ef7d1a15c75..a51452e739f 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -1,7 +1,8 @@ # Python test set -- part 1, grammar. # This just tests whether the parser accepts them all. -from test.support import check_syntax_error, check_syntax_warning +from test.support import check_syntax_error +from test.support.warnings_helper import check_syntax_warning import inspect import unittest import sys @@ -276,7 +277,8 @@ class CNS: class GrammarTests(unittest.TestCase): - from test.support import check_syntax_error, check_syntax_warning + from test.support import check_syntax_error + from test.support.warnings_helper import check_syntax_warning # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE # XXX can't test in a script -- this rule is only used when interactive diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py index 52434693988..a7658b5f476 100644 --- a/Lib/test/test_iter.py +++ b/Lib/test/test_iter.py @@ -2,7 +2,8 @@ import sys import unittest -from test.support import run_unittest, TESTFN, unlink, cpython_only +from test.support import run_unittest, cpython_only +from test.support.os_helper import TESTFN, unlink from test.support import check_free_after_iterating, ALWAYS_EQ, NEVER_EQ import pickle import collections.abc diff --git a/Lib/test/test_lzma.py b/Lib/test/test_lzma.py index 0f3af27efa9..c2427f8cd22 100644 --- a/Lib/test/test_lzma.py +++ b/Lib/test/test_lzma.py @@ -9,7 +9,11 @@ from test import support import unittest from test.support import ( - _4G, TESTFN, import_module, bigmemtest, run_unittest, unlink + _4G, bigmemtest, run_unittest +) +from test.support.import_helper import import_module +from test.support.os_helper import ( + TESTFN, unlink ) lzma = import_module("lzma") diff --git a/Lib/test/test_mailcap.py b/Lib/test/test_mailcap.py index c08423c6707..51a0c7da8bb 100644 --- a/Lib/test/test_mailcap.py +++ b/Lib/test/test_mailcap.py @@ -2,6 +2,7 @@ import mailcap import os import copy import test.support +from test.support import os_helper import unittest # Location of mailcap file @@ -74,7 +75,7 @@ class HelperFunctionTest(unittest.TestCase): self.assertIsInstance(mcfiles, list) for m in mcfiles: self.assertIsInstance(m, str) - with test.support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: # According to RFC 1524, if MAILCAPS env variable exists, use that # and only that. if "MAILCAPS" in env: @@ -136,7 +137,7 @@ class GetcapsTest(unittest.TestCase): # Test mailcap.getcaps() using mock mailcap file in this dir. # Temporarily override any existing system mailcap file by pointing the # MAILCAPS environment variable to our mock file. - with test.support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env["MAILCAPS"] = MAILCAPFILE caps = mailcap.getcaps() self.assertDictEqual(caps, MAILCAPDICT) diff --git a/Lib/test/test_memoryview.py b/Lib/test/test_memoryview.py index ca307d8342f..d7e3f0c0eff 100644 --- a/Lib/test/test_memoryview.py +++ b/Lib/test/test_memoryview.py @@ -14,6 +14,8 @@ import io import copy import pickle +from test.support import import_helper + class AbstractMemoryTests: source_bytes = b"abcdef" @@ -508,7 +510,7 @@ class ArrayMemorySliceSliceTest(unittest.TestCase, class OtherTest(unittest.TestCase): def test_ctypes_cast(self): # Issue 15944: Allow all source formats when casting to bytes. - ctypes = test.support.import_module("ctypes") + ctypes = import_helper.import_module("ctypes") p6 = bytes(ctypes.c_double(0.6)) d = ctypes.c_double() diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index ef2395d87a6..03152072c1b 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -30,8 +30,10 @@ import unittest import uuid import warnings from test import support +from test.support import os_helper from test.support import socket_helper from test.support import threading_helper +from test.support import warnings_helper from platform import win32_is_iot try: @@ -57,7 +59,8 @@ except ImportError: INT_MAX = PY_SSIZE_T_MAX = sys.maxsize from test.support.script_helper import assert_python_ok -from test.support import unix_shell, FakePath +from test.support import unix_shell +from test.support.os_helper import FakePath root_in_posix = False @@ -109,7 +112,7 @@ class MiscTests(unittest.TestCase): dirname = dirname + ('a' * (dirlen - len(dirname))) with tempfile.TemporaryDirectory() as tmpdir: - with support.change_cwd(tmpdir) as path: + with os_helper.change_cwd(tmpdir) as path: expected = path while True: @@ -153,17 +156,17 @@ class MiscTests(unittest.TestCase): # Tests creating TESTFN class FileTests(unittest.TestCase): def setUp(self): - if os.path.lexists(support.TESTFN): - os.unlink(support.TESTFN) + if os.path.lexists(os_helper.TESTFN): + os.unlink(os_helper.TESTFN) tearDown = setUp def test_access(self): - f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) + f = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR) os.close(f) - self.assertTrue(os.access(support.TESTFN, os.W_OK)) + self.assertTrue(os.access(os_helper.TESTFN, os.W_OK)) def test_closerange(self): - first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) + first = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR) # We must allocate two consecutive file descriptors, otherwise # it will mess up other file descriptors (perhaps even the three # standard ones). @@ -185,14 +188,14 @@ class FileTests(unittest.TestCase): @support.cpython_only def test_rename(self): - path = support.TESTFN + path = os_helper.TESTFN old = sys.getrefcount(path) self.assertRaises(TypeError, os.rename, path, 0) new = sys.getrefcount(path) self.assertEqual(old, new) def test_read(self): - with open(support.TESTFN, "w+b") as fobj: + with open(os_helper.TESTFN, "w+b") as fobj: fobj.write(b"spam") fobj.flush() fd = fobj.fileno() @@ -208,12 +211,12 @@ class FileTests(unittest.TestCase): "needs INT_MAX < PY_SSIZE_T_MAX") @support.bigmemtest(size=INT_MAX + 10, memuse=1, dry_run=False) def test_large_read(self, size): - self.addCleanup(support.unlink, support.TESTFN) - create_file(support.TESTFN, b'test') + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + create_file(os_helper.TESTFN, b'test') # Issue #21932: Make sure that os.read() does not raise an # OverflowError for size larger than INT_MAX - with open(support.TESTFN, "rb") as fp: + with open(os_helper.TESTFN, "rb") as fp: data = os.read(fp.fileno(), size) # The test does not try to read more than 2 GiB at once because the @@ -222,13 +225,13 @@ class FileTests(unittest.TestCase): def test_write(self): # os.write() accepts bytes- and buffer-like objects but not strings - fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY) + fd = os.open(os_helper.TESTFN, os.O_CREAT | os.O_WRONLY) self.assertRaises(TypeError, os.write, fd, "beans") os.write(fd, b"bacon\n") os.write(fd, bytearray(b"eggs\n")) os.write(fd, memoryview(b"spam\n")) os.close(fd) - with open(support.TESTFN, "rb") as fobj: + with open(os_helper.TESTFN, "rb") as fobj: self.assertEqual(fobj.read().splitlines(), [b"bacon", b"eggs", b"spam"]) @@ -252,12 +255,12 @@ class FileTests(unittest.TestCase): self.write_windows_console(sys.executable, "-u", "-c", code) def fdopen_helper(self, *args): - fd = os.open(support.TESTFN, os.O_RDONLY) + fd = os.open(os_helper.TESTFN, os.O_RDONLY) f = os.fdopen(fd, *args) f.close() def test_fdopen(self): - fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) + fd = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR) os.close(fd) self.fdopen_helper() @@ -265,15 +268,15 @@ class FileTests(unittest.TestCase): self.fdopen_helper('r', 100) def test_replace(self): - TESTFN2 = support.TESTFN + ".2" - self.addCleanup(support.unlink, support.TESTFN) - self.addCleanup(support.unlink, TESTFN2) + TESTFN2 = os_helper.TESTFN + ".2" + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + self.addCleanup(os_helper.unlink, TESTFN2) - create_file(support.TESTFN, b"1") + create_file(os_helper.TESTFN, b"1") create_file(TESTFN2, b"2") - os.replace(support.TESTFN, TESTFN2) - self.assertRaises(FileNotFoundError, os.stat, support.TESTFN) + os.replace(os_helper.TESTFN, TESTFN2) + self.assertRaises(FileNotFoundError, os.stat, os_helper.TESTFN) with open(TESTFN2, 'r') as f: self.assertEqual(f.read(), "1") @@ -285,7 +288,7 @@ class FileTests(unittest.TestCase): def test_symlink_keywords(self): symlink = support.get_attribute(os, "symlink") try: - symlink(src='target', dst=support.TESTFN, + symlink(src='target', dst=os_helper.TESTFN, target_is_directory=False, dir_fd=None) except (NotImplementedError, OSError): pass # No OS support or unprivileged user @@ -297,18 +300,18 @@ class FileTests(unittest.TestCase): @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()') def test_copy_file_range(self): - TESTFN2 = support.TESTFN + ".3" + TESTFN2 = os_helper.TESTFN + ".3" data = b'0123456789' - create_file(support.TESTFN, data) - self.addCleanup(support.unlink, support.TESTFN) + create_file(os_helper.TESTFN, data) + self.addCleanup(os_helper.unlink, os_helper.TESTFN) - in_file = open(support.TESTFN, 'rb') + in_file = open(os_helper.TESTFN, 'rb') self.addCleanup(in_file.close) in_fd = in_file.fileno() out_file = open(TESTFN2, 'w+b') - self.addCleanup(support.unlink, TESTFN2) + self.addCleanup(os_helper.unlink, TESTFN2) self.addCleanup(out_file.close) out_fd = out_file.fileno() @@ -331,21 +334,21 @@ class FileTests(unittest.TestCase): @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()') def test_copy_file_range_offset(self): - TESTFN4 = support.TESTFN + ".4" + TESTFN4 = os_helper.TESTFN + ".4" data = b'0123456789' bytes_to_copy = 6 in_skip = 3 out_seek = 5 - create_file(support.TESTFN, data) - self.addCleanup(support.unlink, support.TESTFN) + create_file(os_helper.TESTFN, data) + self.addCleanup(os_helper.unlink, os_helper.TESTFN) - in_file = open(support.TESTFN, 'rb') + in_file = open(os_helper.TESTFN, 'rb') self.addCleanup(in_file.close) in_fd = in_file.fileno() out_file = open(TESTFN4, 'w+b') - self.addCleanup(support.unlink, TESTFN4) + self.addCleanup(os_helper.unlink, TESTFN4) self.addCleanup(out_file.close) out_fd = out_file.fileno() @@ -377,8 +380,8 @@ class FileTests(unittest.TestCase): # Test attributes on return values from os.*stat* family. class StatAttributeTests(unittest.TestCase): def setUp(self): - self.fname = support.TESTFN - self.addCleanup(support.unlink, self.fname) + self.fname = os_helper.TESTFN + self.addCleanup(os_helper.unlink, self.fname) create_file(self.fname, b"ABC") def check_stat_attributes(self, fname): @@ -563,7 +566,7 @@ class StatAttributeTests(unittest.TestCase): 0) # test directory st_file_attributes (FILE_ATTRIBUTE_DIRECTORY set) - dirname = support.TESTFN + "dir" + dirname = os_helper.TESTFN + "dir" os.mkdir(dirname) self.addCleanup(os.rmdir, dirname) @@ -580,7 +583,7 @@ class StatAttributeTests(unittest.TestCase): # os.environ['TEMP'] should be located on a volume that # supports file ACLs. fname = os.path.join(os.environ['TEMP'], self.fname) - self.addCleanup(support.unlink, fname) + self.addCleanup(os_helper.unlink, fname) create_file(fname, b'ABC') # Deny the right to [S]YNCHRONIZE on the file to # force CreateFile to fail with ERROR_ACCESS_DENIED. @@ -605,10 +608,10 @@ class StatAttributeTests(unittest.TestCase): class UtimeTests(unittest.TestCase): def setUp(self): - self.dirname = support.TESTFN + self.dirname = os_helper.TESTFN self.fname = os.path.join(self.dirname, "f1") - self.addCleanup(support.rmtree, self.dirname) + self.addCleanup(os_helper.rmtree, self.dirname) os.mkdir(self.dirname) create_file(self.fname) @@ -961,7 +964,7 @@ class EnvironTests(mapping_tests.BasicTestMappingProtocol): value = "testvalue" code = f'import os; print(repr(os.environ.get({name!r})))' - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env.pop(name, None) os.putenv(name, value) @@ -1132,7 +1135,7 @@ class WalkTests(unittest.TestCase): def setUp(self): join = os.path.join - self.addCleanup(support.rmtree, support.TESTFN) + self.addCleanup(os_helper.rmtree, os_helper.TESTFN) # Build: # TESTFN/ @@ -1151,7 +1154,7 @@ class WalkTests(unittest.TestCase): # broken_link3 # TEST2/ # tmp4 a lone file - self.walk_path = join(support.TESTFN, "TEST1") + self.walk_path = join(os_helper.TESTFN, "TEST1") self.sub1_path = join(self.walk_path, "SUB1") self.sub11_path = join(self.sub1_path, "SUB11") sub2_path = join(self.walk_path, "SUB2") @@ -1161,8 +1164,8 @@ class WalkTests(unittest.TestCase): tmp3_path = join(sub2_path, "tmp3") tmp5_path = join(sub21_path, "tmp3") self.link_path = join(sub2_path, "link") - t2_path = join(support.TESTFN, "TEST2") - tmp4_path = join(support.TESTFN, "TEST2", "tmp4") + t2_path = join(os_helper.TESTFN, "TEST2") + tmp4_path = join(os_helper.TESTFN, "TEST2", "tmp4") broken_link_path = join(sub2_path, "broken_link") broken_link2_path = join(sub2_path, "broken_link2") broken_link3_path = join(sub2_path, "broken_link3") @@ -1177,7 +1180,7 @@ class WalkTests(unittest.TestCase): with open(path, "x", encoding='utf-8') as f: f.write("I'm " + path + " and proud of it. Blame test_os.\n") - if support.can_symlink(): + if os_helper.can_symlink(): os.symlink(os.path.abspath(t2_path), self.link_path) os.symlink('broken', broken_link_path, True) os.symlink(join('tmp3', 'broken'), broken_link2_path, True) @@ -1260,7 +1263,7 @@ class WalkTests(unittest.TestCase): self.sub2_tree) def test_walk_symlink(self): - if not support.can_symlink(): + if not os_helper.can_symlink(): self.skipTest("need symlink support") # Walk, following symlinks. @@ -1296,7 +1299,7 @@ class WalkTests(unittest.TestCase): def test_walk_many_open_files(self): depth = 30 - base = os.path.join(support.TESTFN, 'deep') + base = os.path.join(os_helper.TESTFN, 'deep') p = os.path.join(base, *(['d']*depth)) os.makedirs(p) @@ -1346,13 +1349,13 @@ class FwalkTests(WalkTests): self.assertEqual(expected[root], (set(dirs), set(files))) def test_compare_to_walk(self): - kwargs = {'top': support.TESTFN} + kwargs = {'top': os_helper.TESTFN} self._compare_to_walk(kwargs, kwargs) def test_dir_fd(self): try: fd = os.open(".", os.O_RDONLY) - walk_kwargs = {'top': support.TESTFN} + walk_kwargs = {'top': os_helper.TESTFN} fwalk_kwargs = walk_kwargs.copy() fwalk_kwargs['dir_fd'] = fd self._compare_to_walk(walk_kwargs, fwalk_kwargs) @@ -1362,7 +1365,7 @@ class FwalkTests(WalkTests): def test_yields_correct_dir_fd(self): # check returned file descriptors for topdown, follow_symlinks in itertools.product((True, False), repeat=2): - args = support.TESTFN, topdown, None + args = os_helper.TESTFN, topdown, None for root, dirs, files, rootfd in self.fwalk(*args, follow_symlinks=follow_symlinks): # check that the FD is valid os.fstat(rootfd) @@ -1378,7 +1381,7 @@ class FwalkTests(WalkTests): minfd = os.dup(1) os.close(minfd) for i in range(256): - for x in self.fwalk(support.TESTFN): + for x in self.fwalk(os_helper.TESTFN): pass newfd = os.dup(1) self.addCleanup(os.close, newfd) @@ -1416,10 +1419,10 @@ class BytesFwalkTests(FwalkTests): class MakedirTests(unittest.TestCase): def setUp(self): - os.mkdir(support.TESTFN) + os.mkdir(os_helper.TESTFN) def test_makedir(self): - base = support.TESTFN + base = os_helper.TESTFN path = os.path.join(base, 'dir1', 'dir2', 'dir3') os.makedirs(path) # Should work path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4') @@ -1434,8 +1437,8 @@ class MakedirTests(unittest.TestCase): os.makedirs(path) def test_mode(self): - with support.temp_umask(0o002): - base = support.TESTFN + with os_helper.temp_umask(0o002): + base = os_helper.TESTFN parent = os.path.join(base, 'dir1') path = os.path.join(parent, 'dir2') os.makedirs(path, 0o555) @@ -1446,7 +1449,7 @@ class MakedirTests(unittest.TestCase): self.assertEqual(os.stat(parent).st_mode & 0o777, 0o775) def test_exist_ok_existing_directory(self): - path = os.path.join(support.TESTFN, 'dir1') + path = os.path.join(os_helper.TESTFN, 'dir1') mode = 0o777 old_mask = os.umask(0o022) os.makedirs(path, mode) @@ -1460,18 +1463,18 @@ class MakedirTests(unittest.TestCase): os.makedirs(os.path.abspath('/'), exist_ok=True) def test_exist_ok_s_isgid_directory(self): - path = os.path.join(support.TESTFN, 'dir1') + path = os.path.join(os_helper.TESTFN, 'dir1') S_ISGID = stat.S_ISGID mode = 0o777 old_mask = os.umask(0o022) try: existing_testfn_mode = stat.S_IMODE( - os.lstat(support.TESTFN).st_mode) + os.lstat(os_helper.TESTFN).st_mode) try: - os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID) + os.chmod(os_helper.TESTFN, existing_testfn_mode | S_ISGID) except PermissionError: raise unittest.SkipTest('Cannot set S_ISGID for dir.') - if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID): + if (os.lstat(os_helper.TESTFN).st_mode & S_ISGID != S_ISGID): raise unittest.SkipTest('No support for S_ISGID dir mode.') # The os should apply S_ISGID from the parent dir for us, but # this test need not depend on that behavior. Be explicit. @@ -1487,8 +1490,8 @@ class MakedirTests(unittest.TestCase): os.umask(old_mask) def test_exist_ok_existing_regular_file(self): - base = support.TESTFN - path = os.path.join(support.TESTFN, 'dir1') + base = os_helper.TESTFN + path = os.path.join(os_helper.TESTFN, 'dir1') with open(path, 'w') as f: f.write('abc') self.assertRaises(OSError, os.makedirs, path) @@ -1497,12 +1500,12 @@ class MakedirTests(unittest.TestCase): os.remove(path) def tearDown(self): - path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3', + path = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', 'dir6') # If the tests failed, the bottom-most directory ('../dir6') # may not have been created, so we look for the outermost directory # that exists. - while not os.path.exists(path) and path != support.TESTFN: + while not os.path.exists(path) and path != os_helper.TESTFN: path = os.path.dirname(path) os.removedirs(path) @@ -1513,17 +1516,17 @@ class ChownFileTests(unittest.TestCase): @classmethod def setUpClass(cls): - os.mkdir(support.TESTFN) + os.mkdir(os_helper.TESTFN) def test_chown_uid_gid_arguments_must_be_index(self): - stat = os.stat(support.TESTFN) + stat = os.stat(os_helper.TESTFN) uid = stat.st_uid gid = stat.st_gid for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)): - self.assertRaises(TypeError, os.chown, support.TESTFN, value, gid) - self.assertRaises(TypeError, os.chown, support.TESTFN, uid, value) - self.assertIsNone(os.chown(support.TESTFN, uid, gid)) - self.assertIsNone(os.chown(support.TESTFN, -1, -1)) + self.assertRaises(TypeError, os.chown, os_helper.TESTFN, value, gid) + self.assertRaises(TypeError, os.chown, os_helper.TESTFN, uid, value) + self.assertIsNone(os.chown(os_helper.TESTFN, uid, gid)) + self.assertIsNone(os.chown(os_helper.TESTFN, -1, -1)) @unittest.skipUnless(hasattr(os, 'getgroups'), 'need os.getgroups') def test_chown_gid(self): @@ -1532,61 +1535,61 @@ class ChownFileTests(unittest.TestCase): self.skipTest("test needs at least 2 groups") gid_1, gid_2 = groups[:2] - uid = os.stat(support.TESTFN).st_uid + uid = os.stat(os_helper.TESTFN).st_uid - os.chown(support.TESTFN, uid, gid_1) - gid = os.stat(support.TESTFN).st_gid + os.chown(os_helper.TESTFN, uid, gid_1) + gid = os.stat(os_helper.TESTFN).st_gid self.assertEqual(gid, gid_1) - os.chown(support.TESTFN, uid, gid_2) - gid = os.stat(support.TESTFN).st_gid + os.chown(os_helper.TESTFN, uid, gid_2) + gid = os.stat(os_helper.TESTFN).st_gid self.assertEqual(gid, gid_2) @unittest.skipUnless(root_in_posix and len(all_users) > 1, "test needs root privilege and more than one user") def test_chown_with_root(self): uid_1, uid_2 = all_users[:2] - gid = os.stat(support.TESTFN).st_gid - os.chown(support.TESTFN, uid_1, gid) - uid = os.stat(support.TESTFN).st_uid + gid = os.stat(os_helper.TESTFN).st_gid + os.chown(os_helper.TESTFN, uid_1, gid) + uid = os.stat(os_helper.TESTFN).st_uid self.assertEqual(uid, uid_1) - os.chown(support.TESTFN, uid_2, gid) - uid = os.stat(support.TESTFN).st_uid + os.chown(os_helper.TESTFN, uid_2, gid) + uid = os.stat(os_helper.TESTFN).st_uid self.assertEqual(uid, uid_2) @unittest.skipUnless(not root_in_posix and len(all_users) > 1, "test needs non-root account and more than one user") def test_chown_without_permission(self): uid_1, uid_2 = all_users[:2] - gid = os.stat(support.TESTFN).st_gid + gid = os.stat(os_helper.TESTFN).st_gid with self.assertRaises(PermissionError): - os.chown(support.TESTFN, uid_1, gid) - os.chown(support.TESTFN, uid_2, gid) + os.chown(os_helper.TESTFN, uid_1, gid) + os.chown(os_helper.TESTFN, uid_2, gid) @classmethod def tearDownClass(cls): - os.rmdir(support.TESTFN) + os.rmdir(os_helper.TESTFN) class RemoveDirsTests(unittest.TestCase): def setUp(self): - os.makedirs(support.TESTFN) + os.makedirs(os_helper.TESTFN) def tearDown(self): - support.rmtree(support.TESTFN) + os_helper.rmtree(os_helper.TESTFN) def test_remove_all(self): - dira = os.path.join(support.TESTFN, 'dira') + dira = os.path.join(os_helper.TESTFN, 'dira') os.mkdir(dira) dirb = os.path.join(dira, 'dirb') os.mkdir(dirb) os.removedirs(dirb) self.assertFalse(os.path.exists(dirb)) self.assertFalse(os.path.exists(dira)) - self.assertFalse(os.path.exists(support.TESTFN)) + self.assertFalse(os.path.exists(os_helper.TESTFN)) def test_remove_partial(self): - dira = os.path.join(support.TESTFN, 'dira') + dira = os.path.join(os_helper.TESTFN, 'dira') os.mkdir(dira) dirb = os.path.join(dira, 'dirb') os.mkdir(dirb) @@ -1594,10 +1597,10 @@ class RemoveDirsTests(unittest.TestCase): os.removedirs(dirb) self.assertFalse(os.path.exists(dirb)) self.assertTrue(os.path.exists(dira)) - self.assertTrue(os.path.exists(support.TESTFN)) + self.assertTrue(os.path.exists(os_helper.TESTFN)) def test_remove_nothing(self): - dira = os.path.join(support.TESTFN, 'dira') + dira = os.path.join(os_helper.TESTFN, 'dira') os.mkdir(dira) dirb = os.path.join(dira, 'dirb') os.mkdir(dirb) @@ -1606,7 +1609,7 @@ class RemoveDirsTests(unittest.TestCase): os.removedirs(dirb) self.assertTrue(os.path.exists(dirb)) self.assertTrue(os.path.exists(dira)) - self.assertTrue(os.path.exists(support.TESTFN)) + self.assertTrue(os.path.exists(os_helper.TESTFN)) class DevNullTests(unittest.TestCase): @@ -1744,8 +1747,8 @@ class URandomFDTests(unittest.TestCase): def test_urandom_fd_reopened(self): # Issue #21207: urandom() should detect its fd to /dev/urandom # changed to something else, and reopen it. - self.addCleanup(support.unlink, support.TESTFN) - create_file(support.TESTFN, b"x" * 256) + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + create_file(os_helper.TESTFN, b"x" * 256) code = """if 1: import os @@ -1771,7 +1774,7 @@ class URandomFDTests(unittest.TestCase): os.dup2(new_fd, fd) sys.stdout.buffer.write(os.urandom(4)) sys.stdout.buffer.write(os.urandom(4)) - """.format(TESTFN=support.TESTFN) + """.format(TESTFN=os_helper.TESTFN) rc, out, err = assert_python_ok('-Sc', code) self.assertEqual(len(out), 8) self.assertNotEqual(out[0:4], out[4:8]) @@ -1923,36 +1926,36 @@ class ExecTests(unittest.TestCase): class Win32ErrorTests(unittest.TestCase): def setUp(self): try: - os.stat(support.TESTFN) + os.stat(os_helper.TESTFN) except FileNotFoundError: exists = False except OSError as exc: exists = True self.fail("file %s must not exist; os.stat failed with %s" - % (support.TESTFN, exc)) + % (os_helper.TESTFN, exc)) else: - self.fail("file %s must not exist" % support.TESTFN) + self.fail("file %s must not exist" % os_helper.TESTFN) def test_rename(self): - self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak") + self.assertRaises(OSError, os.rename, os_helper.TESTFN, os_helper.TESTFN+".bak") def test_remove(self): - self.assertRaises(OSError, os.remove, support.TESTFN) + self.assertRaises(OSError, os.remove, os_helper.TESTFN) def test_chdir(self): - self.assertRaises(OSError, os.chdir, support.TESTFN) + self.assertRaises(OSError, os.chdir, os_helper.TESTFN) def test_mkdir(self): - self.addCleanup(support.unlink, support.TESTFN) + self.addCleanup(os_helper.unlink, os_helper.TESTFN) - with open(support.TESTFN, "x") as f: - self.assertRaises(OSError, os.mkdir, support.TESTFN) + with open(os_helper.TESTFN, "x") as f: + self.assertRaises(OSError, os.mkdir, os_helper.TESTFN) def test_utime(self): - self.assertRaises(OSError, os.utime, support.TESTFN, None) + self.assertRaises(OSError, os.utime, os_helper.TESTFN, None) def test_chmod(self): - self.assertRaises(OSError, os.chmod, support.TESTFN, 0) + self.assertRaises(OSError, os.chmod, os_helper.TESTFN, 0) class TestInvalidFD(unittest.TestCase): @@ -1970,7 +1973,7 @@ class TestInvalidFD(unittest.TestCase): def check(self, f, *args): try: - f(support.make_bad_fd(), *args) + f(os_helper.make_bad_fd(), *args) except OSError as e: self.assertEqual(e.errno, errno.EBADF) else: @@ -1979,11 +1982,11 @@ class TestInvalidFD(unittest.TestCase): @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()') def test_isatty(self): - self.assertEqual(os.isatty(support.make_bad_fd()), False) + self.assertEqual(os.isatty(os_helper.make_bad_fd()), False) @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()') def test_closerange(self): - fd = support.make_bad_fd() + fd = os_helper.make_bad_fd() # Make sure none of the descriptors we are about to close are # currently valid (issue 6542). for i in range(10): @@ -2057,8 +2060,8 @@ class TestInvalidFD(unittest.TestCase): class LinkTests(unittest.TestCase): def setUp(self): - self.file1 = support.TESTFN - self.file2 = os.path.join(support.TESTFN + "2") + self.file1 = os_helper.TESTFN + self.file2 = os.path.join(os_helper.TESTFN + "2") def tearDown(self): for file in (self.file1, self.file2): @@ -2163,12 +2166,12 @@ class PosixUidGidTests(unittest.TestCase): @unittest.skipIf(sys.platform == "win32", "Posix specific tests") class Pep383Tests(unittest.TestCase): def setUp(self): - if support.TESTFN_UNENCODABLE: - self.dir = support.TESTFN_UNENCODABLE - elif support.TESTFN_NONASCII: - self.dir = support.TESTFN_NONASCII + if os_helper.TESTFN_UNENCODABLE: + self.dir = os_helper.TESTFN_UNENCODABLE + elif os_helper.TESTFN_NONASCII: + self.dir = os_helper.TESTFN_NONASCII else: - self.dir = support.TESTFN + self.dir = os_helper.TESTFN self.bdir = os.fsencode(self.dir) bytesfn = [] @@ -2178,11 +2181,11 @@ class Pep383Tests(unittest.TestCase): except UnicodeEncodeError: return bytesfn.append(fn) - add_filename(support.TESTFN_UNICODE) - if support.TESTFN_UNENCODABLE: - add_filename(support.TESTFN_UNENCODABLE) - if support.TESTFN_NONASCII: - add_filename(support.TESTFN_NONASCII) + add_filename(os_helper.TESTFN_UNICODE) + if os_helper.TESTFN_UNENCODABLE: + add_filename(os_helper.TESTFN_UNENCODABLE) + if os_helper.TESTFN_NONASCII: + add_filename(os_helper.TESTFN_NONASCII) if not bytesfn: self.skipTest("couldn't create any non-ascii filename") @@ -2190,7 +2193,7 @@ class Pep383Tests(unittest.TestCase): os.mkdir(self.dir) try: for fn in bytesfn: - support.create_empty_file(os.path.join(self.bdir, fn)) + os_helper.create_empty_file(os.path.join(self.bdir, fn)) fn = os.fsdecode(fn) if fn in self.unicodefn: raise ValueError("duplicate filename") @@ -2356,9 +2359,9 @@ class Win32ListdirTests(unittest.TestCase): self.created_paths = [] for i in range(2): dir_name = 'SUB%d' % i - dir_path = os.path.join(support.TESTFN, dir_name) + dir_path = os.path.join(os_helper.TESTFN, dir_name) file_name = 'FILE%d' % i - file_path = os.path.join(support.TESTFN, file_name) + file_path = os.path.join(os_helper.TESTFN, file_name) os.makedirs(dir_path) with open(file_path, 'w', encoding='utf-8') as f: f.write("I'm %s and proud of it. Blame test_os.\n" % file_path) @@ -2366,31 +2369,31 @@ class Win32ListdirTests(unittest.TestCase): self.created_paths.sort() def tearDown(self): - shutil.rmtree(support.TESTFN) + shutil.rmtree(os_helper.TESTFN) def test_listdir_no_extended_path(self): """Test when the path is not an "extended" path.""" # unicode self.assertEqual( - sorted(os.listdir(support.TESTFN)), + sorted(os.listdir(os_helper.TESTFN)), self.created_paths) # bytes self.assertEqual( - sorted(os.listdir(os.fsencode(support.TESTFN))), + sorted(os.listdir(os.fsencode(os_helper.TESTFN))), [os.fsencode(path) for path in self.created_paths]) def test_listdir_extended_path(self): """Test when the path starts with '\\\\?\\'.""" # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath # unicode - path = '\\\\?\\' + os.path.abspath(support.TESTFN) + path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN) self.assertEqual( sorted(os.listdir(path)), self.created_paths) # bytes - path = b'\\\\?\\' + os.fsencode(os.path.abspath(support.TESTFN)) + path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN)) self.assertEqual( sorted(os.listdir(path)), [os.fsencode(path) for path in self.created_paths]) @@ -2433,32 +2436,32 @@ class ReadlinkTests(unittest.TestCase): self.assertRaises(FileNotFoundError, os.readlink, FakePath('missing-link')) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_pathlike(self): os.symlink(self.filelink_target, self.filelink) - self.addCleanup(support.unlink, self.filelink) + self.addCleanup(os_helper.unlink, self.filelink) filelink = FakePath(self.filelink) self.assertPathEqual(os.readlink(filelink), self.filelink_target) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_pathlike_bytes(self): os.symlink(self.filelinkb_target, self.filelinkb) - self.addCleanup(support.unlink, self.filelinkb) + self.addCleanup(os_helper.unlink, self.filelinkb) path = os.readlink(FakePath(self.filelinkb)) self.assertPathEqual(path, self.filelinkb_target) self.assertIsInstance(path, bytes) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_bytes(self): os.symlink(self.filelinkb_target, self.filelinkb) - self.addCleanup(support.unlink, self.filelinkb) + self.addCleanup(os_helper.unlink, self.filelinkb) path = os.readlink(self.filelinkb) self.assertPathEqual(path, self.filelinkb_target) self.assertIsInstance(path, bytes) @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") -@support.skip_unless_symlink +@os_helper.skip_unless_symlink class Win32SymlinkTests(unittest.TestCase): filelink = 'filelinktest' filelink_target = os.path.abspath(__file__) @@ -2529,10 +2532,10 @@ class Win32SymlinkTests(unittest.TestCase): self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link)) def test_12084(self): - level1 = os.path.abspath(support.TESTFN) + level1 = os.path.abspath(os_helper.TESTFN) level2 = os.path.join(level1, "level2") level3 = os.path.join(level2, "level3") - self.addCleanup(support.rmtree, level1) + self.addCleanup(os_helper.rmtree, level1) os.mkdir(level1) os.mkdir(level2) @@ -2718,7 +2721,7 @@ class Win32NtTests(unittest.TestCase): self.assertEqual(0, handle_delta) -@support.skip_unless_symlink +@os_helper.skip_unless_symlink class NonLocalSymlinkTests(unittest.TestCase): def setUp(self): @@ -2857,8 +2860,8 @@ class SpawnTests(unittest.TestCase): def create_args(self, *, with_env=False, use_bytes=False): self.exitcode = 17 - filename = support.TESTFN - self.addCleanup(support.unlink, filename) + filename = os_helper.TESTFN + self.addCleanup(os_helper.unlink, filename) if not with_env: code = 'import sys; sys.exit(%s)' % self.exitcode @@ -3009,8 +3012,8 @@ class SpawnTests(unittest.TestCase): self.assertEqual(exitcode, 127) # equal character in the environment variable value - filename = support.TESTFN - self.addCleanup(support.unlink, filename) + filename = os_helper.TESTFN + self.addCleanup(os_helper.unlink, filename) with open(filename, "w") as fp: fp.write('import sys, os\n' 'if os.getenv("FRUIT") != "orange=lemon":\n' @@ -3165,12 +3168,12 @@ class TestSendfile(unittest.TestCase): @classmethod def setUpClass(cls): cls.key = threading_helper.threading_setup() - create_file(support.TESTFN, cls.DATA) + create_file(os_helper.TESTFN, cls.DATA) @classmethod def tearDownClass(cls): threading_helper.threading_cleanup(*cls.key) - support.unlink(support.TESTFN) + os_helper.unlink(os_helper.TESTFN) def setUp(self): self.server = SendfileTestServer((socket_helper.HOST, 0)) @@ -3181,7 +3184,7 @@ class TestSendfile(unittest.TestCase): # synchronize by waiting for "220 ready" response self.client.recv(1024) self.sockno = self.client.fileno() - self.file = open(support.TESTFN, 'rb') + self.file = open(os_helper.TESTFN, 'rb') self.fileno = self.file.fileno() def tearDown(self): @@ -3313,10 +3316,10 @@ class TestSendfile(unittest.TestCase): @requires_headers_trailers def test_trailers(self): - TESTFN2 = support.TESTFN + "2" + TESTFN2 = os_helper.TESTFN + "2" file_data = b"abcdef" - self.addCleanup(support.unlink, TESTFN2) + self.addCleanup(os_helper.unlink, TESTFN2) create_file(TESTFN2, file_data) with open(TESTFN2, 'rb') as f: @@ -3362,13 +3365,13 @@ def supports_extended_attributes(): return False try: - with open(support.TESTFN, "xb", 0) as fp: + with open(os_helper.TESTFN, "xb", 0) as fp: try: os.setxattr(fp.fileno(), b"user.test", b"") except OSError: return False finally: - support.unlink(support.TESTFN) + os_helper.unlink(os_helper.TESTFN) return True @@ -3380,8 +3383,8 @@ def supports_extended_attributes(): class ExtendedAttributeTests(unittest.TestCase): def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs): - fn = support.TESTFN - self.addCleanup(support.unlink, fn) + fn = os_helper.TESTFN + self.addCleanup(os_helper.unlink, fn) create_file(fn) with self.assertRaises(OSError) as cm: @@ -3429,10 +3432,10 @@ class ExtendedAttributeTests(unittest.TestCase): def _check_xattrs(self, *args, **kwargs): self._check_xattrs_str(str, *args, **kwargs) - support.unlink(support.TESTFN) + os_helper.unlink(os_helper.TESTFN) self._check_xattrs_str(os.fsencode, *args, **kwargs) - support.unlink(support.TESTFN) + os_helper.unlink(os_helper.TESTFN) def test_simple(self): self._check_xattrs(os.getxattr, os.setxattr, os.removexattr, @@ -3531,16 +3534,16 @@ class OSErrorTests(unittest.TestCase): self.bytes_filenames = [] self.unicode_filenames = [] - if support.TESTFN_UNENCODABLE is not None: - decoded = support.TESTFN_UNENCODABLE + if os_helper.TESTFN_UNENCODABLE is not None: + decoded = os_helper.TESTFN_UNENCODABLE else: - decoded = support.TESTFN + decoded = os_helper.TESTFN self.unicode_filenames.append(decoded) self.unicode_filenames.append(Str(decoded)) - if support.TESTFN_UNDECODABLE is not None: - encoded = support.TESTFN_UNDECODABLE + if os_helper.TESTFN_UNDECODABLE is not None: + encoded = os_helper.TESTFN_UNDECODABLE else: - encoded = os.fsencode(support.TESTFN) + encoded = os.fsencode(os_helper.TESTFN) self.bytes_filenames.append(encoded) self.bytes_filenames.append(bytearray(encoded)) self.bytes_filenames.append(memoryview(encoded)) @@ -3734,14 +3737,14 @@ class PathTConverterTests(unittest.TestCase): ] def test_path_t_converter(self): - str_filename = support.TESTFN + str_filename = os_helper.TESTFN if os.name == 'nt': bytes_fspath = bytes_filename = None else: - bytes_filename = os.fsencode(support.TESTFN) + bytes_filename = os.fsencode(os_helper.TESTFN) bytes_fspath = FakePath(bytes_filename) fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT) - self.addCleanup(support.unlink, support.TESTFN) + self.addCleanup(os_helper.unlink, os_helper.TESTFN) self.addCleanup(os.close, fd) int_fspath = FakePath(fd) @@ -3811,8 +3814,8 @@ class ExportsTests(unittest.TestCase): class TestDirEntry(unittest.TestCase): def setUp(self): - self.path = os.path.realpath(support.TESTFN) - self.addCleanup(support.rmtree, self.path) + self.path = os.path.realpath(os_helper.TESTFN) + self.addCleanup(os_helper.rmtree, self.path) os.mkdir(self.path) def test_uninstantiable(self): @@ -3828,12 +3831,12 @@ class TestDirEntry(unittest.TestCase): class TestScandir(unittest.TestCase): - check_no_resource_warning = support.check_no_resource_warning + check_no_resource_warning = warnings_helper.check_no_resource_warning def setUp(self): - self.path = os.path.realpath(support.TESTFN) + self.path = os.path.realpath(os_helper.TESTFN) self.bytes_path = os.fsencode(self.path) - self.addCleanup(support.rmtree, self.path) + self.addCleanup(os_helper.rmtree, self.path) os.mkdir(self.path) def create_file(self, name="file.txt"): @@ -3903,7 +3906,7 @@ class TestScandir(unittest.TestCase): def test_attributes(self): link = hasattr(os, 'link') - symlink = support.can_symlink() + symlink = os_helper.can_symlink() dirname = os.path.join(self.path, "dir") os.mkdir(dirname) @@ -4027,7 +4030,7 @@ class TestScandir(unittest.TestCase): self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False) def test_broken_symlink(self): - if not support.can_symlink(): + if not os_helper.can_symlink(): return self.skipTest('cannot create symbolic link') filename = self.create_file("file.txt") @@ -4081,7 +4084,7 @@ class TestScandir(unittest.TestCase): self.assertIn(os.scandir, os.supports_fd) self.create_file('file.txt') expected_names = ['file.txt'] - if support.can_symlink(): + if os_helper.can_symlink(): os.symlink('file.txt', os.path.join(self.path, 'link')) expected_names.append('link') diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index e56b337083c..06ca50af143 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -30,7 +30,8 @@ except ImportError: posix = None from test import support -from test.support import TESTFN, FakePath +from test.support import os_helper +from test.support.os_helper import TESTFN, FakePath TESTFN2 = TESTFN + "2" MACOS = sys.platform.startswith("darwin") @@ -140,9 +141,9 @@ def supports_file2file_sendfile(): return True finally: if srcname is not None: - support.unlink(srcname) + os_helper.unlink(srcname) if dstname is not None: - support.unlink(dstname) + os_helper.unlink(dstname) SUPPORTS_SENDFILE = supports_file2file_sendfile() @@ -168,7 +169,7 @@ class BaseTest: Returns the path of the directory. """ d = tempfile.mkdtemp(prefix=prefix, dir=os.getcwd()) - self.addCleanup(support.rmtree, d) + self.addCleanup(os_helper.rmtree, d) return d @@ -183,7 +184,7 @@ class TestRmTree(BaseTest, unittest.TestCase): self.assertIsInstance(victim, bytes) shutil.rmtree(victim) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_rmtree_fails_on_symlink(self): tmp = self.mkdtemp() dir_ = os.path.join(tmp, 'dir') @@ -202,7 +203,7 @@ class TestRmTree(BaseTest, unittest.TestCase): self.assertEqual(errors[0][1], link) self.assertIsInstance(errors[0][2][1], OSError) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_rmtree_works_on_symlinks(self): tmp = self.mkdtemp() dir1 = os.path.join(tmp, 'dir1') @@ -231,7 +232,7 @@ class TestRmTree(BaseTest, unittest.TestCase): os.mkdir(dir_) link = os.path.join(tmp, 'link') _winapi.CreateJunction(dir_, link) - self.addCleanup(support.unlink, link) + self.addCleanup(os_helper.unlink, link) self.assertRaises(OSError, shutil.rmtree, link) self.assertTrue(os.path.exists(dir_)) self.assertTrue(os.path.lexists(link)) @@ -313,7 +314,7 @@ class TestRmTree(BaseTest, unittest.TestCase): self.child_file_path = os.path.join(TESTFN, 'a') self.child_dir_path = os.path.join(TESTFN, 'b') - support.create_empty_file(self.child_file_path) + os_helper.create_empty_file(self.child_file_path) os.mkdir(self.child_dir_path) old_dir_mode = os.stat(TESTFN).st_mode old_child_file_mode = os.stat(self.child_file_path).st_mode @@ -407,7 +408,7 @@ class TestRmTree(BaseTest, unittest.TestCase): self.assertRaises(NotADirectoryError, shutil.rmtree, path) os.remove(path) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_rmtree_on_symlink(self): # bug 1669. os.mkdir(TESTFN) @@ -482,7 +483,7 @@ class TestCopyTree(BaseTest, unittest.TestCase): with self.assertRaises(FileExistsError): shutil.copytree(src_dir, dst_dir, dirs_exist_ok=False) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copytree_symlinks(self): tmp_dir = self.mkdtemp() src_dir = os.path.join(tmp_dir, 'src') @@ -634,7 +635,7 @@ class TestCopyTree(BaseTest, unittest.TestCase): write_file((src_dir, 'restrictive.txt'), '456') os.chmod(os.path.join(src_dir, 'restrictive.txt'), 0o600) restrictive_subdir = tempfile.mkdtemp(dir=src_dir) - self.addCleanup(support.rmtree, restrictive_subdir) + self.addCleanup(os_helper.rmtree, restrictive_subdir) os.chmod(restrictive_subdir, 0o600) shutil.copytree(src_dir, dst_dir) @@ -681,7 +682,7 @@ class TestCopyTree(BaseTest, unittest.TestCase): # Issue #3002: copyfile and copytree block indefinitely on named pipes @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()') - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copytree_named_pipe(self): os.mkdir(TESTFN) try: @@ -719,7 +720,7 @@ class TestCopyTree(BaseTest, unittest.TestCase): shutil.copytree(src_dir, dst_dir, copy_function=_copy) self.assertEqual(len(copied), 2) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copytree_dangling_symlinks(self): # a dangling symlink raises an error at the end src_dir = self.mkdtemp() @@ -739,7 +740,7 @@ class TestCopyTree(BaseTest, unittest.TestCase): shutil.copytree(src_dir, dst_dir, symlinks=True) self.assertIn('test.txt', os.listdir(dst_dir)) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copytree_symlink_dir(self): src_dir = self.mkdtemp() dst_dir = os.path.join(self.mkdtemp(), 'destination') @@ -785,7 +786,7 @@ class TestCopy(BaseTest, unittest.TestCase): ### shutil.copymode - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copymode_follow_symlinks(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -818,7 +819,7 @@ class TestCopy(BaseTest, unittest.TestCase): self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode) @unittest.skipUnless(hasattr(os, 'lchmod'), 'requires os.lchmod') - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copymode_symlink_to_symlink(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -848,7 +849,7 @@ class TestCopy(BaseTest, unittest.TestCase): self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode) @unittest.skipIf(hasattr(os, 'lchmod'), 'requires os.lchmod to be missing') - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copymode_symlink_to_symlink_wo_lchmod(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -863,7 +864,7 @@ class TestCopy(BaseTest, unittest.TestCase): ### shutil.copystat - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copystat_symlinks(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -935,7 +936,7 @@ class TestCopy(BaseTest, unittest.TestCase): ### shutil.copyxattr - @support.skip_unless_xattr + @os_helper.skip_unless_xattr def test_copyxattr(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -999,8 +1000,8 @@ class TestCopy(BaseTest, unittest.TestCase): self.assertEqual(os.getxattr(dst, 'user.the_value'), b'fiddly') self.assertEqual(os.getxattr(dstro, 'user.the_value'), b'fiddly') - @support.skip_unless_symlink - @support.skip_unless_xattr + @os_helper.skip_unless_symlink + @os_helper.skip_unless_xattr @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') def test_copyxattr_symlinks(self): @@ -1042,7 +1043,7 @@ class TestCopy(BaseTest, unittest.TestCase): self.assertTrue(os.path.exists(file2)) self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copy_symlinks(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -1084,7 +1085,7 @@ class TestCopy(BaseTest, unittest.TestCase): self.assertEqual(getattr(file1_stat, 'st_flags'), getattr(file2_stat, 'st_flags')) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copy2_symlinks(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -1119,7 +1120,7 @@ class TestCopy(BaseTest, unittest.TestCase): if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'): self.assertEqual(src_link_stat.st_flags, dst_stat.st_flags) - @support.skip_unless_xattr + @os_helper.skip_unless_xattr def test_copy2_xattr(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'foo') @@ -1146,7 +1147,7 @@ class TestCopy(BaseTest, unittest.TestCase): ### shutil.copyfile - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_copyfile_symlinks(self): tmp_dir = self.mkdtemp() src = os.path.join(tmp_dir, 'src') @@ -1183,7 +1184,7 @@ class TestCopy(BaseTest, unittest.TestCase): finally: shutil.rmtree(TESTFN, ignore_errors=True) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_dont_copy_file_onto_symlink_to_itself(self): # bug 851123. os.mkdir(TESTFN) @@ -1258,7 +1259,7 @@ class TestArchives(BaseTest, unittest.TestCase): work_dir = os.path.dirname(tmpdir2) rel_base_name = os.path.join(os.path.basename(tmpdir2), 'archive') - with support.change_cwd(work_dir): + with os_helper.change_cwd(work_dir): base_name = os.path.abspath(rel_base_name) tarball = make_archive(rel_base_name, 'gztar', root_dir, '.') @@ -1272,7 +1273,7 @@ class TestArchives(BaseTest, unittest.TestCase): './file1', './file2', './sub/file3']) # trying an uncompressed one - with support.change_cwd(work_dir): + with os_helper.change_cwd(work_dir): tarball = make_archive(rel_base_name, 'tar', root_dir, '.') self.assertEqual(tarball, base_name + '.tar') self.assertTrue(os.path.isfile(tarball)) @@ -1347,7 +1348,7 @@ class TestArchives(BaseTest, unittest.TestCase): work_dir = os.path.dirname(tmpdir2) rel_base_name = os.path.join(os.path.basename(tmpdir2), 'archive') - with support.change_cwd(work_dir): + with os_helper.change_cwd(work_dir): base_name = os.path.abspath(rel_base_name) res = make_archive(rel_base_name, 'zip', root_dir) @@ -1360,7 +1361,7 @@ class TestArchives(BaseTest, unittest.TestCase): 'dist/file1', 'dist/file2', 'dist/sub/file3', 'outer']) - with support.change_cwd(work_dir): + with os_helper.change_cwd(work_dir): base_name = os.path.abspath(rel_base_name) res = make_archive(rel_base_name, 'zip', root_dir, base_dir) @@ -1412,7 +1413,7 @@ class TestArchives(BaseTest, unittest.TestCase): # now check the ZIP file using `unzip -t` zip_cmd = ['unzip', '-t', archive] - with support.change_cwd(root_dir): + with os_helper.change_cwd(root_dir): try: subprocess.check_output(zip_cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: @@ -1462,7 +1463,7 @@ class TestArchives(BaseTest, unittest.TestCase): base_name = os.path.join(self.mkdtemp(), 'archive') group = grp.getgrgid(0)[0] owner = pwd.getpwuid(0)[0] - with support.change_cwd(root_dir): + with os_helper.change_cwd(root_dir): archive_name = make_archive(base_name, 'gztar', root_dir, 'dist', owner=owner, group=group) @@ -1496,7 +1497,7 @@ class TestArchives(BaseTest, unittest.TestCase): def test_make_tarfile_in_curdir(self): # Issue #21280 root_dir = self.mkdtemp() - with support.change_cwd(root_dir): + with os_helper.change_cwd(root_dir): self.assertEqual(make_archive('test', 'tar'), 'test.tar') self.assertTrue(os.path.isfile('test.tar')) @@ -1504,7 +1505,7 @@ class TestArchives(BaseTest, unittest.TestCase): def test_make_zipfile_in_curdir(self): # Issue #21280 root_dir = self.mkdtemp() - with support.change_cwd(root_dir): + with os_helper.change_cwd(root_dir): self.assertEqual(make_archive('test', 'zip'), 'test.zip') self.assertTrue(os.path.isfile('test.zip')) @@ -1711,18 +1712,18 @@ class TestWhich(BaseTest, unittest.TestCase): # that exists, it should be returned. base_dir, tail_dir = os.path.split(self.dir) relpath = os.path.join(tail_dir, self.file) - with support.change_cwd(path=base_dir): + with os_helper.change_cwd(path=base_dir): rv = shutil.which(relpath, path=self.temp_dir) self.assertEqual(rv, relpath) # But it shouldn't be searched in PATH directories (issue #16957). - with support.change_cwd(path=self.dir): + with os_helper.change_cwd(path=self.dir): rv = shutil.which(relpath, path=base_dir) self.assertIsNone(rv) def test_cwd(self): # Issue #16957 base_dir = os.path.dirname(self.dir) - with support.change_cwd(path=self.dir): + with os_helper.change_cwd(path=self.dir): rv = shutil.which(self.file, path=base_dir) if sys.platform == "win32": # Windows: current directory implicitly on PATH @@ -1743,7 +1744,7 @@ class TestWhich(BaseTest, unittest.TestCase): def test_relative_path(self): base_dir, tail_dir = os.path.split(self.dir) - with support.change_cwd(path=base_dir): + with os_helper.change_cwd(path=base_dir): rv = shutil.which(self.file, path=tail_dir) self.assertEqual(rv, os.path.join(tail_dir, self.file)) @@ -1761,19 +1762,19 @@ class TestWhich(BaseTest, unittest.TestCase): self.assertEqual(rv, self.temp_file.name[:-4] + self.ext) def test_environ_path(self): - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env['PATH'] = self.env_path rv = shutil.which(self.file) self.assertEqual(rv, self.temp_file.name) def test_environ_path_empty(self): # PATH='': no match - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env['PATH'] = '' with unittest.mock.patch('os.confstr', return_value=self.dir, \ create=True), \ support.swap_attr(os, 'defpath', self.dir), \ - support.change_cwd(self.dir): + os_helper.change_cwd(self.dir): rv = shutil.which(self.file) self.assertIsNone(rv) @@ -1786,7 +1787,7 @@ class TestWhich(BaseTest, unittest.TestCase): expected_cwd = os.path.join(curdir, expected_cwd) # PATH=':': explicitly looks in the current directory - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env['PATH'] = os.pathsep with unittest.mock.patch('os.confstr', return_value=self.dir, \ create=True), \ @@ -1795,12 +1796,12 @@ class TestWhich(BaseTest, unittest.TestCase): self.assertIsNone(rv) # look in current directory - with support.change_cwd(self.dir): + with os_helper.change_cwd(self.dir): rv = shutil.which(self.file) self.assertEqual(rv, expected_cwd) def test_environ_path_missing(self): - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env.pop('PATH', None) # without confstr @@ -1819,14 +1820,14 @@ class TestWhich(BaseTest, unittest.TestCase): def test_empty_path(self): base_dir = os.path.dirname(self.dir) - with support.change_cwd(path=self.dir), \ - support.EnvironmentVarGuard() as env: + with os_helper.change_cwd(path=self.dir), \ + os_helper.EnvironmentVarGuard() as env: env['PATH'] = self.env_path rv = shutil.which(self.file, path='') self.assertIsNone(rv) def test_empty_path_no_PATH(self): - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env.pop('PATH', None) rv = shutil.which(self.file) self.assertIsNone(rv) @@ -1843,7 +1844,7 @@ class TestWhich(BaseTest, unittest.TestCase): program = os.path.basename(temp_filexyz.name) program = os.path.splitext(program)[0] - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env['PATHEXT'] = ext rv = shutil.which(program, path=self.temp_dir) self.assertEqual(rv, temp_filexyz.name) @@ -1918,7 +1919,7 @@ class TestMove(BaseTest, unittest.TestCase): try: self._check_move_dir(self.src_dir, dst_dir, dst_dir) finally: - support.rmtree(dst_dir) + os_helper.rmtree(dst_dir) @mock_rename def test_move_dir_other_fs(self): @@ -1965,7 +1966,7 @@ class TestMove(BaseTest, unittest.TestCase): msg='_destinsrc() wrongly concluded that ' 'dst (%s) is not in src (%s)' % (dst, src)) finally: - support.rmtree(TESTFN) + os_helper.rmtree(TESTFN) def test_destinsrc_false_positive(self): os.mkdir(TESTFN) @@ -1977,9 +1978,9 @@ class TestMove(BaseTest, unittest.TestCase): msg='_destinsrc() wrongly concluded that ' 'dst (%s) is in src (%s)' % (dst, src)) finally: - support.rmtree(TESTFN) + os_helper.rmtree(TESTFN) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink @mock_rename def test_move_file_symlink(self): dst = os.path.join(self.src_dir, 'bar') @@ -1988,7 +1989,7 @@ class TestMove(BaseTest, unittest.TestCase): self.assertTrue(os.path.islink(self.dst_file)) self.assertTrue(os.path.samefile(self.src_file, self.dst_file)) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink @mock_rename def test_move_file_symlink_to_dir(self): filename = "bar" @@ -1999,7 +2000,7 @@ class TestMove(BaseTest, unittest.TestCase): self.assertTrue(os.path.islink(final_link)) self.assertTrue(os.path.samefile(self.src_file, final_link)) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink @mock_rename def test_move_dangling_symlink(self): src = os.path.join(self.src_dir, 'baz') @@ -2010,7 +2011,7 @@ class TestMove(BaseTest, unittest.TestCase): self.assertTrue(os.path.islink(dst_link)) self.assertEqual(os.path.realpath(src), os.path.realpath(dst_link)) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink @mock_rename def test_move_dir_symlink(self): src = os.path.join(self.src_dir, 'baz') @@ -2044,8 +2045,8 @@ class TestMove(BaseTest, unittest.TestCase): moved = [] def _copy(src, dst): moved.append((src, dst)) - support.create_empty_file(os.path.join(self.src_dir, 'child')) - support.create_empty_file(os.path.join(self.src_dir, 'child1')) + os_helper.create_empty_file(os.path.join(self.src_dir, 'child')) + os_helper.create_empty_file(os.path.join(self.src_dir, 'child1')) shutil.move(self.src_dir, self.dst_dir, copy_function=_copy) self.assertEqual(len(moved), 3) @@ -2167,11 +2168,11 @@ class TestCopyFileObj(unittest.TestCase): @classmethod def tearDownClass(cls): - support.unlink(TESTFN) - support.unlink(TESTFN2) + os_helper.unlink(TESTFN) + os_helper.unlink(TESTFN2) def tearDown(self): - support.unlink(TESTFN2) + os_helper.unlink(TESTFN2) @contextlib.contextmanager def get_files(self): @@ -2216,7 +2217,7 @@ class TestCopyFileObj(unittest.TestCase): with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f: f.write(b'foo') fname = f.name - self.addCleanup(support.unlink, fname) + self.addCleanup(os_helper.unlink, fname) with unittest.mock.patch("shutil._copyfileobj_readinto") as m: shutil.copyfile(fname, TESTFN2) self.assertEqual(m.call_args[0][2], 3) @@ -2225,7 +2226,7 @@ class TestCopyFileObj(unittest.TestCase): with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f: pass fname = f.name - self.addCleanup(support.unlink, fname) + self.addCleanup(os_helper.unlink, fname) with unittest.mock.patch("shutil._copyfileobj_readinto") as m: shutil.copyfile(fname, TESTFN2) assert not m.called @@ -2247,10 +2248,10 @@ class _ZeroCopyFileTest(object): @classmethod def tearDownClass(cls): - support.unlink(TESTFN) + os_helper.unlink(TESTFN) def tearDown(self): - support.unlink(TESTFN2) + os_helper.unlink(TESTFN2) @contextlib.contextmanager def get_files(self): @@ -2296,8 +2297,8 @@ class _ZeroCopyFileTest(object): def test_empty_file(self): srcname = TESTFN + 'src' dstname = TESTFN + 'dst' - self.addCleanup(lambda: support.unlink(srcname)) - self.addCleanup(lambda: support.unlink(dstname)) + self.addCleanup(lambda: os_helper.unlink(srcname)) + self.addCleanup(lambda: os_helper.unlink(dstname)) with open(srcname, "wb"): pass @@ -2421,9 +2422,9 @@ class TestZeroCopySendfile(_ZeroCopyFileTest, unittest.TestCase): # sendfile() are the same. self.assertEqual(blocksize, os.path.getsize(TESTFN)) # ...unless we're dealing with a small file. - support.unlink(TESTFN2) + os_helper.unlink(TESTFN2) write_file(TESTFN2, b"hello", binary=True) - self.addCleanup(support.unlink, TESTFN2 + '3') + self.addCleanup(os_helper.unlink, TESTFN2 + '3') self.assertRaises(ZeroDivisionError, shutil.copyfile, TESTFN2, TESTFN2 + '3') blocksize = m.call_args[0][3] @@ -2473,20 +2474,20 @@ class TestGetTerminalSize(unittest.TestCase): def test_os_environ_first(self): "Check if environment variables have precedence" - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env['COLUMNS'] = '777' del env['LINES'] size = shutil.get_terminal_size() self.assertEqual(size.columns, 777) - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: del env['COLUMNS'] env['LINES'] = '888' size = shutil.get_terminal_size() self.assertEqual(size.lines, 888) def test_bad_environ(self): - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: env['COLUMNS'] = 'xxx' env['LINES'] = 'yyy' size = shutil.get_terminal_size() @@ -2510,7 +2511,7 @@ class TestGetTerminalSize(unittest.TestCase): self.skipTest("stty invocation failed") expected = (int(size[1]), int(size[0])) # reversed order - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: del env['LINES'] del env['COLUMNS'] actual = shutil.get_terminal_size() @@ -2518,7 +2519,7 @@ class TestGetTerminalSize(unittest.TestCase): self.assertEqual(expected, actual) def test_fallback(self): - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: del env['LINES'] del env['COLUMNS'] diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index aced87694cf..0162424e2fd 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -1,6 +1,9 @@ import unittest from unittest import mock from test import support +from test.support import import_helper +from test.support import os_helper +from test.support import warnings_helper import subprocess import sys import signal @@ -20,7 +23,7 @@ import threading import gc import textwrap import json -from test.support import FakePath +from test.support.os_helper import FakePath try: import _testcapi @@ -357,7 +360,7 @@ class ProcessTestCase(BaseTestCase): # Normalize an expected cwd (for Tru64 support). # We can't use os.path.realpath since it doesn't expand Tru64 {memb} # strings. See bug #1063571. - with support.change_cwd(cwd): + with os_helper.change_cwd(cwd): return os.getcwd() # For use in the test_cwd* tests below. @@ -406,7 +409,7 @@ class ProcessTestCase(BaseTestCase): # is relative. python_dir, python_base = self._split_python_path() rel_python = os.path.join(os.curdir, python_base) - with support.temp_cwd() as wrong_dir: + with os_helper.temp_cwd() as wrong_dir: # Before calling with the correct cwd, confirm that the call fails # without cwd and with the wrong cwd. self.assertRaises(FileNotFoundError, subprocess.Popen, @@ -423,7 +426,7 @@ class ProcessTestCase(BaseTestCase): python_dir, python_base = self._split_python_path() rel_python = os.path.join(os.curdir, python_base) doesntexist = "somethingyoudonthave" - with support.temp_cwd() as wrong_dir: + with os_helper.temp_cwd() as wrong_dir: # Before calling with the correct cwd, confirm that the call fails # without cwd and with the wrong cwd. self.assertRaises(FileNotFoundError, subprocess.Popen, @@ -441,7 +444,7 @@ class ProcessTestCase(BaseTestCase): python_dir, python_base = self._split_python_path() abs_python = os.path.join(python_dir, python_base) rel_python = os.path.join(os.curdir, python_base) - with support.temp_dir() as wrong_dir: + with os_helper.temp_dir() as wrong_dir: # Before calling with an absolute path, confirm that using a # relative path fails. self.assertRaises(FileNotFoundError, subprocess.Popen, @@ -1052,7 +1055,7 @@ class ProcessTestCase(BaseTestCase): try: for i in range(max_handles): try: - tmpfile = os.path.join(tmpdir, support.TESTFN) + tmpfile = os.path.join(tmpdir, os_helper.TESTFN) handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT)) except OSError as e: if e.errno != errno.EMFILE: @@ -2881,7 +2884,7 @@ class POSIXProcessTestCase(BaseTestCase): def test_select_unbuffered(self): # Issue #11459: bufsize=0 should really set the pipes as # unbuffered (and therefore let select() work properly). - select = support.import_module("select") + select = import_helper.import_module("select") p = subprocess.Popen([sys.executable, "-c", 'import sys;' 'sys.stdout.write("apple")'], @@ -2909,7 +2912,7 @@ class POSIXProcessTestCase(BaseTestCase): self.addCleanup(p.stderr.close) ident = id(p) pid = p.pid - with support.check_warnings(('', ResourceWarning)): + with warnings_helper.check_warnings(('', ResourceWarning)): p = None if mswindows: @@ -2934,7 +2937,7 @@ class POSIXProcessTestCase(BaseTestCase): self.addCleanup(p.stderr.close) ident = id(p) pid = p.pid - with support.check_warnings(('', ResourceWarning)): + with warnings_helper.check_warnings(('', ResourceWarning)): p = None os.kill(pid, signal.SIGKILL) @@ -3288,7 +3291,8 @@ class Win32ProcessTestCase(BaseTestCase): self.assertIn(b"OSError", stderr) # Check for a warning due to using handle_list and close_fds=False - with support.check_warnings((".*overriding close_fds", RuntimeWarning)): + with warnings_helper.check_warnings((".*overriding close_fds", + RuntimeWarning)): startupinfo = subprocess.STARTUPINFO() startupinfo.lpAttributeList = {"handle_list": handles[:]} p = subprocess.Popen([sys.executable, "-c", diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py index a7d5b1bfe4e..b268511844b 100644 --- a/Lib/test/test_support.py +++ b/Lib/test/test_support.py @@ -12,20 +12,24 @@ import textwrap import time import unittest from test import support +from test.support import import_helper +from test.support import os_helper from test.support import script_helper from test.support import socket_helper +from test.support import warnings_helper -TESTFN = support.TESTFN +TESTFN = os_helper.TESTFN class TestSupport(unittest.TestCase): def test_import_module(self): - support.import_module("ftplib") - self.assertRaises(unittest.SkipTest, support.import_module, "foo") + import_helper.import_module("ftplib") + self.assertRaises(unittest.SkipTest, + import_helper.import_module, "foo") def test_import_fresh_module(self): - support.import_fresh_module("ftplib") + import_helper.import_fresh_module("ftplib") def test_get_attribute(self): self.assertEqual(support.get_attribute(self, "test_get_attribute"), @@ -39,38 +43,38 @@ class TestSupport(unittest.TestCase): def test_unload(self): import sched self.assertIn("sched", sys.modules) - support.unload("sched") + import_helper.unload("sched") self.assertNotIn("sched", sys.modules) def test_unlink(self): with open(TESTFN, "w") as f: pass - support.unlink(TESTFN) + os_helper.unlink(TESTFN) self.assertFalse(os.path.exists(TESTFN)) - support.unlink(TESTFN) + os_helper.unlink(TESTFN) def test_rmtree(self): - dirpath = support.TESTFN + 'd' + dirpath = os_helper.TESTFN + 'd' subdirpath = os.path.join(dirpath, 'subdir') os.mkdir(dirpath) os.mkdir(subdirpath) - support.rmtree(dirpath) + os_helper.rmtree(dirpath) self.assertFalse(os.path.exists(dirpath)) with support.swap_attr(support, 'verbose', 0): - support.rmtree(dirpath) + os_helper.rmtree(dirpath) os.mkdir(dirpath) os.mkdir(subdirpath) os.chmod(dirpath, stat.S_IRUSR|stat.S_IXUSR) with support.swap_attr(support, 'verbose', 0): - support.rmtree(dirpath) + os_helper.rmtree(dirpath) self.assertFalse(os.path.exists(dirpath)) os.mkdir(dirpath) os.mkdir(subdirpath) os.chmod(dirpath, 0) with support.swap_attr(support, 'verbose', 0): - support.rmtree(dirpath) + os_helper.rmtree(dirpath) self.assertFalse(os.path.exists(dirpath)) def test_forget(self): @@ -83,12 +87,12 @@ class TestSupport(unittest.TestCase): mod = __import__(TESTFN) self.assertIn(TESTFN, sys.modules) - support.forget(TESTFN) + import_helper.forget(TESTFN) self.assertNotIn(TESTFN, sys.modules) finally: del sys.path[0] - support.unlink(mod_filename) - support.rmtree('__pycache__') + os_helper.unlink(mod_filename) + os_helper.rmtree('__pycache__') def test_HOST(self): s = socket.create_server((socket_helper.HOST, 0)) @@ -115,23 +119,23 @@ class TestSupport(unittest.TestCase): try: path = os.path.join(parent_dir, 'temp') self.assertFalse(os.path.isdir(path)) - with support.temp_dir(path) as temp_path: + with os_helper.temp_dir(path) as temp_path: self.assertEqual(temp_path, path) self.assertTrue(os.path.isdir(path)) self.assertFalse(os.path.isdir(path)) finally: - support.rmtree(parent_dir) + os_helper.rmtree(parent_dir) def test_temp_dir__path_none(self): """Test passing no path.""" - with support.temp_dir() as temp_path: + with os_helper.temp_dir() as temp_path: self.assertTrue(os.path.isdir(temp_path)) self.assertFalse(os.path.isdir(temp_path)) def test_temp_dir__existing_dir__quiet_default(self): """Test passing a directory that already exists.""" def call_temp_dir(path): - with support.temp_dir(path) as temp_path: + with os_helper.temp_dir(path) as temp_path: raise Exception("should not get here") path = tempfile.mkdtemp() @@ -150,8 +154,8 @@ class TestSupport(unittest.TestCase): path = os.path.realpath(path) try: - with support.check_warnings() as recorder: - with support.temp_dir(path, quiet=True) as temp_path: + with warnings_helper.check_warnings() as recorder: + with os_helper.temp_dir(path, quiet=True) as temp_path: self.assertEqual(path, temp_path) warnings = [str(w.message) for w in recorder.warnings] # Make sure temp_dir did not delete the original directory. @@ -173,7 +177,8 @@ class TestSupport(unittest.TestCase): script_helper.assert_python_ok("-c", textwrap.dedent(""" import os from test import support - with support.temp_cwd() as temp_path: + from test.support import os_helper + with os_helper.temp_cwd() as temp_path: pid = os.fork() if pid != 0: # parent process @@ -194,8 +199,8 @@ class TestSupport(unittest.TestCase): def test_change_cwd(self): original_cwd = os.getcwd() - with support.temp_dir() as temp_path: - with support.change_cwd(temp_path) as new_cwd: + with os_helper.temp_dir() as temp_path: + with os_helper.change_cwd(temp_path) as new_cwd: self.assertEqual(new_cwd, temp_path) self.assertEqual(os.getcwd(), new_cwd) @@ -206,10 +211,10 @@ class TestSupport(unittest.TestCase): original_cwd = os.getcwd() def call_change_cwd(path): - with support.change_cwd(path) as new_cwd: + with os_helper.change_cwd(path) as new_cwd: raise Exception("should not get here") - with support.temp_dir() as parent_dir: + with os_helper.temp_dir() as parent_dir: non_existent_dir = os.path.join(parent_dir, 'does_not_exist') self.assertRaises(FileNotFoundError, call_change_cwd, non_existent_dir) @@ -220,10 +225,10 @@ class TestSupport(unittest.TestCase): """Test passing a non-existent directory with quiet=True.""" original_cwd = os.getcwd() - with support.temp_dir() as parent_dir: + with os_helper.temp_dir() as parent_dir: bad_dir = os.path.join(parent_dir, 'does_not_exist') - with support.check_warnings() as recorder: - with support.change_cwd(bad_dir, quiet=True) as new_cwd: + with warnings_helper.check_warnings() as recorder: + with os_helper.change_cwd(bad_dir, quiet=True) as new_cwd: self.assertEqual(new_cwd, original_cwd) self.assertEqual(os.getcwd(), new_cwd) warnings = [str(w.message) for w in recorder.warnings] @@ -240,8 +245,8 @@ class TestSupport(unittest.TestCase): def test_change_cwd__chdir_warning(self): """Check the warning message when os.chdir() fails.""" path = TESTFN + '_does_not_exist' - with support.check_warnings() as recorder: - with support.change_cwd(path=path, quiet=True): + with warnings_helper.check_warnings() as recorder: + with os_helper.change_cwd(path=path, quiet=True): pass messages = [str(w.message) for w in recorder.warnings] @@ -256,7 +261,7 @@ class TestSupport(unittest.TestCase): def test_temp_cwd(self): here = os.getcwd() - with support.temp_cwd(name=TESTFN): + with os_helper.temp_cwd(name=TESTFN): self.assertEqual(os.path.basename(os.getcwd()), TESTFN) self.assertFalse(os.path.exists(TESTFN)) self.assertEqual(os.getcwd(), here) @@ -265,7 +270,7 @@ class TestSupport(unittest.TestCase): def test_temp_cwd__name_none(self): """Test passing None to temp_cwd().""" original_cwd = os.getcwd() - with support.temp_cwd(name=None) as new_cwd: + with os_helper.temp_cwd(name=None) as new_cwd: self.assertNotEqual(new_cwd, original_cwd) self.assertTrue(os.path.isdir(new_cwd)) self.assertEqual(os.getcwd(), new_cwd) @@ -275,7 +280,7 @@ class TestSupport(unittest.TestCase): self.assertEqual(support.sortdict({3:3, 2:2, 1:1}), "{1: 1, 2: 2, 3: 3}") def test_make_bad_fd(self): - fd = support.make_bad_fd() + fd = os_helper.make_bad_fd() with self.assertRaises(OSError) as cm: os.write(fd, b"foo") self.assertEqual(cm.exception.errno, errno.EBADF) @@ -287,11 +292,11 @@ class TestSupport(unittest.TestCase): def test_CleanImport(self): import importlib - with support.CleanImport("asyncore"): + with import_helper.CleanImport("asyncore"): importlib.import_module("asyncore") def test_DirsOnSysPath(self): - with support.DirsOnSysPath('foo', 'bar'): + with import_helper.DirsOnSysPath('foo', 'bar'): self.assertIn("foo", sys.path) self.assertIn("bar", sys.path) self.assertNotIn("foo", sys.path) @@ -625,10 +630,10 @@ class TestSupport(unittest.TestCase): # We cannot test the absolute value of fd_count(): on old Linux # kernel or glibc versions, os.urandom() keeps a FD open on # /dev/urandom device and Python has 4 FD opens instead of 3. - start = support.fd_count() + start = os_helper.fd_count() fd = os.open(__file__, os.O_RDONLY) try: - more = support.fd_count() + more = os_helper.fd_count() finally: os.close(fd) self.assertEqual(more - start, 1) diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index fcc706ede5a..8ace883d74b 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -15,7 +15,9 @@ from unittest import mock import unittest from test import support +from test.support import os_helper from test.support import script_helper +from test.support import warnings_helper has_textmode = (tempfile._text_openflags != tempfile._bin_openflags) @@ -69,7 +71,7 @@ class BaseTestCase(unittest.TestCase): b_check = re.compile(br"^[a-z0-9_-]{8}$") def setUp(self): - self._warnings_manager = support.check_warnings() + self._warnings_manager = warnings_helper.check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings("ignore", category=RuntimeWarning, message="mktemp", module=__name__) @@ -224,7 +226,7 @@ class TestCandidateTempdirList(BaseTestCase): # _candidate_tempdir_list contains the expected directories # Make sure the interesting environment variables are all set. - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: for envname in 'TMPDIR', 'TEMP', 'TMP': dirname = os.getenv(envname) if not dirname: @@ -310,7 +312,7 @@ def _inside_empty_temp_dir(): with support.swap_attr(tempfile, 'tempdir', dir): yield finally: - support.rmtree(dir) + os_helper.rmtree(dir) def _mock_candidate_names(*names): @@ -594,13 +596,13 @@ class TestGetTempDir(BaseTestCase): case_sensitive_tempdir = tempfile.mkdtemp("-Temp") _tempdir, tempfile.tempdir = tempfile.tempdir, None try: - with support.EnvironmentVarGuard() as env: + with os_helper.EnvironmentVarGuard() as env: # Fake the first env var which is checked as a candidate env["TMPDIR"] = case_sensitive_tempdir self.assertEqual(tempfile.gettempdir(), case_sensitive_tempdir) finally: tempfile.tempdir = _tempdir - support.rmdir(case_sensitive_tempdir) + os_helper.rmdir(case_sensitive_tempdir) class TestMkstemp(BaseTestCase): @@ -950,7 +952,7 @@ class TestNamedTemporaryFile(BaseTestCase): def test_bad_mode(self): dir = tempfile.mkdtemp() - self.addCleanup(support.rmtree, dir) + self.addCleanup(os_helper.rmtree, dir) with self.assertRaises(ValueError): tempfile.NamedTemporaryFile(mode='wr', dir=dir) with self.assertRaises(TypeError): @@ -1351,7 +1353,7 @@ class TestTemporaryDirectory(BaseTestCase): finally: os.rmdir(dir) - @support.skip_unless_symlink + @os_helper.skip_unless_symlink def test_cleanup_with_symlink_to_a_directory(self): # cleanup() should not follow symlinks to directories (issue #12464) d1 = self.do_create() @@ -1448,7 +1450,9 @@ class TestTemporaryDirectory(BaseTestCase): name = d.name # Check for the resource warning - with support.check_warnings(('Implicitly', ResourceWarning), quiet=False): + with warnings_helper.check_warnings(('Implicitly', + ResourceWarning), + quiet=False): warnings.filterwarnings("always", category=ResourceWarning) del d support.gc_collect()