Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5517596

Browse files
committed
Close #15415: Factor out temp dir helpers to test.support
Patch by Chris Jerdonek
1 parent 69e3bda commit 5517596

7 files changed

Lines changed: 223 additions & 54 deletions

File tree

Doc/library/test.rst

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -387,18 +387,40 @@ The :mod:`test.support` module defines the following functions:
387387
self.assertEqual(captured, "hello")
388388

389389

390-
.. function:: temp_cwd(name='tempcwd', quiet=False, path=None)
390+
.. function:: temp_dir(path=None, quiet=False)
391+
392+
A context manager that creates a temporary directory at *path* and
393+
yields the directory.
394+
395+
If *path* is None, the temporary directory is created using
396+
:func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
397+
raises an exception on error. Otherwise, if *path* is specified and
398+
cannot be created, only a warning is issued.
399+
400+
401+
.. function:: change_cwd(path, quiet=False)
391402

392403
A context manager that temporarily changes the current working
393-
directory (CWD).
404+
directory to *path* and yields the directory.
405+
406+
If *quiet* is ``False``, the context manager raises an exception
407+
on error. Otherwise, it issues only a warning and keeps the current
408+
working directory the same.
409+
410+
411+
.. function:: temp_cwd(name='tempcwd', quiet=False)
412+
413+
A context manager that temporarily creates a new directory and
414+
changes the current working directory (CWD).
394415

395-
An existing path may be provided as *path*, in which case this function
396-
makes no changes to the file system.
416+
The context manager creates a temporary directory in the current
417+
directory with name *name* before temporarily changing the current
418+
working directory. If *name* is None, the temporary directory is
419+
created using :func:`tempfile.mkdtemp`.
397420

398-
Otherwise, the new CWD is created in the current directory and it's named
399-
*name*. If *quiet* is ``False`` and it's not possible to create or
400-
change the CWD, an error is raised. If it's ``True``, only a warning
401-
is raised and the original CWD is used.
421+
If *quiet* is ``False`` and it is not possible to create or change
422+
the CWD, an error is raised. Otherwise, only a warning is raised
423+
and the original CWD is used.
402424

403425

404426
.. function:: temp_umask(umask)

Lib/test/script_helper.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import zipfile
1414

1515
from imp import source_from_cache
16-
from test.support import make_legacy_pyc, strip_python_stderr
16+
from test.support import make_legacy_pyc, strip_python_stderr, temp_dir
1717

1818
# Executing the interpreter in a subprocess
1919
def _assert_python(expected_success, *args, **env_vars):
@@ -77,16 +77,6 @@ def kill_python(p):
7777
subprocess._cleanup()
7878
return data
7979

80-
# Script creation utilities
81-
@contextlib.contextmanager
82-
def temp_dir():
83-
dirname = tempfile.mkdtemp()
84-
dirname = os.path.realpath(dirname)
85-
try:
86-
yield dirname
87-
finally:
88-
shutil.rmtree(dirname)
89-
9080
def make_script(script_dir, script_basename, source):
9181
script_filename = script_basename+os.extsep+'py'
9282
script_name = os.path.join(script_dir, script_filename)

Lib/test/support/__init__.py

Lines changed: 58 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -738,45 +738,85 @@ def _is_ipv6_enabled():
738738
SAVEDCWD = os.getcwd()
739739

