Debian Codegraph @

lib-python/3/test/test_tempfile.py

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