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