def test_realpath_cwd(self): ABSTFN = ntpath.abspath(os_helper.TESTFN) os_helper.unlink(ABSTFN) os_helper.rmtree(ABSTFN) os.mkdir(ABSTFN) self.addCleanup(os_helper.rmtree, ABSTFN) test_dir_long = ntpath.join(ABSTFN, "MyVeryLongDirectoryName") os.mkdir(test_dir_long) test_dir_short = _getshortpathname(test_dir_long) test_file_long = ntpath.join(test_dir_long, "file.txt") test_file_short = ntpath.join(test_dir_short, "file.txt") with open(test_file_long, "wb") as f: f.write(b"content") self.assertPathEqual(test_file_long, ntpath.realpath(test_file_short)) with os_helper.change_cwd(test_dir_long): self.assertPathEqual(test_file_long, ntpath.realpath("file.txt")) with os_helper.change_cwd(test_dir_long.lower()): self.assertPathEqual(test_file_long, ntpath.realpath("file.txt")) with os_helper.change_cwd(test_dir_short): self.assertPathEqual(test_file_long, ntpath.realpath("file.txt"))
def test_realpath_resolve_before_normalizing(self): # Bug #990669: Symbolic links should be resolved before we # normalize the path. E.g.: if we have directories 'a', 'k' and 'y' # in the following hierarchy: # a/k/y # # and a symbolic link 'link-y' pointing to 'y' in directory 'a', # then realpath("link-y/..") should return 'k', not 'a'. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k/y") os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y") # Absolute path. self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k") # Relative path. with os_helper.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k") finally: os_helper.unlink(ABSTFN + "/link-y") safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
def test_ismount(self): self.assertTrue(ntpath.ismount("c:\\")) self.assertTrue(ntpath.ismount("C:\\")) self.assertTrue(ntpath.ismount("c:/")) self.assertTrue(ntpath.ismount("C:/")) self.assertTrue(ntpath.ismount("\\\\.\\c:\\")) self.assertTrue(ntpath.ismount("\\\\.\\C:\\")) self.assertTrue(ntpath.ismount(b"c:\\")) self.assertTrue(ntpath.ismount(b"C:\\")) self.assertTrue(ntpath.ismount(b"c:/")) self.assertTrue(ntpath.ismount(b"C:/")) self.assertTrue(ntpath.ismount(b"\\\\.\\c:\\")) self.assertTrue(ntpath.ismount(b"\\\\.\\C:\\")) with os_helper.temp_dir() as d: self.assertFalse(ntpath.ismount(d)) if sys.platform == "win32": # # Make sure the current folder isn't the root folder # (or any other volume root). The drive-relative # locations below cannot then refer to mount points # drive, path = ntpath.splitdrive(sys.executable) with os_helper.change_cwd(ntpath.dirname(sys.executable)): self.assertFalse(ntpath.ismount(drive.lower())) self.assertFalse(ntpath.ismount(drive.upper())) self.assertTrue(ntpath.ismount("\\\\localhost\\c$")) self.assertTrue(ntpath.ismount("\\\\localhost\\c$\\")) self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$")) self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$\\"))
def test_srcdir_independent_of_cwd(self): # srcdir should be independent of the current working directory # See Issues #15322, #15364. srcdir = sysconfig.get_config_var('srcdir') with change_cwd(os.pardir): srcdir2 = sysconfig.get_config_var('srcdir') self.assertEqual(srcdir, srcdir2)
def test_make_zipfile_no_zlib(self): patch(self, archive_util.zipfile, 'zlib', None) # force zlib ImportError called = [] zipfile_class = zipfile.ZipFile def fake_zipfile(*a, **kw): if kw.get('compression', None) == zipfile.ZIP_STORED: called.append((a, kw)) return zipfile_class(*a, **kw) patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile) # create something to tar and compress tmpdir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') with change_cwd(tmpdir): make_zipfile(base_name, 'dist') tarball = base_name + '.zip' self.assertEqual(called, [((tarball, "w"), { 'compression': zipfile.ZIP_STORED })]) self.assertTrue(os.path.exists(tarball)) with zipfile.ZipFile(tarball) as zf: self.assertEqual(sorted(zf.namelist()), self._zip_created_files)
def setUp(self): self._backup_config_vars = dict(sysconfig._CONFIG_VARS) cmd = support.missing_compiler_executable() if cmd is not None: self.skipTest("The %r command is not found" % cmd) self.old_cwd = os.getcwd() self.tmp_path = tempfile.mkdtemp(dir=self.tmp_base) self.enterContext(os_helper.change_cwd(self.tmp_path))
def test_relativedir_bug46421(self): # Test `python -m unittest` with a relative directory beginning with ./ # Note: We have to switch to the project's top module's directory, as per # the python unittest wiki. We will switch back when we are done. projectlibpath = os.path.dirname(__file__).removesuffix("test") with os_helper.change_cwd(projectlibpath): # Testing with and without ./ assert_python_ok('-m', 'unittest', "test/test_longexp.py") assert_python_ok('-m', 'unittest', "./test/test_longexp.py")
def test_hint_when_triying_to_import_a_py_file(self): with os_helper.temp_dir() as script_dir, \ os_helper.change_cwd(path=script_dir): # Create invalid *.pyc as empty file with open('asyncio.py', 'wb'): pass err = self.check_dash_m_failure('asyncio.py') self.assertIn(b"Try using 'asyncio' instead " b"of 'asyncio.py' as the module name", err)
def test_change_cwd(self): original_cwd = os.getcwd() 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) self.assertEqual(os.getcwd(), original_cwd)
def setUp(self): cmd = support.missing_compiler_executable() if cmd is not None: self.skipTest("The %r command is not found" % cmd) super(TestCParser, self).setUp() self.tmp_path = self.mkdtemp() change_cwd = os_helper.change_cwd(self.tmp_path) change_cwd.__enter__() self.addCleanup(change_cwd.__exit__, None, None, None)
def test_empty(self): # We need to make sure the child process starts in a directory # we're not about to delete. If we're running under -j, that # means the test harness provided directory isn't a safe option. # See http://bugs.python.org/issue15526 for more details with os_helper.change_cwd(path.dirname(sys.executable)): empty = path.join(path.dirname(__file__), "empty.vbs") startfile(empty) startfile(empty, "open")
def test_realpath_broken_symlinks(self): ABSTFN = ntpath.abspath(os_helper.TESTFN) os.mkdir(ABSTFN) self.addCleanup(os_helper.rmtree, ABSTFN) with os_helper.change_cwd(ABSTFN): os.mkdir("subdir") os.chdir("subdir") os.symlink(".", "recursive") os.symlink("..", "parent") os.chdir("..") os.symlink(".", "self") os.symlink("missing", "broken") os.symlink(r"broken\bar", "broken1") os.symlink(r"self\self\broken", "broken2") os.symlink(r"subdir\parent\subdir\parent\broken", "broken3") os.symlink(ABSTFN + r"\broken", "broken4") os.symlink(r"recursive\..\broken", "broken5") self.assertPathEqual(ntpath.realpath("broken"), ABSTFN + r"\missing") self.assertPathEqual(ntpath.realpath(r"broken\foo"), ABSTFN + r"\missing\foo") # bpo-38453: We no longer recursively resolve segments of relative # symlinks that the OS cannot resolve. self.assertPathEqual(ntpath.realpath(r"broken1"), ABSTFN + r"\broken\bar") self.assertPathEqual(ntpath.realpath(r"broken1\baz"), ABSTFN + r"\broken\bar\baz") self.assertPathEqual(ntpath.realpath("broken2"), ABSTFN + r"\self\self\missing") self.assertPathEqual( ntpath.realpath("broken3"), ABSTFN + r"\subdir\parent\subdir\parent\missing") self.assertPathEqual(ntpath.realpath("broken4"), ABSTFN + r"\missing") self.assertPathEqual(ntpath.realpath("broken5"), ABSTFN + r"\missing") self.assertPathEqual(ntpath.realpath(b"broken"), os.fsencode(ABSTFN + r"\missing")) self.assertPathEqual(ntpath.realpath(rb"broken\foo"), os.fsencode(ABSTFN + r"\missing\foo")) self.assertPathEqual(ntpath.realpath(rb"broken1"), os.fsencode(ABSTFN + r"\broken\bar")) self.assertPathEqual(ntpath.realpath(rb"broken1\baz"), os.fsencode(ABSTFN + r"\broken\bar\baz")) self.assertPathEqual(ntpath.realpath(b"broken2"), os.fsencode(ABSTFN + r"\self\self\missing")) self.assertPathEqual( ntpath.realpath(rb"broken3"), os.fsencode(ABSTFN + r"\subdir\parent\subdir\parent\missing")) self.assertPathEqual(ntpath.realpath(b"broken4"), os.fsencode(ABSTFN + r"\missing")) self.assertPathEqual(ntpath.realpath(b"broken5"), os.fsencode(ABSTFN + r"\missing"))
def setUp(self): self._backup_config_vars = dict(sysconfig._CONFIG_VARS) cmd = support.missing_compiler_executable() if cmd is not None: self.skipTest("The %r command is not found" % cmd) self.old_cwd = os.getcwd() self.tmp_path = tempfile.mkdtemp() change_cwd = os_helper.change_cwd(self.tmp_path) change_cwd.__enter__() self.addCleanup(change_cwd.__exit__, None, None, None)
def test_make_zipfile(self): # creating something to tar tmpdir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') with change_cwd(tmpdir): make_zipfile(base_name, 'dist') # check if the compressed tarball was created tarball = base_name + '.zip' self.assertTrue(os.path.exists(tarball)) with zipfile.ZipFile(tarball) as zf: self.assertEqual(sorted(zf.namelist()), self._zip_created_files)
def test_dash_m_bad_pyc(self): with os_helper.temp_dir() as script_dir, \ os_helper.change_cwd(path=script_dir): os.mkdir('test_pkg') # Create invalid *.pyc as empty file with open('test_pkg/__init__.pyc', 'wb'): pass err = self.check_dash_m_failure('test_pkg') self.assertRegex( err, br'Error while finding module specification.*' br'ImportError.*bad magic number') self.assertNotIn(b'is a package', err) self.assertNotIn(b'Traceback', err)
def test_issue8202_dash_m_file_ignored(self): # Make sure a "-m" file in the current directory # does not alter the value of sys.path[0] with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'other') with os_helper.change_cwd(path=script_dir): with open("-m", "w", encoding="utf-8") as f: f.write("data") rc, out, err = assert_python_ok('-m', 'other', *example_args, __isolated=False) self._check_output(script_name, rc, out, script_name, script_name, script_dir, '', importlib.machinery.SourceFileLoader)
def test_output_file_when_changing_directory(self): with temp_dir() as tmpdir, change_cwd(tmpdir): os.mkdir('dest') with open('demo.py', 'w') as f: f.write('import os; os.chdir("dest")') assert_python_ok( '-m', self.profilermodule.__name__, '-o', 'out.pstats', 'demo.py', ) self.assertTrue(os.path.exists('out.pstats'))
def glob(self, *parts, **kwargs): if len(parts) == 1: pattern = parts[0] else: pattern = os.path.join(*parts) p = os.path.join(self.tempdir, pattern) res = glob.glob(p, **kwargs) res2 = glob.iglob(p, **kwargs) self.assertCountEqual(glob.iglob(p, **kwargs), res) bres = [os.fsencode(x) for x in res] self.assertCountEqual(glob.glob(os.fsencode(p), **kwargs), bres) self.assertCountEqual(glob.iglob(os.fsencode(p), **kwargs), bres) with change_cwd(self.tempdir): res2 = glob.glob(pattern, **kwargs) for x in res2: self.assertFalse(os.path.isabs(x), x) if pattern == '**' or pattern == '**' + os.sep: expected = res[1:] else: expected = res self.assertCountEqual( [os.path.join(self.tempdir, x) for x in res2], expected) self.assertCountEqual(glob.iglob(pattern, **kwargs), res2) bpattern = os.fsencode(pattern) bres2 = [os.fsencode(x) for x in res2] self.assertCountEqual(glob.glob(bpattern, **kwargs), bres2) self.assertCountEqual(glob.iglob(bpattern, **kwargs), bres2) self.assertCountEqual( glob.glob(pattern, root_dir=self.tempdir, **kwargs), res2) self.assertCountEqual( glob.iglob(pattern, root_dir=self.tempdir, **kwargs), res2) btempdir = os.fsencode(self.tempdir) self.assertCountEqual(glob.glob(bpattern, root_dir=btempdir, **kwargs), bres2) self.assertCountEqual( glob.iglob(bpattern, root_dir=btempdir, **kwargs), bres2) if self.dir_fd is not None: self.assertCountEqual( glob.glob(pattern, dir_fd=self.dir_fd, **kwargs), res2) self.assertCountEqual( glob.iglob(pattern, dir_fd=self.dir_fd, **kwargs), res2) self.assertCountEqual( glob.glob(bpattern, dir_fd=self.dir_fd, **kwargs), bres2) self.assertCountEqual( glob.iglob(bpattern, dir_fd=self.dir_fd, **kwargs), bres2) return res
def test_abs_paths(self): # Make sure all imported modules have their __file__ and __cached__ # attributes as absolute paths. Arranging to put the Lib directory on # PYTHONPATH would cause the os module to have a relative path for # __file__ if abs_paths() does not get run. sys and builtins (the # only other modules imported before site.py runs) do not have # __file__ or __cached__ because they are built-in. try: parent = os.path.relpath(os.path.dirname(os.__file__)) cwd = os.getcwd() except ValueError: # Failure to get relpath probably means we need to chdir # to the same drive. cwd, parent = os.path.split(os.path.dirname(os.__file__)) with change_cwd(cwd): env = os.environ.copy() env['PYTHONPATH'] = parent code = ( 'import os, sys', # use ASCII to avoid locale issues with non-ASCII directories 'os_file = os.__file__.encode("ascii", "backslashreplace")', r'sys.stdout.buffer.write(os_file + b"\n")', 'os_cached = os.__cached__.encode("ascii", "backslashreplace")', r'sys.stdout.buffer.write(os_cached + b"\n")') command = '\n'.join(code) # First, prove that with -S (no 'import site'), the paths are # relative. proc = subprocess.Popen([sys.executable, '-S', '-c', command], env=env, stdout=subprocess.PIPE) stdout, stderr = proc.communicate() self.assertEqual(proc.returncode, 0) os__file__, os__cached__ = stdout.splitlines()[:2] self.assertFalse(os.path.isabs(os__file__)) self.assertFalse(os.path.isabs(os__cached__)) # Now, with 'import site', it works. proc = subprocess.Popen([sys.executable, '-c', command], env=env, stdout=subprocess.PIPE) stdout, stderr = proc.communicate() self.assertEqual(proc.returncode, 0) os__file__, os__cached__ = stdout.splitlines()[:2] self.assertTrue( os.path.isabs(os__file__), "expected absolute path, got {}".format( os__file__.decode('ascii'))) self.assertTrue( os.path.isabs(os__cached__), "expected absolute path, got {}".format( os__cached__.decode('ascii')))
def test_change_cwd__chdir_warning(self): """Check the warning message when os.chdir() fails.""" path = TESTFN + '_does_not_exist' 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] self.assertEqual(len(messages), 1, messages) msg = messages[0] self.assertTrue( msg.startswith(f'tests may fail, unable to change ' f'the current working directory ' f'to {path!r}: '), msg)
def test_issue8202_dash_c_file_ignored(self): # Make sure a "-c" file in the current directory # does not alter the value of sys.path[0] with os_helper.temp_dir() as script_dir: with os_helper.change_cwd(path=script_dir): with open("-c", "w", encoding="utf-8") as f: f.write("data") rc, out, err = assert_python_ok('-c', 'import sys; print("sys.path[0]==%r" % sys.path[0])', __isolated=False) if verbose > 1: print(repr(out)) expected = "sys.path[0]==%r" % '' self.assertIn(expected.encode('utf-8'), out)
def test_realpath_symlink_loops_strict(self): # Bug #43757, raise OSError if we get into an infinite symlink loop in # strict mode. try: os.symlink(ABSTFN, ABSTFN) self.assertRaises(OSError, realpath, ABSTFN, strict=True) os.symlink(ABSTFN + "1", ABSTFN + "2") os.symlink(ABSTFN + "2", ABSTFN + "1") self.assertRaises(OSError, realpath, ABSTFN + "1", strict=True) self.assertRaises(OSError, realpath, ABSTFN + "2", strict=True) self.assertRaises(OSError, realpath, ABSTFN + "1/x", strict=True) self.assertRaises(OSError, realpath, ABSTFN + "1/..", strict=True) self.assertRaises(OSError, realpath, ABSTFN + "1/../x", strict=True) os.symlink(ABSTFN + "x", ABSTFN + "y") self.assertRaises(OSError, realpath, ABSTFN + "1/../" + basename(ABSTFN) + "y", strict=True) self.assertRaises(OSError, realpath, ABSTFN + "1/../" + basename(ABSTFN) + "1", strict=True) os.symlink(basename(ABSTFN) + "a/b", ABSTFN + "a") self.assertRaises(OSError, realpath, ABSTFN + "a", strict=True) os.symlink( "../" + basename(dirname(ABSTFN)) + "/" + basename(ABSTFN) + "c", ABSTFN + "c") self.assertRaises(OSError, realpath, ABSTFN + "c", strict=True) # Test using relative path as well. with os_helper.change_cwd(dirname(ABSTFN)): self.assertRaises(OSError, realpath, basename(ABSTFN), strict=True) finally: os_helper.unlink(ABSTFN) os_helper.unlink(ABSTFN + "1") os_helper.unlink(ABSTFN + "2") os_helper.unlink(ABSTFN + "y") os_helper.unlink(ABSTFN + "c") os_helper.unlink(ABSTFN + "a")
def _make_tarball(self, tmpdir, target_name, suffix, **kwargs): tmpdir2 = self.mkdtemp() unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0], "source and target should be on same drive") base_name = os.path.join(tmpdir2, target_name) # working with relative paths to avoid tar warnings with change_cwd(tmpdir): make_tarball(splitdrive(base_name)[1], 'dist', **kwargs) # check if the compressed tarball was created tarball = base_name + suffix self.assertTrue(os.path.exists(tarball)) self.assertEqual(self._tarinfo(tarball), self._created_files)
def _do_directory(self, make_name, chdir_name): if os.path.isdir(make_name): rmtree(make_name) os.mkdir(make_name) try: with change_cwd(chdir_name): cwd_result = os.getcwd() name_result = make_name cwd_result = unicodedata.normalize("NFD", cwd_result) name_result = unicodedata.normalize("NFD", name_result) self.assertEqual(os.path.basename(cwd_result), name_result) finally: os.rmdir(make_name)
def setUp(self): # Create a simple test environment super(BuildExtTestCase, self).setUp() self.tmp_dir = self.mkdtemp() import site self.old_user_base = site.USER_BASE site.USER_BASE = self.mkdtemp() from distutils.command import build_ext build_ext.USER_BASE = site.USER_BASE self.old_config_vars = dict(sysconfig._config_vars) # bpo-30132: On Windows, a .pdb file may be created in the current # working directory. Create a temporary working directory to cleanup # everything at the end of the test. self.enterContext(os_helper.change_cwd(self.tmp_dir))
def test_realpath_resolve_parents(self): # We also need to resolve any symlinks in the parents of a relative # path passed to realpath. E.g.: current working directory is # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call # realpath("a"). This should return /usr/share/doc/a/. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/y") os.symlink(ABSTFN + "/y", ABSTFN + "/k") with os_helper.change_cwd(ABSTFN + "/k"): self.assertEqual(realpath("a"), ABSTFN + "/y/a") finally: os_helper.unlink(ABSTFN + "/k") safe_rmdir(ABSTFN + "/y") safe_rmdir(ABSTFN)
def test_realpath_resolve_first(self): # Bug #1213894: The first component of the path, if not absolute, # must be resolved too. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.symlink(ABSTFN, ABSTFN + "link") with os_helper.change_cwd(dirname(ABSTFN)): base = basename(ABSTFN) self.assertEqual(realpath(base + "link"), ABSTFN) self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k") finally: os_helper.unlink(ABSTFN + "link") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
def setUp(self): # Create a simple test environment super(BuildExtTestCase, self).setUp() self.tmp_dir = self.mkdtemp() import site self.old_user_base = site.USER_BASE site.USER_BASE = self.mkdtemp() from distutils.command import build_ext build_ext.USER_BASE = site.USER_BASE # bpo-30132: On Windows, a .pdb file may be created in the current # working directory. Create a temporary working directory to cleanup # everything at the end of the test. change_cwd = os_helper.change_cwd(self.tmp_dir) change_cwd.__enter__() self.addCleanup(change_cwd.__exit__, None, None, None)
def test_issue20884(self): # On Windows, script with encoding cookie and LF line ending # will be failed. with os_helper.temp_dir() as script_dir: script_name = os.path.join(script_dir, "issue20884.py") with open(script_name, "w", encoding="latin1", newline='\n') as f: f.write("#coding: iso-8859-1\n") f.write('"""\n') for _ in range(30): f.write('x' * 80 + '\n') f.write('"""\n') with os_helper.change_cwd(path=script_dir): rc, out, err = assert_python_ok(script_name) self.assertEqual(b"", out) self.assertEqual(b"", err)
def test_issue8202(self): # Make sure package __init__ modules see "-m" in sys.argv0 while # searching for the module to execute with os_helper.temp_dir() as script_dir: with os_helper.change_cwd(path=script_dir): pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])") script_name = _make_test_script(pkg_dir, 'script') rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False) if verbose > 1: print(repr(out)) expected = "init_argv0==%r" % '-m' self.assertIn(expected.encode('utf-8'), out) self._check_output(script_name, rc, out, script_name, script_name, script_dir, 'test_pkg', importlib.machinery.SourceFileLoader)