Debian Codegraph @

Lib/test/test_tempfile.py

raw
1 # tempfile.py unit tests.
2 import tempfile
3 import errno
4 import io
5 import os
6 import pathlib
7 import sys
8 import re
9 import warnings
10 import contextlib
11 import stat
12 import types
13 import weakref
14 import gc
15 import shutil
16 import subprocess
17 from unittest import mock
18
19 import unittest
20 from test import support
21 from test.support import os_helper
22 from test.support import script_helper
23 from test.support import warnings_helper
24
25
26 has_textmode = (tempfile._text_openflags != tempfile._bin_openflags)
27 has_spawnl = hasattr(os, 'spawnl')
28
29 # TEST_FILES may need to be tweaked for systems depending on the maximum
30 # number of files that can be opened at one time (see ulimit -n)
31 if sys.platform.startswith('openbsd'):
32 TEST_FILES = 48
33 else:
34 TEST_FILES = 100
35
36 # This is organized as one test for each chunk of code in tempfile.py,
37 # in order of their appearance in the file. Testing which requires
38 # threads is not done here.
39
40 class TestLowLevelInternals(unittest.TestCase):
41 def test_infer_return_type_singles(self):
42 self.assertIs(str, tempfile._infer_return_type(''))
43 self.assertIs(bytes, tempfile._infer_return_type(b''))
44 self.assertIs(str, tempfile._infer_return_type(None))
45
46 def test_infer_return_type_multiples(self):
47 self.assertIs(str, tempfile._infer_return_type('', ''))
48 self.assertIs(bytes, tempfile._infer_return_type(b'', b''))
49 with self.assertRaises(TypeError):
50 tempfile._infer_return_type('', b'')
51 with self.assertRaises(TypeError):
52 tempfile._infer_return_type(b'', '')
53
54 def test_infer_return_type_multiples_and_none(self):
55 self.assertIs(str, tempfile._infer_return_type(None, ''))
56 self.assertIs(str, tempfile._infer_return_type('', None))
57 self.assertIs(str, tempfile._infer_return_type(None, None))
58 self.assertIs(bytes, tempfile._infer_return_type(b'', None))
59 self.assertIs(bytes, tempfile._infer_return_type(None, b''))
60 with self.assertRaises(TypeError):
61 tempfile._infer_return_type('', None, b'')
62 with self.assertRaises(TypeError):
63 tempfile._infer_return_type(b'', None, '')
64
65 def test_infer_return_type_pathlib(self):
66 self.assertIs(str, tempfile._infer_return_type(os_helper.FakePath('/')))
67
68 def test_infer_return_type_pathlike(self):
69 Path = os_helper.FakePath
70 self.assertIs(str, tempfile._infer_return_type(Path('/')))
71 self.assertIs(bytes, tempfile._infer_return_type(Path(b'/')))
72 self.assertIs(str, tempfile._infer_return_type('', Path('')))
73 self.assertIs(bytes, tempfile._infer_return_type(b'', Path(b'')))
74 self.assertIs(bytes, tempfile._infer_return_type(None, Path(b'')))
75 self.assertIs(str, tempfile._infer_return_type(None, Path('')))
76
77 with self.assertRaises(TypeError):
78 tempfile._infer_return_type('', Path(b''))
79 with self.assertRaises(TypeError):
80 tempfile._infer_return_type(b'', Path(''))
81
82 # Common functionality.
83
84 class BaseTestCase(unittest.TestCase):
85
86 str_check = re.compile(r"^[a-z0-9_-]{8}$")
87 b_check = re.compile(br"^[a-z0-9_-]{8}$")
88
89 def setUp(self):
90 self.enterContext(warnings_helper.check_warnings())
91 warnings.filterwarnings("ignore", category=RuntimeWarning,
92 message="mktemp", module=__name__)
93
94 def nameCheck(self, name, dir, pre, suf):
95 (ndir, nbase) = os.path.split(name)
96 npre = nbase[:len(pre)]
97 nsuf = nbase[len(nbase)-len(suf):]
98
99 if dir is not None:
100 self.assertIs(
101 type(name),
102 str
103 if type(dir) is str or isinstance(dir, os.PathLike) else
104 bytes,
105 "unexpected return type",
106 )
107 if pre is not None:
108 self.assertIs(type(name), str if type(pre) is str else bytes,
109 "unexpected return type")
110 if suf is not None:
111 self.assertIs(type(name), str if type(suf) is str else bytes,
112 "unexpected return type")
113 if (dir, pre, suf) == (None, None, None):
114 self.assertIs(type(name), str, "default return type must be str")
115
116 # check for equality of the absolute paths!
117 self.assertEqual(os.path.abspath(ndir), os.path.abspath(dir),
118 "file %r not in directory %r" % (name, dir))
119 self.assertEqual(npre, pre,
120 "file %r does not begin with %r" % (nbase, pre))
121 self.assertEqual(nsuf, suf,
122 "file %r does not end with %r" % (nbase, suf))
123
124 nbase = nbase[len(pre):len(nbase)-len(suf)]
125 check = self.str_check if isinstance(nbase, str) else self.b_check
126 self.assertTrue(check.match(nbase),
127 "random characters %r do not match %r"
128 % (nbase, check.pattern))
129
130
131 class TestExports(BaseTestCase):
132 def test_exports(self):
133 # There are no surprising symbols in the tempfile module
134 dict = tempfile.__dict__
135
136 expected = {
137 "NamedTemporaryFile" : 1,
138 "TemporaryFile" : 1,
139 "mkstemp" : 1,
140 "mkdtemp" : 1,
141 "mktemp" : 1,
142 "TMP_MAX" : 1,
143 "gettempprefix" : 1,
144 "gettempprefixb" : 1,
145 "gettempdir" : 1,
146 "gettempdirb" : 1,
147 "tempdir" : 1,
148 "template" : 1,
149 "SpooledTemporaryFile" : 1,
150 "TemporaryDirectory" : 1,
151 }
152
153 unexp = []
154 for key in dict:
155 if key[0] != '_' and key not in expected:
156 unexp.append(key)
157 self.assertTrue(len(unexp) == 0,
158 "unexpected keys: %s" % unexp)
159
160
161 class TestRandomNameSequence(BaseTestCase):
162 """Test the internal iterator object _RandomNameSequence."""
163
164 def setUp(self):
165 self.r = tempfile._RandomNameSequence()
166 super().setUp()
167
168 def test_get_eight_char_str(self):
169 # _RandomNameSequence returns a eight-character string
170 s = next(self.r)
171 self.nameCheck(s, '', '', '')
172
173 def test_many(self):
174 # _RandomNameSequence returns no duplicate strings (stochastic)
175
176 dict = {}
177 r = self.r
178 for i in range(TEST_FILES):
179 s = next(r)
180 self.nameCheck(s, '', '', '')
181 self.assertNotIn(s, dict)
182 dict[s] = 1
183
184 def supports_iter(self):
185 # _RandomNameSequence supports the iterator protocol
186
187 i = 0
188 r = self.r
189 for s in r:
190 i += 1
191 if i == 20:
192 break
193
194 @support.requires_fork()
195 def test_process_awareness(self):
196 # ensure that the random source differs between
197 # child and parent.
198 read_fd, write_fd = os.pipe()
199 pid = None
200 try:
201 pid = os.fork()
202 if not pid:
203 # child process
204 os.close(read_fd)
205 os.write(write_fd, next(self.r).encode("ascii"))
206 os.close(write_fd)
207 # bypass the normal exit handlers- leave those to
208 # the parent.
209 os._exit(0)
210
211 # parent process
212 parent_value = next(self.r)
213 child_value = os.read(read_fd, len(parent_value)).decode("ascii")
214 finally:
215 if pid:
216 support.wait_process(pid, exitcode=0)
217
218 os.close(read_fd)
219 os.close(write_fd)
220 self.assertNotEqual(child_value, parent_value)
221
222
223
224 class TestCandidateTempdirList(BaseTestCase):
225 """Test the internal function _candidate_tempdir_list."""
226
227 def test_nonempty_list(self):
228 # _candidate_tempdir_list returns a nonempty list of strings
229
230 cand = tempfile._candidate_tempdir_list()
231
232 self.assertFalse(len(cand) == 0)
233 for c in cand:
234 self.assertIsInstance(c, str)
235
236 def test_wanted_dirs(self):
237 # _candidate_tempdir_list contains the expected directories
238
239 # Make sure the interesting environment variables are all set.
240 with os_helper.EnvironmentVarGuard() as env:
241 for envname in 'TMPDIR', 'TEMP', 'TMP':
242 dirname = os.getenv(envname)
243 if not dirname:
244 env[envname] = os.path.abspath(envname)
245
246 cand = tempfile._candidate_tempdir_list()
247
248 for envname in 'TMPDIR', 'TEMP', 'TMP':
249 dirname = os.getenv(envname)
250 if not dirname: raise ValueError
251 self.assertIn(dirname, cand)
252
253 try:
254 dirname = os.getcwd()
255 except (AttributeError, OSError):
256 dirname = os.curdir
257
258 self.assertIn(dirname, cand)
259
260 # Not practical to try to verify the presence of OS-specific
261 # paths in this list.
262
263
264 # We test _get_default_tempdir some more by testing gettempdir.
265
266 class TestGetDefaultTempdir(BaseTestCase):
267 """Test _get_default_tempdir()."""
268
269 def test_no_files_left_behind(self):
270 # use a private empty directory
271 with tempfile.TemporaryDirectory() as our_temp_directory:
272 # force _get_default_tempdir() to consider our empty directory
273 def our_candidate_list():
274 return [our_temp_directory]
275
276 with support.swap_attr(tempfile, "_candidate_tempdir_list",
277 our_candidate_list):
278 # verify our directory is empty after _get_default_tempdir()
279 tempfile._get_default_tempdir()
280 self.assertEqual(os.listdir(our_temp_directory), [])
281
282 def raise_OSError(*args, **kwargs):
283 raise OSError()
284
285 with support.swap_attr(os, "open", raise_OSError):
286 # test again with failing os.open()
287 with self.assertRaises(FileNotFoundError):
288 tempfile._get_default_tempdir()
289 self.assertEqual(os.listdir(our_temp_directory), [])
290
291 with support.swap_attr(os, "write", raise_OSError):
292 # test again with failing os.write()
293 with self.assertRaises(FileNotFoundError):
294 tempfile._get_default_tempdir()
295 self.assertEqual(os.listdir(our_temp_directory), [])
296
297
298 class TestGetCandidateNames(BaseTestCase):
299 """Test the internal function _get_candidate_names."""
300
301 def test_retval(self):
302 # _get_candidate_names returns a _RandomNameSequence object
303 obj = tempfile._get_candidate_names()
304 self.assertIsInstance(obj, tempfile._RandomNameSequence)
305
306 def test_same_thing(self):
307 # _get_candidate_names always returns the same object
308 a = tempfile._get_candidate_names()
309 b = tempfile._get_candidate_names()
310
311 self.assertTrue(a is b)
312
313
314 @contextlib.contextmanager
315 def _inside_empty_temp_dir():
316 dir = tempfile.mkdtemp()
317 try:
318 with support.swap_attr(tempfile, 'tempdir', dir):
319 yield
320 finally:
321 os_helper.rmtree(dir)
322
323
324 def _mock_candidate_names(*names):
325 return support.swap_attr(tempfile,
326 '_get_candidate_names',
327 lambda: iter(names))
328
329
330 class TestBadTempdir:
331 def test_read_only_directory(self):
332 with _inside_empty_temp_dir():
333 probe = os.path.join(tempfile.tempdir, 'probe')
334 if os.name == 'nt':
335 # Use security identifier *S-1-1-0 instead
336 # of localized "Everyone" to not depend on the locale.
337 cmd = ['icacls', tempfile.tempdir, '/deny', '*S-1-1-0:(W)']
338 stdout = None if support.verbose > 1 else subprocess.DEVNULL
339 subprocess.run(cmd, check=True, stdout=stdout)
340 else:
341 oldmode = mode = os.stat(tempfile.tempdir).st_mode
342 mode &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
343 mode = stat.S_IREAD
344 os.chmod(tempfile.tempdir, mode)
345 try:
346 # Check that the directory is read-only.
347 try:
348 os.mkdir(probe)
349 except PermissionError:
350 pass
351 else:
352 os.rmdir(probe)
353 self.skipTest("can't set the directory read-only")
354 # gh-66305: Now it takes a split second, but previously
355 # it took about 10 days on Windows.
356 with self.assertRaises(PermissionError):
357 self.make_temp()
358 finally:
359 if os.name == 'nt':
360 # Use security identifier *S-1-1-0 instead
361 # of localized "Everyone" to not depend on the locale.
362 cmd = ['icacls', tempfile.tempdir, '/grant:r', '*S-1-1-0:(M)']
363 subprocess.run(cmd, check=True, stdout=stdout)
364 else:
365 os.chmod(tempfile.tempdir, oldmode)
366 self.assertEqual(os.listdir(tempfile.tempdir), [])
367
368 def test_nonexisting_directory(self):
369 with _inside_empty_temp_dir():
370 tempdir = os.path.join(tempfile.tempdir, 'nonexistent')
371 with support.swap_attr(tempfile, 'tempdir', tempdir):
372 with self.assertRaises(FileNotFoundError):
373 self.make_temp()
374
375 def test_non_directory(self):
376 with _inside_empty_temp_dir():
377 tempdir = os.path.join(tempfile.tempdir, 'file')
378 open(tempdir, 'wb').close()
379 with support.swap_attr(tempfile, 'tempdir', tempdir):
380 with self.assertRaises((NotADirectoryError, FileNotFoundError)):
381 self.make_temp()
382
383
384 class TestMkstempInner(TestBadTempdir, BaseTestCase):
385 """Test the internal function _mkstemp_inner."""
386
387 class mkstemped:
388 _bflags = tempfile._bin_openflags
389 _tflags = tempfile._text_openflags
390 _close = os.close
391 _unlink = os.unlink
392
393 def __init__(self, dir, pre, suf, bin):
394 if bin: flags = self._bflags
395 else: flags = self._tflags
396
397 output_type = tempfile._infer_return_type(dir, pre, suf)
398 (self.fd, self.name) = tempfile._mkstemp_inner(dir, pre, suf, flags, output_type)
399
400 def write(self, str):
401 os.write(self.fd, str)
402
403 def __del__(self):
404 self._close(self.fd)
405 self._unlink(self.name)
406
407 def do_create(self, dir=None, pre=None, suf=None, bin=1):
408 output_type = tempfile._infer_return_type(dir, pre, suf)
409 if dir is None:
410 if output_type is str:
411 dir = tempfile.gettempdir()
412 else:
413 dir = tempfile.gettempdirb()
414 if pre is None:
415 pre = output_type()
416 if suf is None:
417 suf = output_type()
418 file = self.mkstemped(dir, pre, suf, bin)
419
420 self.nameCheck(file.name, dir, pre, suf)
421 return file
422
423 def test_basic(self):
424 # _mkstemp_inner can create files
425 self.do_create().write(b"blat")
426 self.do_create(pre="a").write(b"blat")
427 self.do_create(suf="b").write(b"blat")
428 self.do_create(pre="a", suf="b").write(b"blat")
429 self.do_create(pre="aa", suf=".txt").write(b"blat")
430
431 def test_basic_with_bytes_names(self):
432 # _mkstemp_inner can create files when given name parts all
433 # specified as bytes.
434 dir_b = tempfile.gettempdirb()
435 self.do_create(dir=dir_b, suf=b"").write(b"blat")
436 self.do_create(dir=dir_b, pre=b"a").write(b"blat")
437 self.do_create(dir=dir_b, suf=b"b").write(b"blat")
438 self.do_create(dir=dir_b, pre=b"a", suf=b"b").write(b"blat")
439 self.do_create(dir=dir_b, pre=b"aa", suf=b".txt").write(b"blat")
440 # Can't mix str & binary types in the args.
441 with self.assertRaises(TypeError):
442 self.do_create(dir="", suf=b"").write(b"blat")
443 with self.assertRaises(TypeError):
444 self.do_create(dir=dir_b, pre="").write(b"blat")
445 with self.assertRaises(TypeError):
446 self.do_create(dir=dir_b, pre=b"", suf="").write(b"blat")
447
448 def test_basic_many(self):
449 # _mkstemp_inner can create many files (stochastic)
450 extant = list(range(TEST_FILES))
451 for i in extant:
452 extant[i] = self.do_create(pre="aa")
453
454 def test_choose_directory(self):
455 # _mkstemp_inner can create files in a user-selected directory
456 dir = tempfile.mkdtemp()
457 try:
458 self.do_create(dir=dir).write(b"blat")
459 self.do_create(dir=os_helper.FakePath(dir)).write(b"blat")
460 finally:
461 support.gc_collect() # For PyPy or other GCs.
462 os.rmdir(dir)
463
464 @os_helper.skip_unless_working_chmod
465 def test_file_mode(self):
466 # _mkstemp_inner creates files with the proper mode
467
468 file = self.do_create()
469 mode = stat.S_IMODE(os.stat(file.name).st_mode)
470 expected = 0o600
471 if sys.platform == 'win32':
472 # There's no distinction among 'user', 'group' and 'world';
473 # replicate the 'user' bits.
474 user = expected >> 6
475 expected = user * (1 + 8 + 64)
476 self.assertEqual(mode, expected)
477
478 @unittest.skipUnless(has_spawnl, 'os.spawnl not available')
479 @support.requires_subprocess()
480 def test_noinherit(self):
481 # _mkstemp_inner file handles are not inherited by child processes
482
483 if support.verbose:
484 v="v"
485 else:
486 v="q"
487
488 file = self.do_create()
489 self.assertEqual(os.get_inheritable(file.fd), False)
490 fd = "%d" % file.fd
491
492 try:
493 me = __file__
494 except NameError:
495 me = sys.argv[0]
496
497 # We have to exec something, so that FD_CLOEXEC will take
498 # effect. The core of this test is therefore in
499 # tf_inherit_check.py, which see.
500 tester = os.path.join(os.path.dirname(os.path.abspath(me)),
501 "tf_inherit_check.py")
502
503 # On Windows a spawn* /path/ with embedded spaces shouldn't be quoted,
504 # but an arg with embedded spaces should be decorated with double
505 # quotes on each end
506 if sys.platform == 'win32':
507 decorated = '"%s"' % sys.executable
508 tester = '"%s"' % tester
509 else:
510 decorated = sys.executable
511
512 retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd)
513 self.assertFalse(retval < 0,
514 "child process caught fatal signal %d" % -retval)
515 self.assertFalse(retval > 0, "child process reports failure %d"%retval)
516
517 @unittest.skipUnless(has_textmode, "text mode not available")
518 def test_textmode(self):
519 # _mkstemp_inner can create files in text mode
520
521 # A text file is truncated at the first Ctrl+Z byte
522 f = self.do_create(bin=0)
523 f.write(b"blat\x1a")
524 f.write(b"extra\n")
525 os.lseek(f.fd, 0, os.SEEK_SET)
526 self.assertEqual(os.read(f.fd, 20), b"blat")
527
528 def make_temp(self):
529 return tempfile._mkstemp_inner(tempfile.gettempdir(),
530 tempfile.gettempprefix(),
531 '',
532 tempfile._bin_openflags,
533 str)
534
535 def test_collision_with_existing_file(self):
536 # _mkstemp_inner tries another name when a file with
537 # the chosen name already exists
538 with _inside_empty_temp_dir(), \
539 _mock_candidate_names('aaa', 'aaa', 'bbb'):
540 (fd1, name1) = self.make_temp()
541 os.close(fd1)
542 self.assertEndsWith(name1, 'aaa')
543
544 (fd2, name2) = self.make_temp()
545 os.close(fd2)
546 self.assertEndsWith(name2, 'bbb')
547
548 def test_collision_with_existing_directory(self):
549 # _mkstemp_inner tries another name when a directory with
550 # the chosen name already exists
551 with _inside_empty_temp_dir(), \
552 _mock_candidate_names('aaa', 'aaa', 'bbb'):
553 dir = tempfile.mkdtemp()
554 self.assertEndsWith(dir, 'aaa')
555
556 (fd, name) = self.make_temp()
557 os.close(fd)
558 self.assertEndsWith(name, 'bbb')
559
560
561 class TestGetTempPrefix(BaseTestCase):
562 """Test gettempprefix()."""
563
564 def test_sane_template(self):
565 # gettempprefix returns a nonempty prefix string
566 p = tempfile.gettempprefix()
567
568 self.assertIsInstance(p, str)
569 self.assertGreater(len(p), 0)
570
571 pb = tempfile.gettempprefixb()
572
573 self.assertIsInstance(pb, bytes)
574 self.assertGreater(len(pb), 0)
575
576 def test_usable_template(self):
577 # gettempprefix returns a usable prefix string
578
579 # Create a temp directory, avoiding use of the prefix.
580 # Then attempt to create a file whose name is
581 # prefix + 'xxxxxx.xxx' in that directory.
582 p = tempfile.gettempprefix() + "xxxxxx.xxx"
583 d = tempfile.mkdtemp(prefix="")
584 try:
585 p = os.path.join(d, p)
586 fd = os.open(p, os.O_RDWR | os.O_CREAT)
587 os.close(fd)
588 os.unlink(p)
589 finally:
590 os.rmdir(d)
591
592
593 class TestGetTempDir(BaseTestCase):
594 """Test gettempdir()."""
595
596 def test_directory_exists(self):
597 # gettempdir returns a directory which exists
598
599 for d in (tempfile.gettempdir(), tempfile.gettempdirb()):
600 self.assertTrue(os.path.isabs(d) or d == os.curdir,
601 "%r is not an absolute path" % d)
602 self.assertTrue(os.path.isdir(d),
603 "%r is not a directory" % d)
604
605 def test_directory_writable(self):
606 # gettempdir returns a directory writable by the user
607
608 # sneaky: just instantiate a NamedTemporaryFile, which
609 # defaults to writing into the directory returned by
610 # gettempdir.
611 with tempfile.NamedTemporaryFile() as file:
612 file.write(b"blat")
613
614 def test_same_thing(self):
615 # gettempdir always returns the same object
616 a = tempfile.gettempdir()
617 b = tempfile.gettempdir()
618 c = tempfile.gettempdirb()
619
620 self.assertTrue(a is b)
621 self.assertNotEqual(type(a), type(c))
622 self.assertEqual(a, os.fsdecode(c))
623
624 def test_case_sensitive(self):
625 # gettempdir should not flatten its case
626 # even on a case-insensitive file system
627 case_sensitive_tempdir = tempfile.mkdtemp("-Temp")
628 _tempdir, tempfile.tempdir = tempfile.tempdir, None
629 try:
630 with os_helper.EnvironmentVarGuard() as env:
631 # Fake the first env var which is checked as a candidate
632 env["TMPDIR"] = case_sensitive_tempdir
633 self.assertEqual(tempfile.gettempdir(), case_sensitive_tempdir)
634 finally:
635 tempfile.tempdir = _tempdir
636 os_helper.rmdir(case_sensitive_tempdir)
637
638
639 class TestMkstemp(BaseTestCase):
640 """Test mkstemp()."""
641
642 def do_create(self, dir=None, pre=None, suf=None):
643 output_type = tempfile._infer_return_type(dir, pre, suf)
644 if dir is None:
645 if output_type is str:
646 dir = tempfile.gettempdir()
647 else:
648 dir = tempfile.gettempdirb()
649 if pre is None:
650 pre = output_type()
651 if suf is None:
652 suf = output_type()
653 (fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf)
654 (ndir, nbase) = os.path.split(name)
655 adir = os.path.abspath(dir)
656 self.assertEqual(adir, ndir,
657 "Directory '%s' incorrectly returned as '%s'" % (adir, ndir))
658
659 try:
660 self.nameCheck(name, dir, pre, suf)
661 finally:
662 os.close(fd)
663 os.unlink(name)
664
665 def test_basic(self):
666 # mkstemp can create files
667 self.do_create()
668 self.do_create(pre="a")
669 self.do_create(suf="b")
670 self.do_create(pre="a", suf="b")
671 self.do_create(pre="aa", suf=".txt")
672 self.do_create(dir=".")
673
674 def test_basic_with_bytes_names(self):
675 # mkstemp can create files when given name parts all
676 # specified as bytes.
677 d = tempfile.gettempdirb()
678 self.do_create(dir=d, suf=b"")
679 self.do_create(dir=d, pre=b"a")
680 self.do_create(dir=d, suf=b"b")
681 self.do_create(dir=d, pre=b"a", suf=b"b")
682 self.do_create(dir=d, pre=b"aa", suf=b".txt")
683 self.do_create(dir=b".")
684 with self.assertRaises(TypeError):
685 self.do_create(dir=".", pre=b"aa", suf=b".txt")
686 with self.assertRaises(TypeError):
687 self.do_create(dir=b".", pre="aa", suf=b".txt")
688 with self.assertRaises(TypeError):
689 self.do_create(dir=b".", pre=b"aa", suf=".txt")
690
691
692 def test_choose_directory(self):
693 # mkstemp can create directories in a user-selected directory
694 dir = tempfile.mkdtemp()
695 try:
696 self.do_create(dir=dir)
697 self.do_create(dir=os_helper.FakePath(dir))
698 finally:
699 os.rmdir(dir)
700
701 def test_for_tempdir_is_bytes_issue40701_api_warts(self):
702 orig_tempdir = tempfile.tempdir
703 self.assertIsInstance(tempfile.tempdir, (str, type(None)))
704 try:
705 fd, path = tempfile.mkstemp()
706 os.close(fd)
707 os.unlink(path)
708 self.assertIsInstance(path, str)
709 tempfile.tempdir = tempfile.gettempdirb()
710 self.assertIsInstance(tempfile.tempdir, bytes)
711 self.assertIsInstance(tempfile.gettempdir(), str)
712 self.assertIsInstance(tempfile.gettempdirb(), bytes)
713 fd, path = tempfile.mkstemp()
714 os.close(fd)
715 os.unlink(path)
716 self.assertIsInstance(path, bytes)
717 fd, path = tempfile.mkstemp(suffix='.txt')
718 os.close(fd)
719 os.unlink(path)
720 self.assertIsInstance(path, str)
721 fd, path = tempfile.mkstemp(prefix='test-temp-')
722 os.close(fd)
723 os.unlink(path)
724 self.assertIsInstance(path, str)
725 fd, path = tempfile.mkstemp(dir=tempfile.gettempdir())
726 os.close(fd)
727 os.unlink(path)
728 self.assertIsInstance(path, str)
729 finally:
730 tempfile.tempdir = orig_tempdir
731
732
733 class TestMkdtemp(TestBadTempdir, BaseTestCase):
734 """Test mkdtemp()."""
735
736 def make_temp(self):
737 return tempfile.mkdtemp()
738
739 def do_create(self, dir=None, pre=None, suf=None):
740 output_type = tempfile._infer_return_type(dir, pre, suf)
741 if dir is None:
742 if output_type is str:
743 dir = tempfile.gettempdir()
744 else:
745 dir = tempfile.gettempdirb()
746 if pre is None:
747 pre = output_type()
748 if suf is None:
749 suf = output_type()
750 name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf)
751
752 try:
753 self.nameCheck(name, dir, pre, suf)
754 return name
755 except:
756 os.rmdir(name)
757 raise
758
759 def test_basic(self):
760 # mkdtemp can create directories
761 os.rmdir(self.do_create())
762 os.rmdir(self.do_create(pre="a"))
763 os.rmdir(self.do_create(suf="b"))
764 os.rmdir(self.do_create(pre="a", suf="b"))
765 os.rmdir(self.do_create(pre="aa", suf=".txt"))
766
767 def test_basic_with_bytes_names(self):
768 # mkdtemp can create directories when given all binary parts
769 d = tempfile.gettempdirb()
770 os.rmdir(self.do_create(dir=d))
771 os.rmdir(self.do_create(dir=d, pre=b"a"))
772 os.rmdir(self.do_create(dir=d, suf=b"b"))
773 os.rmdir(self.do_create(dir=d, pre=b"a", suf=b"b"))
774 os.rmdir(self.do_create(dir=d, pre=b"aa", suf=b".txt"))
775 with self.assertRaises(TypeError):
776 os.rmdir(self.do_create(dir=d, pre="aa", suf=b".txt"))
777 with self.assertRaises(TypeError):
778 os.rmdir(self.do_create(dir=d, pre=b"aa", suf=".txt"))
779 with self.assertRaises(TypeError):
780 os.rmdir(self.do_create(dir="", pre=b"aa", suf=b".txt"))
781
782 def test_basic_many(self):
783 # mkdtemp can create many directories (stochastic)
784 extant = list(range(TEST_FILES))
785 try:
786 for i in extant:
787 extant[i] = self.do_create(pre="aa")
788 finally:
789 for i in extant:
790 if(isinstance(i, str)):
791 os.rmdir(i)
792
793 def test_choose_directory(self):
794 # mkdtemp can create directories in a user-selected directory
795 dir = tempfile.mkdtemp()
796 try:
797 os.rmdir(self.do_create(dir=dir))
798 os.rmdir(self.do_create(dir=os_helper.FakePath(dir)))
799 finally:
800 os.rmdir(dir)
801
802 @os_helper.skip_unless_working_chmod
803 def test_mode(self):
804 # mkdtemp creates directories with the proper mode
805
806 dir = self.do_create()
807 try:
808 mode = stat.S_IMODE(os.stat(dir).st_mode)
809 mode &= 0o777 # Mask off sticky bits inherited from /tmp
810 expected = 0o700
811 if sys.platform == 'win32':
812 # There's no distinction among 'user', 'group' and 'world';
813 # replicate the 'user' bits.
814 user = expected >> 6
815 expected = user * (1 + 8 + 64)
816 self.assertEqual(mode, expected)
817 finally:
818 os.rmdir(dir)
819
820 @unittest.skipUnless(os.name == "nt", "Only on Windows.")
821 def test_mode_win32(self):
822 # Use icacls.exe to extract the users with some level of access
823 # Main thing we are testing is that the BUILTIN\Users group has
824 # no access. The exact ACL is going to vary based on which user
825 # is running the test.
826 dir = self.do_create()
827 try:
828 out = subprocess.check_output(["icacls.exe", dir], encoding="oem").casefold()
829 finally:
830 os.rmdir(dir)
831
832 dir = dir.casefold()
833 users = set()
834 found_user = False
835 for line in out.strip().splitlines():
836 acl = None
837 # First line of result includes our directory
838 if line.startswith(dir):
839 acl = line.removeprefix(dir).strip()
840 elif line and line[:1].isspace():
841 acl = line.strip()
842 if acl:
843 users.add(acl.partition(":")[0])
844
845 self.assertNotIn(r"BUILTIN\Users".casefold(), users)
846
847 def test_collision_with_existing_file(self):
848 # mkdtemp tries another name when a file with
849 # the chosen name already exists
850 with _inside_empty_temp_dir(), \
851 _mock_candidate_names('aaa', 'aaa', 'bbb'):
852 file = tempfile.NamedTemporaryFile(delete=False)
853 file.close()
854 self.assertEndsWith(file.name, 'aaa')
855 dir = tempfile.mkdtemp()
856 self.assertEndsWith(dir, 'bbb')
857
858 def test_collision_with_existing_directory(self):
859 # mkdtemp tries another name when a directory with
860 # the chosen name already exists
861 with _inside_empty_temp_dir(), \
862 _mock_candidate_names('aaa', 'aaa', 'bbb'):
863 dir1 = tempfile.mkdtemp()
864 self.assertEndsWith(dir1, 'aaa')
865 dir2 = tempfile.mkdtemp()
866 self.assertEndsWith(dir2, 'bbb')
867
868 def test_for_tempdir_is_bytes_issue40701_api_warts(self):
869 orig_tempdir = tempfile.tempdir
870 self.assertIsInstance(tempfile.tempdir, (str, type(None)))
871 try:
872 path = tempfile.mkdtemp()
873 os.rmdir(path)
874 self.assertIsInstance(path, str)
875 tempfile.tempdir = tempfile.gettempdirb()
876 self.assertIsInstance(tempfile.tempdir, bytes)
877 self.assertIsInstance(tempfile.gettempdir(), str)
878 self.assertIsInstance(tempfile.gettempdirb(), bytes)
879 path = tempfile.mkdtemp()
880 os.rmdir(path)
881 self.assertIsInstance(path, bytes)
882 path = tempfile.mkdtemp(suffix='-dir')
883 os.rmdir(path)
884 self.assertIsInstance(path, str)
885 path = tempfile.mkdtemp(prefix='test-mkdtemp-')
886 os.rmdir(path)
887 self.assertIsInstance(path, str)
888 path = tempfile.mkdtemp(dir=tempfile.gettempdir())
889 os.rmdir(path)
890 self.assertIsInstance(path, str)
891 finally:
892 tempfile.tempdir = orig_tempdir
893
894 def test_path_is_absolute(self):
895 # Test that the path returned by mkdtemp with a relative `dir`
896 # argument is absolute
897 try:
898 path = tempfile.mkdtemp(dir=".")
899 self.assertTrue(os.path.isabs(path))
900 finally:
901 os.rmdir(path)
902
903
904 class TestMktemp(BaseTestCase):
905 """Test mktemp()."""
906
907 # For safety, all use of mktemp must occur in a private directory.
908 # We must also suppress the RuntimeWarning it generates.
909 def setUp(self):
910 self.dir = tempfile.mkdtemp()
911 super().setUp()
912
913 def tearDown(self):
914 if self.dir:
915 os.rmdir(self.dir)
916 self.dir = None
917 super().tearDown()
918
919 class mktemped:
920 _unlink = os.unlink
921 _bflags = tempfile._bin_openflags
922
923 def __init__(self, dir, pre, suf):
924 self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf)
925 # Create the file. This will raise an exception if it's
926 # mysteriously appeared in the meanwhile.
927 os.close(os.open(self.name, self._bflags, 0o600))
928
929 def __del__(self):
930 self._unlink(self.name)
931
932 def do_create(self, pre="", suf=""):
933 file = self.mktemped(self.dir, pre, suf)
934
935 self.nameCheck(file.name, self.dir, pre, suf)
936 return file
937
938 def test_basic(self):
939 # mktemp can choose usable file names
940 self.do_create()
941 self.do_create(pre="a")
942 self.do_create(suf="b")
943 self.do_create(pre="a", suf="b")
944 self.do_create(pre="aa", suf=".txt")
945
946 def test_many(self):
947 # mktemp can choose many usable file names (stochastic)
948 extant = list(range(TEST_FILES))
949 for i in extant:
950 extant[i] = self.do_create(pre="aa")
951 del extant
952 support.gc_collect() # For PyPy or other GCs.
953
954 ## def test_warning(self):
955 ## # mktemp issues a warning when used
956 ## warnings.filterwarnings("error",
957 ## category=RuntimeWarning,
958 ## message="mktemp")
959 ## self.assertRaises(RuntimeWarning,
960 ## tempfile.mktemp, dir=self.dir)
961
962
963 # We test _TemporaryFileWrapper by testing NamedTemporaryFile.
964
965
966 class TestNamedTemporaryFile(BaseTestCase):
967 """Test NamedTemporaryFile()."""
968
969 def do_create(self, dir=None, pre="", suf="", delete=True):
970 if dir is None:
971 dir = tempfile.gettempdir()
972 file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf,
973 delete=delete)
974
975 self.nameCheck(file.name, dir, pre, suf)
976 return file
977
978
979 def test_basic(self):
980 # NamedTemporaryFile can create files
981 self.do_create()
982 self.do_create(pre="a")
983 self.do_create(suf="b")
984 self.do_create(pre="a", suf="b")
985 self.do_create(pre="aa", suf=".txt")
986
987 def test_method_lookup(self):
988 # Issue #18879: Looking up a temporary file method should keep it
989 # alive long enough.
990 f = self.do_create()
991 wr = weakref.ref(f)
992 write = f.write
993 write2 = f.write
994 del f
995 write(b'foo')
996 del write
997 write2(b'bar')
998 del write2
999 if support.check_impl_detail(cpython=True):
1000 # No reference cycle was created.
1001 self.assertIsNone(wr())
1002
1003 def test_iter(self):
1004 # Issue #23700: getting iterator from a temporary file should keep
1005 # it alive as long as it's being iterated over
1006 lines = [b'spam\n', b'eggs\n', b'beans\n']
1007 def make_file():
1008 f = tempfile.NamedTemporaryFile(mode='w+b')
1009 f.write(b''.join(lines))
1010 f.seek(0)
1011 return f
1012 for i, l in enumerate(make_file()):
1013 self.assertEqual(l, lines[i])
1014 self.assertEqual(i, len(lines) - 1)
1015
1016 def test_creates_named(self):
1017 # NamedTemporaryFile creates files with names
1018 f = tempfile.NamedTemporaryFile()
1019 self.assertTrue(os.path.exists(f.name),
1020 "NamedTemporaryFile %s does not exist" % f.name)
1021
1022 def test_del_on_close(self):
1023 # A NamedTemporaryFile is deleted when closed
1024 dir = tempfile.mkdtemp()
1025 try:
1026 with tempfile.NamedTemporaryFile(dir=dir) as f:
1027 f.write(b'blat')
1028 self.assertEqual(os.listdir(dir), [])
1029 self.assertFalse(os.path.exists(f.name),
1030 "NamedTemporaryFile %s exists after close" % f.name)
1031 finally:
1032 os.rmdir(dir)
1033
1034 def test_dis_del_on_close(self):
1035 # Tests that delete-on-close can be disabled
1036 dir = tempfile.mkdtemp()
1037 tmp = None
1038 try:
1039 f = tempfile.NamedTemporaryFile(dir=dir, delete=False)
1040 tmp = f.name
1041 f.write(b'blat')
1042 f.close()
1043 self.assertTrue(os.path.exists(f.name),
1044 "NamedTemporaryFile %s missing after close" % f.name)
1045 finally:
1046 if tmp is not None:
1047 os.unlink(tmp)
1048 os.rmdir(dir)
1049
1050 def test_multiple_close(self):
1051 # A NamedTemporaryFile can be closed many times without error
1052 f = tempfile.NamedTemporaryFile()
1053 f.write(b'abc\n')
1054 f.close()
1055 f.close()
1056 f.close()
1057
1058 def test_context_manager(self):
1059 # A NamedTemporaryFile can be used as a context manager
1060 with tempfile.NamedTemporaryFile() as f:
1061 self.assertTrue(os.path.exists(f.name))
1062 self.assertFalse(os.path.exists(f.name))
1063 def use_closed():
1064 with f:
1065 pass
1066 self.assertRaises(ValueError, use_closed)
1067
1068 def test_context_man_not_del_on_close_if_delete_on_close_false(self):
1069 # Issue gh-58451: tempfile.NamedTemporaryFile is not particularly useful
1070 # on Windows
1071 # A NamedTemporaryFile is NOT deleted when closed if
1072 # delete_on_close=False, but is deleted on context manager exit
1073 dir = tempfile.mkdtemp()
1074 try:
1075 with tempfile.NamedTemporaryFile(dir=dir,
1076 delete=True,
1077 delete_on_close=False) as f:
1078 f.write(b'blat')
1079 f_name = f.name
1080 f.close()
1081 with self.subTest():
1082 # Testing that file is not deleted on close
1083 self.assertTrue(os.path.exists(f.name),
1084 f"NamedTemporaryFile {f.name!r} is incorrectly "
1085 f"deleted on closure when delete_on_close=False")
1086
1087 with self.subTest():
1088 # Testing that file is deleted on context manager exit
1089 self.assertFalse(os.path.exists(f.name),
1090 f"NamedTemporaryFile {f.name!r} exists "
1091 f"after context manager exit")
1092
1093 finally:
1094 os.rmdir(dir)
1095
1096 def test_context_man_ok_to_delete_manually(self):
1097 # In the case of delete=True, a NamedTemporaryFile can be manually
1098 # deleted in a with-statement context without causing an error.
1099 dir = tempfile.mkdtemp()
1100 try:
1101 with tempfile.NamedTemporaryFile(dir=dir,
1102 delete=True,
1103 delete_on_close=False) as f:
1104 f.write(b'blat')
1105 f.close()
1106 os.unlink(f.name)
1107
1108 finally:
1109 os.rmdir(dir)
1110
1111 def test_context_man_not_del_if_delete_false(self):
1112 # A NamedTemporaryFile is not deleted if delete = False
1113 dir = tempfile.mkdtemp()
1114 f_name = ""
1115 try:
1116 # Test that delete_on_close=True has no effect if delete=False.
1117 with tempfile.NamedTemporaryFile(dir=dir, delete=False,
1118 delete_on_close=True) as f:
1119 f.write(b'blat')
1120 f_name = f.name
1121 self.assertTrue(os.path.exists(f.name),
1122 f"NamedTemporaryFile {f.name!r} exists after close")
1123 finally:
1124 os.unlink(f_name)
1125 os.rmdir(dir)
1126
1127 def test_del_by_finalizer(self):
1128 # A NamedTemporaryFile is deleted when finalized in the case of
1129 # delete=True, delete_on_close=False, and no with-statement is used.
1130 def my_func(dir):
1131 f = tempfile.NamedTemporaryFile(dir=dir, delete=True,
1132 delete_on_close=False)
1133 tmp_name = f.name
1134 f.write(b'blat')
1135 # Testing extreme case, where the file is not explicitly closed
1136 # f.close()
1137 return tmp_name
1138 dir = tempfile.mkdtemp()
1139 try:
1140 with self.assertWarnsRegex(
1141 expected_warning=ResourceWarning,
1142 expected_regex=r"Implicitly cleaning up <_TemporaryFileWrapper file=.*>",
1143 ):
1144 tmp_name = my_func(dir)
1145 support.gc_collect()
1146 self.assertFalse(os.path.exists(tmp_name),
1147 f"NamedTemporaryFile {tmp_name!r} "
1148 f"exists after finalizer ")
1149 finally:
1150 os.rmdir(dir)
1151
1152 def test_correct_finalizer_work_if_already_deleted(self):
1153 # There should be no error in the case of delete=True,
1154 # delete_on_close=False, no with-statement is used, and the file is
1155 # deleted manually.
1156 def my_func(dir)->str:
1157 f = tempfile.NamedTemporaryFile(dir=dir, delete=True,
1158 delete_on_close=False)
1159 tmp_name = f.name
1160 f.write(b'blat')
1161 f.close()
1162 os.unlink(tmp_name)
1163 return tmp_name
1164 # Make sure that the garbage collector has finalized the file object.
1165 gc.collect()
1166
1167 def test_bad_mode(self):
1168 dir = tempfile.mkdtemp()
1169 self.addCleanup(os_helper.rmtree, dir)
1170 with self.assertRaises(ValueError):
1171 tempfile.NamedTemporaryFile(mode='wr', dir=dir)
1172 with self.assertRaises(TypeError):
1173 tempfile.NamedTemporaryFile(mode=2, dir=dir)
1174 self.assertEqual(os.listdir(dir), [])
1175
1176 def test_bad_encoding(self):
1177 dir = tempfile.mkdtemp()
1178 self.addCleanup(os_helper.rmtree, dir)
1179 with self.assertRaises(LookupError):
1180 tempfile.NamedTemporaryFile('w', encoding='bad-encoding', dir=dir)
1181 self.assertEqual(os.listdir(dir), [])
1182
1183 def test_unexpected_error(self):
1184 dir = tempfile.mkdtemp()
1185 self.addCleanup(os_helper.rmtree, dir)
1186 with mock.patch('tempfile._TemporaryFileWrapper') as mock_ntf, \
1187 mock.patch('io.open', mock.mock_open()) as mock_open:
1188 mock_ntf.side_effect = KeyboardInterrupt()
1189 with self.assertRaises(KeyboardInterrupt):
1190 tempfile.NamedTemporaryFile(dir=dir)
1191 mock_open().close.assert_called()
1192 self.assertEqual(os.listdir(dir), [])
1193
1194 # How to test the mode and bufsize parameters?
1195
1196 class TestSpooledTemporaryFile(BaseTestCase):
1197 """Test SpooledTemporaryFile()."""
1198
1199 def do_create(self, max_size=0, dir=None, pre="", suf=""):
1200 if dir is None:
1201 dir = tempfile.gettempdir()
1202 file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf)
1203
1204 return file
1205
1206
1207 def test_basic(self):
1208 # SpooledTemporaryFile can create files
1209 f = self.do_create()
1210 self.assertFalse(f._rolled)
1211 f = self.do_create(max_size=100, pre="a", suf=".txt")
1212 self.assertFalse(f._rolled)
1213
1214 def test_is_iobase(self):
1215 # SpooledTemporaryFile should implement io.IOBase
1216 self.assertIsInstance(self.do_create(), io.IOBase)
1217
1218 def test_iobase_interface(self):
1219 # SpooledTemporaryFile should implement the io.IOBase interface.
1220 # Ensure it has all the required methods and properties.
1221 iobase_attrs = {
1222 # From IOBase
1223 'fileno', 'seek', 'truncate', 'close', 'closed', '__enter__',
1224 '__exit__', 'flush', 'isatty', '__iter__', '__next__', 'readable',
1225 'readline', 'readlines', 'seekable', 'tell', 'writable',
1226 'writelines',
1227 # From BufferedIOBase (binary mode) and TextIOBase (text mode)
1228 'detach', 'read', 'read1', 'write', 'readinto', 'readinto1',
1229 'encoding', 'errors', 'newlines',
1230 }
1231 spooledtempfile_attrs = set(dir(tempfile.SpooledTemporaryFile))
1232 missing_attrs = iobase_attrs - spooledtempfile_attrs
1233 self.assertFalse(
1234 missing_attrs,
1235 'SpooledTemporaryFile missing attributes from '
1236 'IOBase/BufferedIOBase/TextIOBase'
1237 )
1238
1239 def test_del_on_close(self):
1240 # A SpooledTemporaryFile is deleted when closed
1241 dir = tempfile.mkdtemp()
1242 try:
1243 f = tempfile.SpooledTemporaryFile(max_size=10, dir=dir)
1244 self.assertFalse(f._rolled)
1245 f.write(b'blat ' * 5)
1246 self.assertTrue(f._rolled)
1247 filename = f.name
1248 f.close()
1249 self.assertEqual(os.listdir(dir), [])
1250 if not isinstance(filename, int):
1251 self.assertFalse(os.path.exists(filename),
1252 "SpooledTemporaryFile %s exists after close" % filename)
1253 finally:
1254 os.rmdir(dir)
1255
1256 def test_del_unrolled_file(self):
1257 # The unrolled SpooledTemporaryFile should raise a ResourceWarning
1258 # when deleted since the file was not explicitly closed.
1259 f = self.do_create(max_size=10)
1260 f.write(b'foo')
1261 self.assertEqual(f.name, None) # Unrolled so no filename/fd
1262 with self.assertWarns(ResourceWarning):
1263 f.__del__()
1264
1265 def test_del_rolled_file(self):
1266 # The rolled file should be deleted when the SpooledTemporaryFile
1267 # object is deleted. This should raise a ResourceWarning since the file
1268 # was not explicitly closed.
1269 f = self.do_create(max_size=2)
1270 f.write(b'foo')
1271 name = f.name # This is a fd on posix+cygwin, a filename everywhere else
1272 self.assertTrue(os.path.exists(name))
1273 with self.assertWarns(ResourceWarning):
1274 f.__del__()
1275 self.assertFalse(
1276 os.path.exists(name),
1277 "Rolled SpooledTemporaryFile (name=%s) exists after delete" % name
1278 )
1279
1280 def test_rewrite_small(self):
1281 # A SpooledTemporaryFile can be written to multiple within the max_size
1282 f = self.do_create(max_size=30)
1283 self.assertFalse(f._rolled)
1284 for i in range(5):
1285 f.seek(0, 0)
1286 f.write(b'x' * 20)
1287 self.assertFalse(f._rolled)
1288
1289 def test_write_sequential(self):
1290 # A SpooledTemporaryFile should hold exactly max_size bytes, and roll
1291 # over afterward
1292 f = self.do_create(max_size=30)
1293 self.assertFalse(f._rolled)
1294 f.write(b'x' * 20)
1295 self.assertFalse(f._rolled)
1296 f.write(b'x' * 10)
1297 self.assertFalse(f._rolled)
1298 f.write(b'x')
1299 self.assertTrue(f._rolled)
1300
1301 def test_writelines(self):
1302 # Verify writelines with a SpooledTemporaryFile
1303 f = self.do_create()
1304 f.writelines((b'x', b'y', b'z'))
1305 pos = f.seek(0)
1306 self.assertEqual(pos, 0)
1307 buf = f.read()
1308 self.assertEqual(buf, b'xyz')
1309
1310 def test_writelines_rollover(self):
1311 # Verify writelines rolls over before exhausting the iterator
1312 f = self.do_create(max_size=2)
1313
1314 def it():
1315 yield b'xy'
1316 self.assertFalse(f._rolled)
1317 yield b'z'
1318 self.assertTrue(f._rolled)
1319
1320 f.writelines(it())
1321 pos = f.seek(0)
1322 self.assertEqual(pos, 0)
1323 buf = f.read()
1324 self.assertEqual(buf, b'xyz')
1325
1326 def test_writelines_fast_path(self):
1327 f = self.do_create(max_size=2)
1328 f.write(b'abc')
1329 self.assertTrue(f._rolled)
1330
1331 f.writelines([b'd', b'e', b'f'])
1332 pos = f.seek(0)
1333 self.assertEqual(pos, 0)
1334 buf = f.read()
1335 self.assertEqual(buf, b'abcdef')
1336
1337
1338 def test_writelines_sequential(self):
1339 # A SpooledTemporaryFile should hold exactly max_size bytes, and roll
1340 # over afterward
1341 f = self.do_create(max_size=35)
1342 f.writelines((b'x' * 20, b'x' * 10, b'x' * 5))
1343 self.assertFalse(f._rolled)
1344 f.write(b'x')
1345 self.assertTrue(f._rolled)
1346
1347 def test_sparse(self):
1348 # A SpooledTemporaryFile that is written late in the file will extend
1349 # when that occurs
1350 f = self.do_create(max_size=30)
1351 self.assertFalse(f._rolled)
1352 pos = f.seek(100, 0)
1353 self.assertEqual(pos, 100)
1354 self.assertFalse(f._rolled)
1355 f.write(b'x')
1356 self.assertTrue(f._rolled)
1357
1358 def test_fileno(self):
1359 # A SpooledTemporaryFile should roll over to a real file on fileno()
1360 f = self.do_create(max_size=30)
1361 self.assertFalse(f._rolled)
1362 self.assertTrue(f.fileno() > 0)
1363 self.assertTrue(f._rolled)
1364
1365 def test_multiple_close_before_rollover(self):
1366 # A SpooledTemporaryFile can be closed many times without error
1367 f = tempfile.SpooledTemporaryFile()
1368 f.write(b'abc\n')
1369 self.assertFalse(f._rolled)
1370 f.close()
1371 f.close()
1372 f.close()
1373
1374 def test_multiple_close_after_rollover(self):
1375 # A SpooledTemporaryFile can be closed many times without error
1376 f = tempfile.SpooledTemporaryFile(max_size=1)
1377 f.write(b'abc\n')
1378 self.assertTrue(f._rolled)
1379 f.close()
1380 f.close()
1381 f.close()
1382
1383 def test_bound_methods(self):
1384 # It should be OK to steal a bound method from a SpooledTemporaryFile
1385 # and use it independently; when the file rolls over, those bound
1386 # methods should continue to function
1387 f = self.do_create(max_size=30)
1388 read = f.read
1389 write = f.write
1390 seek = f.seek
1391
1392 write(b"a" * 35)
1393 write(b"b" * 35)
1394 seek(0, 0)
1395 self.assertEqual(read(70), b'a'*35 + b'b'*35)
1396
1397 def test_properties(self):
1398 f = tempfile.SpooledTemporaryFile(max_size=10)
1399 f.write(b'x' * 10)
1400 self.assertFalse(f._rolled)
1401 self.assertEqual(f.mode, 'w+b')
1402 self.assertIsNone(f.name)
1403 with self.assertRaises(AttributeError):
1404 f.newlines
1405 with self.assertRaises(AttributeError):
1406 f.encoding
1407 with self.assertRaises(AttributeError):
1408 f.errors
1409
1410 f.write(b'x')
1411 self.assertTrue(f._rolled)
1412 self.assertEqual(f.mode, 'rb+')
1413 self.assertIsNotNone(f.name)
1414 with self.assertRaises(AttributeError):
1415 f.newlines
1416 with self.assertRaises(AttributeError):
1417 f.encoding
1418 with self.assertRaises(AttributeError):
1419 f.errors
1420
1421 def test_text_mode(self):
1422 # Creating a SpooledTemporaryFile with a text mode should produce
1423 # a file object reading and writing (Unicode) text strings.
1424 f = tempfile.SpooledTemporaryFile(mode='w+', max_size=10,
1425 encoding="utf-8")
1426 f.write("abc\n")
1427 f.seek(0)
1428 self.assertEqual(f.read(), "abc\n")
1429 f.write("def\n")
1430 f.seek(0)
1431 self.assertEqual(f.read(), "abc\ndef\n")
1432 self.assertFalse(f._rolled)
1433 self.assertEqual(f.mode, 'w+')
1434 self.assertIsNone(f.name)
1435 self.assertEqual(f.newlines, os.linesep)
1436 self.assertEqual(f.encoding, "utf-8")
1437 self.assertEqual(f.errors, "strict")
1438
1439 f.write("xyzzy\n")
1440 f.seek(0)
1441 self.assertEqual(f.read(), "abc\ndef\nxyzzy\n")
1442 # Check that Ctrl+Z doesn't truncate the file
1443 f.write("foo\x1abar\n")
1444 f.seek(0)
1445 self.assertEqual(f.read(), "abc\ndef\nxyzzy\nfoo\x1abar\n")
1446 self.assertTrue(f._rolled)
1447 self.assertEqual(f.mode, 'w+')
1448 self.assertIsNotNone(f.name)
1449 self.assertEqual(f.newlines, os.linesep)
1450 self.assertEqual(f.encoding, "utf-8")
1451 self.assertEqual(f.errors, "strict")
1452
1453 def test_text_newline_and_encoding(self):
1454 f = tempfile.SpooledTemporaryFile(mode='w+', max_size=10,
1455 newline='', encoding='utf-8',
1456 errors='ignore')
1457 f.write("\u039B\r\n")
1458 f.seek(0)
1459 self.assertEqual(f.read(), "\u039B\r\n")
1460 self.assertFalse(f._rolled)
1461 self.assertEqual(f.mode, 'w+')
1462 self.assertIsNone(f.name)
1463 self.assertIsNotNone(f.newlines)
1464 self.assertEqual(f.encoding, "utf-8")
1465 self.assertEqual(f.errors, "ignore")
1466
1467 f.write("\u039C" * 10 + "\r\n")
1468 f.write("\u039D" * 20)
1469 f.seek(0)
1470 self.assertEqual(f.read(),
1471 "\u039B\r\n" + ("\u039C" * 10) + "\r\n" + ("\u039D" * 20))
1472 self.assertTrue(f._rolled)
1473 self.assertEqual(f.mode, 'w+')
1474 self.assertIsNotNone(f.name)
1475 self.assertIsNotNone(f.newlines)
1476 self.assertEqual(f.encoding, 'utf-8')
1477 self.assertEqual(f.errors, 'ignore')
1478
1479 def test_context_manager_before_rollover(self):
1480 # A SpooledTemporaryFile can be used as a context manager
1481 with tempfile.SpooledTemporaryFile(max_size=1) as f:
1482 self.assertFalse(f._rolled)
1483 self.assertFalse(f.closed)
1484 self.assertTrue(f.closed)
1485 def use_closed():
1486 with f:
1487 pass
1488 self.assertRaises(ValueError, use_closed)
1489
1490 def test_context_manager_during_rollover(self):
1491 # A SpooledTemporaryFile can be used as a context manager
1492 with tempfile.SpooledTemporaryFile(max_size=1) as f:
1493 self.assertFalse(f._rolled)
1494 f.write(b'abc\n')
1495 f.flush()
1496 self.assertTrue(f._rolled)
1497 self.assertFalse(f.closed)
1498 self.assertTrue(f.closed)
1499 def use_closed():
1500 with f:
1501 pass
1502 self.assertRaises(ValueError, use_closed)
1503
1504 def test_context_manager_after_rollover(self):
1505 # A SpooledTemporaryFile can be used as a context manager
1506 f = tempfile.SpooledTemporaryFile(max_size=1)
1507 f.write(b'abc\n')
1508 f.flush()
1509 self.assertTrue(f._rolled)
1510 with f:
1511 self.assertFalse(f.closed)
1512 self.assertTrue(f.closed)
1513 def use_closed():
1514 with f:
1515 pass
1516 self.assertRaises(ValueError, use_closed)
1517
1518 def test_truncate_with_size_parameter(self):
1519 # A SpooledTemporaryFile can be truncated to zero size
1520 f = tempfile.SpooledTemporaryFile(max_size=10)
1521 f.write(b'abcdefg\n')
1522 f.seek(0)
1523 f.truncate()
1524 self.assertFalse(f._rolled)
1525 self.assertEqual(f._file.getvalue(), b'')
1526 # A SpooledTemporaryFile can be truncated to a specific size
1527 f = tempfile.SpooledTemporaryFile(max_size=10)
1528 f.write(b'abcdefg\n')
1529 f.truncate(4)
1530 self.assertFalse(f._rolled)
1531 self.assertEqual(f._file.getvalue(), b'abcd')
1532 # A SpooledTemporaryFile rolls over if truncated to large size
1533 f = tempfile.SpooledTemporaryFile(max_size=10)
1534 f.write(b'abcdefg\n')
1535 f.truncate(20)
1536 self.assertTrue(f._rolled)
1537 self.assertEqual(os.fstat(f.fileno()).st_size, 20)
1538
1539 def test_class_getitem(self):
1540 self.assertIsInstance(tempfile.SpooledTemporaryFile[bytes],
1541 types.GenericAlias)
1542
1543 if tempfile.NamedTemporaryFile is not tempfile.TemporaryFile:
1544
1545 class TestTemporaryFile(BaseTestCase):
1546 """Test TemporaryFile()."""
1547
1548 def test_basic(self):
1549 # TemporaryFile can create files
1550 # No point in testing the name params - the file has no name.
1551 tempfile.TemporaryFile()
1552
1553 def test_has_no_name(self):
1554 # TemporaryFile creates files with no names (on this system)
1555 dir = tempfile.mkdtemp()
1556 f = tempfile.TemporaryFile(dir=dir)
1557 f.write(b'blat')
1558
1559 # Sneaky: because this file has no name, it should not prevent
1560 # us from removing the directory it was created in.
1561 try:
1562 os.rmdir(dir)
1563 except:
1564 # cleanup
1565 f.close()
1566 os.rmdir(dir)
1567 raise
1568
1569 def test_multiple_close(self):
1570 # A TemporaryFile can be closed many times without error
1571 f = tempfile.TemporaryFile()
1572 f.write(b'abc\n')
1573 f.close()
1574 f.close()
1575 f.close()
1576
1577 # How to test the mode and bufsize parameters?
1578 def test_mode_and_encoding(self):
1579
1580 def roundtrip(input, *args, **kwargs):
1581 with tempfile.TemporaryFile(*args, **kwargs) as fileobj:
1582 fileobj.write(input)
1583 fileobj.seek(0)
1584 self.assertEqual(input, fileobj.read())
1585
1586 roundtrip(b"1234", "w+b")
1587 roundtrip("abdc\n", "w+")
1588 roundtrip("\u039B", "w+", encoding="utf-16")
1589 roundtrip("foo\r\n", "w+", newline="")
1590
1591 def test_bad_mode(self):
1592 dir = tempfile.mkdtemp()
1593 self.addCleanup(os_helper.rmtree, dir)
1594 with self.assertRaises(ValueError):
1595 tempfile.TemporaryFile(mode='wr', dir=dir)
1596 with self.assertRaises(TypeError):
1597 tempfile.TemporaryFile(mode=2, dir=dir)
1598 self.assertEqual(os.listdir(dir), [])
1599
1600 def test_bad_encoding(self):
1601 dir = tempfile.mkdtemp()
1602 self.addCleanup(os_helper.rmtree, dir)
1603 with self.assertRaises(LookupError):
1604 tempfile.TemporaryFile('w', encoding='bad-encoding', dir=dir)
1605 self.assertEqual(os.listdir(dir), [])
1606
1607 def test_unexpected_error(self):
1608 dir = tempfile.mkdtemp()
1609 self.addCleanup(os_helper.rmtree, dir)
1610 with mock.patch('tempfile._O_TMPFILE_WORKS', False), \
1611 mock.patch('os.unlink') as mock_unlink, \
1612 mock.patch('os.open') as mock_open, \
1613 mock.patch('os.close') as mock_close:
1614 mock_unlink.side_effect = KeyboardInterrupt()
1615 with self.assertRaises(KeyboardInterrupt):
1616 tempfile.TemporaryFile(dir=dir)
1617 mock_close.assert_called()
1618 self.assertEqual(os.listdir(dir), [])
1619
1620
1621 # Helper for test_del_on_shutdown
1622 class NulledModules:
1623 def __init__(self, *modules):
1624 self.refs = [mod.__dict__ for mod in modules]
1625 self.contents = [ref.copy() for ref in self.refs]
1626
1627 def __enter__(self):
1628 for d in self.refs:
1629 for key in d:
1630 d[key] = None
1631
1632 def __exit__(self, *exc_info):
1633 for d, c in zip(self.refs, self.contents):
1634 d.clear()
1635 d.update(c)
1636
1637
1638 class TestTemporaryDirectory(BaseTestCase):
1639 """Test TemporaryDirectory()."""
1640
1641 def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
1642 ignore_cleanup_errors=False):
1643 if dir is None:
1644 dir = tempfile.gettempdir()
1645 tmp = tempfile.TemporaryDirectory(
1646 dir=dir, prefix=pre, suffix=suf,
1647 ignore_cleanup_errors=ignore_cleanup_errors)
1648 self.nameCheck(tmp.name, dir, pre, suf)
1649 self.do_create2(tmp.name, recurse, dirs, files)
1650 return tmp
1651
1652 def do_create2(self, path, recurse=1, dirs=1, files=1):
1653 # Create subdirectories and some files
1654 if recurse:
1655 for i in range(dirs):
1656 name = os.path.join(path, "dir%d" % i)
1657 os.mkdir(name)
1658 self.do_create2(name, recurse-1, dirs, files)
1659 for i in range(files):
1660 with open(os.path.join(path, "test%d.txt" % i), "wb") as f:
1661 f.write(b"Hello world!")
1662
1663 def test_mkdtemp_failure(self):
1664 # Check no additional exception if mkdtemp fails
1665 # Previously would raise AttributeError instead
1666 # (noted as part of Issue #10188)
1667 with tempfile.TemporaryDirectory() as nonexistent:
1668 pass
1669 with self.assertRaises(FileNotFoundError) as cm:
1670 tempfile.TemporaryDirectory(dir=nonexistent)
1671 self.assertEqual(cm.exception.errno, errno.ENOENT)
1672
1673 def test_explicit_cleanup(self):
1674 # A TemporaryDirectory is deleted when cleaned up
1675 dir = tempfile.mkdtemp()
1676 try:
1677 d = self.do_create(dir=dir)
1678 self.assertTrue(os.path.exists(d.name),
1679 "TemporaryDirectory %s does not exist" % d.name)
1680 d.cleanup()
1681 self.assertFalse(os.path.exists(d.name),
1682 "TemporaryDirectory %s exists after cleanup" % d.name)
1683 finally:
1684 os.rmdir(dir)
1685
1686 def test_explicit_cleanup_ignore_errors(self):
1687 """Test that cleanup doesn't return an error when ignoring them."""
1688 with tempfile.TemporaryDirectory() as working_dir:
1689 temp_dir = self.do_create(
1690 dir=working_dir, ignore_cleanup_errors=True)
1691 temp_path = pathlib.Path(temp_dir.name)
1692 self.assertTrue(temp_path.exists(),
1693 f"TemporaryDirectory {temp_path!s} does not exist")
1694 with open(temp_path / "a_file.txt", "w+t") as open_file:
1695 open_file.write("Hello world!\n")
1696 temp_dir.cleanup()
1697 self.assertEqual(len(list(temp_path.glob("*"))),
1698 int(sys.platform.startswith("win")),
1699 "Unexpected number of files in "
1700 f"TemporaryDirectory {temp_path!s}")
1701 self.assertEqual(
1702 temp_path.exists(),
1703 sys.platform.startswith("win"),
1704 f"TemporaryDirectory {temp_path!s} existence state unexpected")
1705 temp_dir.cleanup()
1706 self.assertFalse(
1707 temp_path.exists(),
1708 f"TemporaryDirectory {temp_path!s} exists after cleanup")
1709
1710 @unittest.skipUnless(os.name == "nt", "Only on Windows.")
1711 def test_explicit_cleanup_correct_error(self):
1712 with tempfile.TemporaryDirectory() as working_dir:
1713 temp_dir = self.do_create(dir=working_dir)
1714 with open(os.path.join(temp_dir.name, "example.txt"), 'wb'):
1715 # Previously raised NotADirectoryError on some OSes
1716 # (e.g. Windows). See bpo-43153.
1717 with self.assertRaises(PermissionError):
1718 temp_dir.cleanup()
1719
1720 @unittest.skipUnless(os.name == "nt", "Only on Windows.")
1721 def test_cleanup_with_used_directory(self):
1722 with tempfile.TemporaryDirectory() as working_dir:
1723 temp_dir = self.do_create(dir=working_dir)
1724 subdir = os.path.join(temp_dir.name, "subdir")
1725 os.mkdir(subdir)
1726 with os_helper.change_cwd(subdir):
1727 # Previously raised RecursionError on some OSes
1728 # (e.g. Windows). See bpo-35144.
1729 with self.assertRaises(PermissionError):
1730 temp_dir.cleanup()
1731
1732 @os_helper.skip_unless_symlink
1733 def test_cleanup_with_symlink_to_a_directory(self):
1734 # cleanup() should not follow symlinks to directories (issue #12464)
1735 d1 = self.do_create()
1736 d2 = self.do_create(recurse=0)
1737
1738 # Symlink d1/foo -> d2
1739 os.symlink(d2.name, os.path.join(d1.name, "foo"))
1740
1741 # This call to cleanup() should not follow the "foo" symlink
1742 d1.cleanup()
1743
1744 self.assertFalse(os.path.exists(d1.name),
1745 "TemporaryDirectory %s exists after cleanup" % d1.name)
1746 self.assertTrue(os.path.exists(d2.name),
1747 "Directory pointed to by a symlink was deleted")
1748 self.assertEqual(os.listdir(d2.name), ['test0.txt'],
1749 "Contents of the directory pointed to by a symlink "
1750 "were deleted")
1751 d2.cleanup()
1752
1753 @os_helper.skip_unless_symlink
1754 def test_cleanup_with_symlink_modes(self):
1755 # cleanup() should not follow symlinks when fixing mode bits (#91133)
1756 with self.do_create(recurse=0) as d2:
1757 file1 = os.path.join(d2, 'file1')
1758 open(file1, 'wb').close()
1759 dir1 = os.path.join(d2, 'dir1')
1760 os.mkdir(dir1)
1761 for mode in range(8):
1762 mode <<= 6
1763 with self.subTest(mode=format(mode, '03o')):
1764 def test(target, target_is_directory):
1765 d1 = self.do_create(recurse=0)
1766 symlink = os.path.join(d1.name, 'symlink')
1767 os.symlink(target, symlink,
1768 target_is_directory=target_is_directory)
1769 try:
1770 os.chmod(symlink, mode, follow_symlinks=False)
1771 except NotImplementedError:
1772 pass
1773 try:
1774 os.chmod(symlink, mode)
1775 except FileNotFoundError:
1776 pass
1777 os.chmod(d1.name, mode)
1778 d1.cleanup()
1779 self.assertFalse(os.path.exists(d1.name))
1780
1781 with self.subTest('nonexisting file'):
1782 test('nonexisting', target_is_directory=False)
1783 with self.subTest('nonexisting dir'):
1784 test('nonexisting', target_is_directory=True)
1785
1786 with self.subTest('existing file'):
1787 os.chmod(file1, mode)
1788 old_mode = os.stat(file1).st_mode
1789 test(file1, target_is_directory=False)
1790 new_mode = os.stat(file1).st_mode
1791 self.assertEqual(new_mode, old_mode,
1792 '%03o != %03o' % (new_mode, old_mode))
1793
1794 with self.subTest('existing dir'):
1795 os.chmod(dir1, mode)
1796 old_mode = os.stat(dir1).st_mode
1797 test(dir1, target_is_directory=True)
1798 new_mode = os.stat(dir1).st_mode
1799 self.assertEqual(new_mode, old_mode,
1800 '%03o != %03o' % (new_mode, old_mode))
1801
1802 @unittest.skipUnless(hasattr(os, 'chflags'), 'requires os.chflags')
1803 @os_helper.skip_unless_symlink
1804 def test_cleanup_with_symlink_flags(self):
1805 # cleanup() should not follow symlinks when fixing flags (#91133)
1806 flags = stat.UF_IMMUTABLE | stat.UF_NOUNLINK
1807 self.check_flags(flags)
1808
1809 with self.do_create(recurse=0) as d2:
1810 file1 = os.path.join(d2, 'file1')
1811 open(file1, 'wb').close()
1812 dir1 = os.path.join(d2, 'dir1')
1813 os.mkdir(dir1)
1814 def test(target, target_is_directory):
1815 d1 = self.do_create(recurse=0)
1816 symlink = os.path.join(d1.name, 'symlink')
1817 os.symlink(target, symlink,
1818 target_is_directory=target_is_directory)
1819 try:
1820 os.chflags(symlink, flags, follow_symlinks=False)
1821 except NotImplementedError:
1822 pass
1823 try:
1824 os.chflags(symlink, flags)
1825 except FileNotFoundError:
1826 pass
1827 os.chflags(d1.name, flags)
1828 d1.cleanup()
1829 self.assertFalse(os.path.exists(d1.name))
1830
1831 with self.subTest('nonexisting file'):
1832 test('nonexisting', target_is_directory=False)
1833 with self.subTest('nonexisting dir'):
1834 test('nonexisting', target_is_directory=True)
1835
1836 with self.subTest('existing file'):
1837 os.chflags(file1, flags)
1838 old_flags = os.stat(file1).st_flags
1839 test(file1, target_is_directory=False)
1840 new_flags = os.stat(file1).st_flags
1841 self.assertEqual(new_flags, old_flags)
1842
1843 with self.subTest('existing dir'):
1844 os.chflags(dir1, flags)
1845 old_flags = os.stat(dir1).st_flags
1846 test(dir1, target_is_directory=True)
1847 new_flags = os.stat(dir1).st_flags
1848 self.assertEqual(new_flags, old_flags)
1849
1850 @support.cpython_only
1851 def test_del_on_collection(self):
1852 # A TemporaryDirectory is deleted when garbage collected
1853 dir = tempfile.mkdtemp()
1854 try:
1855 d = self.do_create(dir=dir)
1856 name = d.name
1857 del d # Rely on refcounting to invoke __del__
1858 self.assertFalse(os.path.exists(name),
1859 "TemporaryDirectory %s exists after __del__" % name)
1860 finally:
1861 os.rmdir(dir)
1862
1863 @support.cpython_only
1864 def test_del_on_collection_ignore_errors(self):
1865 """Test that ignoring errors works when TemporaryDirectory is gced."""
1866 with tempfile.TemporaryDirectory() as working_dir:
1867 temp_dir = self.do_create(
1868 dir=working_dir, ignore_cleanup_errors=True)
1869 temp_path = pathlib.Path(temp_dir.name)
1870 self.assertTrue(temp_path.exists(),
1871 f"TemporaryDirectory {temp_path!s} does not exist")
1872 with open(temp_path / "a_file.txt", "w+t") as open_file:
1873 open_file.write("Hello world!\n")
1874 del temp_dir
1875 self.assertEqual(len(list(temp_path.glob("*"))),
1876 int(sys.platform.startswith("win")),
1877 "Unexpected number of files in "
1878 f"TemporaryDirectory {temp_path!s}")
1879 self.assertEqual(
1880 temp_path.exists(),
1881 sys.platform.startswith("win"),
1882 f"TemporaryDirectory {temp_path!s} existence state unexpected")
1883
1884 def test_del_on_shutdown(self):
1885 # A TemporaryDirectory may be cleaned up during shutdown
1886 with self.do_create() as dir:
1887 for mod in ('builtins', 'os', 'shutil', 'sys', 'tempfile', 'warnings'):
1888 code = """if True:
1889 import builtins
1890 import os
1891 import shutil
1892 import sys
1893 import tempfile
1894 import warnings
1895
1896 tmp = tempfile.TemporaryDirectory(dir={dir!r})
1897 sys.stdout.buffer.write(tmp.name.encode())
1898
1899 tmp2 = os.path.join(tmp.name, 'test_dir')
1900 os.mkdir(tmp2)
1901 with open(os.path.join(tmp2, "test0.txt"), "w") as f:
1902 f.write("Hello world!")
1903
1904 {mod}.tmp = tmp
1905
1906 warnings.filterwarnings("always", category=ResourceWarning)
1907 """.format(dir=dir, mod=mod)
1908 rc, out, err = script_helper.assert_python_ok("-c", code)
1909 tmp_name = out.decode().strip()
1910 self.assertFalse(os.path.exists(tmp_name),
1911 "TemporaryDirectory %s exists after cleanup" % tmp_name)
1912 err = err.decode('utf-8', 'backslashreplace')
1913 self.assertNotIn("Exception ", err)
1914 self.assertIn("ResourceWarning: Implicitly cleaning up", err)
1915
1916 def test_del_on_shutdown_ignore_errors(self):
1917 """Test ignoring errors works when a tempdir is gc'ed on shutdown."""
1918 with tempfile.TemporaryDirectory() as working_dir:
1919 code = """if True:
1920 import pathlib
1921 import sys
1922 import tempfile
1923 import warnings
1924
1925 temp_dir = tempfile.TemporaryDirectory(
1926 dir={working_dir!r}, ignore_cleanup_errors=True)
1927 sys.stdout.buffer.write(temp_dir.name.encode())
1928
1929 temp_dir_2 = pathlib.Path(temp_dir.name) / "test_dir"
1930 temp_dir_2.mkdir()
1931 with open(temp_dir_2 / "test0.txt", "w") as test_file:
1932 test_file.write("Hello world!")
1933 open_file = open(temp_dir_2 / "open_file.txt", "w")
1934 open_file.write("Hello world!")
1935
1936 warnings.filterwarnings("always", category=ResourceWarning)
1937 """.format(working_dir=working_dir)
1938 __, out, err = script_helper.assert_python_ok("-c", code)
1939 temp_path = pathlib.Path(out.decode().strip())
1940 self.assertEqual(len(list(temp_path.glob("*"))),
1941 int(sys.platform.startswith("win")),
1942 "Unexpected number of files in "
1943 f"TemporaryDirectory {temp_path!s}")
1944 self.assertEqual(
1945 temp_path.exists(),
1946 sys.platform.startswith("win"),
1947 f"TemporaryDirectory {temp_path!s} existence state unexpected")
1948 err = err.decode('utf-8', 'backslashreplace')
1949 self.assertNotIn("Exception", err)
1950 self.assertNotIn("Error", err)
1951 self.assertIn("ResourceWarning: Implicitly cleaning up", err)
1952
1953 def test_exit_on_shutdown(self):
1954 # Issue #22427
1955 with self.do_create() as dir:
1956 code = """if True:
1957 import sys
1958 import tempfile
1959 import warnings
1960
1961 def generator():
1962 with tempfile.TemporaryDirectory(dir={dir!r}) as tmp:
1963 yield tmp
1964 g = generator()
1965 sys.stdout.buffer.write(next(g).encode())
1966
1967 warnings.filterwarnings("always", category=ResourceWarning)
1968 """.format(dir=dir)
1969 rc, out, err = script_helper.assert_python_ok("-c", code)
1970 tmp_name = out.decode().strip()
1971 self.assertFalse(os.path.exists(tmp_name),
1972 "TemporaryDirectory %s exists after cleanup" % tmp_name)
1973 err = err.decode('utf-8', 'backslashreplace')
1974 self.assertNotIn("Exception ", err)
1975 self.assertIn("ResourceWarning: Implicitly cleaning up", err)
1976
1977 def test_warnings_on_cleanup(self):
1978 # ResourceWarning will be triggered by __del__
1979 with self.do_create() as dir:
1980 d = self.do_create(dir=dir, recurse=3)
1981 name = d.name
1982
1983 # Check for the resource warning
1984 with warnings_helper.check_warnings(('Implicitly',
1985 ResourceWarning),
1986 quiet=False):
1987 warnings.filterwarnings("always", category=ResourceWarning)
1988 del d
1989 support.gc_collect()
1990 self.assertFalse(os.path.exists(name),
1991 "TemporaryDirectory %s exists after __del__" % name)
1992
1993 def test_multiple_close(self):
1994 # Can be cleaned-up many times without error
1995 d = self.do_create()
1996 d.cleanup()
1997 d.cleanup()
1998 d.cleanup()
1999
2000 def test_context_manager(self):
2001 # Can be used as a context manager
2002 d = self.do_create()
2003 with d as name:
2004 self.assertTrue(os.path.exists(name))
2005 self.assertEqual(name, d.name)
2006 self.assertFalse(os.path.exists(name))
2007
2008 def test_modes(self):
2009 for mode in range(8):
2010 mode <<= 6
2011 with self.subTest(mode=format(mode, '03o')):
2012 d = self.do_create(recurse=3, dirs=2, files=2)
2013 with d:
2014 # Change files and directories mode recursively.
2015 for root, dirs, files in os.walk(d.name, topdown=False):
2016 for name in files:
2017 os.chmod(os.path.join(root, name), mode)
2018 os.chmod(root, mode)
2019 d.cleanup()
2020 self.assertFalse(os.path.exists(d.name))
2021
2022 def check_flags(self, flags):
2023 # skip the test if these flags are not supported (ex: FreeBSD 13)
2024 filename = os_helper.TESTFN
2025 try:
2026 open(filename, "w").close()
2027 try:
2028 os.chflags(filename, flags)
2029 except OSError as exc:
2030 # "OSError: [Errno 45] Operation not supported"
2031 self.skipTest(f"chflags() doesn't support flags "
2032 f"{flags:#b}: {exc}")
2033 else:
2034 os.chflags(filename, 0)
2035 finally:
2036 os_helper.unlink(filename)
2037
2038 @unittest.skipUnless(hasattr(os, 'chflags'), 'requires os.chflags')
2039 def test_flags(self):
2040 flags = stat.UF_IMMUTABLE | stat.UF_NOUNLINK
2041 self.check_flags(flags)
2042
2043 d = self.do_create(recurse=3, dirs=2, files=2)
2044 with d:
2045 # Change files and directories flags recursively.
2046 for root, dirs, files in os.walk(d.name, topdown=False):
2047 for name in files:
2048 os.chflags(os.path.join(root, name), flags)
2049 os.chflags(root, flags)
2050 d.cleanup()
2051 self.assertFalse(os.path.exists(d.name))
2052
2053 def test_delete_false(self):
2054 with tempfile.TemporaryDirectory(delete=False) as working_dir:
2055 pass
2056 self.assertTrue(os.path.exists(working_dir))
2057 shutil.rmtree(working_dir)
2058
2059 if __name__ == "__main__":
2060 unittest.main()