Kaydet (Commit) 7c7b4b5d authored tarafından Serhiy Storchaka's avatar Serhiy Storchaka

Backport support.change_cwd() and use it in tests.

üst 23ae488f
...@@ -164,17 +164,11 @@ class UnicodeFileTests(unittest.TestCase): ...@@ -164,17 +164,11 @@ class UnicodeFileTests(unittest.TestCase):
dirname = os.path.join(test_support.TESTFN, dirname = os.path.join(test_support.TESTFN,
u'Gr\xfc\xdf-\u66e8\u66e9\u66eb') u'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
filename = u'\xdf-\u66e8\u66e9\u66eb' filename = u'\xdf-\u66e8\u66e9\u66eb'
oldwd = os.getcwd() with test_support.temp_cwd(dirname):
os.mkdir(dirname)
os.chdir(dirname)
try:
with open(filename, 'w') as f: with open(filename, 'w') as f:
f.write((filename + '\n').encode("utf-8")) f.write((filename + '\n').encode("utf-8"))
os.access(filename,os.R_OK) os.access(filename,os.R_OK)
os.remove(filename) os.remove(filename)
finally:
os.chdir(oldwd)
os.rmdir(dirname)
class UnicodeNFCFileTests(UnicodeFileTests): class UnicodeNFCFileTests(UnicodeFileTests):
......
import unittest import unittest
from test import test_support, test_genericpath from test import test_support, test_genericpath
from test import test_support as support
import posixpath import posixpath
import os import os
...@@ -251,7 +252,6 @@ class PosixPathTest(unittest.TestCase): ...@@ -251,7 +252,6 @@ class PosixPathTest(unittest.TestCase):
# Bug #930024, return the path unchanged if we get into an infinite # Bug #930024, return the path unchanged if we get into an infinite
# symlink loop. # symlink loop.
try: try:
old_path = abspath('.')
os.symlink(ABSTFN, ABSTFN) os.symlink(ABSTFN, ABSTFN)
self.assertEqual(realpath(ABSTFN), ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN)
...@@ -277,10 +277,9 @@ class PosixPathTest(unittest.TestCase): ...@@ -277,10 +277,9 @@ class PosixPathTest(unittest.TestCase):
self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c") self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c")
# Test using relative path as well. # Test using relative path as well.
os.chdir(dirname(ABSTFN)) with support.change_cwd(dirname(ABSTFN)):
self.assertEqual(realpath(basename(ABSTFN)), ABSTFN) self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
finally: finally:
os.chdir(old_path)
test_support.unlink(ABSTFN) test_support.unlink(ABSTFN)
test_support.unlink(ABSTFN+"1") test_support.unlink(ABSTFN+"1")
test_support.unlink(ABSTFN+"2") test_support.unlink(ABSTFN+"2")
...@@ -302,7 +301,6 @@ class PosixPathTest(unittest.TestCase): ...@@ -302,7 +301,6 @@ class PosixPathTest(unittest.TestCase):
def test_realpath_deep_recursion(self): def test_realpath_deep_recursion(self):
depth = 10 depth = 10
old_path = abspath('.')
try: try:
os.mkdir(ABSTFN) os.mkdir(ABSTFN)
for i in range(depth): for i in range(depth):
...@@ -311,10 +309,9 @@ class PosixPathTest(unittest.TestCase): ...@@ -311,10 +309,9 @@ class PosixPathTest(unittest.TestCase):
self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN) self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN)
# Test using relative path as well. # Test using relative path as well.
os.chdir(ABSTFN) with support.change_cwd(ABSTFN):
self.assertEqual(realpath('%d' % depth), ABSTFN) self.assertEqual(realpath('%d' % depth), ABSTFN)
finally: finally:
os.chdir(old_path)
for i in range(depth + 1): for i in range(depth + 1):
test_support.unlink(ABSTFN + '/%d' % i) test_support.unlink(ABSTFN + '/%d' % i)
safe_rmdir(ABSTFN) safe_rmdir(ABSTFN)
...@@ -325,15 +322,13 @@ class PosixPathTest(unittest.TestCase): ...@@ -325,15 +322,13 @@ class PosixPathTest(unittest.TestCase):
# /usr/doc with 'doc' being a symlink to /usr/share/doc. We call # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
# realpath("a"). This should return /usr/share/doc/a/. # realpath("a"). This should return /usr/share/doc/a/.
try: try:
old_path = abspath('.')
os.mkdir(ABSTFN) os.mkdir(ABSTFN)
os.mkdir(ABSTFN + "/y") os.mkdir(ABSTFN + "/y")
os.symlink(ABSTFN + "/y", ABSTFN + "/k") os.symlink(ABSTFN + "/y", ABSTFN + "/k")
os.chdir(ABSTFN + "/k") with support.change_cwd(ABSTFN + "/k"):
self.assertEqual(realpath("a"), ABSTFN + "/y/a") self.assertEqual(realpath("a"), ABSTFN + "/y/a")
finally: finally:
os.chdir(old_path)
test_support.unlink(ABSTFN + "/k") test_support.unlink(ABSTFN + "/k")
safe_rmdir(ABSTFN + "/y") safe_rmdir(ABSTFN + "/y")
safe_rmdir(ABSTFN) safe_rmdir(ABSTFN)
...@@ -347,7 +342,6 @@ class PosixPathTest(unittest.TestCase): ...@@ -347,7 +342,6 @@ class PosixPathTest(unittest.TestCase):
# and a symbolic link 'link-y' pointing to 'y' in directory 'a', # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
# then realpath("link-y/..") should return 'k', not 'a'. # then realpath("link-y/..") should return 'k', not 'a'.
try: try:
old_path = abspath('.')
os.mkdir(ABSTFN) os.mkdir(ABSTFN)
os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k")
os.mkdir(ABSTFN + "/k/y") os.mkdir(ABSTFN + "/k/y")
...@@ -356,11 +350,10 @@ class PosixPathTest(unittest.TestCase): ...@@ -356,11 +350,10 @@ class PosixPathTest(unittest.TestCase):
# Absolute path. # Absolute path.
self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k") self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
# Relative path. # Relative path.
os.chdir(dirname(ABSTFN)) with support.change_cwd(dirname(ABSTFN)):
self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
ABSTFN + "/k") ABSTFN + "/k")
finally: finally:
os.chdir(old_path)
test_support.unlink(ABSTFN + "/link-y") test_support.unlink(ABSTFN + "/link-y")
safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k/y")
safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN + "/k")
...@@ -371,17 +364,14 @@ class PosixPathTest(unittest.TestCase): ...@@ -371,17 +364,14 @@ class PosixPathTest(unittest.TestCase):
# must be resolved too. # must be resolved too.
try: try:
old_path = abspath('.')
os.mkdir(ABSTFN) os.mkdir(ABSTFN)
os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k")
os.symlink(ABSTFN, ABSTFN + "link") os.symlink(ABSTFN, ABSTFN + "link")
os.chdir(dirname(ABSTFN)) with support.change_cwd(dirname(ABSTFN)):
base = basename(ABSTFN)
base = basename(ABSTFN) self.assertEqual(realpath(base + "link"), ABSTFN)
self.assertEqual(realpath(base + "link"), ABSTFN) self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
finally: finally:
os.chdir(old_path)
test_support.unlink(ABSTFN + "link") test_support.unlink(ABSTFN + "link")
safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN + "/k")
safe_rmdir(ABSTFN) safe_rmdir(ABSTFN)
......
...@@ -5,7 +5,7 @@ import shutil ...@@ -5,7 +5,7 @@ import shutil
import tempfile import tempfile
import unittest import unittest
from test import test_support from test import test_support as support
class PyCompileTests(unittest.TestCase): class PyCompileTests(unittest.TestCase):
...@@ -35,11 +35,9 @@ class PyCompileTests(unittest.TestCase): ...@@ -35,11 +35,9 @@ class PyCompileTests(unittest.TestCase):
self.assertTrue(os.path.exists(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path))
def test_cwd(self): def test_cwd(self):
cwd = os.getcwd() with support.change_cwd(self.directory):
os.chdir(self.directory) py_compile.compile(os.path.basename(self.source_path),
py_compile.compile(os.path.basename(self.source_path), os.path.basename(self.pyc_path))
os.path.basename(self.pyc_path))
os.chdir(cwd)
self.assertTrue(os.path.exists(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path))
def test_relative_path(self): def test_relative_path(self):
...@@ -48,7 +46,7 @@ class PyCompileTests(unittest.TestCase): ...@@ -48,7 +46,7 @@ class PyCompileTests(unittest.TestCase):
self.assertTrue(os.path.exists(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path))
def test_main(): def test_main():
test_support.run_unittest(PyCompileTests) support.run_unittest(PyCompileTests)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()
...@@ -16,7 +16,7 @@ from shutil import (_make_tarball, _make_zipfile, make_archive, ...@@ -16,7 +16,7 @@ from shutil import (_make_tarball, _make_zipfile, make_archive,
import tarfile import tarfile
import warnings import warnings
from test import test_support from test import test_support as support
from test.test_support import TESTFN, check_warnings, captured_stdout from test.test_support import TESTFN, check_warnings, captured_stdout
TESTFN2 = TESTFN + "2" TESTFN2 = TESTFN + "2"
...@@ -389,12 +389,8 @@ class TestShutil(unittest.TestCase): ...@@ -389,12 +389,8 @@ class TestShutil(unittest.TestCase):
base_name = os.path.join(tmpdir2, 'archive') base_name = os.path.join(tmpdir2, 'archive')
# working with relative paths to avoid tar warnings # working with relative paths to avoid tar warnings
old_dir = os.getcwd() with support.change_cwd(tmpdir):
os.chdir(tmpdir)
try:
_make_tarball(splitdrive(base_name)[1], '.') _make_tarball(splitdrive(base_name)[1], '.')
finally:
os.chdir(old_dir)
# check if the compressed tarball was created # check if the compressed tarball was created
tarball = base_name + '.tar.gz' tarball = base_name + '.tar.gz'
...@@ -402,12 +398,8 @@ class TestShutil(unittest.TestCase): ...@@ -402,12 +398,8 @@ class TestShutil(unittest.TestCase):
# trying an uncompressed one # trying an uncompressed one
base_name = os.path.join(tmpdir2, 'archive') base_name = os.path.join(tmpdir2, 'archive')
old_dir = os.getcwd() with support.change_cwd(tmpdir):
os.chdir(tmpdir)
try:
_make_tarball(splitdrive(base_name)[1], '.', compress=None) _make_tarball(splitdrive(base_name)[1], '.', compress=None)
finally:
os.chdir(old_dir)
tarball = base_name + '.tar' tarball = base_name + '.tar'
self.assertTrue(os.path.exists(tarball)) self.assertTrue(os.path.exists(tarball))
...@@ -439,12 +431,8 @@ class TestShutil(unittest.TestCase): ...@@ -439,12 +431,8 @@ class TestShutil(unittest.TestCase):
'Need the tar command to run') 'Need the tar command to run')
def test_tarfile_vs_tar(self): def test_tarfile_vs_tar(self):
tmpdir, tmpdir2, base_name = self._create_files() tmpdir, tmpdir2, base_name = self._create_files()
old_dir = os.getcwd() with support.change_cwd(tmpdir):
os.chdir(tmpdir)
try:
_make_tarball(base_name, 'dist') _make_tarball(base_name, 'dist')
finally:
os.chdir(old_dir)
# check if the compressed tarball was created # check if the compressed tarball was created
tarball = base_name + '.tar.gz' tarball = base_name + '.tar.gz'
...@@ -454,14 +442,10 @@ class TestShutil(unittest.TestCase): ...@@ -454,14 +442,10 @@ class TestShutil(unittest.TestCase):
tarball2 = os.path.join(tmpdir, 'archive2.tar.gz') tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist'] tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
gzip_cmd = ['gzip', '-f9', 'archive2.tar'] gzip_cmd = ['gzip', '-f9', 'archive2.tar']
old_dir = os.getcwd() with support.change_cwd(tmpdir):
os.chdir(tmpdir)
try:
with captured_stdout() as s: with captured_stdout() as s:
spawn(tar_cmd) spawn(tar_cmd)
spawn(gzip_cmd) spawn(gzip_cmd)
finally:
os.chdir(old_dir)
self.assertTrue(os.path.exists(tarball2)) self.assertTrue(os.path.exists(tarball2))
# let's compare both tarballs # let's compare both tarballs
...@@ -469,23 +453,15 @@ class TestShutil(unittest.TestCase): ...@@ -469,23 +453,15 @@ class TestShutil(unittest.TestCase):
# trying an uncompressed one # trying an uncompressed one
base_name = os.path.join(tmpdir2, 'archive') base_name = os.path.join(tmpdir2, 'archive')
old_dir = os.getcwd() with support.change_cwd(tmpdir):
os.chdir(tmpdir)
try:
_make_tarball(base_name, 'dist', compress=None) _make_tarball(base_name, 'dist', compress=None)
finally:
os.chdir(old_dir)
tarball = base_name + '.tar' tarball = base_name + '.tar'
self.assertTrue(os.path.exists(tarball)) self.assertTrue(os.path.exists(tarball))
# now for a dry_run # now for a dry_run
base_name = os.path.join(tmpdir2, 'archive') base_name = os.path.join(tmpdir2, 'archive')
old_dir = os.getcwd() with support.change_cwd(tmpdir):
os.chdir(tmpdir)
try:
_make_tarball(base_name, 'dist', compress=None, dry_run=True) _make_tarball(base_name, 'dist', compress=None, dry_run=True)
finally:
os.chdir(old_dir)
tarball = base_name + '.tar' tarball = base_name + '.tar'
self.assertTrue(os.path.exists(tarball)) self.assertTrue(os.path.exists(tarball))
...@@ -544,15 +520,11 @@ class TestShutil(unittest.TestCase): ...@@ -544,15 +520,11 @@ class TestShutil(unittest.TestCase):
@unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support") @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
def test_tarfile_root_owner(self): def test_tarfile_root_owner(self):
tmpdir, tmpdir2, base_name = self._create_files() tmpdir, tmpdir2, base_name = self._create_files()
old_dir = os.getcwd()
os.chdir(tmpdir)
group = grp.getgrgid(0)[0] group = grp.getgrgid(0)[0]
owner = pwd.getpwuid(0)[0] owner = pwd.getpwuid(0)[0]
try: with support.change_cwd(tmpdir):
archive_name = _make_tarball(base_name, 'dist', compress=None, archive_name = _make_tarball(base_name, 'dist', compress=None,
owner=owner, group=group) owner=owner, group=group)
finally:
os.chdir(old_dir)
# check if the compressed tarball was created # check if the compressed tarball was created
self.assertTrue(os.path.exists(archive_name)) self.assertTrue(os.path.exists(archive_name))
...@@ -889,7 +861,7 @@ class TestCopyFile(unittest.TestCase): ...@@ -889,7 +861,7 @@ class TestCopyFile(unittest.TestCase):
def test_main(): def test_main():
test_support.run_unittest(TestShutil, TestMove, TestCopyFile) support.run_unittest(TestShutil, TestMove, TestCopyFile)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()
...@@ -668,6 +668,33 @@ TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid()) ...@@ -668,6 +668,33 @@ TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
# Save the initial cwd # Save the initial cwd
SAVEDCWD = os.getcwd() SAVEDCWD = os.getcwd()
@contextlib.contextmanager
def change_cwd(path, quiet=False):
"""Return a context manager that changes the current working directory.
Arguments:
path: the directory to use as the temporary current working directory.
quiet: if False (the default), the context manager raises an exception
on error. Otherwise, it issues only a warning and keeps the current
working directory the same.
"""
saved_dir = os.getcwd()
try:
os.chdir(path)
except OSError:
if not quiet:
raise
warnings.warn('tests may fail, unable to change CWD to: ' + path,
RuntimeWarning, stacklevel=3)
try:
yield os.getcwd()
finally:
os.chdir(saved_dir)
@contextlib.contextmanager @contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False): def temp_cwd(name='tempcwd', quiet=False):
""" """
......
...@@ -11,6 +11,7 @@ import unittest ...@@ -11,6 +11,7 @@ import unittest
import tarfile import tarfile
from test import test_support from test import test_support
from test import test_support as support
# Check for our compression modules. # Check for our compression modules.
try: try:
...@@ -972,9 +973,7 @@ class WriteTest(WriteTestBase): ...@@ -972,9 +973,7 @@ class WriteTest(WriteTestBase):
def test_cwd(self): def test_cwd(self):
# Test adding the current working directory. # Test adding the current working directory.
cwd = os.getcwd() with support.change_cwd(TEMPDIR):
os.chdir(TEMPDIR)
try:
open("foo", "w").close() open("foo", "w").close()
tar = tarfile.open(tmpname, self.mode) tar = tarfile.open(tmpname, self.mode)
...@@ -985,8 +984,6 @@ class WriteTest(WriteTestBase): ...@@ -985,8 +984,6 @@ class WriteTest(WriteTestBase):
for t in tar: for t in tar:
self.assertTrue(t.name == "." or t.name.startswith("./")) self.assertTrue(t.name == "." or t.name.startswith("./"))
tar.close() tar.close()
finally:
os.chdir(cwd)
@unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink") @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
def test_extractall_symlinks(self): def test_extractall_symlinks(self):
......
...@@ -5,7 +5,7 @@ import os, glob, time, shutil ...@@ -5,7 +5,7 @@ import os, glob, time, shutil
import unicodedata import unicodedata
import unittest import unittest
from test.test_support import run_unittest, TESTFN_UNICODE from test.test_support import run_unittest, change_cwd, TESTFN_UNICODE
from test.test_support import TESTFN_ENCODING, TESTFN_UNENCODABLE from test.test_support import TESTFN_ENCODING, TESTFN_UNENCODABLE
try: try:
TESTFN_ENCODED = TESTFN_UNICODE.encode(TESTFN_ENCODING) TESTFN_ENCODED = TESTFN_UNICODE.encode(TESTFN_ENCODING)
...@@ -114,13 +114,11 @@ class TestUnicodeFiles(unittest.TestCase): ...@@ -114,13 +114,11 @@ class TestUnicodeFiles(unittest.TestCase):
os.unlink(filename1 + ".new") os.unlink(filename1 + ".new")
def _do_directory(self, make_name, chdir_name, encoded): def _do_directory(self, make_name, chdir_name, encoded):
cwd = os.getcwd()
if os.path.isdir(make_name): if os.path.isdir(make_name):
os.rmdir(make_name) os.rmdir(make_name)
os.mkdir(make_name) os.mkdir(make_name)
try: try:
os.chdir(chdir_name) with change_cwd(chdir_name):
try:
if not encoded: if not encoded:
cwd_result = os.getcwdu() cwd_result = os.getcwdu()
name_result = make_name name_result = make_name
...@@ -132,8 +130,6 @@ class TestUnicodeFiles(unittest.TestCase): ...@@ -132,8 +130,6 @@ class TestUnicodeFiles(unittest.TestCase):
name_result = unicodedata.normalize("NFD", name_result) name_result = unicodedata.normalize("NFD", name_result)
self.assertEqual(os.path.basename(cwd_result),name_result) self.assertEqual(os.path.basename(cwd_result),name_result)
finally:
os.chdir(cwd)
finally: finally:
os.rmdir(make_name) os.rmdir(make_name)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment