[Python-checkins] cpython (2.7): Backport support.change_cwd() and use it in tests.

serhiy.storchaka python-checkins at python.org
Sun Sep 6 13:17:34 CEST 2015


https://hg.python.org/cpython/rev/7969c9f02a9f
changeset:   97704:7969c9f02a9f
branch:      2.7
parent:      97686:26c4db1a0aea
user:        Serhiy Storchaka <storchaka at gmail.com>
date:        Sun Sep 06 14:16:18 2015 +0300
summary:
  Backport support.change_cwd() and use it in tests.

files:
  Lib/test/test_pep277.py       |   8 +---
  Lib/test/test_posixpath.py    |  38 +++++++------------
  Lib/test/test_py_compile.py   |  12 ++---
  Lib/test/test_shutil.py       |  46 ++++------------------
  Lib/test/test_support.py      |  27 +++++++++++++
  Lib/test/test_tarfile.py      |   7 +--
  Lib/test/test_unicode_file.py |   8 +---
  7 files changed, 60 insertions(+), 86 deletions(-)


diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py
--- a/Lib/test/test_pep277.py
+++ b/Lib/test/test_pep277.py
@@ -164,17 +164,11 @@
         dirname = os.path.join(test_support.TESTFN,
                                u'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
         filename = u'\xdf-\u66e8\u66e9\u66eb'
-        oldwd = os.getcwd()
-        os.mkdir(dirname)
-        os.chdir(dirname)
-        try:
+        with test_support.temp_cwd(dirname):
             with open(filename, 'w') as f:
                 f.write((filename + '\n').encode("utf-8"))
             os.access(filename,os.R_OK)
             os.remove(filename)
-        finally:
-            os.chdir(oldwd)
-            os.rmdir(dirname)
 
 
 class UnicodeNFCFileTests(UnicodeFileTests):
diff --git a/Lib/test/test_posixpath.py b/Lib/test/test_posixpath.py
--- a/Lib/test/test_posixpath.py
+++ b/Lib/test/test_posixpath.py
@@ -1,5 +1,6 @@
 import unittest
 from test import test_support, test_genericpath
+from test import test_support as support
 
 import posixpath
 import os
@@ -251,7 +252,6 @@
             # Bug #930024, return the path unchanged if we get into an infinite
             # symlink loop.
             try:
-                old_path = abspath('.')
                 os.symlink(ABSTFN, ABSTFN)
                 self.assertEqual(realpath(ABSTFN), ABSTFN)
 
@@ -277,10 +277,9 @@
                 self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c")
 
                 # Test using relative path as well.
-                os.chdir(dirname(ABSTFN))
-                self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
+                with support.change_cwd(dirname(ABSTFN)):
+                    self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
             finally:
-                os.chdir(old_path)
                 test_support.unlink(ABSTFN)
                 test_support.unlink(ABSTFN+"1")
                 test_support.unlink(ABSTFN+"2")
@@ -302,7 +301,6 @@
 
         def test_realpath_deep_recursion(self):
             depth = 10
-            old_path = abspath('.')
             try:
                 os.mkdir(ABSTFN)
                 for i in range(depth):
@@ -311,10 +309,9 @@
                 self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN)
 
                 # Test using relative path as well.
-                os.chdir(ABSTFN)
-                self.assertEqual(realpath('%d' % depth), ABSTFN)
+                with support.change_cwd(ABSTFN):
+                    self.assertEqual(realpath('%d' % depth), ABSTFN)
             finally:
-                os.chdir(old_path)
                 for i in range(depth + 1):
                     test_support.unlink(ABSTFN + '/%d' % i)
                 safe_rmdir(ABSTFN)
@@ -325,15 +322,13 @@
             # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
             # realpath("a"). This should return /usr/share/doc/a/.
             try:
-                old_path = abspath('.')
                 os.mkdir(ABSTFN)
                 os.mkdir(ABSTFN + "/y")
                 os.symlink(ABSTFN + "/y", ABSTFN + "/k")
 
-                os.chdir(ABSTFN + "/k")
-                self.assertEqual(realpath("a"), ABSTFN + "/y/a")
+                with support.change_cwd(ABSTFN + "/k"):
+                    self.assertEqual(realpath("a"), ABSTFN + "/y/a")
             finally:
-                os.chdir(old_path)
                 test_support.unlink(ABSTFN + "/k")
                 safe_rmdir(ABSTFN + "/y")
                 safe_rmdir(ABSTFN)
@@ -347,7 +342,6 @@
             # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
             # then realpath("link-y/..") should return 'k', not 'a'.
             try:
-                old_path = abspath('.')
                 os.mkdir(ABSTFN)
                 os.mkdir(ABSTFN + "/k")
                 os.mkdir(ABSTFN + "/k/y")
@@ -356,11 +350,10 @@
                 # Absolute path.
                 self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
                 # Relative path.
-                os.chdir(dirname(ABSTFN))
-                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
-                                 ABSTFN + "/k")
+                with support.change_cwd(dirname(ABSTFN)):
+                    self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
+                                     ABSTFN + "/k")
             finally:
-                os.chdir(old_path)
                 test_support.unlink(ABSTFN + "/link-y")
                 safe_rmdir(ABSTFN + "/k/y")
                 safe_rmdir(ABSTFN + "/k")
@@ -371,17 +364,14 @@
             # must be resolved too.
 
             try:
-                old_path = abspath('.')
                 os.mkdir(ABSTFN)
                 os.mkdir(ABSTFN + "/k")
                 os.symlink(ABSTFN, ABSTFN + "link")
-                os.chdir(dirname(ABSTFN))
-
-                base = basename(ABSTFN)
-                self.assertEqual(realpath(base + "link"), ABSTFN)
-                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
+                with support.change_cwd(dirname(ABSTFN)):
+                    base = basename(ABSTFN)
+                    self.assertEqual(realpath(base + "link"), ABSTFN)
+                    self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
             finally:
-                os.chdir(old_path)
                 test_support.unlink(ABSTFN + "link")
                 safe_rmdir(ABSTFN + "/k")
                 safe_rmdir(ABSTFN)
diff --git a/Lib/test/test_py_compile.py b/Lib/test/test_py_compile.py
--- a/Lib/test/test_py_compile.py
+++ b/Lib/test/test_py_compile.py
@@ -5,7 +5,7 @@
 import tempfile
 import unittest
 
-from test import test_support
+from test import test_support as support
 
 class PyCompileTests(unittest.TestCase):
 
@@ -35,11 +35,9 @@
         self.assertTrue(os.path.exists(self.pyc_path))
 
     def test_cwd(self):
-        cwd = os.getcwd()
-        os.chdir(self.directory)
-        py_compile.compile(os.path.basename(self.source_path),
-                           os.path.basename(self.pyc_path))
-        os.chdir(cwd)
+        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))
 
     def test_relative_path(self):
@@ -48,7 +46,7 @@
         self.assertTrue(os.path.exists(self.pyc_path))
 
 def test_main():
-    test_support.run_unittest(PyCompileTests)
+    support.run_unittest(PyCompileTests)
 
 if __name__ == "__main__":
     test_main()
diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py
--- a/Lib/test/test_shutil.py
+++ b/Lib/test/test_shutil.py
@@ -16,7 +16,7 @@
 import tarfile
 import warnings
 
-from test import test_support
+from test import test_support as support
 from test.test_support import TESTFN, check_warnings, captured_stdout
 
 TESTFN2 = TESTFN + "2"
@@ -389,12 +389,8 @@
         base_name = os.path.join(tmpdir2, 'archive')
 
         # working with relative paths to avoid tar warnings
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
+        with support.change_cwd(tmpdir):
             _make_tarball(splitdrive(base_name)[1], '.')
-        finally:
-            os.chdir(old_dir)
 
         # check if the compressed tarball was created
         tarball = base_name + '.tar.gz'
@@ -402,12 +398,8 @@
 
         # trying an uncompressed one
         base_name = os.path.join(tmpdir2, 'archive')
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
+        with support.change_cwd(tmpdir):
             _make_tarball(splitdrive(base_name)[1], '.', compress=None)
-        finally:
-            os.chdir(old_dir)
         tarball = base_name + '.tar'
         self.assertTrue(os.path.exists(tarball))
 
@@ -439,12 +431,8 @@
                          'Need the tar command to run')
     def test_tarfile_vs_tar(self):
         tmpdir, tmpdir2, base_name =  self._create_files()
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
+        with support.change_cwd(tmpdir):
             _make_tarball(base_name, 'dist')
