summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/test_cgi.py18
-rw-r--r--Lib/test/test_collections.py12
-rw-r--r--Lib/test/test_configparser.py7
-rw-r--r--Lib/test/test_functools.py18
-rw-r--r--Lib/test/test_gdb.py52
-rw-r--r--Lib/test/test_glob.py6
-rw-r--r--Lib/test/test_htmlparser.py15
-rw-r--r--Lib/test/test_mmap.py5
-rw-r--r--Lib/test/test_pdb.py12
-rw-r--r--Lib/test/test_pep277.py8
-rw-r--r--Lib/test/test_posixpath.py37
-rw-r--r--Lib/test/test_py_compile.py8
-rw-r--r--Lib/test/test_shutil.py200
-rw-r--r--Lib/test/test_subprocess.py7
-rw-r--r--Lib/test/test_sysconfig.py8
-rw-r--r--Lib/test/test_tarfile.py12
-rw-r--r--Lib/test/test_unicode_file.py8
-rw-r--r--Lib/test/test_wsgiref.py5
18 files changed, 225 insertions, 213 deletions
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py
index a7a9d02..ab9f6ab 100644
--- a/Lib/test/test_cgi.py
+++ b/Lib/test/test_cgi.py
@@ -326,6 +326,24 @@ Content-Type: text/plain
got = getattr(files[x], k)
self.assertEqual(got, exp)
+ def test_fieldstorage_part_content_length(self):
+ BOUNDARY = "JfISa01"
+ POSTDATA = """--JfISa01
+Content-Disposition: form-data; name="submit-name"
+Content-Length: 5
+
+Larry
+--JfISa01"""
+ env = {
+ 'REQUEST_METHOD': 'POST',
+ 'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
+ 'CONTENT_LENGTH': str(len(POSTDATA))}
+ fp = BytesIO(POSTDATA.encode('latin-1'))
+ fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
+ self.assertEqual(len(fs.list), 1)
+ self.assertEqual(fs.list[0].name, 'submit-name')
+ self.assertEqual(fs.list[0].value, 'Larry')
+
def test_fieldstorage_as_context_manager(self):
fp = BytesIO(b'x' * 10)
env = {'REQUEST_METHOD': 'PUT'}
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index c2d03ee..4124f91 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -257,7 +257,6 @@ class TestNamedTuple(unittest.TestCase):
self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method
- self.assertEqual(vars(p), p._asdict()) # verify that vars() works
try:
p._replace(x=1, error=2)
@@ -412,6 +411,17 @@ class TestNamedTuple(unittest.TestCase):
globals().pop('NTColor', None) # clean-up after this test
+ def test_namedtuple_subclass_issue_24931(self):
+ class Point(namedtuple('_Point', ['x', 'y'])):
+ pass
+
+ a = Point(3, 4)
+ self.assertEqual(a._asdict(), OrderedDict([('x', 3), ('y', 4)]))
+
+ a.w = 5
+ self.assertEqual(a.__dict__, {'w': 5})
+
+
################################################################################
### Abstract Base Classes
################################################################################
diff --git a/Lib/test/test_configparser.py b/Lib/test/test_configparser.py
index 470d2cd..71a8f3f 100644
--- a/Lib/test/test_configparser.py
+++ b/Lib/test/test_configparser.py
@@ -847,7 +847,8 @@ class ConfigParserTestCase(BasicTestCase, unittest.TestCase):
"something with lots of interpolation (10 steps)")
e = self.get_error(cf, configparser.InterpolationDepthError, "Foo", "bar11")
if self.interpolation == configparser._UNSET:
- self.assertEqual(e.args, ("bar11", "Foo", "%(with1)s"))
+ self.assertEqual(e.args, ("bar11", "Foo",
+ "something %(with11)s lots of interpolation (11 steps)"))
elif isinstance(self.interpolation, configparser.LegacyInterpolation):
self.assertEqual(e.args, ("bar11", "Foo",
"something %(with11)s lots of interpolation (11 steps)"))
@@ -861,7 +862,7 @@ class ConfigParserTestCase(BasicTestCase, unittest.TestCase):
self.assertEqual(e.option, "name")
if self.interpolation == configparser._UNSET:
self.assertEqual(e.args, ('name', 'Interpolation Error',
- '', 'reference'))
+ '%(reference)s', 'reference'))
elif isinstance(self.interpolation, configparser.LegacyInterpolation):
self.assertEqual(e.args, ('name', 'Interpolation Error',
'%(reference)s', 'reference'))
@@ -1177,7 +1178,7 @@ class ConfigParserTestCaseExtendedInterpolation(BasicTestCase, unittest.TestCase
with self.assertRaises(exception_class) as cm:
cf['interpolated']['$trying']
self.assertEqual(cm.exception.reference, 'dollars:${sick')
- self.assertEqual(cm.exception.args[2], '}') #rawval
+ self.assertEqual(cm.exception.args[2], '${dollars:${sick}}') #rawval
def test_case_sensitivity_basic(self):
ini = textwrap.dedent("""
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index ac211c4..ae929ec 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -1491,6 +1491,24 @@ class TestSingleDispatch(unittest.TestCase):
many_abcs = [c.Mapping, c.Sized, c.Callable, c.Container, c.Iterable]
self.assertEqual(mro(X, abcs=many_abcs), expected)
+ def test_false_meta(self):
+ # see issue23572
+ class MetaA(type):
+ def __len__(self):
+ return 0
+ class A(metaclass=MetaA):
+ pass
+ class AA(A):
+ pass
+ @functools.singledispatch
+ def fun(a):
+ return 'base A'
+ @fun.register(A)
+ def _(a):
+ return 'fun A'
+ aa = AA()
+ self.assertEqual(fun(aa), 'fun A')
+
def test_mro_conflicts(self):
c = collections
@functools.singledispatch
diff --git a/Lib/test/test_gdb.py b/Lib/test/test_gdb.py
index 0322677..db777be 100644
--- a/Lib/test/test_gdb.py
+++ b/Lib/test/test_gdb.py
@@ -21,19 +21,34 @@ except ImportError:
from test import support
from test.support import run_unittest, findfile, python_is_optimized
-try:
- gdb_version, _ = subprocess.Popen(["gdb", "-nx", "--version"],
- stdout=subprocess.PIPE).communicate()
-except OSError:
- # This is what "no gdb" looks like. There may, however, be other
- # errors that manifest this way too.
- raise unittest.SkipTest("Couldn't find gdb on the path")
-gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.(\d)", gdb_version)
-gdb_major_version = int(gdb_version_number.group(1))
-gdb_minor_version = int(gdb_version_number.group(2))
+def get_gdb_version():
+ try:
+ proc = subprocess.Popen(["gdb", "-nx", "--version"],
+ stdout=subprocess.PIPE,
+ universal_newlines=True)
+ with proc:
+ version = proc.communicate()[0]
+ except OSError:
+ # This is what "no gdb" looks like. There may, however, be other
+ # errors that manifest this way too.
+ raise unittest.SkipTest("Couldn't find gdb on the path")
+
+ # Regex to parse:
+ # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
+ # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
+ # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
+ # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
+ match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d)", version)
+ if match is None:
+ raise Exception("unable to parse GDB version: %r" % version)
+ return (version, int(match.group(1)), int(match.group(2)))
+
+gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
if gdb_major_version < 7:
- raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
- " Saw:\n" + gdb_version.decode('ascii', 'replace'))
+ raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
+ "embedding. Saw %s.%s:\n%s"
+ % (gdb_major_version, gdb_minor_version,
+ gdb_version))
if not sysconfig.is_python_build():
raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
@@ -59,9 +74,12 @@ def run_gdb(*args, **env_vars):
base_cmd = ('gdb', '--batch', '-nx')
if (gdb_major_version, gdb_minor_version) >= (7, 4):
base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
- out, err = subprocess.Popen(base_cmd + args,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
- ).communicate()
+ proc = subprocess.Popen(base_cmd + args,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env)
+ with proc:
+ out, err = proc.communicate()
return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
# Verify that "gdb" was built with the embedded python support enabled:
@@ -880,8 +898,8 @@ class PyLocalsTests(DebuggerTests):
def test_main():
if support.verbose:
- print("GDB version:")
- for line in os.fsdecode(gdb_version).splitlines():
+ print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
+ for line in gdb_version.splitlines():
print(" " * 4 + line)
run_unittest(PrettyPrintTests,
PyListTests,
diff --git a/Lib/test/test_glob.py b/Lib/test/test_glob.py
index 21b0153..926588e 100644
--- a/Lib/test/test_glob.py
+++ b/Lib/test/test_glob.py
@@ -242,9 +242,7 @@ class GlobTests(unittest.TestCase):
('a', 'bcd', 'EF'), ('a', 'bcd', 'efg')))
eq(self.rglob('a', '**', 'bcd'), self.joins(('a', 'bcd')))
- predir = os.path.abspath(os.curdir)
- try:
- os.chdir(self.tempdir)
+ 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),
@@ -256,8 +254,6 @@ class GlobTests(unittest.TestCase):
if can_symlink():
expect += [join('sym3', 'EF')]
eq(glob.glob(join('**', 'EF'), recursive=True), expect)
- finally:
- os.chdir(predir)
@skip_unless_symlink
diff --git a/Lib/test/test_htmlparser.py b/Lib/test/test_htmlparser.py
index de8f3e8..11420b2c 100644
--- a/Lib/test/test_htmlparser.py
+++ b/Lib/test/test_htmlparser.py
@@ -72,9 +72,6 @@ class EventCollectorExtra(EventCollector):
class EventCollectorCharrefs(EventCollector):
- def get_events(self):
- return self.events
-
def handle_charref(self, data):
self.fail('This should never be called with convert_charrefs=True')
@@ -633,6 +630,18 @@ text
]
self._run_check(html, expected)
+ def test_convert_charrefs_dropped_text(self):
+ # #23144: make sure that all the events are triggered when
+ # convert_charrefs is True, even if we don't call .close()
+ parser = EventCollector(convert_charrefs=True)
+ # before the fix, bar & baz was missing
+ parser.feed("foo <a>link</a> bar &amp; baz")
+ self.assertEqual(
+ parser.get_events(),
+ [('data', 'foo '), ('starttag', 'a', []), ('data', 'link'),
+ ('endtag', 'a'), ('data', ' bar & baz')]
+ )
+
class AttributesTestCase(TestCaseBase):
diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py
index 3de84e8..0f25742 100644
--- a/Lib/test/test_mmap.py
+++ b/Lib/test/test_mmap.py
@@ -731,7 +731,10 @@ class LargeMmapTests(unittest.TestCase):
f.write(tail)
f.flush()
except (OSError, OverflowError):
- f.close()
+ try:
+ f.close()
+ except (OSError, OverflowError):
+ pass
raise unittest.SkipTest("filesystem does not have largefile support")
return f
diff --git a/Lib/test/test_pdb.py b/Lib/test/test_pdb.py
index ec8346c..35044ad 100644
--- a/Lib/test/test_pdb.py
+++ b/Lib/test/test_pdb.py
@@ -1043,6 +1043,18 @@ class PdbTestCase(unittest.TestCase):
self.assertNotIn('Error', stdout.decode(),
"Got an error running test script under PDB")
+ def test_issue16180(self):
+ # A syntax error in the debuggee.
+ script = "def f: pass\n"
+ commands = ''
+ expected = "SyntaxError:"
+ stdout, stderr = self.run_pdb(script, commands)
+ self.assertIn(expected, stdout,
+ '\n\nExpected:\n{}\nGot:\n{}\n'
+ 'Fail to handle a syntax error in the debuggee.'
+ .format(expected, stdout))
+
+
def tearDown(self):
support.unlink(support.TESTFN)
diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py
index 6c833a8..98c716b 100644
--- a/Lib/test/test_pep277.py
+++ b/Lib/test/test_pep277.py
@@ -158,17 +158,11 @@ class UnicodeFileTests(unittest.TestCase):
def test_directory(self):
dirname = os.path.join(support.TESTFN, 'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
filename = '\xdf-\u66e8\u66e9\u66eb'
- oldwd = os.getcwd()
- os.mkdir(dirname)
- os.chdir(dirname)
- try:
+ with support.temp_cwd(dirname):
with open(filename, 'wb') 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
index ece3555..9d20471 100644
--- a/Lib/test/test_posixpath.py
+++ b/Lib/test/test_posixpath.py
@@ -316,7 +316,6 @@ class PosixPathTest(unittest.TestCase):
# 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)
@@ -342,10 +341,9 @@ class PosixPathTest(unittest.TestCase):
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)
support.unlink(ABSTFN)
support.unlink(ABSTFN+"1")
support.unlink(ABSTFN+"2")
@@ -373,7 +371,6 @@ class PosixPathTest(unittest.TestCase):
@skip_if_ABSTFN_contains_backslash
def test_realpath_deep_recursion(self):
depth = 10
- old_path = abspath('.')
try:
os.mkdir(ABSTFN)
for i in range(depth):
@@ -382,10 +379,9 @@ class PosixPathTest(unittest.TestCase):
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):
support.unlink(ABSTFN + '/%d' % i)
safe_rmdir(ABSTFN)
@@ -399,15 +395,13 @@ class PosixPathTest(unittest.TestCase):
# /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)
support.unlink(ABSTFN + "/k")
safe_rmdir(ABSTFN + "/y")
safe_rmdir(ABSTFN)
@@ -424,7 +418,6 @@ class PosixPathTest(unittest.TestCase):
# 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")
@@ -433,11 +426,10 @@ class PosixPathTest(unittest.TestCase):
# 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)
support.unlink(ABSTFN + "/link-y")
safe_rmdir(ABSTFN + "/k/y")
safe_rmdir(ABSTFN + "/k")
@@ -451,17 +443,14 @@ class PosixPathTest(unittest.TestCase):
# 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)
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
index 03cca5d..4a6caa5 100644
--- a/Lib/test/test_py_compile.py
+++ b/Lib/test/test_py_compile.py
@@ -63,11 +63,9 @@ class PyCompileTests(unittest.TestCase):
self.assertTrue(os.path.exists(self.cache_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))
self.assertFalse(os.path.exists(self.cache_path))
diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py
index 5183c3c..1c14b5c 100644
--- a/Lib/test/test_shutil.py
+++ b/Lib/test/test_shutil.py
@@ -12,11 +12,9 @@ import errno
import functools
import subprocess
from contextlib import ExitStack
-from test import support
-from test.support import TESTFN
from os.path import splitdrive
from distutils.spawn import find_executable, spawn
-from shutil import (_make_tarball, _make_zipfile, make_archive,
+from shutil import (make_archive,
register_archive_format, unregister_archive_format,
get_archive_formats, Error, unpack_archive,
register_unpack_format, RegistryError,
@@ -94,6 +92,18 @@ def read_file(path, binary=False):
with open(path, 'rb' if binary else 'r') as fp:
return fp.read()
+def rlistdir(path):
+ res = []
+ for name in sorted(os.listdir(path)):
+ p = os.path.join(path, name)
+ if os.path.isdir(p) and not os.path.islink(p):
+ res.append(name + '/')
+ for n in rlistdir(p):
+ res.append(name + '/' + n)
+ else:
+ res.append(name)
+ return res
+
class TestShutil(unittest.TestCase):
@@ -959,138 +969,105 @@ class TestShutil(unittest.TestCase):
@requires_zlib
def test_make_tarball(self):
# creating something to tar
- tmpdir = self.mkdtemp()
- write_file((tmpdir, 'file1'), 'xxx')
- write_file((tmpdir, 'file2'), 'xxx')
- os.mkdir(os.path.join(tmpdir, 'sub'))
- write_file((tmpdir, 'sub', 'file3'), 'xxx')
+ root_dir, base_dir = self._create_files('')
tmpdir2 = self.mkdtemp()
# force shutil to create the directory
os.rmdir(tmpdir2)
- unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
+ unittest.skipUnless(splitdrive(root_dir)[0] == splitdrive(tmpdir2)[0],
"source and target should be on same drive")
base_name = os.path.join(tmpdir2, 'archive')
# working with relative paths to avoid tar warnings
- old_dir = os.getcwd()
- os.chdir(tmpdir)
- try:
- _make_tarball(splitdrive(base_name)[1], '.')
- finally:
- os.chdir(old_dir)
+ make_archive(splitdrive(base_name)[1], 'gztar', root_dir, '.')
# check if the compressed tarball was created
tarball = base_name + '.tar.gz'
- self.assertTrue(os.path.exists(tarball))
+ self.assertTrue(os.path.isfile(tarball))
+ self.assertTrue(tarfile.is_tarfile(tarball))
+ with tarfile.open(tarball, 'r:gz') as tf:
+ self.assertCountEqual(tf.getnames(),
+ ['.', './sub', './sub2',
+ './file1', './file2', './sub/file3'])
# trying an uncompressed one
base_name = os.path.join(tmpdir2, 'archive')
- old_dir = os.getcwd()
- os.chdir(tmpdir)
- try:
- _make_tarball(splitdrive(base_name)[1], '.', compress=None)
- finally:
- os.chdir(old_dir)
+ make_archive(splitdrive(base_name)[1], 'tar', root_dir, '.')
tarball = base_name + '.tar'
- self.assertTrue(os.path.exists(tarball))
+ self.assertTrue(os.path.isfile(tarball))
+ self.assertTrue(tarfile.is_tarfile(tarball))
+ with tarfile.open(tarball, 'r') as tf:
+ self.assertCountEqual(tf.getnames(),
+ ['.', './sub', './sub2',
+ './file1', './file2', './sub/file3'])
def _tarinfo(self, path):
- tar = tarfile.open(path)
- try:
+ with tarfile.open(path) as tar:
names = tar.getnames()
names.sort()
return tuple(names)
- finally:
- tar.close()
- def _create_files(self):
+ def _create_files(self, base_dir='dist'):
# creating something to tar
- tmpdir = self.mkdtemp()
- dist = os.path.join(tmpdir, 'dist')
- os.mkdir(dist)
+ root_dir = self.mkdtemp()
+ dist = os.path.join(root_dir, base_dir)
+ os.makedirs(dist, exist_ok=True)
write_file((dist, 'file1'), 'xxx')
write_file((dist, 'file2'), 'xxx')
os.mkdir(os.path.join(dist, 'sub'))
write_file((dist, 'sub', 'file3'), 'xxx')
os.mkdir(os.path.join(dist, 'sub2'))
- tmpdir2 = self.mkdtemp()
- base_name = os.path.join(tmpdir2, 'archive')
- return tmpdir, tmpdir2, base_name
+ if base_dir:
+ write_file((root_dir, 'outer'), 'xxx')
+ return root_dir, base_dir
@requires_zlib
- @unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
+ @unittest.skipUnless(find_executable('tar'),
'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:
- _make_tarball(base_name, 'dist')
- finally:
- os.chdir(old_dir)
+ root_dir, base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
+ make_archive(base_name, 'gztar', root_dir, base_dir)
# check if the compressed tarball was created
tarball = base_name + '.tar.gz'
- self.assertTrue(os.path.exists(tarball))
+ self.assertTrue(os.path.isfile(tarball))
# now create another tarball using `tar`
- 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 captured_stdout() as s:
- spawn(tar_cmd)
- spawn(gzip_cmd)
- finally:
- os.chdir(old_dir)
+ tarball2 = os.path.join(root_dir, 'archive2.tar')
+ tar_cmd = ['tar', '-cf', 'archive2.tar', base_dir]
+ with support.change_cwd(root_dir), captured_stdout():
+ spawn(tar_cmd)
- self.assertTrue(os.path.exists(tarball2))
+ self.assertTrue(os.path.isfile(tarball2))
# let's compare both tarballs
self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
# trying an uncompressed one
- base_name = os.path.join(tmpdir2, 'archive')
- old_dir = os.getcwd()
- os.chdir(tmpdir)
- try:
- _make_tarball(base_name, 'dist', compress=None)
- finally:
- os.chdir(old_dir)
+ make_archive(base_name, 'tar', root_dir, base_dir)
tarball = base_name + '.tar'
- self.assertTrue(os.path.exists(tarball))
+ self.assertTrue(os.path.isfile(tarball))
# now for a dry_run
- base_name = os.path.join(tmpdir2, 'archive')
- old_dir = os.getcwd()
- os.chdir(tmpdir)
- try:
- _make_tarball(base_name, 'dist', compress=None, dry_run=True)
- finally:
- os.chdir(old_dir)
+ make_archive(base_name, 'tar', root_dir, base_dir, dry_run=True)
tarball = base_name + '.tar'
- self.assertTrue(os.path.exists(tarball))
+ self.assertTrue(os.path.isfile(tarball))
@requires_zlib
@unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
def test_make_zipfile(self):
- # creating something to tar
- tmpdir = self.mkdtemp()
- write_file((tmpdir, 'file1'), 'xxx')
- write_file((tmpdir, 'file2'), 'xxx')
+ # creating something to zip
+ root_dir, base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
+ res = make_archive(base_name, 'zip', root_dir, 'dist')
- tmpdir2 = self.mkdtemp()
- # force shutil to create the directory
- os.rmdir(tmpdir2)
- base_name = os.path.join(tmpdir2, 'archive')
- _make_zipfile(base_name, tmpdir)
-
- # check if the compressed tarball was created
- tarball = base_name + '.zip'
- self.assertTrue(os.path.exists(tarball))
+ self.assertEqual(res, base_name + '.zip')
+ self.assertTrue(os.path.isfile(res))
+ self.assertTrue(zipfile.is_zipfile(res))
+ with zipfile.ZipFile(res) as zf:
+ self.assertCountEqual(zf.namelist(),
+ ['dist/file1', 'dist/file2', 'dist/sub/file3'])
def test_make_archive(self):
@@ -1108,40 +1085,37 @@ class TestShutil(unittest.TestCase):
else:
group = owner = 'root'
- base_dir, root_dir, base_name = self._create_files()
- base_name = os.path.join(self.mkdtemp() , 'archive')
+ root_dir, base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
group=group)
- self.assertTrue(os.path.exists(res))
+ self.assertTrue(os.path.isfile(res))
res = make_archive(base_name, 'zip', root_dir, base_dir)
- self.assertTrue(os.path.exists(res))
+ self.assertTrue(os.path.isfile(res))
res = make_archive(base_name, 'tar', root_dir, base_dir,
owner=owner, group=group)
- self.assertTrue(os.path.exists(res))
+ self.assertTrue(os.path.isfile(res))
res = make_archive(base_name, 'tar', root_dir, base_dir,
owner='kjhkjhkjg', group='oihohoh')
- self.assertTrue(os.path.exists(res))
+ self.assertTrue(os.path.isfile(res))
@requires_zlib
@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)
+ root_dir, base_dir = self._create_files()
+ base_name = os.path.join(self.mkdtemp(), 'archive')
group = grp.getgrgid(0)[0]
owner = pwd.getpwuid(0)[0]
- try:
- archive_name = _make_tarball(base_name, 'dist', compress=None,
- owner=owner, group=group)
- finally:
- os.chdir(old_dir)
+ with support.change_cwd(root_dir):
+ archive_name = make_archive(base_name, 'gztar', root_dir, 'dist',
+ owner=owner, group=group)
# check if the compressed tarball was created
- self.assertTrue(os.path.exists(archive_name))
+ self.assertTrue(os.path.isfile(archive_name))
# now checks the rights
archive = tarfile.open(archive_name)
@@ -1198,18 +1172,6 @@ class TestShutil(unittest.TestCase):
formats = [name for name, params in get_archive_formats()]
self.assertNotIn('xxx', formats)
- def _compare_dirs(self, dir1, dir2):
- # check that dir1 and dir2 are equivalent,
- # return the diff
- diff = []
- for root, dirs, files in os.walk(dir1):
- for file_ in files:
- path = os.path.join(root, file_)
- target_path = os.path.join(dir2, os.path.split(path)[-1])
- if not os.path.exists(target_path):
- diff.append(file_)
- return diff
-
@requires_zlib
def test_unpack_archive(self):
formats = ['tar', 'gztar', 'zip']
@@ -1218,22 +1180,24 @@ class TestShutil(unittest.TestCase):
if LZMA_SUPPORTED:
formats.append('xztar')
+ root_dir, base_dir = self._create_files()
for format in formats:
- tmpdir = self.mkdtemp()
- base_dir, root_dir, base_name = self._create_files()
- tmpdir2 = self.mkdtemp()
+ expected = rlistdir(root_dir)
+ expected.remove('outer')
+ if format == 'zip':
+ expected.remove('dist/sub2/')
+ base_name = os.path.join(self.mkdtemp(), 'archive')
filename = make_archive(base_name, format, root_dir, base_dir)
# let's try to unpack it now
+ tmpdir2 = self.mkdtemp()
unpack_archive(filename, tmpdir2)
- diff = self._compare_dirs(tmpdir, tmpdir2)
- self.assertEqual(diff, [])
+ self.assertEqual(rlistdir(tmpdir2), expected)
# and again, this time with the format specified
tmpdir3 = self.mkdtemp()
unpack_archive(filename, tmpdir3, format=format)
- diff = self._compare_dirs(tmpdir, tmpdir3)
- self.assertEqual(diff, [])
+ self.assertEqual(rlistdir(tmpdir3), expected)
self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py
index 9c0229a..ff2010d 100644
--- a/Lib/test/test_subprocess.py
+++ b/Lib/test/test_subprocess.py
@@ -317,11 +317,8 @@ class ProcessTestCase(BaseTestCase):
# Normalize an expected cwd (for Tru64 support).
# We can't use os.path.realpath since it doesn't expand Tru64 {memb}
# strings. See bug #1063571.
- original_cwd = os.getcwd()
- os.chdir(cwd)
- cwd = os.getcwd()
- os.chdir(original_cwd)
- return cwd
+ with support.change_cwd(cwd):
+ return os.getcwd()
# For use in the test_cwd* tests below.
def _split_python_path(self):
diff --git a/Lib/test/test_sysconfig.py b/Lib/test/test_sysconfig.py
index c0f27a6..0917c3e 100644
--- a/Lib/test/test_sysconfig.py
+++ b/Lib/test/test_sysconfig.py
@@ -6,7 +6,7 @@ import shutil
from copy import copy
from test.support import (run_unittest, TESTFN, unlink, check_warnings,
- captured_stdout, skip_unless_symlink)
+ captured_stdout, skip_unless_symlink, change_cwd)
import sysconfig
from sysconfig import (get_paths, get_platform, get_config_vars,
@@ -361,12 +361,8 @@ class TestSysConfig(unittest.TestCase):
# srcdir should be independent of the current working directory
# See Issues #15322, #15364.
srcdir = sysconfig.get_config_var('srcdir')
- cwd = os.getcwd()
- try:
- os.chdir('..')
+ with change_cwd(os.pardir):
srcdir2 = sysconfig.get_config_var('srcdir')
- finally:
- os.chdir(cwd)
self.assertEqual(srcdir, srcdir2)
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
index 57cddb2..1412cae 100644
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -1132,10 +1132,8 @@ class WriteTest(WriteTestBase, unittest.TestCase):
self.assertEqual(tar.getnames(), [],
"added the archive to itself")
- cwd = os.getcwd()
- os.chdir(TEMPDIR)
- tar.add(dstname)
- os.chdir(cwd)
+ with support.change_cwd(TEMPDIR):
+ tar.add(dstname)
self.assertEqual(tar.getnames(), [],
"added the archive to itself")
finally:
@@ -1292,9 +1290,7 @@ class WriteTest(WriteTestBase, unittest.TestCase):
def test_cwd(self):
# Test adding the current working directory.
- cwd = os.getcwd()
- os.chdir(TEMPDIR)
- try:
+ with support.change_cwd(TEMPDIR):
tar = tarfile.open(tmpname, self.mode)
try:
tar.add(".")
@@ -1308,8 +1304,6 @@ class WriteTest(WriteTestBase, unittest.TestCase):
self.assertTrue(t.name.startswith("./"), t.name)
finally:
tar.close()
- finally:
- os.chdir(cwd)
def test_open_nonwritable_fileobj(self):
for exctype in OSError, EOFError, RuntimeError:
diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py
index faa8da3..e4709a1 100644
--- a/Lib/test/test_unicode_file.py
+++ b/Lib/test/test_unicode_file.py
@@ -5,7 +5,7 @@ import os, glob, time, shutil
import unicodedata
import unittest
-from test.support import (run_unittest, rmtree,
+from test.support import (run_unittest, rmtree, change_cwd,
TESTFN_ENCODING, TESTFN_UNICODE, TESTFN_UNENCODABLE, create_empty_file)
if not os.path.supports_unicode_filenames:
@@ -82,13 +82,11 @@ class TestUnicodeFiles(unittest.TestCase):
self.assertFalse(os.path.exists(filename2 + '.new'))
def _do_directory(self, make_name, chdir_name):
- cwd = os.getcwd()
if os.path.isdir(make_name):
rmtree(make_name)
os.mkdir(make_name)
try:
- os.chdir(chdir_name)
- try:
+ with change_cwd(chdir_name):
cwd_result = os.getcwd()
name_result = make_name
@@ -96,8 +94,6 @@ class TestUnicodeFiles(unittest.TestCase):
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)
diff --git a/Lib/test/test_wsgiref.py b/Lib/test/test_wsgiref.py
index 112a1b9..8cca595 100644
--- a/Lib/test/test_wsgiref.py
+++ b/Lib/test/test_wsgiref.py
@@ -1,11 +1,10 @@
-from __future__ import nested_scopes # Backward compat for 2.1
from unittest import TestCase
from wsgiref.util import setup_testing_defaults
from wsgiref.headers import Headers
from wsgiref.handlers import BaseHandler, BaseCGIHandler
from wsgiref import util
from wsgiref.validate import validator
-from wsgiref.simple_server import WSGIServer, WSGIRequestHandler, demo_app
+from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
from wsgiref.simple_server import make_server
from io import StringIO, BytesIO, BufferedReader
from socketserver import BaseServer
@@ -14,8 +13,8 @@ from platform import python_implementation
import os
import re
import sys
+import unittest
-from test import support
class MockServer(WSGIServer):
"""Non-socket HTTP server"""