summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_tempfile.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test/test_tempfile.py')
-rw-r--r--Lib/test/test_tempfile.py457
1 files changed, 233 insertions, 224 deletions
diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py
index cf8b35a..5a97035 100644
--- a/Lib/test/test_tempfile.py
+++ b/Lib/test/test_tempfile.py
@@ -7,9 +7,11 @@ import signal
import sys
import re
import warnings
+import contextlib
+import weakref
import unittest
-from test import support
+from test import support, script_helper
if hasattr(os, 'stat'):
@@ -23,7 +25,7 @@ has_spawnl = hasattr(os, 'spawnl')
# TEST_FILES may need to be tweaked for systems depending on the maximum
# number of files that can be opened at one time (see ulimit -n)
-if sys.platform in ('openbsd3', 'openbsd4'):
+if sys.platform.startswith('openbsd'):
TEST_FILES = 48
else:
TEST_FILES = 100
@@ -33,7 +35,7 @@ else:
# threads is not done here.
# Common functionality.
-class TC(unittest.TestCase):
+class BaseTestCase(unittest.TestCase):
str_check = re.compile(r"[a-zA-Z0-9_-]{6}$")
@@ -47,11 +49,6 @@ class TC(unittest.TestCase):
self._warnings_manager.__exit__(None, None, None)
- def failOnException(self, what, ei=None):
- if ei is None:
- ei = sys.exc_info()
- self.fail("%s raised %s: %s" % (what, ei[0], ei[1]))
-
def nameCheck(self, name, dir, pre, suf):
(ndir, nbase) = os.path.split(name)
npre = nbase[:len(pre)]
@@ -70,9 +67,8 @@ class TC(unittest.TestCase):
"random string '%s' does not match /^[a-zA-Z0-9_-]{6}$/"
% nbase)
-test_classes = []
-class test_exports(TC):
+class TestExports(BaseTestCase):
def test_exports(self):
# There are no surprising symbols in the tempfile module
dict = tempfile.__dict__
@@ -99,10 +95,8 @@ class test_exports(TC):
self.assertTrue(len(unexp) == 0,
"unexpected keys: %s" % unexp)
-test_classes.append(test_exports)
-
-class test__RandomNameSequence(TC):
+class TestRandomNameSequence(BaseTestCase):
"""Test the internal iterator object _RandomNameSequence."""
def setUp(self):
@@ -130,13 +124,10 @@ class test__RandomNameSequence(TC):
i = 0
r = self.r
- try:
- for s in r:
- i += 1
- if i == 20:
- break
- except:
- self.failOnException("iteration")
+ for s in r:
+ i += 1
+ if i == 20:
+ break
@unittest.skipUnless(hasattr(os, 'fork'),
"os.fork is required for this test")
@@ -169,10 +160,8 @@ class test__RandomNameSequence(TC):
self.assertNotEqual(child_value, parent_value)
-test_classes.append(test__RandomNameSequence)
-
-class test__candidate_tempdir_list(TC):
+class TestCandidateTempdirList(BaseTestCase):
"""Test the internal function _candidate_tempdir_list."""
def test_nonempty_list(self):
@@ -211,11 +200,10 @@ class test__candidate_tempdir_list(TC):
# Not practical to try to verify the presence of OS-specific
# paths in this list.
-test_classes.append(test__candidate_tempdir_list)
# We test _get_default_tempdir some more by testing gettempdir.
-class TestGetDefaultTempdir(TC):
+class TestGetDefaultTempdir(BaseTestCase):
"""Test _get_default_tempdir()."""
def test_no_files_left_behind(self):
@@ -232,13 +220,12 @@ class TestGetDefaultTempdir(TC):
self.assertEqual(os.listdir(our_temp_directory), [])
def raise_OSError(*args, **kwargs):
- raise OSError(-1)
+ raise OSError()
with support.swap_attr(io, "open", raise_OSError):
# test again with failing io.open()
- with self.assertRaises(IOError) as cm:
+ with self.assertRaises(FileNotFoundError):
tempfile._get_default_tempdir()
- self.assertEqual(cm.exception.args[0], errno.ENOENT)
self.assertEqual(os.listdir(our_temp_directory), [])
open = io.open
@@ -249,15 +236,12 @@ class TestGetDefaultTempdir(TC):
with support.swap_attr(io, "open", bad_writer):
# test again with failing write()
- with self.assertRaises(IOError) as cm:
+ with self.assertRaises(FileNotFoundError):
tempfile._get_default_tempdir()
- self.assertEqual(cm.exception.errno, errno.ENOENT)
self.assertEqual(os.listdir(our_temp_directory), [])
-test_classes.append(TestGetDefaultTempdir)
-
-class test__get_candidate_names(TC):
+class TestGetCandidateNames(BaseTestCase):
"""Test the internal function _get_candidate_names."""
def test_retval(self):
@@ -272,10 +256,24 @@ class test__get_candidate_names(TC):
self.assertTrue(a is b)
-test_classes.append(test__get_candidate_names)
+
+@contextlib.contextmanager
+def _inside_empty_temp_dir():
+ dir = tempfile.mkdtemp()
+ try:
+ with support.swap_attr(tempfile, 'tempdir', dir):
+ yield
+ finally:
+ support.rmtree(dir)
-class test__mkstemp_inner(TC):
+def _mock_candidate_names(*names):
+ return support.swap_attr(tempfile,
+ '_get_candidate_names',
+ lambda: iter(names))
+
+
+class TestMkstempInner(BaseTestCase):
"""Test the internal function _mkstemp_inner."""
class mkstemped:
@@ -300,10 +298,7 @@ class test__mkstemp_inner(TC):
def do_create(self, dir=None, pre="", suf="", bin=1):
if dir is None:
dir = tempfile.gettempdir()
- try:
- file = self.mkstemped(dir, pre, suf, bin)
- except:
- self.failOnException("_mkstemp_inner")
+ file = self.mkstemped(dir, pre, suf, bin)
self.nameCheck(file.name, dir, pre, suf)
return file
@@ -330,10 +325,9 @@ class test__mkstemp_inner(TC):
finally:
os.rmdir(dir)
+ @unittest.skipUnless(has_stat, 'os.stat not available')
def test_file_mode(self):
# _mkstemp_inner creates files with the proper mode
- if not has_stat:
- return # ugh, can't use SkipTest.
file = self.do_create()
mode = stat.S_IMODE(os.stat(file.name).st_mode)
@@ -345,10 +339,9 @@ class test__mkstemp_inner(TC):
expected = user * (1 + 8 + 64)
self.assertEqual(mode, expected)
+ @unittest.skipUnless(has_spawnl, 'os.spawnl not available')
def test_noinherit(self):
# _mkstemp_inner file handles are not inherited by child processes
- if not has_spawnl:
- return # ugh, can't use SkipTest.
if support.verbose:
v="v"
@@ -383,10 +376,9 @@ class test__mkstemp_inner(TC):
"child process caught fatal signal %d" % -retval)
self.assertFalse(retval > 0, "child process reports failure %d"%retval)
+ @unittest.skipUnless(has_textmode, "text mode not available")
def test_textmode(self):
# _mkstemp_inner can create files in text mode
- if not has_textmode:
- return # ugh, can't use SkipTest.
# A text file is truncated at the first Ctrl+Z byte
f = self.do_create(bin=0)
@@ -395,10 +387,39 @@ class test__mkstemp_inner(TC):
os.lseek(f.fd, 0, os.SEEK_SET)
self.assertEqual(os.read(f.fd, 20), b"blat")
-test_classes.append(test__mkstemp_inner)
+ def default_mkstemp_inner(self):
+ return tempfile._mkstemp_inner(tempfile.gettempdir(),
+ tempfile.template,
+ '',
+ tempfile._bin_openflags)
+
+ def test_collision_with_existing_file(self):
+ # _mkstemp_inner tries another name when a file with
+ # the chosen name already exists
+ with _inside_empty_temp_dir(), \
+ _mock_candidate_names('aaa', 'aaa', 'bbb'):
+ (fd1, name1) = self.default_mkstemp_inner()
+ os.close(fd1)
+ self.assertTrue(name1.endswith('aaa'))
+
+ (fd2, name2) = self.default_mkstemp_inner()
+ os.close(fd2)
+ self.assertTrue(name2.endswith('bbb'))
+
+ def test_collision_with_existing_directory(self):
+ # _mkstemp_inner tries another name when a directory with
+ # the chosen name already exists
+ with _inside_empty_temp_dir(), \
+ _mock_candidate_names('aaa', 'aaa', 'bbb'):
+ dir = tempfile.mkdtemp()
+ self.assertTrue(dir.endswith('aaa'))
+
+ (fd, name) = self.default_mkstemp_inner()
+ os.close(fd)
+ self.assertTrue(name.endswith('bbb'))
-class test_gettempprefix(TC):
+class TestGetTempPrefix(BaseTestCase):
"""Test gettempprefix()."""
def test_sane_template(self):
@@ -418,19 +439,14 @@ class test_gettempprefix(TC):
d = tempfile.mkdtemp(prefix="")
try:
p = os.path.join(d, p)
- try:
- fd = os.open(p, os.O_RDWR | os.O_CREAT)
- except:
- self.failOnException("os.open")
+ fd = os.open(p, os.O_RDWR | os.O_CREAT)
os.close(fd)
os.unlink(p)
finally:
os.rmdir(d)
-test_classes.append(test_gettempprefix)
-
-class test_gettempdir(TC):
+class TestGetTempDir(BaseTestCase):
"""Test gettempdir()."""
def test_directory_exists(self):
@@ -448,12 +464,9 @@ class test_gettempdir(TC):
# sneaky: just instantiate a NamedTemporaryFile, which
# defaults to writing into the directory returned by
# gettempdir.
- try:
- file = tempfile.NamedTemporaryFile()
- file.write(b"blat")
- file.close()
- except:
- self.failOnException("create file in %s" % tempfile.gettempdir())
+ file = tempfile.NamedTemporaryFile()
+ file.write(b"blat")
+ file.close()
def test_same_thing(self):
# gettempdir always returns the same object
@@ -462,23 +475,18 @@ class test_gettempdir(TC):
self.assertTrue(a is b)
-test_classes.append(test_gettempdir)
-
-class test_mkstemp(TC):
+class TestMkstemp(BaseTestCase):
"""Test mkstemp()."""
def do_create(self, dir=None, pre="", suf=""):
if dir is None:
dir = tempfile.gettempdir()
- try:
- (fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf)
- (ndir, nbase) = os.path.split(name)
- adir = os.path.abspath(dir)
- self.assertEqual(adir, ndir,
- "Directory '%s' incorrectly returned as '%s'" % (adir, ndir))
- except:
- self.failOnException("mkstemp")
+ (fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf)
+ (ndir, nbase) = os.path.split(name)
+ adir = os.path.abspath(dir)
+ self.assertEqual(adir, ndir,
+ "Directory '%s' incorrectly returned as '%s'" % (adir, ndir))
try:
self.nameCheck(name, dir, pre, suf)
@@ -503,19 +511,14 @@ class test_mkstemp(TC):
finally:
os.rmdir(dir)
-test_classes.append(test_mkstemp)
-
-class test_mkdtemp(TC):
+class TestMkdtemp(BaseTestCase):
"""Test mkdtemp()."""
def do_create(self, dir=None, pre="", suf=""):
if dir is None:
dir = tempfile.gettempdir()
- try:
- name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf)
- except:
- self.failOnException("mkdtemp")
+ name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf)
try:
self.nameCheck(name, dir, pre, suf)
@@ -551,10 +554,9 @@ class test_mkdtemp(TC):
finally:
os.rmdir(dir)
+ @unittest.skipUnless(has_stat, 'os.stat not available')
def test_mode(self):
# mkdtemp creates directories with the proper mode
- if not has_stat:
- return # ugh, can't use SkipTest.
dir = self.do_create()
try:
@@ -570,10 +572,29 @@ class test_mkdtemp(TC):
finally:
os.rmdir(dir)
-test_classes.append(test_mkdtemp)
-
-
-class test_mktemp(TC):
+ def test_collision_with_existing_file(self):
+ # mkdtemp tries another name when a file with
+ # the chosen name already exists
+ with _inside_empty_temp_dir(), \
+ _mock_candidate_names('aaa', 'aaa', 'bbb'):
+ file = tempfile.NamedTemporaryFile(delete=False)
+ file.close()
+ self.assertTrue(file.name.endswith('aaa'))
+ dir = tempfile.mkdtemp()
+ self.assertTrue(dir.endswith('bbb'))
+
+ def test_collision_with_existing_directory(self):
+ # mkdtemp tries another name when a directory with
+ # the chosen name already exists
+ with _inside_empty_temp_dir(), \
+ _mock_candidate_names('aaa', 'aaa', 'bbb'):
+ dir1 = tempfile.mkdtemp()
+ self.assertTrue(dir1.endswith('aaa'))
+ dir2 = tempfile.mkdtemp()
+ self.assertTrue(dir2.endswith('bbb'))
+
+
+class TestMktemp(BaseTestCase):
"""Test mktemp()."""
# For safety, all use of mktemp must occur in a private directory.
@@ -602,10 +623,7 @@ class test_mktemp(TC):
self._unlink(self.name)
def do_create(self, pre="", suf=""):
- try:
- file = self.mktemped(self.dir, pre, suf)
- except:
- self.failOnException("mktemp")
+ file = self.mktemped(self.dir, pre, suf)
self.nameCheck(file.name, self.dir, pre, suf)
return file
@@ -632,23 +650,18 @@ class test_mktemp(TC):
## self.assertRaises(RuntimeWarning,
## tempfile.mktemp, dir=self.dir)
-test_classes.append(test_mktemp)
-
# We test _TemporaryFileWrapper by testing NamedTemporaryFile.
-class test_NamedTemporaryFile(TC):
+class TestNamedTemporaryFile(BaseTestCase):
"""Test NamedTemporaryFile()."""
def do_create(self, dir=None, pre="", suf="", delete=True):
if dir is None:
dir = tempfile.gettempdir()
- try:
- file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf,
- delete=delete)
- except:
- self.failOnException("NamedTemporaryFile")
+ file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf,
+ delete=delete)
self.nameCheck(file.name, dir, pre, suf)
return file
@@ -662,6 +675,22 @@ class test_NamedTemporaryFile(TC):
self.do_create(pre="a", suf="b")
self.do_create(pre="aa", suf=".txt")
+ def test_method_lookup(self):
+ # Issue #18879: Looking up a temporary file method should keep it
+ # alive long enough.
+ f = self.do_create()
+ wr = weakref.ref(f)
+ write = f.write
+ write2 = f.write
+ del f
+ write(b'foo')
+ del write
+ write2(b'bar')
+ del write2
+ if support.check_impl_detail(cpython=True):
+ # No reference cycle was created.
+ self.assertIsNone(wr())
+
def test_creates_named(self):
# NamedTemporaryFile creates files with names
f = tempfile.NamedTemporaryFile()
@@ -701,11 +730,8 @@ class test_NamedTemporaryFile(TC):
f = tempfile.NamedTemporaryFile()
f.write(b'abc\n')
f.close()
- try:
- f.close()
- f.close()
- except:
- self.failOnException("close")
+ f.close()
+ f.close()
def test_context_manager(self):
# A NamedTemporaryFile can be used as a context manager
@@ -719,18 +745,14 @@ class test_NamedTemporaryFile(TC):
# How to test the mode and bufsize parameters?
-test_classes.append(test_NamedTemporaryFile)
-class test_SpooledTemporaryFile(TC):
+class TestSpooledTemporaryFile(BaseTestCase):
"""Test SpooledTemporaryFile()."""
def do_create(self, max_size=0, dir=None, pre="", suf=""):
if dir is None:
dir = tempfile.gettempdir()
- try:
- file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf)
- except:
- self.failOnException("SpooledTemporaryFile")
+ file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf)
return file
@@ -818,11 +840,8 @@ class test_SpooledTemporaryFile(TC):
f.write(b'abc\n')
self.assertFalse(f._rolled)
f.close()
- try:
- f.close()
- f.close()
- except:
- self.failOnException("close")
+ f.close()
+ f.close()
def test_multiple_close_after_rollover(self):
# A SpooledTemporaryFile can be closed many times without error
@@ -830,11 +849,8 @@ class test_SpooledTemporaryFile(TC):
f.write(b'abc\n')
self.assertTrue(f._rolled)
f.close()
- try:
- f.close()
- f.close()
- except:
- self.failOnException("close")
+ f.close()
+ f.close()
def test_bound_methods(self):
# It should be OK to steal a bound method from a SpooledTemporaryFile
@@ -959,66 +975,76 @@ class test_SpooledTemporaryFile(TC):
pass
self.assertRaises(ValueError, use_closed)
+ def test_truncate_with_size_parameter(self):
+ # A SpooledTemporaryFile can be truncated to zero size
+ f = tempfile.SpooledTemporaryFile(max_size=10)
+ f.write(b'abcdefg\n')
+ f.seek(0)
+ f.truncate()
+ self.assertFalse(f._rolled)
+ self.assertEqual(f._file.getvalue(), b'')
+ # A SpooledTemporaryFile can be truncated to a specific size
+ f = tempfile.SpooledTemporaryFile(max_size=10)
+ f.write(b'abcdefg\n')
+ f.truncate(4)
+ self.assertFalse(f._rolled)
+ self.assertEqual(f._file.getvalue(), b'abcd')
+ # A SpooledTemporaryFile rolls over if truncated to large size
+ f = tempfile.SpooledTemporaryFile(max_size=10)
+ f.write(b'abcdefg\n')
+ f.truncate(20)
+ self.assertTrue(f._rolled)
+ if has_stat:
+ self.assertEqual(os.fstat(f.fileno()).st_size, 20)
-test_classes.append(test_SpooledTemporaryFile)
+if tempfile.NamedTemporaryFile is not tempfile.TemporaryFile:
-class test_TemporaryFile(TC):
- """Test TemporaryFile()."""
+ class TestTemporaryFile(BaseTestCase):
+ """Test TemporaryFile()."""
- def test_basic(self):
- # TemporaryFile can create files
- # No point in testing the name params - the file has no name.
- try:
+ def test_basic(self):
+ # TemporaryFile can create files
+ # No point in testing the name params - the file has no name.
tempfile.TemporaryFile()
- except:
- self.failOnException("TemporaryFile")
- def test_has_no_name(self):
- # TemporaryFile creates files with no names (on this system)
- dir = tempfile.mkdtemp()
- f = tempfile.TemporaryFile(dir=dir)
- f.write(b'blat')
+ def test_has_no_name(self):
+ # TemporaryFile creates files with no names (on this system)
+ dir = tempfile.mkdtemp()
+ f = tempfile.TemporaryFile(dir=dir)
+ f.write(b'blat')
- # Sneaky: because this file has no name, it should not prevent
- # us from removing the directory it was created in.
- try:
- os.rmdir(dir)
- except:
- ei = sys.exc_info()
- # cleanup
+ # Sneaky: because this file has no name, it should not prevent
+ # us from removing the directory it was created in.
+ try:
+ os.rmdir(dir)
+ except:
+ # cleanup
+ f.close()
+ os.rmdir(dir)
+ raise
+
+ def test_multiple_close(self):
+ # A TemporaryFile can be closed many times without error
+ f = tempfile.TemporaryFile()
+ f.write(b'abc\n')
f.close()
- os.rmdir(dir)
- self.failOnException("rmdir", ei)
-
- def test_multiple_close(self):
- # A TemporaryFile can be closed many times without error
- f = tempfile.TemporaryFile()
- f.write(b'abc\n')
- f.close()
- try:
f.close()
f.close()
- except:
- self.failOnException("close")
- # How to test the mode and bufsize parameters?
- def test_mode_and_encoding(self):
+ # How to test the mode and bufsize parameters?
+ def test_mode_and_encoding(self):
- def roundtrip(input, *args, **kwargs):
- with tempfile.TemporaryFile(*args, **kwargs) as fileobj:
- fileobj.write(input)
- fileobj.seek(0)
- self.assertEqual(input, fileobj.read())
+ def roundtrip(input, *args, **kwargs):
+ with tempfile.TemporaryFile(*args, **kwargs) as fileobj:
+ fileobj.write(input)
+ fileobj.seek(0)
+ self.assertEqual(input, fileobj.read())
- roundtrip(b"1234", "w+b")
- roundtrip("abdc\n", "w+")
- roundtrip("\u039B", "w+", encoding="utf-16")
- roundtrip("foo\r\n", "w+", newline="")
-
-
-if tempfile.NamedTemporaryFile is not tempfile.TemporaryFile:
- test_classes.append(test_TemporaryFile)
+ roundtrip(b"1234", "w+b")
+ roundtrip("abdc\n", "w+")
+ roundtrip("\u039B", "w+", encoding="utf-16")
+ roundtrip("foo\r\n", "w+", newline="")
# Helper for test_del_on_shutdown
@@ -1037,20 +1063,18 @@ class NulledModules:
d.clear()
d.update(c)
-class test_TemporaryDirectory(TC):
+class TestTemporaryDirectory(BaseTestCase):
"""Test TemporaryDirectory()."""
def do_create(self, dir=None, pre="", suf="", recurse=1):
if dir is None:
dir = tempfile.gettempdir()
- try:
- tmp = tempfile.TemporaryDirectory(dir=dir, prefix=pre, suffix=suf)
- except:
- self.failOnException("TemporaryDirectory")
+ tmp = tempfile.TemporaryDirectory(dir=dir, prefix=pre, suffix=suf)
self.nameCheck(tmp.name, dir, pre, suf)
# Create a subdirectory and some files
if recurse:
- self.do_create(tmp.name, pre, suf, recurse-1)
+ d1 = self.do_create(tmp.name, pre, suf, recurse-1)
+ d1.name = None
with open(os.path.join(tmp.name, "test.txt"), "wb") as f:
f.write(b"Hello world!")
return tmp
@@ -1061,8 +1085,9 @@ class test_TemporaryDirectory(TC):
# (noted as part of Issue #10188)
with tempfile.TemporaryDirectory() as nonexistent:
pass
- with self.assertRaises(os.error):
+ with self.assertRaises(FileNotFoundError) as cm:
tempfile.TemporaryDirectory(dir=nonexistent)
+ self.assertEqual(cm.exception.errno, errno.ENOENT)
def test_explicit_cleanup(self):
# A TemporaryDirectory is deleted when cleaned up
@@ -1081,7 +1106,7 @@ class test_TemporaryDirectory(TC):
def test_cleanup_with_symlink_to_a_directory(self):
# cleanup() should not follow symlinks to directories (issue #12464)
d1 = self.do_create()
- d2 = self.do_create()
+ d2 = self.do_create(recurse=0)
# Symlink d1/foo -> d2
os.symlink(d2.name, os.path.join(d1.name, "foo"))
@@ -1111,70 +1136,56 @@ class test_TemporaryDirectory(TC):
finally:
os.rmdir(dir)
- @unittest.expectedFailure # See issue #10188
def test_del_on_shutdown(self):
# A TemporaryDirectory may be cleaned up during shutdown
- # Make sure it works with the relevant modules nulled out
with self.do_create() as dir:
- d = self.do_create(dir=dir)
- # Mimic the nulling out of modules that
- # occurs during system shutdown
- modules = [os, os.path]
- if has_stat:
- modules.append(stat)
- # Currently broken, so suppress the warning
- # that is otherwise emitted on stdout
- with support.captured_stderr() as err:
- with NulledModules(*modules):
- d.cleanup()
- # Currently broken, so stop spurious exception by
- # indicating the object has already been closed
- d._closed = True
- # And this assert will fail, as expected by the
- # unittest decorator...
- self.assertFalse(os.path.exists(d.name),
- "TemporaryDirectory %s exists after cleanup" % d.name)
+ for mod in ('os', 'shutil', 'sys', 'tempfile', 'warnings'):
+ code = """if True:
+ import os
+ import shutil
+ import sys
+ import tempfile
+ import warnings
+
+ tmp = tempfile.TemporaryDirectory(dir={dir!r})
+ sys.stdout.buffer.write(tmp.name.encode())
+
+ tmp2 = os.path.join(tmp.name, 'test_dir')
+ os.mkdir(tmp2)
+ with open(os.path.join(tmp2, "test.txt"), "w") as f:
+ f.write("Hello world!")
+
+ {mod}.tmp = tmp
+
+ warnings.filterwarnings("always", category=ResourceWarning)
+ """.format(dir=dir, mod=mod)
+ rc, out, err = script_helper.assert_python_ok("-c", code)
+ tmp_name = out.decode().strip()
+ self.assertFalse(os.path.exists(tmp_name),
+ "TemporaryDirectory %s exists after cleanup" % tmp_name)
+ err = err.decode('utf-8', 'backslashreplace')
+ self.assertNotIn("Exception ", err)
def test_warnings_on_cleanup(self):
- # Two kinds of warning on shutdown
- # Issue 10888: may write to stderr if modules are nulled out
- # ResourceWarning will be triggered by __del__
+ # ResourceWarning will be triggered by __del__
with self.do_create() as dir:
- if os.sep != '\\':
- # Embed a backslash in order to make sure string escaping
- # in the displayed error message is dealt with correctly
- suffix = '\\check_backslash_handling'
- else:
- suffix = ''
- d = self.do_create(dir=dir, suf=suffix)
-
- #Check for the Issue 10888 message
- modules = [os, os.path]
- if has_stat:
- modules.append(stat)
- with support.captured_stderr() as err:
- with NulledModules(*modules):
- d.cleanup()
- message = err.getvalue().replace('\\\\', '\\')
- self.assertIn("while cleaning up", message)
- self.assertIn(d.name, message)
+ d = self.do_create(dir=dir, recurse=3)
+ name = d.name
# Check for the resource warning
with support.check_warnings(('Implicitly', ResourceWarning), quiet=False):
warnings.filterwarnings("always", category=ResourceWarning)
- d.__del__()
- self.assertFalse(os.path.exists(d.name),
- "TemporaryDirectory %s exists after __del__" % d.name)
+ del d
+ support.gc_collect()
+ self.assertFalse(os.path.exists(name),
+ "TemporaryDirectory %s exists after __del__" % name)
def test_multiple_close(self):
# Can be cleaned-up many times without error
d = self.do_create()
d.cleanup()
- try:
- d.cleanup()
- d.cleanup()
- except:
- self.failOnException("cleanup")
+ d.cleanup()
+ d.cleanup()
def test_context_manager(self):
# Can be used as a context manager
@@ -1185,10 +1196,8 @@ class test_TemporaryDirectory(TC):
self.assertFalse(os.path.exists(name))
-test_classes.append(test_TemporaryDirectory)
-
def test_main():
- support.run_unittest(*test_classes)
+ support.run_unittest(__name__)
if __name__ == "__main__":
test_main()