-        finally:
-            os.chdir(old_dir)
 
         # check if the compressed tarball was created
         tarball = base_name + '.tar.gz'
@@ -454,14 +442,10 @@
         tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
         tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
         gzip_cmd = ['gzip', '-f9', 'archive2.tar']
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
+        with support.change_cwd(tmpdir):
             with captured_stdout() as s:
                 spawn(tar_cmd)
                 spawn(gzip_cmd)
-        finally:
-            os.chdir(old_dir)
 
         self.assertTrue(os.path.exists(tarball2))
         # let's compare both tarballs
@@ -469,23 +453,15 @@
 
         # trying an uncompressed one
         base_name = os.path.join(tmpdir2, 'archive')
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
+        with support.change_cwd(tmpdir):
             _make_tarball(base_name, 'dist', compress=None)
-        finally:
-            os.chdir(old_dir)
         tarball = base_name + '.tar'
         self.assertTrue(os.path.exists(tarball))
 
         # now for a dry_run
         base_name = os.path.join(tmpdir2, 'archive')
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
-        try:
+        with support.change_cwd(tmpdir):
             _make_tarball(base_name, 'dist', compress=None, dry_run=True)
-        finally:
-            os.chdir(old_dir)
         tarball = base_name + '.tar'
         self.assertTrue(os.path.exists(tarball))
 
@@ -544,15 +520,11 @@
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
     def test_tarfile_root_owner(self):
         tmpdir, tmpdir2, base_name =  self._create_files()
-        old_dir = os.getcwd()
-        os.chdir(tmpdir)
         group = grp.getgrgid(0)[0]
         owner = pwd.getpwuid(0)[0]
-        try:
+        with support.change_cwd(tmpdir):
             archive_name = _make_tarball(base_name, 'dist', compress=None,
                                          owner=owner, group=group)
-        finally:
-            os.chdir(old_dir)
 
         # check if the compressed tarball was created
         self.assertTrue(os.path.exists(archive_name))
@@ -889,7 +861,7 @@
 
 
 def test_main():
-    test_support.run_unittest(TestShutil, TestMove, TestCopyFile)
+    support.run_unittest(TestShutil, TestMove, TestCopyFile)
 
 if __name__ == '__main__':
     test_main()
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -669,6 +669,33 @@
 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)
+
+
+ at contextlib.contextmanager
 def temp_cwd(name='tempcwd', quiet=False):
     """
     Context manager that creates a temporary directory and set it as CWD.
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -11,6 +11,7 @@
 import tarfile
 
 from test import test_support
+from test import test_support as support
 
 # Check for our compression modules.
 try:
@@ -972,9 +973,7 @@
 
     def test_cwd(self):
         # Test adding the current working directory.
-        cwd = os.getcwd()
-        os.chdir(TEMPDIR)
-        try:
+        with support.change_cwd(TEMPDIR):
             open("foo", "w").close()
 
             tar = tarfile.open(tmpname, self.mode)
@@ -985,8 +984,6 @@
             for t in tar:
                 self.assertTrue(t.name == "." or t.name.startswith("./"))
             tar.close()
-        finally:
-            os.chdir(cwd)
 
     @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
     def test_extractall_symlinks(self):
diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py
--- a/Lib/test/test_unicode_file.py
+++ b/Lib/test/test_unicode_file.py
@@ -5,7 +5,7 @@
 import unicodedata
 
 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
 try:
     TESTFN_ENCODED = TESTFN_UNICODE.encode(TESTFN_ENCODING)
@@ -114,13 +114,11 @@
         os.unlink(filename1 + ".new")
 
     def _do_directory(self, make_name, chdir_name, encoded):
-        cwd = os.getcwd()
         if os.path.isdir(make_name):
             os.rmdir(make_name)
         os.mkdir(make_name)
         try:
-            os.chdir(chdir_name)
-            try:
+            with change_cwd(chdir_name):
                 if not encoded:
                     cwd_result = os.getcwdu()
                     name_result = make_name
@@ -132,8 +130,6 @@
                 name_result = unicodedata.normalize("NFD", name_result)
 
                 self.assertEqual(os.path.basename(cwd_result),name_result)
-            finally:
-                os.chdir(cwd)
         finally:
             os.rmdir(make_name)
 

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list