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

Skip to content

Commit cf67b2a

Browse files
committed
Merge #15415 from 3.3
2 parents b8de598 + 5517596 commit cf67b2a

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 importlib.util 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
@@ -740,45 +740,85 @@ def _is_ipv6_enabled():
740740
SAVEDCWD = os.getcwd()
741741

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

781802

803+
@contextlib.contextmanager
804+
def temp_cwd(name='tempcwd', quiet=False):
805+
"""
806+
Context manager that temporarily creates and changes the CWD.
807+
808+
The function temporarily changes the current working directory
809+
after creating a temporary directory in the current directory with
810+
name *name*. If *name* is None, the temporary directory is
811+
created using tempfile.mkdtemp.
812+
813+
If *quiet* is False (default) and it is not possible to
814+
create or change the CWD, an error is raised. If *quiet* is True,
815+
only a warning is raised and the original CWD is used.
816+
817+
"""
818+
with temp_dir(path=name, quiet=quiet) as temp_path:
819+
with change_cwd(temp_path, quiet=quiet) as cwd_dir:
820+
yield cwd_dir
821+
782822
if hasattr(os, "umask"):
783823
@contextlib.contextmanager
784824
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
@@ -1318,18 +1318,18 @@ def test_relative_cmd(self):
13181318
# that exists, it should be returned.
13191319
base_dir, tail_dir = os.path.split(self.dir)
13201320
relpath = os.path.join(tail_dir, self.file)
1321-
with support.temp_cwd(path=base_dir):
1321+
with support.change_cwd(path=base_dir):
13221322
rv = shutil.which(relpath, path=self.temp_dir)
13231323
self.assertEqual(rv, relpath)
13241324
# But it shouldn't be searched in PATH directories (issue #16957).
1325-
with support.temp_cwd(path=self.dir):
1325+
with support.change_cwd(path=self.dir):
13261326
rv = shutil.which(relpath, path=base_dir)
13271327
self.assertIsNone(rv)
13281328

13291329
def test_cwd(self):
13301330
# Issue #16957
13311331
base_dir = os.path.dirname(self.dir)
1332-
with support.temp_cwd(path=self.dir):
1332+
with support.change_cwd(path=self.dir):
13331333
rv = shutil.which(self.file, path=base_dir)
13341334
if sys.platform == "win32":
13351335
# Windows: current directory implicitly on PATH
@@ -1350,7 +1350,7 @@ def test_non_matching_mode(self):
13501350

13511351
def test_relative_path(self):
13521352
base_dir, tail_dir = os.path.split(self.dir)
1353-
with support.temp_cwd(path=base_dir):
1353+
with support.change_cwd(path=base_dir):
13541354
rv = shutil.which(self.file, path=tail_dir)
13551355
self.assertEqual(rv, os.path.join(tail_dir, self.file))
13561356

@@ -1375,7 +1375,7 @@ def test_environ_path(self):
13751375

13761376
def test_empty_path(self):
13771377
base_dir = os.path.dirname(self.dir)
1378-
with support.temp_cwd(path=self.dir), \
1378+
with support.change_cwd(path=self.dir), \
13791379
support.EnvironmentVarGuard() as env:
13801380
env['PATH'] = self.dir
13811381
rv = shutil.which(self.file, path='')

0 commit comments

Comments
 (0)