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()), ['dist/file1', 'dist/file2', 'dist/sub/file3'])
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 support.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 support.change_cwd(os.path.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_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 support.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k") finally: support.unlink(ABSTFN + "/link-y") safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
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_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): pass messages = [str(w.message) for w in recorder.warnings] self.assertEqual(messages, ['tests may fail, unable to change CWD to: ' + path])
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 support.change_cwd(path.dirname(sys.executable)): empty = path.join(path.dirname(__file__), "empty.vbs") startfile(empty) startfile(empty, "open")
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: self.assertEqual(new_cwd, temp_path) self.assertEqual(os.getcwd(), new_cwd) self.assertEqual(os.getcwd(), original_cwd)
def test_dash_m_bad_pyc(self): with support.temp_dir() as script_dir, \ support.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_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()), ['dist/file1', 'dist/file2', 'dist/sub/file3'])
def test_change_cwd__non_existent_dir__quiet_true(self): """Test passing a non-existent directory with quiet=True.""" original_cwd = os.getcwd() with support.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: self.assertEqual(new_cwd, original_cwd) self.assertEqual(os.getcwd(), new_cwd) warnings = [str(w.message) for w in recorder.warnings] expected = ['tests may fail, unable to change CWD to: ' + bad_dir] self.assertEqual(warnings, expected)
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 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 support.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'other') with support.change_cwd(path=script_dir): with open("-m", "w") 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, '', '', importlib.machinery.SourceFileLoader)
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 support.temp_dir() as script_dir: with support.change_cwd(path=script_dir): with open("-c", "w") 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_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 support.change_cwd(ABSTFN + "/k"): self.assertEqual(realpath("a"), ABSTFN + "/y/a") finally: support.unlink(ABSTFN + "/k") safe_rmdir(ABSTFN + "/y") safe_rmdir(ABSTFN)
def test_realpath_deep_recursion(self): depth = 10 try: os.mkdir(ABSTFN) for i in range(depth): os.symlink('/'.join(['%d' % i] * 10), ABSTFN + '/%d' % (i + 1)) os.symlink('.', ABSTFN + '/0') self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN) # Test using relative path as well. with support.change_cwd(ABSTFN): self.assertEqual(realpath('%d' % depth), ABSTFN) finally: for i in range(depth + 1): support.unlink(ABSTFN + '/%d' % i) safe_rmdir(ABSTFN)
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 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 support.change_cwd(dirname(ABSTFN)): base = basename(ABSTFN) self.assertEqual(realpath(base + "link"), ABSTFN) self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k") finally: support.unlink(ABSTFN + "link") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
def test_selflink(self): tempdir = TESTFN + "_dir" os.makedirs(tempdir) self.addCleanup(shutil.rmtree, tempdir) with change_cwd(tempdir): os.makedirs('dir') create_empty_file(os.path.join('dir', 'file')) os.symlink(os.curdir, os.path.join('dir', 'link')) results = glob.glob('**', recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(['dir'] + ['link'] * depth)) self.assertIn(path, results) results.remove(path) if not results: break path = os.path.join(path, 'file') self.assertIn(path, results) results.remove(path) depth += 1 results = glob.glob(os.path.join('**', 'file'), recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(['dir'] + ['link'] * depth + ['file'])) self.assertIn(path, results) results.remove(path) depth += 1 results = glob.glob(os.path.join('**', ''), recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(['dir'] + ['link'] * depth + [''])) self.assertIn(path, results) results.remove(path) depth += 1
def test_realpath_symlink_loops(self): # Bug #930024, return the path unchanged if we get into an infinite # symlink loop. try: os.symlink(ABSTFN, ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN) os.symlink(ABSTFN + "1", ABSTFN + "2") os.symlink(ABSTFN + "2", ABSTFN + "1") self.assertEqual(realpath(ABSTFN + "1"), ABSTFN + "1") self.assertEqual(realpath(ABSTFN + "2"), ABSTFN + "2") self.assertEqual(realpath(ABSTFN + "1/x"), ABSTFN + "1/x") self.assertEqual(realpath(ABSTFN + "1/.."), dirname(ABSTFN)) self.assertEqual(realpath(ABSTFN + "1/../x"), dirname(ABSTFN) + "/x") os.symlink(ABSTFN + "x", ABSTFN + "y") self.assertEqual( realpath(ABSTFN + "1/../" + basename(ABSTFN) + "y"), ABSTFN + "y") self.assertEqual( realpath(ABSTFN + "1/../" + basename(ABSTFN) + "1"), ABSTFN + "1") os.symlink(basename(ABSTFN) + "a/b", ABSTFN + "a") self.assertEqual(realpath(ABSTFN + "a"), ABSTFN + "a/b") os.symlink( "../" + basename(dirname(ABSTFN)) + "/" + basename(ABSTFN) + "c", ABSTFN + "c") self.assertEqual(realpath(ABSTFN + "c"), ABSTFN + "c") # Test using relative path as well. with support.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN)), ABSTFN) finally: support.unlink(ABSTFN) support.unlink(ABSTFN + "1") support.unlink(ABSTFN + "2") support.unlink(ABSTFN + "y") support.unlink(ABSTFN + "c") support.unlink(ABSTFN + "a")
def test_issue8202(self): # Make sure package __init__ modules see "-m" in sys.argv0 while # searching for the module to execute with support.temp_dir() as script_dir: with support.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, '', 'test_pkg', importlib.machinery.SourceFileLoader)
def setup_test_pkg(self, *args): with support.temp_dir() as script_dir, \ support.change_cwd(path=script_dir): pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir, *args) yield pkg_dir
def test_recursive_glob(self): eq = self.assertSequencesEqual_noorder full = [('EF',), ('ZZZ',), ('a',), ('a', 'D'), ('a', 'bcd'), ('a', 'bcd', 'EF'), ('a', 'bcd', 'efg'), ('a', 'bcd', 'efg', 'ha'), ('aaa',), ('aaa', 'zzzF'), ('aab',), ('aab', 'F'), ] if can_symlink(): full += [('sym1',), ('sym2',), ('sym3',), ('sym3', 'EF'), ('sym3', 'efg'), ('sym3', 'efg', 'ha'), ] eq(self.rglob('**'), self.joins(('',), *full)) eq(self.rglob(os.curdir, '**'), self.joins((os.curdir, ''), *((os.curdir,) + i for i in full))) dirs = [('a', ''), ('a', 'bcd', ''), ('a', 'bcd', 'efg', ''), ('aaa', ''), ('aab', '')] if can_symlink(): dirs += [('sym3', ''), ('sym3', 'efg', '')] eq(self.rglob('**', ''), self.joins(('',), *dirs)) eq(self.rglob('a', '**'), self.joins( ('a', ''), ('a', 'D'), ('a', 'bcd'), ('a', 'bcd', 'EF'), ('a', 'bcd', 'efg'), ('a', 'bcd', 'efg', 'ha'))) eq(self.rglob('a**'), self.joins(('a',), ('aaa',), ('aab',))) expect = [('a', 'bcd', 'EF'), ('EF',)] if can_symlink(): expect += [('sym3', 'EF')] eq(self.rglob('**', 'EF'), self.joins(*expect)) expect = [('a', 'bcd', 'EF'), ('aaa', 'zzzF'), ('aab', 'F'), ('EF',)] if can_symlink(): expect += [('sym3', 'EF')] eq(self.rglob('**', '*F'), self.joins(*expect)) eq(self.rglob('**', '*F', ''), []) eq(self.rglob('**', 'bcd', '*'), self.joins( ('a', 'bcd', 'EF'), ('a', 'bcd', 'efg'))) eq(self.rglob('a', '**', 'bcd'), self.joins(('a', 'bcd'))) with change_cwd(self.tempdir): join = os.path.join eq(glob.glob('**', recursive=True), [join(*i) for i in full]) eq(glob.glob(join('**', ''), recursive=True), [join(*i) for i in dirs]) eq(glob.glob(join('**', '*'), recursive=True), [join(*i) for i in full]) eq(glob.glob(join(os.curdir, '**'), recursive=True), [join(os.curdir, '')] + [join(os.curdir, *i) for i in full]) eq(glob.glob(join(os.curdir, '**', ''), recursive=True), [join(os.curdir, '')] + [join(os.curdir, *i) for i in dirs]) eq(glob.glob(join(os.curdir, '**', '*'), recursive=True), [join(os.curdir, *i) for i in full]) eq(glob.glob(join('**','zz*F'), recursive=True), [join('aaa', 'zzzF')]) eq(glob.glob('**zz*F', recursive=True), []) expect = [join('a', 'bcd', 'EF'), 'EF'] if can_symlink(): expect += [join('sym3', 'EF')] eq(glob.glob(join('**', 'EF'), recursive=True), expect)
def call_change_cwd(path): with support.change_cwd(path) as new_cwd: raise Exception("should not get here")
def test_cwd(self): with support.change_cwd(self.directory): py_compile.compile(os.path.basename(self.source_path), os.path.basename(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path)) self.assertFalse(os.path.exists(self.cache_path))