740740
@contextlib.contextmanager
741-
def temp_cwd(name='tempcwd', quiet=False, path=None):
742-
"""
743-
Context manager that temporarily changes the CWD.
741+
def temp_dir(path=None, quiet=False):
742+
"""Return a context manager that creates a temporary directory.
743+
744+
Arguments:
745+
746+
path: the directory to create temporarily. If omitted or None,
747+
defaults to creating a temporary directory using tempfile.mkdtemp.
744748
745-
An existing path may be provided as *path*, in which case this
746-
function makes no changes to the file system.
749+
quiet: if False (the default), the context manager raises an exception
750+
on error. Otherwise, if the path is specified and cannot be
751+
created, only a warning is issued.
747752
748-
Otherwise, the new CWD is created in the current directory and it's
749-
named *name*. If *quiet* is False (default) and it's not possible to
750-
create or change the CWD, an error is raised. If it's True, only a
751-
warning is raised and the original CWD is used.
752753
"""
753-
saved_dir = os.getcwd()
754-
is_temporary = False
754+
dir_created = False
755755
if path is None:
756-
path = name
756+
path = tempfile.mkdtemp()
757+
dir_created = True
758+
path = os.path.realpath(path)
759+
else:
757760
try:
758-
os.mkdir(name)
759-
is_temporary = True
761+
os.mkdir(path)
762+
dir_created = True
760763
except OSError:
761764
if not quiet:
762765
raise
763-
warnings.warn('tests may fail, unable to create temp CWD ' + name,
766+
warnings.warn('tests may fail, unable to create temp dir: ' + path,
764767
RuntimeWarning, stacklevel=3)
768+
try:
769+
yield path
770+
finally:
771+
if dir_created:
772+
shutil.rmtree(path)
773+
774+
@contextlib.contextmanager
775+
def change_cwd(path, quiet=False):
776+
"""Return a context manager that changes the current working directory.
777+
778+
Arguments:
779+
780+
path: the directory to use as the temporary current working directory.
781+
782+
quiet: if False (the default), the context manager raises an exception
783+
on error. Otherwise, it issues only a warning and keeps the current
784+
working directory the same.
785+
786+
"""
787+
saved_dir = os.getcwd()
765788
try:
766789
os.chdir(path)
767790
except OSError:
768791
if not quiet:
769792
raise
770-
warnings.warn('tests may fail, unable to change the CWD to ' + path,
793+
warnings.warn('tests may fail, unable to change CWD to: ' + path,
771794
RuntimeWarning, stacklevel=3)
772795
try:
773796
yield os.getcwd()
774797
finally:
775798
os.chdir(saved_dir)
776-
if is_temporary:
777-
rmtree(name)
778799

779800

801+
@contextlib.contextmanager
802+
def temp_cwd(name='tempcwd', quiet=False):
803+
"""
804+
Context manager that temporarily creates and changes the CWD.
805+
806+
The function temporarily changes the current working directory
807+
after creating a temporary directory in the current directory with
808+
name *name*. If *name* is None, the temporary directory is
809+
created using tempfile.mkdtemp.
810+
811+
If *quiet* is False (default) and it is not possible to
812+
create or change the CWD, an error is raised. If *quiet* is True,
813+
only a warning is raised and the original CWD is used.
814+
815+
"""
816+
with temp_dir(path=name, quiet=quiet) as temp_path:
817+
with change_cwd(temp_path, quiet=quiet) as cwd_dir:
818+
yield cwd_dir
819+
780820
if hasattr(os, "umask"):
781821
@contextlib.contextmanager
782822
def temp_umask(umask):

Lib/test/test_cmd_line_script.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def test_issue8202(self):
290290
# Make sure package __init__ modules see "-m" in sys.argv0 while
291291
# searching for the module to execute
292292
with temp_dir() as script_dir:
293-
with support.temp_cwd(path=script_dir):
293+
with support.change_cwd(path=script_dir):
294294
pkg_dir = os.path.join(script_dir, 'test_pkg')
295295
make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
296296
script_name = _make_test_script(pkg_dir, 'script')
@@ -307,7 +307,7 @@ def test_issue8202_dash_c_file_ignored(self):
307307
# Make sure a "-c" file in the current directory
308308
# does not alter the value of sys.path[0]
309309
with temp_dir() as script_dir:
310-
with support.temp_cwd(path=script_dir):
310+
with support.change_cwd(path=script_dir):
311311
with open("-c", "w") as f:
312312
f.write("data")
313313
rc, out, err = assert_python_ok('-c',
@@ -322,7 +322,7 @@ def test_issue8202_dash_m_file_ignored(self):
322322
# does not alter the value of sys.path[0]
323323
with temp_dir() as script_dir:
324324
script_name = _make_test_script(script_dir, 'other')
325-
with support.temp_cwd(path=script_dir):
325+
with support.change_cwd(path=script_dir):
326326
with open("-m", "w") as f:
327327
f.write("data")
328328
rc, out, err = assert_python_ok('-m', 'other', *example_args)
@@ -335,7 +335,7 @@ def test_dash_m_error_code_is_one(self):
335335
# and results in an error that the return code to the
336336
# shell is '1'
337337
with temp_dir() as script_dir:
338-
with support.temp_cwd(path=script_dir):
338+
with support.change_cwd(path=script_dir):
339339
pkg_dir = os.path.join(script_dir, 'test_pkg')
340340
make_pkg(pkg_dir)
341341
script_name = _make_test_script(pkg_dir, 'other',

Lib/test/test_shutil.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1307,18 +1307,18 @@ def test_relative_cmd(self):
13071307
# that exists, it should be returned.
13081308
base_dir, tail_dir = os.path.split(self.dir)
13091309
relpath = os.path.join(tail_dir, self.file)
1310-
with support.temp_cwd(path=base_dir):
1310+
with support.change_cwd(path=base_dir):
13111311
rv = shutil.which(relpath, path=self.temp_dir)
13121312
self.assertEqual(rv, relpath)
13131313
# But it shouldn't be searched in PATH directories (issue #16957).
1314-
with support.temp_cwd(path=self.dir):
1314+
with support.change_cwd(path=self.dir):
13151315
rv = shutil.which(relpath, path=base_dir)
13161316
self.assertIsNone(rv)
13171317

13181318
def test_cwd(self):
13191319
# Issue #16957
13201320
base_dir = os.path.dirname(self.dir)
1321-
with support.temp_cwd(path=self.dir):
1321+
with support.change_cwd(path=self.dir):
13221322
rv = shutil.which(self.file, path=base_dir)
13231323
if sys.platform == "win32":
13241324
# Windows: current directory implicitly on PATH
@@ -1339,7 +1339,7 @@ def test_non_matching_mode(self):
13391339

13401340
def test_relative_path(self):
13411341
base_dir, tail_dir = os.path.split(self.dir)
1342-
with support.temp_cwd(path=base_dir):
1342+
with support.change_cwd(path=base_dir):
13431343
rv = shutil.which(self.file, path=tail_dir)
13441344
self.assertEqual(rv, os.path.join(tail_dir, self.file))
13451345

@@ -1364,7 +1364,7 @@ def test_environ_path(self):
13641364

13651365
def test_empty_path(self):
13661366
base_dir = os.path.dirname(self.dir)
1367-
with support.temp_cwd(path=self.dir), \
1367+
with support.change_cwd(path=self.dir), \
13681368
support.EnvironmentVarGuard() as env:
13691369
env['PATH'] = self.dir
13701370
rv = shutil.which(self.file, path='')

0 commit comments

Comments
 (0)