1 | n/a | # tempfile.py unit tests. |
---|
2 | n/a | import tempfile |
---|
3 | n/a | import errno |
---|
4 | n/a | import io |
---|
5 | n/a | import os |
---|
6 | n/a | import signal |
---|
7 | n/a | import sys |
---|
8 | n/a | import re |
---|
9 | n/a | import warnings |
---|
10 | n/a | import contextlib |
---|
11 | n/a | import weakref |
---|
12 | n/a | from unittest import mock |
---|
13 | n/a | |
---|
14 | n/a | import unittest |
---|
15 | n/a | from test import support |
---|
16 | n/a | from test.support import script_helper |
---|
17 | n/a | |
---|
18 | n/a | |
---|
19 | n/a | if hasattr(os, 'stat'): |
---|
20 | n/a | import stat |
---|
21 | n/a | has_stat = 1 |
---|
22 | n/a | else: |
---|
23 | n/a | has_stat = 0 |
---|
24 | n/a | |
---|
25 | n/a | has_textmode = (tempfile._text_openflags != tempfile._bin_openflags) |
---|
26 | n/a | has_spawnl = hasattr(os, 'spawnl') |
---|
27 | n/a | |
---|
28 | n/a | # TEST_FILES may need to be tweaked for systems depending on the maximum |
---|
29 | n/a | # number of files that can be opened at one time (see ulimit -n) |
---|
30 | n/a | if sys.platform.startswith('openbsd'): |
---|
31 | n/a | TEST_FILES = 48 |
---|
32 | n/a | else: |
---|
33 | n/a | TEST_FILES = 100 |
---|
34 | n/a | |
---|
35 | n/a | # This is organized as one test for each chunk of code in tempfile.py, |
---|
36 | n/a | # in order of their appearance in the file. Testing which requires |
---|
37 | n/a | # threads is not done here. |
---|
38 | n/a | |
---|
39 | n/a | class TestLowLevelInternals(unittest.TestCase): |
---|
40 | n/a | def test_infer_return_type_singles(self): |
---|
41 | n/a | self.assertIs(str, tempfile._infer_return_type('')) |
---|
42 | n/a | self.assertIs(bytes, tempfile._infer_return_type(b'')) |
---|
43 | n/a | self.assertIs(str, tempfile._infer_return_type(None)) |
---|
44 | n/a | |
---|
45 | n/a | def test_infer_return_type_multiples(self): |
---|
46 | n/a | self.assertIs(str, tempfile._infer_return_type('', '')) |
---|
47 | n/a | self.assertIs(bytes, tempfile._infer_return_type(b'', b'')) |
---|
48 | n/a | with self.assertRaises(TypeError): |
---|
49 | n/a | tempfile._infer_return_type('', b'') |
---|
50 | n/a | with self.assertRaises(TypeError): |
---|
51 | n/a | tempfile._infer_return_type(b'', '') |
---|
52 | n/a | |
---|
53 | n/a | def test_infer_return_type_multiples_and_none(self): |
---|
54 | n/a | self.assertIs(str, tempfile._infer_return_type(None, '')) |
---|
55 | n/a | self.assertIs(str, tempfile._infer_return_type('', None)) |
---|
56 | n/a | self.assertIs(str, tempfile._infer_return_type(None, None)) |
---|
57 | n/a | self.assertIs(bytes, tempfile._infer_return_type(b'', None)) |
---|
58 | n/a | self.assertIs(bytes, tempfile._infer_return_type(None, b'')) |
---|
59 | n/a | with self.assertRaises(TypeError): |
---|
60 | n/a | tempfile._infer_return_type('', None, b'') |
---|
61 | n/a | with self.assertRaises(TypeError): |
---|
62 | n/a | tempfile._infer_return_type(b'', None, '') |
---|
63 | n/a | |
---|
64 | n/a | |
---|
65 | n/a | # Common functionality. |
---|
66 | n/a | |
---|
67 | n/a | class BaseTestCase(unittest.TestCase): |
---|
68 | n/a | |
---|
69 | n/a | str_check = re.compile(r"^[a-z0-9_-]{8}$") |
---|
70 | n/a | b_check = re.compile(br"^[a-z0-9_-]{8}$") |
---|
71 | n/a | |
---|
72 | n/a | def setUp(self): |
---|
73 | n/a | self._warnings_manager = support.check_warnings() |
---|
74 | n/a | self._warnings_manager.__enter__() |
---|
75 | n/a | warnings.filterwarnings("ignore", category=RuntimeWarning, |
---|
76 | n/a | message="mktemp", module=__name__) |
---|
77 | n/a | |
---|
78 | n/a | def tearDown(self): |
---|
79 | n/a | self._warnings_manager.__exit__(None, None, None) |
---|
80 | n/a | |
---|
81 | n/a | |
---|
82 | n/a | def nameCheck(self, name, dir, pre, suf): |
---|
83 | n/a | (ndir, nbase) = os.path.split(name) |
---|
84 | n/a | npre = nbase[:len(pre)] |
---|
85 | n/a | nsuf = nbase[len(nbase)-len(suf):] |
---|
86 | n/a | |
---|
87 | n/a | if dir is not None: |
---|
88 | n/a | self.assertIs(type(name), str if type(dir) is str else bytes, |
---|
89 | n/a | "unexpected return type") |
---|
90 | n/a | if pre is not None: |
---|
91 | n/a | self.assertIs(type(name), str if type(pre) is str else bytes, |
---|
92 | n/a | "unexpected return type") |
---|
93 | n/a | if suf is not None: |
---|
94 | n/a | self.assertIs(type(name), str if type(suf) is str else bytes, |
---|
95 | n/a | "unexpected return type") |
---|
96 | n/a | if (dir, pre, suf) == (None, None, None): |
---|
97 | n/a | self.assertIs(type(name), str, "default return type must be str") |
---|
98 | n/a | |
---|
99 | n/a | # check for equality of the absolute paths! |
---|
100 | n/a | self.assertEqual(os.path.abspath(ndir), os.path.abspath(dir), |
---|
101 | n/a | "file %r not in directory %r" % (name, dir)) |
---|
102 | n/a | self.assertEqual(npre, pre, |
---|
103 | n/a | "file %r does not begin with %r" % (nbase, pre)) |
---|
104 | n/a | self.assertEqual(nsuf, suf, |
---|
105 | n/a | "file %r does not end with %r" % (nbase, suf)) |
---|
106 | n/a | |
---|
107 | n/a | nbase = nbase[len(pre):len(nbase)-len(suf)] |
---|
108 | n/a | check = self.str_check if isinstance(nbase, str) else self.b_check |
---|
109 | n/a | self.assertTrue(check.match(nbase), |
---|
110 | n/a | "random characters %r do not match %r" |
---|
111 | n/a | % (nbase, check.pattern)) |
---|
112 | n/a | |
---|
113 | n/a | |
---|
114 | n/a | class TestExports(BaseTestCase): |
---|
115 | n/a | def test_exports(self): |
---|
116 | n/a | # There are no surprising symbols in the tempfile module |
---|
117 | n/a | dict = tempfile.__dict__ |
---|
118 | n/a | |
---|
119 | n/a | expected = { |
---|
120 | n/a | "NamedTemporaryFile" : 1, |
---|
121 | n/a | "TemporaryFile" : 1, |
---|
122 | n/a | "mkstemp" : 1, |
---|
123 | n/a | "mkdtemp" : 1, |
---|
124 | n/a | "mktemp" : 1, |
---|
125 | n/a | "TMP_MAX" : 1, |
---|
126 | n/a | "gettempprefix" : 1, |
---|
127 | n/a | "gettempprefixb" : 1, |
---|
128 | n/a | "gettempdir" : 1, |
---|
129 | n/a | "gettempdirb" : 1, |
---|
130 | n/a | "tempdir" : 1, |
---|
131 | n/a | "template" : 1, |
---|
132 | n/a | "SpooledTemporaryFile" : 1, |
---|
133 | n/a | "TemporaryDirectory" : 1, |
---|
134 | n/a | } |
---|
135 | n/a | |
---|
136 | n/a | unexp = [] |
---|
137 | n/a | for key in dict: |
---|
138 | n/a | if key[0] != '_' and key not in expected: |
---|
139 | n/a | unexp.append(key) |
---|
140 | n/a | self.assertTrue(len(unexp) == 0, |
---|
141 | n/a | "unexpected keys: %s" % unexp) |
---|
142 | n/a | |
---|
143 | n/a | |
---|
144 | n/a | class TestRandomNameSequence(BaseTestCase): |
---|
145 | n/a | """Test the internal iterator object _RandomNameSequence.""" |
---|
146 | n/a | |
---|
147 | n/a | def setUp(self): |
---|
148 | n/a | self.r = tempfile._RandomNameSequence() |
---|
149 | n/a | super().setUp() |
---|
150 | n/a | |
---|
151 | n/a | def test_get_six_char_str(self): |
---|
152 | n/a | # _RandomNameSequence returns a six-character string |
---|
153 | n/a | s = next(self.r) |
---|
154 | n/a | self.nameCheck(s, '', '', '') |
---|
155 | n/a | |
---|
156 | n/a | def test_many(self): |
---|
157 | n/a | # _RandomNameSequence returns no duplicate strings (stochastic) |
---|
158 | n/a | |
---|
159 | n/a | dict = {} |
---|
160 | n/a | r = self.r |
---|
161 | n/a | for i in range(TEST_FILES): |
---|
162 | n/a | s = next(r) |
---|
163 | n/a | self.nameCheck(s, '', '', '') |
---|
164 | n/a | self.assertNotIn(s, dict) |
---|
165 | n/a | dict[s] = 1 |
---|
166 | n/a | |
---|
167 | n/a | def supports_iter(self): |
---|
168 | n/a | # _RandomNameSequence supports the iterator protocol |
---|
169 | n/a | |
---|
170 | n/a | i = 0 |
---|
171 | n/a | r = self.r |
---|
172 | n/a | for s in r: |
---|
173 | n/a | i += 1 |
---|
174 | n/a | if i == 20: |
---|
175 | n/a | break |
---|
176 | n/a | |
---|
177 | n/a | @unittest.skipUnless(hasattr(os, 'fork'), |
---|
178 | n/a | "os.fork is required for this test") |
---|
179 | n/a | def test_process_awareness(self): |
---|
180 | n/a | # ensure that the random source differs between |
---|
181 | n/a | # child and parent. |
---|
182 | n/a | read_fd, write_fd = os.pipe() |
---|
183 | n/a | pid = None |
---|
184 | n/a | try: |
---|
185 | n/a | pid = os.fork() |
---|
186 | n/a | if not pid: |
---|
187 | n/a | os.close(read_fd) |
---|
188 | n/a | os.write(write_fd, next(self.r).encode("ascii")) |
---|
189 | n/a | os.close(write_fd) |
---|
190 | n/a | # bypass the normal exit handlers- leave those to |
---|
191 | n/a | # the parent. |
---|
192 | n/a | os._exit(0) |
---|
193 | n/a | parent_value = next(self.r) |
---|
194 | n/a | child_value = os.read(read_fd, len(parent_value)).decode("ascii") |
---|
195 | n/a | finally: |
---|
196 | n/a | if pid: |
---|
197 | n/a | # best effort to ensure the process can't bleed out |
---|
198 | n/a | # via any bugs above |
---|
199 | n/a | try: |
---|
200 | n/a | os.kill(pid, signal.SIGKILL) |
---|
201 | n/a | except OSError: |
---|
202 | n/a | pass |
---|
203 | n/a | os.close(read_fd) |
---|
204 | n/a | os.close(write_fd) |
---|
205 | n/a | self.assertNotEqual(child_value, parent_value) |
---|
206 | n/a | |
---|
207 | n/a | |
---|
208 | n/a | |
---|
209 | n/a | class TestCandidateTempdirList(BaseTestCase): |
---|
210 | n/a | """Test the internal function _candidate_tempdir_list.""" |
---|
211 | n/a | |
---|
212 | n/a | def test_nonempty_list(self): |
---|
213 | n/a | # _candidate_tempdir_list returns a nonempty list of strings |
---|
214 | n/a | |
---|
215 | n/a | cand = tempfile._candidate_tempdir_list() |
---|
216 | n/a | |
---|
217 | n/a | self.assertFalse(len(cand) == 0) |
---|
218 | n/a | for c in cand: |
---|
219 | n/a | self.assertIsInstance(c, str) |
---|
220 | n/a | |
---|
221 | n/a | def test_wanted_dirs(self): |
---|
222 | n/a | # _candidate_tempdir_list contains the expected directories |
---|
223 | n/a | |
---|
224 | n/a | # Make sure the interesting environment variables are all set. |
---|
225 | n/a | with support.EnvironmentVarGuard() as env: |
---|
226 | n/a | for envname in 'TMPDIR', 'TEMP', 'TMP': |
---|
227 | n/a | dirname = os.getenv(envname) |
---|
228 | n/a | if not dirname: |
---|
229 | n/a | env[envname] = os.path.abspath(envname) |
---|
230 | n/a | |
---|
231 | n/a | cand = tempfile._candidate_tempdir_list() |
---|
232 | n/a | |
---|
233 | n/a | for envname in 'TMPDIR', 'TEMP', 'TMP': |
---|
234 | n/a | dirname = os.getenv(envname) |
---|
235 | n/a | if not dirname: raise ValueError |
---|
236 | n/a | self.assertIn(dirname, cand) |
---|
237 | n/a | |
---|
238 | n/a | try: |
---|
239 | n/a | dirname = os.getcwd() |
---|
240 | n/a | except (AttributeError, OSError): |
---|
241 | n/a | dirname = os.curdir |
---|
242 | n/a | |
---|
243 | n/a | self.assertIn(dirname, cand) |
---|
244 | n/a | |
---|
245 | n/a | # Not practical to try to verify the presence of OS-specific |
---|
246 | n/a | # paths in this list. |
---|
247 | n/a | |
---|
248 | n/a | |
---|
249 | n/a | # We test _get_default_tempdir some more by testing gettempdir. |
---|
250 | n/a | |
---|
251 | n/a | class TestGetDefaultTempdir(BaseTestCase): |
---|
252 | n/a | """Test _get_default_tempdir().""" |
---|
253 | n/a | |
---|
254 | n/a | def test_no_files_left_behind(self): |
---|
255 | n/a | # use a private empty directory |
---|
256 | n/a | with tempfile.TemporaryDirectory() as our_temp_directory: |
---|
257 | n/a | # force _get_default_tempdir() to consider our empty directory |
---|
258 | n/a | def our_candidate_list(): |
---|
259 | n/a | return [our_temp_directory] |
---|
260 | n/a | |
---|
261 | n/a | with support.swap_attr(tempfile, "_candidate_tempdir_list", |
---|
262 | n/a | our_candidate_list): |
---|
263 | n/a | # verify our directory is empty after _get_default_tempdir() |
---|
264 | n/a | tempfile._get_default_tempdir() |
---|
265 | n/a | self.assertEqual(os.listdir(our_temp_directory), []) |
---|
266 | n/a | |
---|
267 | n/a | def raise_OSError(*args, **kwargs): |
---|
268 | n/a | raise OSError() |
---|
269 | n/a | |
---|
270 | n/a | with support.swap_attr(io, "open", raise_OSError): |
---|
271 | n/a | # test again with failing io.open() |
---|
272 | n/a | with self.assertRaises(FileNotFoundError): |
---|
273 | n/a | tempfile._get_default_tempdir() |
---|
274 | n/a | self.assertEqual(os.listdir(our_temp_directory), []) |
---|
275 | n/a | |
---|
276 | n/a | open = io.open |
---|
277 | n/a | def bad_writer(*args, **kwargs): |
---|
278 | n/a | fp = open(*args, **kwargs) |
---|
279 | n/a | fp.write = raise_OSError |
---|
280 | n/a | return fp |
---|
281 | n/a | |
---|
282 | n/a | with support.swap_attr(io, "open", bad_writer): |
---|
283 | n/a | # test again with failing write() |
---|
284 | n/a | with self.assertRaises(FileNotFoundError): |
---|
285 | n/a | tempfile._get_default_tempdir() |
---|
286 | n/a | self.assertEqual(os.listdir(our_temp_directory), []) |
---|
287 | n/a | |
---|
288 | n/a | |
---|
289 | n/a | class TestGetCandidateNames(BaseTestCase): |
---|
290 | n/a | """Test the internal function _get_candidate_names.""" |
---|
291 | n/a | |
---|
292 | n/a | def test_retval(self): |
---|
293 | n/a | # _get_candidate_names returns a _RandomNameSequence object |
---|
294 | n/a | obj = tempfile._get_candidate_names() |
---|
295 | n/a | self.assertIsInstance(obj, tempfile._RandomNameSequence) |
---|
296 | n/a | |
---|
297 | n/a | def test_same_thing(self): |
---|
298 | n/a | # _get_candidate_names always returns the same object |
---|
299 | n/a | a = tempfile._get_candidate_names() |
---|
300 | n/a | b = tempfile._get_candidate_names() |
---|
301 | n/a | |
---|
302 | n/a | self.assertTrue(a is b) |
---|
303 | n/a | |
---|
304 | n/a | |
---|
305 | n/a | @contextlib.contextmanager |
---|
306 | n/a | def _inside_empty_temp_dir(): |
---|
307 | n/a | dir = tempfile.mkdtemp() |
---|
308 | n/a | try: |
---|
309 | n/a | with support.swap_attr(tempfile, 'tempdir', dir): |
---|
310 | n/a | yield |
---|
311 | n/a | finally: |
---|
312 | n/a | support.rmtree(dir) |
---|
313 | n/a | |
---|
314 | n/a | |
---|
315 | n/a | def _mock_candidate_names(*names): |
---|
316 | n/a | return support.swap_attr(tempfile, |
---|
317 | n/a | '_get_candidate_names', |
---|
318 | n/a | lambda: iter(names)) |
---|
319 | n/a | |
---|
320 | n/a | |
---|
321 | n/a | class TestBadTempdir: |
---|
322 | n/a | |
---|
323 | n/a | def test_read_only_directory(self): |
---|
324 | n/a | with _inside_empty_temp_dir(): |
---|
325 | n/a | oldmode = mode = os.stat(tempfile.tempdir).st_mode |
---|
326 | n/a | mode &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) |
---|
327 | n/a | os.chmod(tempfile.tempdir, mode) |
---|
328 | n/a | try: |
---|
329 | n/a | if os.access(tempfile.tempdir, os.W_OK): |
---|
330 | n/a | self.skipTest("can't set the directory read-only") |
---|
331 | n/a | with self.assertRaises(PermissionError): |
---|
332 | n/a | self.make_temp() |
---|
333 | n/a | self.assertEqual(os.listdir(tempfile.tempdir), []) |
---|
334 | n/a | finally: |
---|
335 | n/a | os.chmod(tempfile.tempdir, oldmode) |
---|
336 | n/a | |
---|
337 | n/a | def test_nonexisting_directory(self): |
---|
338 | n/a | with _inside_empty_temp_dir(): |
---|
339 | n/a | tempdir = os.path.join(tempfile.tempdir, 'nonexistent') |
---|
340 | n/a | with support.swap_attr(tempfile, 'tempdir', tempdir): |
---|
341 | n/a | with self.assertRaises(FileNotFoundError): |
---|
342 | n/a | self.make_temp() |
---|
343 | n/a | |
---|
344 | n/a | def test_non_directory(self): |
---|
345 | n/a | with _inside_empty_temp_dir(): |
---|
346 | n/a | tempdir = os.path.join(tempfile.tempdir, 'file') |
---|
347 | n/a | open(tempdir, 'wb').close() |
---|
348 | n/a | with support.swap_attr(tempfile, 'tempdir', tempdir): |
---|
349 | n/a | with self.assertRaises((NotADirectoryError, FileNotFoundError)): |
---|
350 | n/a | self.make_temp() |
---|
351 | n/a | |
---|
352 | n/a | |
---|
353 | n/a | class TestMkstempInner(TestBadTempdir, BaseTestCase): |
---|
354 | n/a | """Test the internal function _mkstemp_inner.""" |
---|
355 | n/a | |
---|
356 | n/a | class mkstemped: |
---|
357 | n/a | _bflags = tempfile._bin_openflags |
---|
358 | n/a | _tflags = tempfile._text_openflags |
---|
359 | n/a | _close = os.close |
---|
360 | n/a | _unlink = os.unlink |
---|
361 | n/a | |
---|
362 | n/a | def __init__(self, dir, pre, suf, bin): |
---|
363 | n/a | if bin: flags = self._bflags |
---|
364 | n/a | else: flags = self._tflags |
---|
365 | n/a | |
---|
366 | n/a | output_type = tempfile._infer_return_type(dir, pre, suf) |
---|
367 | n/a | (self.fd, self.name) = tempfile._mkstemp_inner(dir, pre, suf, flags, output_type) |
---|
368 | n/a | |
---|
369 | n/a | def write(self, str): |
---|
370 | n/a | os.write(self.fd, str) |
---|
371 | n/a | |
---|
372 | n/a | def __del__(self): |
---|
373 | n/a | self._close(self.fd) |
---|
374 | n/a | self._unlink(self.name) |
---|
375 | n/a | |
---|
376 | n/a | def do_create(self, dir=None, pre=None, suf=None, bin=1): |
---|
377 | n/a | output_type = tempfile._infer_return_type(dir, pre, suf) |
---|
378 | n/a | if dir is None: |
---|
379 | n/a | if output_type is str: |
---|
380 | n/a | dir = tempfile.gettempdir() |
---|
381 | n/a | else: |
---|
382 | n/a | dir = tempfile.gettempdirb() |
---|
383 | n/a | if pre is None: |
---|
384 | n/a | pre = output_type() |
---|
385 | n/a | if suf is None: |
---|
386 | n/a | suf = output_type() |
---|
387 | n/a | file = self.mkstemped(dir, pre, suf, bin) |
---|
388 | n/a | |
---|
389 | n/a | self.nameCheck(file.name, dir, pre, suf) |
---|
390 | n/a | return file |
---|
391 | n/a | |
---|
392 | n/a | def test_basic(self): |
---|
393 | n/a | # _mkstemp_inner can create files |
---|
394 | n/a | self.do_create().write(b"blat") |
---|
395 | n/a | self.do_create(pre="a").write(b"blat") |
---|
396 | n/a | self.do_create(suf="b").write(b"blat") |
---|
397 | n/a | self.do_create(pre="a", suf="b").write(b"blat") |
---|
398 | n/a | self.do_create(pre="aa", suf=".txt").write(b"blat") |
---|
399 | n/a | |
---|
400 | n/a | def test_basic_with_bytes_names(self): |
---|
401 | n/a | # _mkstemp_inner can create files when given name parts all |
---|
402 | n/a | # specified as bytes. |
---|
403 | n/a | dir_b = tempfile.gettempdirb() |
---|
404 | n/a | self.do_create(dir=dir_b, suf=b"").write(b"blat") |
---|
405 | n/a | self.do_create(dir=dir_b, pre=b"a").write(b"blat") |
---|
406 | n/a | self.do_create(dir=dir_b, suf=b"b").write(b"blat") |
---|
407 | n/a | self.do_create(dir=dir_b, pre=b"a", suf=b"b").write(b"blat") |
---|
408 | n/a | self.do_create(dir=dir_b, pre=b"aa", suf=b".txt").write(b"blat") |
---|
409 | n/a | # Can't mix str & binary types in the args. |
---|
410 | n/a | with self.assertRaises(TypeError): |
---|
411 | n/a | self.do_create(dir="", suf=b"").write(b"blat") |
---|
412 | n/a | with self.assertRaises(TypeError): |
---|
413 | n/a | self.do_create(dir=dir_b, pre="").write(b"blat") |
---|
414 | n/a | with self.assertRaises(TypeError): |
---|
415 | n/a | self.do_create(dir=dir_b, pre=b"", suf="").write(b"blat") |
---|
416 | n/a | |
---|
417 | n/a | def test_basic_many(self): |
---|
418 | n/a | # _mkstemp_inner can create many files (stochastic) |
---|
419 | n/a | extant = list(range(TEST_FILES)) |
---|
420 | n/a | for i in extant: |
---|
421 | n/a | extant[i] = self.do_create(pre="aa") |
---|
422 | n/a | |
---|
423 | n/a | def test_choose_directory(self): |
---|
424 | n/a | # _mkstemp_inner can create files in a user-selected directory |
---|
425 | n/a | dir = tempfile.mkdtemp() |
---|
426 | n/a | try: |
---|
427 | n/a | self.do_create(dir=dir).write(b"blat") |
---|
428 | n/a | finally: |
---|
429 | n/a | os.rmdir(dir) |
---|
430 | n/a | |
---|
431 | n/a | @unittest.skipUnless(has_stat, 'os.stat not available') |
---|
432 | n/a | def test_file_mode(self): |
---|
433 | n/a | # _mkstemp_inner creates files with the proper mode |
---|
434 | n/a | |
---|
435 | n/a | file = self.do_create() |
---|
436 | n/a | mode = stat.S_IMODE(os.stat(file.name).st_mode) |
---|
437 | n/a | expected = 0o600 |
---|
438 | n/a | if sys.platform == 'win32': |
---|
439 | n/a | # There's no distinction among 'user', 'group' and 'world'; |
---|
440 | n/a | # replicate the 'user' bits. |
---|
441 | n/a | user = expected >> 6 |
---|
442 | n/a | expected = user * (1 + 8 + 64) |
---|
443 | n/a | self.assertEqual(mode, expected) |
---|
444 | n/a | |
---|
445 | n/a | @unittest.skipUnless(has_spawnl, 'os.spawnl not available') |
---|
446 | n/a | def test_noinherit(self): |
---|
447 | n/a | # _mkstemp_inner file handles are not inherited by child processes |
---|
448 | n/a | |
---|
449 | n/a | if support.verbose: |
---|
450 | n/a | v="v" |
---|
451 | n/a | else: |
---|
452 | n/a | v="q" |
---|
453 | n/a | |
---|
454 | n/a | file = self.do_create() |
---|
455 | n/a | self.assertEqual(os.get_inheritable(file.fd), False) |
---|
456 | n/a | fd = "%d" % file.fd |
---|
457 | n/a | |
---|
458 | n/a | try: |
---|
459 | n/a | me = __file__ |
---|
460 | n/a | except NameError: |
---|
461 | n/a | me = sys.argv[0] |
---|
462 | n/a | |
---|
463 | n/a | # We have to exec something, so that FD_CLOEXEC will take |
---|
464 | n/a | # effect. The core of this test is therefore in |
---|
465 | n/a | # tf_inherit_check.py, which see. |
---|
466 | n/a | tester = os.path.join(os.path.dirname(os.path.abspath(me)), |
---|
467 | n/a | "tf_inherit_check.py") |
---|
468 | n/a | |
---|
469 | n/a | # On Windows a spawn* /path/ with embedded spaces shouldn't be quoted, |
---|
470 | n/a | # but an arg with embedded spaces should be decorated with double |
---|
471 | n/a | # quotes on each end |
---|
472 | n/a | if sys.platform == 'win32': |
---|
473 | n/a | decorated = '"%s"' % sys.executable |
---|
474 | n/a | tester = '"%s"' % tester |
---|
475 | n/a | else: |
---|
476 | n/a | decorated = sys.executable |
---|
477 | n/a | |
---|
478 | n/a | retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd) |
---|
479 | n/a | self.assertFalse(retval < 0, |
---|
480 | n/a | "child process caught fatal signal %d" % -retval) |
---|
481 | n/a | self.assertFalse(retval > 0, "child process reports failure %d"%retval) |
---|
482 | n/a | |
---|
483 | n/a | @unittest.skipUnless(has_textmode, "text mode not available") |
---|
484 | n/a | def test_textmode(self): |
---|
485 | n/a | # _mkstemp_inner can create files in text mode |
---|
486 | n/a | |
---|
487 | n/a | # A text file is truncated at the first Ctrl+Z byte |
---|
488 | n/a | f = self.do_create(bin=0) |
---|
489 | n/a | f.write(b"blat\x1a") |
---|
490 | n/a | f.write(b"extra\n") |
---|
491 | n/a | os.lseek(f.fd, 0, os.SEEK_SET) |
---|
492 | n/a | self.assertEqual(os.read(f.fd, 20), b"blat") |
---|
493 | n/a | |
---|
494 | n/a | def make_temp(self): |
---|
495 | n/a | return tempfile._mkstemp_inner(tempfile.gettempdir(), |
---|
496 | n/a | tempfile.gettempprefix(), |
---|
497 | n/a | '', |
---|
498 | n/a | tempfile._bin_openflags, |
---|
499 | n/a | str) |
---|
500 | n/a | |
---|
501 | n/a | def test_collision_with_existing_file(self): |
---|
502 | n/a | # _mkstemp_inner tries another name when a file with |
---|
503 | n/a | # the chosen name already exists |
---|
504 | n/a | with _inside_empty_temp_dir(), \ |
---|
505 | n/a | _mock_candidate_names('aaa', 'aaa', 'bbb'): |
---|
506 | n/a | (fd1, name1) = self.make_temp() |
---|
507 | n/a | os.close(fd1) |
---|
508 | n/a | self.assertTrue(name1.endswith('aaa')) |
---|
509 | n/a | |
---|
510 | n/a | (fd2, name2) = self.make_temp() |
---|
511 | n/a | os.close(fd2) |
---|
512 | n/a | self.assertTrue(name2.endswith('bbb')) |
---|
513 | n/a | |
---|
514 | n/a | def test_collision_with_existing_directory(self): |
---|
515 | n/a | # _mkstemp_inner tries another name when a directory with |
---|
516 | n/a | # the chosen name already exists |
---|
517 | n/a | with _inside_empty_temp_dir(), \ |
---|
518 | n/a | _mock_candidate_names('aaa', 'aaa', 'bbb'): |
---|
519 | n/a | dir = tempfile.mkdtemp() |
---|
520 | n/a | self.assertTrue(dir.endswith('aaa')) |
---|
521 | n/a | |
---|
522 | n/a | (fd, name) = self.make_temp() |
---|
523 | n/a | os.close(fd) |
---|
524 | n/a | self.assertTrue(name.endswith('bbb')) |
---|
525 | n/a | |
---|
526 | n/a | |
---|
527 | n/a | class TestGetTempPrefix(BaseTestCase): |
---|
528 | n/a | """Test gettempprefix().""" |
---|
529 | n/a | |
---|
530 | n/a | def test_sane_template(self): |
---|
531 | n/a | # gettempprefix returns a nonempty prefix string |
---|
532 | n/a | p = tempfile.gettempprefix() |
---|
533 | n/a | |
---|
534 | n/a | self.assertIsInstance(p, str) |
---|
535 | n/a | self.assertGreater(len(p), 0) |
---|
536 | n/a | |
---|
537 | n/a | pb = tempfile.gettempprefixb() |
---|
538 | n/a | |
---|
539 | n/a | self.assertIsInstance(pb, bytes) |
---|
540 | n/a | self.assertGreater(len(pb), 0) |
---|
541 | n/a | |
---|
542 | n/a | def test_usable_template(self): |
---|
543 | n/a | # gettempprefix returns a usable prefix string |
---|
544 | n/a | |
---|
545 | n/a | # Create a temp directory, avoiding use of the prefix. |
---|
546 | n/a | # Then attempt to create a file whose name is |
---|
547 | n/a | # prefix + 'xxxxxx.xxx' in that directory. |
---|
548 | n/a | p = tempfile.gettempprefix() + "xxxxxx.xxx" |
---|
549 | n/a | d = tempfile.mkdtemp(prefix="") |
---|
550 | n/a | try: |
---|
551 | n/a | p = os.path.join(d, p) |
---|
552 | n/a | fd = os.open(p, os.O_RDWR | os.O_CREAT) |
---|
553 | n/a | os.close(fd) |
---|
554 | n/a | os.unlink(p) |
---|
555 | n/a | finally: |
---|
556 | n/a | os.rmdir(d) |
---|
557 | n/a | |
---|
558 | n/a | |
---|
559 | n/a | class TestGetTempDir(BaseTestCase): |
---|
560 | n/a | """Test gettempdir().""" |
---|
561 | n/a | |
---|
562 | n/a | def test_directory_exists(self): |
---|
563 | n/a | # gettempdir returns a directory which exists |
---|
564 | n/a | |
---|
565 | n/a | for d in (tempfile.gettempdir(), tempfile.gettempdirb()): |
---|
566 | n/a | self.assertTrue(os.path.isabs(d) or d == os.curdir, |
---|
567 | n/a | "%r is not an absolute path" % d) |
---|
568 | n/a | self.assertTrue(os.path.isdir(d), |
---|
569 | n/a | "%r is not a directory" % d) |
---|
570 | n/a | |
---|
571 | n/a | def test_directory_writable(self): |
---|
572 | n/a | # gettempdir returns a directory writable by the user |
---|
573 | n/a | |
---|
574 | n/a | # sneaky: just instantiate a NamedTemporaryFile, which |
---|
575 | n/a | # defaults to writing into the directory returned by |
---|
576 | n/a | # gettempdir. |
---|
577 | n/a | file = tempfile.NamedTemporaryFile() |
---|
578 | n/a | file.write(b"blat") |
---|
579 | n/a | file.close() |
---|
580 | n/a | |
---|
581 | n/a | def test_same_thing(self): |
---|
582 | n/a | # gettempdir always returns the same object |
---|
583 | n/a | a = tempfile.gettempdir() |
---|
584 | n/a | b = tempfile.gettempdir() |
---|
585 | n/a | c = tempfile.gettempdirb() |
---|
586 | n/a | |
---|
587 | n/a | self.assertTrue(a is b) |
---|
588 | n/a | self.assertNotEqual(type(a), type(c)) |
---|
589 | n/a | self.assertEqual(a, os.fsdecode(c)) |
---|
590 | n/a | |
---|
591 | n/a | def test_case_sensitive(self): |
---|
592 | n/a | # gettempdir should not flatten its case |
---|
593 | n/a | # even on a case-insensitive file system |
---|
594 | n/a | case_sensitive_tempdir = tempfile.mkdtemp("-Temp") |
---|
595 | n/a | _tempdir, tempfile.tempdir = tempfile.tempdir, None |
---|
596 | n/a | try: |
---|
597 | n/a | with support.EnvironmentVarGuard() as env: |
---|
598 | n/a | # Fake the first env var which is checked as a candidate |
---|
599 | n/a | env["TMPDIR"] = case_sensitive_tempdir |
---|
600 | n/a | self.assertEqual(tempfile.gettempdir(), case_sensitive_tempdir) |
---|
601 | n/a | finally: |
---|
602 | n/a | tempfile.tempdir = _tempdir |
---|
603 | n/a | support.rmdir(case_sensitive_tempdir) |
---|
604 | n/a | |
---|
605 | n/a | |
---|
606 | n/a | class TestMkstemp(BaseTestCase): |
---|
607 | n/a | """Test mkstemp().""" |
---|
608 | n/a | |
---|
609 | n/a | def do_create(self, dir=None, pre=None, suf=None): |
---|
610 | n/a | output_type = tempfile._infer_return_type(dir, pre, suf) |
---|
611 | n/a | if dir is None: |
---|
612 | n/a | if output_type is str: |
---|
613 | n/a | dir = tempfile.gettempdir() |
---|
614 | n/a | else: |
---|
615 | n/a | dir = tempfile.gettempdirb() |
---|
616 | n/a | if pre is None: |
---|
617 | n/a | pre = output_type() |
---|
618 | n/a | if suf is None: |
---|
619 | n/a | suf = output_type() |
---|
620 | n/a | (fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf) |
---|
621 | n/a | (ndir, nbase) = os.path.split(name) |
---|
622 | n/a | adir = os.path.abspath(dir) |
---|
623 | n/a | self.assertEqual(adir, ndir, |
---|
624 | n/a | "Directory '%s' incorrectly returned as '%s'" % (adir, ndir)) |
---|
625 | n/a | |
---|
626 | n/a | try: |
---|
627 | n/a | self.nameCheck(name, dir, pre, suf) |
---|
628 | n/a | finally: |
---|
629 | n/a | os.close(fd) |
---|
630 | n/a | os.unlink(name) |
---|
631 | n/a | |
---|
632 | n/a | def test_basic(self): |
---|
633 | n/a | # mkstemp can create files |
---|
634 | n/a | self.do_create() |
---|
635 | n/a | self.do_create(pre="a") |
---|
636 | n/a | self.do_create(suf="b") |
---|
637 | n/a | self.do_create(pre="a", suf="b") |
---|
638 | n/a | self.do_create(pre="aa", suf=".txt") |
---|
639 | n/a | self.do_create(dir=".") |
---|
640 | n/a | |
---|
641 | n/a | def test_basic_with_bytes_names(self): |
---|
642 | n/a | # mkstemp can create files when given name parts all |
---|
643 | n/a | # specified as bytes. |
---|
644 | n/a | d = tempfile.gettempdirb() |
---|
645 | n/a | self.do_create(dir=d, suf=b"") |
---|
646 | n/a | self.do_create(dir=d, pre=b"a") |
---|
647 | n/a | self.do_create(dir=d, suf=b"b") |
---|
648 | n/a | self.do_create(dir=d, pre=b"a", suf=b"b") |
---|
649 | n/a | self.do_create(dir=d, pre=b"aa", suf=b".txt") |
---|
650 | n/a | self.do_create(dir=b".") |
---|
651 | n/a | with self.assertRaises(TypeError): |
---|
652 | n/a | self.do_create(dir=".", pre=b"aa", suf=b".txt") |
---|
653 | n/a | with self.assertRaises(TypeError): |
---|
654 | n/a | self.do_create(dir=b".", pre="aa", suf=b".txt") |
---|
655 | n/a | with self.assertRaises(TypeError): |
---|
656 | n/a | self.do_create(dir=b".", pre=b"aa", suf=".txt") |
---|
657 | n/a | |
---|
658 | n/a | |
---|
659 | n/a | def test_choose_directory(self): |
---|
660 | n/a | # mkstemp can create directories in a user-selected directory |
---|
661 | n/a | dir = tempfile.mkdtemp() |
---|
662 | n/a | try: |
---|
663 | n/a | self.do_create(dir=dir) |
---|
664 | n/a | finally: |
---|
665 | n/a | os.rmdir(dir) |
---|
666 | n/a | |
---|
667 | n/a | |
---|
668 | n/a | class TestMkdtemp(TestBadTempdir, BaseTestCase): |
---|
669 | n/a | """Test mkdtemp().""" |
---|
670 | n/a | |
---|
671 | n/a | def make_temp(self): |
---|
672 | n/a | return tempfile.mkdtemp() |
---|
673 | n/a | |
---|
674 | n/a | def do_create(self, dir=None, pre=None, suf=None): |
---|
675 | n/a | output_type = tempfile._infer_return_type(dir, pre, suf) |
---|
676 | n/a | if dir is None: |
---|
677 | n/a | if output_type is str: |
---|
678 | n/a | dir = tempfile.gettempdir() |
---|
679 | n/a | else: |
---|
680 | n/a | dir = tempfile.gettempdirb() |
---|
681 | n/a | if pre is None: |
---|
682 | n/a | pre = output_type() |
---|
683 | n/a | if suf is None: |
---|
684 | n/a | suf = output_type() |
---|
685 | n/a | name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf) |
---|
686 | n/a | |
---|
687 | n/a | try: |
---|
688 | n/a | self.nameCheck(name, dir, pre, suf) |
---|
689 | n/a | return name |
---|
690 | n/a | except: |
---|
691 | n/a | os.rmdir(name) |
---|
692 | n/a | raise |
---|
693 | n/a | |
---|
694 | n/a | def test_basic(self): |
---|
695 | n/a | # mkdtemp can create directories |
---|
696 | n/a | os.rmdir(self.do_create()) |
---|
697 | n/a | os.rmdir(self.do_create(pre="a")) |
---|
698 | n/a | os.rmdir(self.do_create(suf="b")) |
---|
699 | n/a | os.rmdir(self.do_create(pre="a", suf="b")) |
---|
700 | n/a | os.rmdir(self.do_create(pre="aa", suf=".txt")) |
---|
701 | n/a | |
---|
702 | n/a | def test_basic_with_bytes_names(self): |
---|
703 | n/a | # mkdtemp can create directories when given all binary parts |
---|
704 | n/a | d = tempfile.gettempdirb() |
---|
705 | n/a | os.rmdir(self.do_create(dir=d)) |
---|
706 | n/a | os.rmdir(self.do_create(dir=d, pre=b"a")) |
---|
707 | n/a | os.rmdir(self.do_create(dir=d, suf=b"b")) |
---|
708 | n/a | os.rmdir(self.do_create(dir=d, pre=b"a", suf=b"b")) |
---|
709 | n/a | os.rmdir(self.do_create(dir=d, pre=b"aa", suf=b".txt")) |
---|
710 | n/a | with self.assertRaises(TypeError): |
---|
711 | n/a | os.rmdir(self.do_create(dir=d, pre="aa", suf=b".txt")) |
---|
712 | n/a | with self.assertRaises(TypeError): |
---|
713 | n/a | os.rmdir(self.do_create(dir=d, pre=b"aa", suf=".txt")) |
---|
714 | n/a | with self.assertRaises(TypeError): |
---|
715 | n/a | os.rmdir(self.do_create(dir="", pre=b"aa", suf=b".txt")) |
---|
716 | n/a | |
---|
717 | n/a | def test_basic_many(self): |
---|
718 | n/a | # mkdtemp can create many directories (stochastic) |
---|
719 | n/a | extant = list(range(TEST_FILES)) |
---|
720 | n/a | try: |
---|
721 | n/a | for i in extant: |
---|
722 | n/a | extant[i] = self.do_create(pre="aa") |
---|
723 | n/a | finally: |
---|
724 | n/a | for i in extant: |
---|
725 | n/a | if(isinstance(i, str)): |
---|
726 | n/a | os.rmdir(i) |
---|
727 | n/a | |
---|
728 | n/a | def test_choose_directory(self): |
---|
729 | n/a | # mkdtemp can create directories in a user-selected directory |
---|
730 | n/a | dir = tempfile.mkdtemp() |
---|
731 | n/a | try: |
---|
732 | n/a | os.rmdir(self.do_create(dir=dir)) |
---|
733 | n/a | finally: |
---|
734 | n/a | os.rmdir(dir) |
---|
735 | n/a | |
---|
736 | n/a | @unittest.skipUnless(has_stat, 'os.stat not available') |
---|
737 | n/a | def test_mode(self): |
---|
738 | n/a | # mkdtemp creates directories with the proper mode |
---|
739 | n/a | |
---|
740 | n/a | dir = self.do_create() |
---|
741 | n/a | try: |
---|
742 | n/a | mode = stat.S_IMODE(os.stat(dir).st_mode) |
---|
743 | n/a | mode &= 0o777 # Mask off sticky bits inherited from /tmp |
---|
744 | n/a | expected = 0o700 |
---|
745 | n/a | if sys.platform == 'win32': |
---|
746 | n/a | # There's no distinction among 'user', 'group' and 'world'; |
---|
747 | n/a | # replicate the 'user' bits. |
---|
748 | n/a | user = expected >> 6 |
---|
749 | n/a | expected = user * (1 + 8 + 64) |
---|
750 | n/a | self.assertEqual(mode, expected) |
---|
751 | n/a | finally: |
---|
752 | n/a | os.rmdir(dir) |
---|
753 | n/a | |
---|
754 | n/a | def test_collision_with_existing_file(self): |
---|
755 | n/a | # mkdtemp tries another name when a file with |
---|
756 | n/a | # the chosen name already exists |
---|
757 | n/a | with _inside_empty_temp_dir(), \ |
---|
758 | n/a | _mock_candidate_names('aaa', 'aaa', 'bbb'): |
---|
759 | n/a | file = tempfile.NamedTemporaryFile(delete=False) |
---|
760 | n/a | file.close() |
---|
761 | n/a | self.assertTrue(file.name.endswith('aaa')) |
---|
762 | n/a | dir = tempfile.mkdtemp() |
---|
763 | n/a | self.assertTrue(dir.endswith('bbb')) |
---|
764 | n/a | |
---|
765 | n/a | def test_collision_with_existing_directory(self): |
---|
766 | n/a | # mkdtemp tries another name when a directory with |
---|
767 | n/a | # the chosen name already exists |
---|
768 | n/a | with _inside_empty_temp_dir(), \ |
---|
769 | n/a | _mock_candidate_names('aaa', 'aaa', 'bbb'): |
---|
770 | n/a | dir1 = tempfile.mkdtemp() |
---|
771 | n/a | self.assertTrue(dir1.endswith('aaa')) |
---|
772 | n/a | dir2 = tempfile.mkdtemp() |
---|
773 | n/a | self.assertTrue(dir2.endswith('bbb')) |
---|
774 | n/a | |
---|
775 | n/a | |
---|
776 | n/a | class TestMktemp(BaseTestCase): |
---|
777 | n/a | """Test mktemp().""" |
---|
778 | n/a | |
---|
779 | n/a | # For safety, all use of mktemp must occur in a private directory. |
---|
780 | n/a | # We must also suppress the RuntimeWarning it generates. |
---|
781 | n/a | def setUp(self): |
---|
782 | n/a | self.dir = tempfile.mkdtemp() |
---|
783 | n/a | super().setUp() |
---|
784 | n/a | |
---|
785 | n/a | def tearDown(self): |
---|
786 | n/a | if self.dir: |
---|
787 | n/a | os.rmdir(self.dir) |
---|
788 | n/a | self.dir = None |
---|
789 | n/a | super().tearDown() |
---|
790 | n/a | |
---|
791 | n/a | class mktemped: |
---|
792 | n/a | _unlink = os.unlink |
---|
793 | n/a | _bflags = tempfile._bin_openflags |
---|
794 | n/a | |
---|
795 | n/a | def __init__(self, dir, pre, suf): |
---|
796 | n/a | self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf) |
---|
797 | n/a | # Create the file. This will raise an exception if it's |
---|
798 | n/a | # mysteriously appeared in the meanwhile. |
---|
799 | n/a | os.close(os.open(self.name, self._bflags, 0o600)) |
---|
800 | n/a | |
---|
801 | n/a | def __del__(self): |
---|
802 | n/a | self._unlink(self.name) |
---|
803 | n/a | |
---|
804 | n/a | def do_create(self, pre="", suf=""): |
---|
805 | n/a | file = self.mktemped(self.dir, pre, suf) |
---|
806 | n/a | |
---|
807 | n/a | self.nameCheck(file.name, self.dir, pre, suf) |
---|
808 | n/a | return file |
---|
809 | n/a | |
---|
810 | n/a | def test_basic(self): |
---|
811 | n/a | # mktemp can choose usable file names |
---|
812 | n/a | self.do_create() |
---|
813 | n/a | self.do_create(pre="a") |
---|
814 | n/a | self.do_create(suf="b") |
---|
815 | n/a | self.do_create(pre="a", suf="b") |
---|
816 | n/a | self.do_create(pre="aa", suf=".txt") |
---|
817 | n/a | |
---|
818 | n/a | def test_many(self): |
---|
819 | n/a | # mktemp can choose many usable file names (stochastic) |
---|
820 | n/a | extant = list(range(TEST_FILES)) |
---|
821 | n/a | for i in extant: |
---|
822 | n/a | extant[i] = self.do_create(pre="aa") |
---|
823 | n/a | |
---|
824 | n/a | ## def test_warning(self): |
---|
825 | n/a | ## # mktemp issues a warning when used |
---|
826 | n/a | ## warnings.filterwarnings("error", |
---|
827 | n/a | ## category=RuntimeWarning, |
---|
828 | n/a | ## message="mktemp") |
---|
829 | n/a | ## self.assertRaises(RuntimeWarning, |
---|
830 | n/a | ## tempfile.mktemp, dir=self.dir) |
---|
831 | n/a | |
---|
832 | n/a | |
---|
833 | n/a | # We test _TemporaryFileWrapper by testing NamedTemporaryFile. |
---|
834 | n/a | |
---|
835 | n/a | |
---|
836 | n/a | class TestNamedTemporaryFile(BaseTestCase): |
---|
837 | n/a | """Test NamedTemporaryFile().""" |
---|
838 | n/a | |
---|
839 | n/a | def do_create(self, dir=None, pre="", suf="", delete=True): |
---|
840 | n/a | if dir is None: |
---|
841 | n/a | dir = tempfile.gettempdir() |
---|
842 | n/a | file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf, |
---|
843 | n/a | delete=delete) |
---|
844 | n/a | |
---|
845 | n/a | self.nameCheck(file.name, dir, pre, suf) |
---|
846 | n/a | return file |
---|
847 | n/a | |
---|
848 | n/a | |
---|
849 | n/a | def test_basic(self): |
---|
850 | n/a | # NamedTemporaryFile can create files |
---|
851 | n/a | self.do_create() |
---|
852 | n/a | self.do_create(pre="a") |
---|
853 | n/a | self.do_create(suf="b") |
---|
854 | n/a | self.do_create(pre="a", suf="b") |
---|
855 | n/a | self.do_create(pre="aa", suf=".txt") |
---|
856 | n/a | |
---|
857 | n/a | def test_method_lookup(self): |
---|
858 | n/a | # Issue #18879: Looking up a temporary file method should keep it |
---|
859 | n/a | # alive long enough. |
---|
860 | n/a | f = self.do_create() |
---|
861 | n/a | wr = weakref.ref(f) |
---|
862 | n/a | write = f.write |
---|
863 | n/a | write2 = f.write |
---|
864 | n/a | del f |
---|
865 | n/a | write(b'foo') |
---|
866 | n/a | del write |
---|
867 | n/a | write2(b'bar') |
---|
868 | n/a | del write2 |
---|
869 | n/a | if support.check_impl_detail(cpython=True): |
---|
870 | n/a | # No reference cycle was created. |
---|
871 | n/a | self.assertIsNone(wr()) |
---|
872 | n/a | |
---|
873 | n/a | def test_iter(self): |
---|
874 | n/a | # Issue #23700: getting iterator from a temporary file should keep |
---|
875 | n/a | # it alive as long as it's being iterated over |
---|
876 | n/a | lines = [b'spam\n', b'eggs\n', b'beans\n'] |
---|
877 | n/a | def make_file(): |
---|
878 | n/a | f = tempfile.NamedTemporaryFile(mode='w+b') |
---|
879 | n/a | f.write(b''.join(lines)) |
---|
880 | n/a | f.seek(0) |
---|
881 | n/a | return f |
---|
882 | n/a | for i, l in enumerate(make_file()): |
---|
883 | n/a | self.assertEqual(l, lines[i]) |
---|
884 | n/a | self.assertEqual(i, len(lines) - 1) |
---|
885 | n/a | |
---|
886 | n/a | def test_creates_named(self): |
---|
887 | n/a | # NamedTemporaryFile creates files with names |
---|
888 | n/a | f = tempfile.NamedTemporaryFile() |
---|
889 | n/a | self.assertTrue(os.path.exists(f.name), |
---|
890 | n/a | "NamedTemporaryFile %s does not exist" % f.name) |
---|
891 | n/a | |
---|
892 | n/a | def test_del_on_close(self): |
---|
893 | n/a | # A NamedTemporaryFile is deleted when closed |
---|
894 | n/a | dir = tempfile.mkdtemp() |
---|
895 | n/a | try: |
---|
896 | n/a | f = tempfile.NamedTemporaryFile(dir=dir) |
---|
897 | n/a | f.write(b'blat') |
---|
898 | n/a | f.close() |
---|
899 | n/a | self.assertFalse(os.path.exists(f.name), |
---|
900 | n/a | "NamedTemporaryFile %s exists after close" % f.name) |
---|
901 | n/a | finally: |
---|
902 | n/a | os.rmdir(dir) |
---|
903 | n/a | |
---|
904 | n/a | def test_dis_del_on_close(self): |
---|
905 | n/a | # Tests that delete-on-close can be disabled |
---|
906 | n/a | dir = tempfile.mkdtemp() |
---|
907 | n/a | tmp = None |
---|
908 | n/a | try: |
---|
909 | n/a | f = tempfile.NamedTemporaryFile(dir=dir, delete=False) |
---|
910 | n/a | tmp = f.name |
---|
911 | n/a | f.write(b'blat') |
---|
912 | n/a | f.close() |
---|
913 | n/a | self.assertTrue(os.path.exists(f.name), |
---|
914 | n/a | "NamedTemporaryFile %s missing after close" % f.name) |
---|
915 | n/a | finally: |
---|
916 | n/a | if tmp is not None: |
---|
917 | n/a | os.unlink(tmp) |
---|
918 | n/a | os.rmdir(dir) |
---|
919 | n/a | |
---|
920 | n/a | def test_multiple_close(self): |
---|
921 | n/a | # A NamedTemporaryFile can be closed many times without error |
---|
922 | n/a | f = tempfile.NamedTemporaryFile() |
---|
923 | n/a | f.write(b'abc\n') |
---|
924 | n/a | f.close() |
---|
925 | n/a | f.close() |
---|
926 | n/a | f.close() |
---|
927 | n/a | |
---|
928 | n/a | def test_context_manager(self): |
---|
929 | n/a | # A NamedTemporaryFile can be used as a context manager |
---|
930 | n/a | with tempfile.NamedTemporaryFile() as f: |
---|
931 | n/a | self.assertTrue(os.path.exists(f.name)) |
---|
932 | n/a | self.assertFalse(os.path.exists(f.name)) |
---|
933 | n/a | def use_closed(): |
---|
934 | n/a | with f: |
---|
935 | n/a | pass |
---|
936 | n/a | self.assertRaises(ValueError, use_closed) |
---|
937 | n/a | |
---|
938 | n/a | def test_no_leak_fd(self): |
---|
939 | n/a | # Issue #21058: don't leak file descriptor when io.open() fails |
---|
940 | n/a | closed = [] |
---|
941 | n/a | os_close = os.close |
---|
942 | n/a | def close(fd): |
---|
943 | n/a | closed.append(fd) |
---|
944 | n/a | os_close(fd) |
---|
945 | n/a | |
---|
946 | n/a | with mock.patch('os.close', side_effect=close): |
---|
947 | n/a | with mock.patch('io.open', side_effect=ValueError): |
---|
948 | n/a | self.assertRaises(ValueError, tempfile.NamedTemporaryFile) |
---|
949 | n/a | self.assertEqual(len(closed), 1) |
---|
950 | n/a | |
---|
951 | n/a | def test_bad_mode(self): |
---|
952 | n/a | dir = tempfile.mkdtemp() |
---|
953 | n/a | self.addCleanup(support.rmtree, dir) |
---|
954 | n/a | with self.assertRaises(ValueError): |
---|
955 | n/a | tempfile.NamedTemporaryFile(mode='wr', dir=dir) |
---|
956 | n/a | with self.assertRaises(TypeError): |
---|
957 | n/a | tempfile.NamedTemporaryFile(mode=2, dir=dir) |
---|
958 | n/a | self.assertEqual(os.listdir(dir), []) |
---|
959 | n/a | |
---|
960 | n/a | # How to test the mode and bufsize parameters? |
---|
961 | n/a | |
---|
962 | n/a | class TestSpooledTemporaryFile(BaseTestCase): |
---|
963 | n/a | """Test SpooledTemporaryFile().""" |
---|
964 | n/a | |
---|
965 | n/a | def do_create(self, max_size=0, dir=None, pre="", suf=""): |
---|
966 | n/a | if dir is None: |
---|
967 | n/a | dir = tempfile.gettempdir() |
---|
968 | n/a | file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf) |
---|
969 | n/a | |
---|
970 | n/a | return file |
---|
971 | n/a | |
---|
972 | n/a | |
---|
973 | n/a | def test_basic(self): |
---|
974 | n/a | # SpooledTemporaryFile can create files |
---|
975 | n/a | f = self.do_create() |
---|
976 | n/a | self.assertFalse(f._rolled) |
---|
977 | n/a | f = self.do_create(max_size=100, pre="a", suf=".txt") |
---|
978 | n/a | self.assertFalse(f._rolled) |
---|
979 | n/a | |
---|
980 | n/a | def test_del_on_close(self): |
---|
981 | n/a | # A SpooledTemporaryFile is deleted when closed |
---|
982 | n/a | dir = tempfile.mkdtemp() |
---|
983 | n/a | try: |
---|
984 | n/a | f = tempfile.SpooledTemporaryFile(max_size=10, dir=dir) |
---|
985 | n/a | self.assertFalse(f._rolled) |
---|
986 | n/a | f.write(b'blat ' * 5) |
---|
987 | n/a | self.assertTrue(f._rolled) |
---|
988 | n/a | filename = f.name |
---|
989 | n/a | f.close() |
---|
990 | n/a | self.assertFalse(isinstance(filename, str) and os.path.exists(filename), |
---|
991 | n/a | "SpooledTemporaryFile %s exists after close" % filename) |
---|
992 | n/a | finally: |
---|
993 | n/a | os.rmdir(dir) |
---|
994 | n/a | |
---|
995 | n/a | def test_rewrite_small(self): |
---|
996 | n/a | # A SpooledTemporaryFile can be written to multiple within the max_size |
---|
997 | n/a | f = self.do_create(max_size=30) |
---|
998 | n/a | self.assertFalse(f._rolled) |
---|
999 | n/a | for i in range(5): |
---|
1000 | n/a | f.seek(0, 0) |
---|
1001 | n/a | f.write(b'x' * 20) |
---|
1002 | n/a | self.assertFalse(f._rolled) |
---|
1003 | n/a | |
---|
1004 | n/a | def test_write_sequential(self): |
---|
1005 | n/a | # A SpooledTemporaryFile should hold exactly max_size bytes, and roll |
---|
1006 | n/a | # over afterward |
---|
1007 | n/a | f = self.do_create(max_size=30) |
---|
1008 | n/a | self.assertFalse(f._rolled) |
---|
1009 | n/a | f.write(b'x' * 20) |
---|
1010 | n/a | self.assertFalse(f._rolled) |
---|
1011 | n/a | f.write(b'x' * 10) |
---|
1012 | n/a | self.assertFalse(f._rolled) |
---|
1013 | n/a | f.write(b'x') |
---|
1014 | n/a | self.assertTrue(f._rolled) |
---|
1015 | n/a | |
---|
1016 | n/a | def test_writelines(self): |
---|
1017 | n/a | # Verify writelines with a SpooledTemporaryFile |
---|
1018 | n/a | f = self.do_create() |
---|
1019 | n/a | f.writelines((b'x', b'y', b'z')) |
---|
1020 | n/a | f.seek(0) |
---|
1021 | n/a | buf = f.read() |
---|
1022 | n/a | self.assertEqual(buf, b'xyz') |
---|
1023 | n/a | |
---|
1024 | n/a | def test_writelines_sequential(self): |
---|
1025 | n/a | # A SpooledTemporaryFile should hold exactly max_size bytes, and roll |
---|
1026 | n/a | # over afterward |
---|
1027 | n/a | f = self.do_create(max_size=35) |
---|
1028 | n/a | f.writelines((b'x' * 20, b'x' * 10, b'x' * 5)) |
---|
1029 | n/a | self.assertFalse(f._rolled) |
---|
1030 | n/a | f.write(b'x') |
---|
1031 | n/a | self.assertTrue(f._rolled) |
---|
1032 | n/a | |
---|
1033 | n/a | def test_sparse(self): |
---|
1034 | n/a | # A SpooledTemporaryFile that is written late in the file will extend |
---|
1035 | n/a | # when that occurs |
---|
1036 | n/a | f = self.do_create(max_size=30) |
---|
1037 | n/a | self.assertFalse(f._rolled) |
---|
1038 | n/a | f.seek(100, 0) |
---|
1039 | n/a | self.assertFalse(f._rolled) |
---|
1040 | n/a | f.write(b'x') |
---|
1041 | n/a | self.assertTrue(f._rolled) |
---|
1042 | n/a | |
---|
1043 | n/a | def test_fileno(self): |
---|
1044 | n/a | # A SpooledTemporaryFile should roll over to a real file on fileno() |
---|
1045 | n/a | f = self.do_create(max_size=30) |
---|
1046 | n/a | self.assertFalse(f._rolled) |
---|
1047 | n/a | self.assertTrue(f.fileno() > 0) |
---|
1048 | n/a | self.assertTrue(f._rolled) |
---|
1049 | n/a | |
---|
1050 | n/a | def test_multiple_close_before_rollover(self): |
---|
1051 | n/a | # A SpooledTemporaryFile can be closed many times without error |
---|
1052 | n/a | f = tempfile.SpooledTemporaryFile() |
---|
1053 | n/a | f.write(b'abc\n') |
---|
1054 | n/a | self.assertFalse(f._rolled) |
---|
1055 | n/a | f.close() |
---|
1056 | n/a | f.close() |
---|
1057 | n/a | f.close() |
---|
1058 | n/a | |
---|
1059 | n/a | def test_multiple_close_after_rollover(self): |
---|
1060 | n/a | # A SpooledTemporaryFile can be closed many times without error |
---|
1061 | n/a | f = tempfile.SpooledTemporaryFile(max_size=1) |
---|
1062 | n/a | f.write(b'abc\n') |
---|
1063 | n/a | self.assertTrue(f._rolled) |
---|
1064 | n/a | f.close() |
---|
1065 | n/a | f.close() |
---|
1066 | n/a | f.close() |
---|
1067 | n/a | |
---|
1068 | n/a | def test_bound_methods(self): |
---|
1069 | n/a | # It should be OK to steal a bound method from a SpooledTemporaryFile |
---|
1070 | n/a | # and use it independently; when the file rolls over, those bound |
---|
1071 | n/a | # methods should continue to function |
---|
1072 | n/a | f = self.do_create(max_size=30) |
---|
1073 | n/a | read = f.read |
---|
1074 | n/a | write = f.write |
---|
1075 | n/a | seek = f.seek |
---|
1076 | n/a | |
---|
1077 | n/a | write(b"a" * 35) |
---|
1078 | n/a | write(b"b" * 35) |
---|
1079 | n/a | seek(0, 0) |
---|
1080 | n/a | self.assertEqual(read(70), b'a'*35 + b'b'*35) |
---|
1081 | n/a | |
---|
1082 | n/a | def test_properties(self): |
---|
1083 | n/a | f = tempfile.SpooledTemporaryFile(max_size=10) |
---|
1084 | n/a | f.write(b'x' * 10) |
---|
1085 | n/a | self.assertFalse(f._rolled) |
---|
1086 | n/a | self.assertEqual(f.mode, 'w+b') |
---|
1087 | n/a | self.assertIsNone(f.name) |
---|
1088 | n/a | with self.assertRaises(AttributeError): |
---|
1089 | n/a | f.newlines |
---|
1090 | n/a | with self.assertRaises(AttributeError): |
---|
1091 | n/a | f.encoding |
---|
1092 | n/a | |
---|
1093 | n/a | f.write(b'x') |
---|
1094 | n/a | self.assertTrue(f._rolled) |
---|
1095 | n/a | self.assertEqual(f.mode, 'rb+') |
---|
1096 | n/a | self.assertIsNotNone(f.name) |
---|
1097 | n/a | with self.assertRaises(AttributeError): |
---|
1098 | n/a | f.newlines |
---|
1099 | n/a | with self.assertRaises(AttributeError): |
---|
1100 | n/a | f.encoding |
---|
1101 | n/a | |
---|
1102 | n/a | def test_text_mode(self): |
---|
1103 | n/a | # Creating a SpooledTemporaryFile with a text mode should produce |
---|
1104 | n/a | # a file object reading and writing (Unicode) text strings. |
---|
1105 | n/a | f = tempfile.SpooledTemporaryFile(mode='w+', max_size=10) |
---|
1106 | n/a | f.write("abc\n") |
---|
1107 | n/a | f.seek(0) |
---|
1108 | n/a | self.assertEqual(f.read(), "abc\n") |
---|
1109 | n/a | f.write("def\n") |
---|
1110 | n/a | f.seek(0) |
---|
1111 | n/a | self.assertEqual(f.read(), "abc\ndef\n") |
---|
1112 | n/a | self.assertFalse(f._rolled) |
---|
1113 | n/a | self.assertEqual(f.mode, 'w+') |
---|
1114 | n/a | self.assertIsNone(f.name) |
---|
1115 | n/a | self.assertIsNone(f.newlines) |
---|
1116 | n/a | self.assertIsNone(f.encoding) |
---|
1117 | n/a | |
---|
1118 | n/a | f.write("xyzzy\n") |
---|
1119 | n/a | f.seek(0) |
---|
1120 | n/a | self.assertEqual(f.read(), "abc\ndef\nxyzzy\n") |
---|
1121 | n/a | # Check that Ctrl+Z doesn't truncate the file |
---|
1122 | n/a | f.write("foo\x1abar\n") |
---|
1123 | n/a | f.seek(0) |
---|
1124 | n/a | self.assertEqual(f.read(), "abc\ndef\nxyzzy\nfoo\x1abar\n") |
---|
1125 | n/a | self.assertTrue(f._rolled) |
---|
1126 | n/a | self.assertEqual(f.mode, 'w+') |
---|
1127 | n/a | self.assertIsNotNone(f.name) |
---|
1128 | n/a | self.assertEqual(f.newlines, os.linesep) |
---|
1129 | n/a | self.assertIsNotNone(f.encoding) |
---|
1130 | n/a | |
---|
1131 | n/a | def test_text_newline_and_encoding(self): |
---|
1132 | n/a | f = tempfile.SpooledTemporaryFile(mode='w+', max_size=10, |
---|
1133 | n/a | newline='', encoding='utf-8') |
---|
1134 | n/a | f.write("\u039B\r\n") |
---|
1135 | n/a | f.seek(0) |
---|
1136 | n/a | self.assertEqual(f.read(), "\u039B\r\n") |
---|
1137 | n/a | self.assertFalse(f._rolled) |
---|
1138 | n/a | self.assertEqual(f.mode, 'w+') |
---|
1139 | n/a | self.assertIsNone(f.name) |
---|
1140 | n/a | self.assertIsNone(f.newlines) |
---|
1141 | n/a | self.assertIsNone(f.encoding) |
---|
1142 | n/a | |
---|
1143 | n/a | f.write("\u039B" * 20 + "\r\n") |
---|
1144 | n/a | f.seek(0) |
---|
1145 | n/a | self.assertEqual(f.read(), "\u039B\r\n" + ("\u039B" * 20) + "\r\n") |
---|
1146 | n/a | self.assertTrue(f._rolled) |
---|
1147 | n/a | self.assertEqual(f.mode, 'w+') |
---|
1148 | n/a | self.assertIsNotNone(f.name) |
---|
1149 | n/a | self.assertIsNotNone(f.newlines) |
---|
1150 | n/a | self.assertEqual(f.encoding, 'utf-8') |
---|
1151 | n/a | |
---|
1152 | n/a | def test_context_manager_before_rollover(self): |
---|
1153 | n/a | # A SpooledTemporaryFile can be used as a context manager |
---|
1154 | n/a | with tempfile.SpooledTemporaryFile(max_size=1) as f: |
---|
1155 | n/a | self.assertFalse(f._rolled) |
---|
1156 | n/a | self.assertFalse(f.closed) |
---|
1157 | n/a | self.assertTrue(f.closed) |
---|
1158 | n/a | def use_closed(): |
---|
1159 | n/a | with f: |
---|
1160 | n/a | pass |
---|
1161 | n/a | self.assertRaises(ValueError, use_closed) |
---|
1162 | n/a | |
---|
1163 | n/a | def test_context_manager_during_rollover(self): |
---|
1164 | n/a | # A SpooledTemporaryFile can be used as a context manager |
---|
1165 | n/a | with tempfile.SpooledTemporaryFile(max_size=1) as f: |
---|
1166 | n/a | self.assertFalse(f._rolled) |
---|
1167 | n/a | f.write(b'abc\n') |
---|
1168 | n/a | f.flush() |
---|
1169 | n/a | self.assertTrue(f._rolled) |
---|
1170 | n/a | self.assertFalse(f.closed) |
---|
1171 | n/a | self.assertTrue(f.closed) |
---|
1172 | n/a | def use_closed(): |
---|
1173 | n/a | with f: |
---|
1174 | n/a | pass |
---|
1175 | n/a | self.assertRaises(ValueError, use_closed) |
---|
1176 | n/a | |
---|
1177 | n/a | def test_context_manager_after_rollover(self): |
---|
1178 | n/a | # A SpooledTemporaryFile can be used as a context manager |
---|
1179 | n/a | f = tempfile.SpooledTemporaryFile(max_size=1) |
---|
1180 | n/a | f.write(b'abc\n') |
---|
1181 | n/a | f.flush() |
---|
1182 | n/a | self.assertTrue(f._rolled) |
---|
1183 | n/a | with f: |
---|
1184 | n/a | self.assertFalse(f.closed) |
---|
1185 | n/a | self.assertTrue(f.closed) |
---|
1186 | n/a | def use_closed(): |
---|
1187 | n/a | with f: |
---|
1188 | n/a | pass |
---|
1189 | n/a | self.assertRaises(ValueError, use_closed) |
---|
1190 | n/a | |
---|
1191 | n/a | def test_truncate_with_size_parameter(self): |
---|
1192 | n/a | # A SpooledTemporaryFile can be truncated to zero size |
---|
1193 | n/a | f = tempfile.SpooledTemporaryFile(max_size=10) |
---|
1194 | n/a | f.write(b'abcdefg\n') |
---|
1195 | n/a | f.seek(0) |
---|
1196 | n/a | f.truncate() |
---|
1197 | n/a | self.assertFalse(f._rolled) |
---|
1198 | n/a | self.assertEqual(f._file.getvalue(), b'') |
---|
1199 | n/a | # A SpooledTemporaryFile can be truncated to a specific size |
---|
1200 | n/a | f = tempfile.SpooledTemporaryFile(max_size=10) |
---|
1201 | n/a | f.write(b'abcdefg\n') |
---|
1202 | n/a | f.truncate(4) |
---|
1203 | n/a | self.assertFalse(f._rolled) |
---|
1204 | n/a | self.assertEqual(f._file.getvalue(), b'abcd') |
---|
1205 | n/a | # A SpooledTemporaryFile rolls over if truncated to large size |
---|
1206 | n/a | f = tempfile.SpooledTemporaryFile(max_size=10) |
---|
1207 | n/a | f.write(b'abcdefg\n') |
---|
1208 | n/a | f.truncate(20) |
---|
1209 | n/a | self.assertTrue(f._rolled) |
---|
1210 | n/a | if has_stat: |
---|
1211 | n/a | self.assertEqual(os.fstat(f.fileno()).st_size, 20) |
---|
1212 | n/a | |
---|
1213 | n/a | |
---|
1214 | n/a | if tempfile.NamedTemporaryFile is not tempfile.TemporaryFile: |
---|
1215 | n/a | |
---|
1216 | n/a | class TestTemporaryFile(BaseTestCase): |
---|
1217 | n/a | """Test TemporaryFile().""" |
---|
1218 | n/a | |
---|
1219 | n/a | def test_basic(self): |
---|
1220 | n/a | # TemporaryFile can create files |
---|
1221 | n/a | # No point in testing the name params - the file has no name. |
---|
1222 | n/a | tempfile.TemporaryFile() |
---|
1223 | n/a | |
---|
1224 | n/a | def test_has_no_name(self): |
---|
1225 | n/a | # TemporaryFile creates files with no names (on this system) |
---|
1226 | n/a | dir = tempfile.mkdtemp() |
---|
1227 | n/a | f = tempfile.TemporaryFile(dir=dir) |
---|
1228 | n/a | f.write(b'blat') |
---|
1229 | n/a | |
---|
1230 | n/a | # Sneaky: because this file has no name, it should not prevent |
---|
1231 | n/a | # us from removing the directory it was created in. |
---|
1232 | n/a | try: |
---|
1233 | n/a | os.rmdir(dir) |
---|
1234 | n/a | except: |
---|
1235 | n/a | # cleanup |
---|
1236 | n/a | f.close() |
---|
1237 | n/a | os.rmdir(dir) |
---|
1238 | n/a | raise |
---|
1239 | n/a | |
---|
1240 | n/a | def test_multiple_close(self): |
---|
1241 | n/a | # A TemporaryFile can be closed many times without error |
---|
1242 | n/a | f = tempfile.TemporaryFile() |
---|
1243 | n/a | f.write(b'abc\n') |
---|
1244 | n/a | f.close() |
---|
1245 | n/a | f.close() |
---|
1246 | n/a | f.close() |
---|
1247 | n/a | |
---|
1248 | n/a | # How to test the mode and bufsize parameters? |
---|
1249 | n/a | def test_mode_and_encoding(self): |
---|
1250 | n/a | |
---|
1251 | n/a | def roundtrip(input, *args, **kwargs): |
---|
1252 | n/a | with tempfile.TemporaryFile(*args, **kwargs) as fileobj: |
---|
1253 | n/a | fileobj.write(input) |
---|
1254 | n/a | fileobj.seek(0) |
---|
1255 | n/a | self.assertEqual(input, fileobj.read()) |
---|
1256 | n/a | |
---|
1257 | n/a | roundtrip(b"1234", "w+b") |
---|
1258 | n/a | roundtrip("abdc\n", "w+") |
---|
1259 | n/a | roundtrip("\u039B", "w+", encoding="utf-16") |
---|
1260 | n/a | roundtrip("foo\r\n", "w+", newline="") |
---|
1261 | n/a | |
---|
1262 | n/a | def test_no_leak_fd(self): |
---|
1263 | n/a | # Issue #21058: don't leak file descriptor when io.open() fails |
---|
1264 | n/a | closed = [] |
---|
1265 | n/a | os_close = os.close |
---|
1266 | n/a | def close(fd): |
---|
1267 | n/a | closed.append(fd) |
---|
1268 | n/a | os_close(fd) |
---|
1269 | n/a | |
---|
1270 | n/a | with mock.patch('os.close', side_effect=close): |
---|
1271 | n/a | with mock.patch('io.open', side_effect=ValueError): |
---|
1272 | n/a | self.assertRaises(ValueError, tempfile.TemporaryFile) |
---|
1273 | n/a | self.assertEqual(len(closed), 1) |
---|
1274 | n/a | |
---|
1275 | n/a | |
---|
1276 | n/a | |
---|
1277 | n/a | # Helper for test_del_on_shutdown |
---|
1278 | n/a | class NulledModules: |
---|
1279 | n/a | def __init__(self, *modules): |
---|
1280 | n/a | self.refs = [mod.__dict__ for mod in modules] |
---|
1281 | n/a | self.contents = [ref.copy() for ref in self.refs] |
---|
1282 | n/a | |
---|
1283 | n/a | def __enter__(self): |
---|
1284 | n/a | for d in self.refs: |
---|
1285 | n/a | for key in d: |
---|
1286 | n/a | d[key] = None |
---|
1287 | n/a | |
---|
1288 | n/a | def __exit__(self, *exc_info): |
---|
1289 | n/a | for d, c in zip(self.refs, self.contents): |
---|
1290 | n/a | d.clear() |
---|
1291 | n/a | d.update(c) |
---|
1292 | n/a | |
---|
1293 | n/a | class TestTemporaryDirectory(BaseTestCase): |
---|
1294 | n/a | """Test TemporaryDirectory().""" |
---|
1295 | n/a | |
---|
1296 | n/a | def do_create(self, dir=None, pre="", suf="", recurse=1): |
---|
1297 | n/a | if dir is None: |
---|
1298 | n/a | dir = tempfile.gettempdir() |
---|
1299 | n/a | tmp = tempfile.TemporaryDirectory(dir=dir, prefix=pre, suffix=suf) |
---|
1300 | n/a | self.nameCheck(tmp.name, dir, pre, suf) |
---|
1301 | n/a | # Create a subdirectory and some files |
---|
1302 | n/a | if recurse: |
---|
1303 | n/a | d1 = self.do_create(tmp.name, pre, suf, recurse-1) |
---|
1304 | n/a | d1.name = None |
---|
1305 | n/a | with open(os.path.join(tmp.name, "test.txt"), "wb") as f: |
---|
1306 | n/a | f.write(b"Hello world!") |
---|
1307 | n/a | return tmp |
---|
1308 | n/a | |
---|
1309 | n/a | def test_mkdtemp_failure(self): |
---|
1310 | n/a | # Check no additional exception if mkdtemp fails |
---|
1311 | n/a | # Previously would raise AttributeError instead |
---|
1312 | n/a | # (noted as part of Issue #10188) |
---|
1313 | n/a | with tempfile.TemporaryDirectory() as nonexistent: |
---|
1314 | n/a | pass |
---|
1315 | n/a | with self.assertRaises(FileNotFoundError) as cm: |
---|
1316 | n/a | tempfile.TemporaryDirectory(dir=nonexistent) |
---|
1317 | n/a | self.assertEqual(cm.exception.errno, errno.ENOENT) |
---|
1318 | n/a | |
---|
1319 | n/a | def test_explicit_cleanup(self): |
---|
1320 | n/a | # A TemporaryDirectory is deleted when cleaned up |
---|
1321 | n/a | dir = tempfile.mkdtemp() |
---|
1322 | n/a | try: |
---|
1323 | n/a | d = self.do_create(dir=dir) |
---|
1324 | n/a | self.assertTrue(os.path.exists(d.name), |
---|
1325 | n/a | "TemporaryDirectory %s does not exist" % d.name) |
---|
1326 | n/a | d.cleanup() |
---|
1327 | n/a | self.assertFalse(os.path.exists(d.name), |
---|
1328 | n/a | "TemporaryDirectory %s exists after cleanup" % d.name) |
---|
1329 | n/a | finally: |
---|
1330 | n/a | os.rmdir(dir) |
---|
1331 | n/a | |
---|
1332 | n/a | @support.skip_unless_symlink |
---|
1333 | n/a | def test_cleanup_with_symlink_to_a_directory(self): |
---|
1334 | n/a | # cleanup() should not follow symlinks to directories (issue #12464) |
---|
1335 | n/a | d1 = self.do_create() |
---|
1336 | n/a | d2 = self.do_create(recurse=0) |
---|
1337 | n/a | |
---|
1338 | n/a | # Symlink d1/foo -> d2 |
---|
1339 | n/a | os.symlink(d2.name, os.path.join(d1.name, "foo")) |
---|
1340 | n/a | |
---|
1341 | n/a | # This call to cleanup() should not follow the "foo" symlink |
---|
1342 | n/a | d1.cleanup() |
---|
1343 | n/a | |
---|
1344 | n/a | self.assertFalse(os.path.exists(d1.name), |
---|
1345 | n/a | "TemporaryDirectory %s exists after cleanup" % d1.name) |
---|
1346 | n/a | self.assertTrue(os.path.exists(d2.name), |
---|
1347 | n/a | "Directory pointed to by a symlink was deleted") |
---|
1348 | n/a | self.assertEqual(os.listdir(d2.name), ['test.txt'], |
---|
1349 | n/a | "Contents of the directory pointed to by a symlink " |
---|
1350 | n/a | "were deleted") |
---|
1351 | n/a | d2.cleanup() |
---|
1352 | n/a | |
---|
1353 | n/a | @support.cpython_only |
---|
1354 | n/a | def test_del_on_collection(self): |
---|
1355 | n/a | # A TemporaryDirectory is deleted when garbage collected |
---|
1356 | n/a | dir = tempfile.mkdtemp() |
---|
1357 | n/a | try: |
---|
1358 | n/a | d = self.do_create(dir=dir) |
---|
1359 | n/a | name = d.name |
---|
1360 | n/a | del d # Rely on refcounting to invoke __del__ |
---|
1361 | n/a | self.assertFalse(os.path.exists(name), |
---|
1362 | n/a | "TemporaryDirectory %s exists after __del__" % name) |
---|
1363 | n/a | finally: |
---|
1364 | n/a | os.rmdir(dir) |
---|
1365 | n/a | |
---|
1366 | n/a | def test_del_on_shutdown(self): |
---|
1367 | n/a | # A TemporaryDirectory may be cleaned up during shutdown |
---|
1368 | n/a | with self.do_create() as dir: |
---|
1369 | n/a | for mod in ('builtins', 'os', 'shutil', 'sys', 'tempfile', 'warnings'): |
---|
1370 | n/a | code = """if True: |
---|
1371 | n/a | import builtins |
---|
1372 | n/a | import os |
---|
1373 | n/a | import shutil |
---|
1374 | n/a | import sys |
---|
1375 | n/a | import tempfile |
---|
1376 | n/a | import warnings |
---|
1377 | n/a | |
---|
1378 | n/a | tmp = tempfile.TemporaryDirectory(dir={dir!r}) |
---|
1379 | n/a | sys.stdout.buffer.write(tmp.name.encode()) |
---|
1380 | n/a | |
---|
1381 | n/a | tmp2 = os.path.join(tmp.name, 'test_dir') |
---|
1382 | n/a | os.mkdir(tmp2) |
---|
1383 | n/a | with open(os.path.join(tmp2, "test.txt"), "w") as f: |
---|
1384 | n/a | f.write("Hello world!") |
---|
1385 | n/a | |
---|
1386 | n/a | {mod}.tmp = tmp |
---|
1387 | n/a | |
---|
1388 | n/a | warnings.filterwarnings("always", category=ResourceWarning) |
---|
1389 | n/a | """.format(dir=dir, mod=mod) |
---|
1390 | n/a | rc, out, err = script_helper.assert_python_ok("-c", code) |
---|
1391 | n/a | tmp_name = out.decode().strip() |
---|
1392 | n/a | self.assertFalse(os.path.exists(tmp_name), |
---|
1393 | n/a | "TemporaryDirectory %s exists after cleanup" % tmp_name) |
---|
1394 | n/a | err = err.decode('utf-8', 'backslashreplace') |
---|
1395 | n/a | self.assertNotIn("Exception ", err) |
---|
1396 | n/a | self.assertIn("ResourceWarning: Implicitly cleaning up", err) |
---|
1397 | n/a | |
---|
1398 | n/a | def test_exit_on_shutdown(self): |
---|
1399 | n/a | # Issue #22427 |
---|
1400 | n/a | with self.do_create() as dir: |
---|
1401 | n/a | code = """if True: |
---|
1402 | n/a | import sys |
---|
1403 | n/a | import tempfile |
---|
1404 | n/a | import warnings |
---|
1405 | n/a | |
---|
1406 | n/a | def generator(): |
---|
1407 | n/a | with tempfile.TemporaryDirectory(dir={dir!r}) as tmp: |
---|
1408 | n/a | yield tmp |
---|
1409 | n/a | g = generator() |
---|
1410 | n/a | sys.stdout.buffer.write(next(g).encode()) |
---|
1411 | n/a | |
---|
1412 | n/a | warnings.filterwarnings("always", category=ResourceWarning) |
---|
1413 | n/a | """.format(dir=dir) |
---|
1414 | n/a | rc, out, err = script_helper.assert_python_ok("-c", code) |
---|
1415 | n/a | tmp_name = out.decode().strip() |
---|
1416 | n/a | self.assertFalse(os.path.exists(tmp_name), |
---|
1417 | n/a | "TemporaryDirectory %s exists after cleanup" % tmp_name) |
---|
1418 | n/a | err = err.decode('utf-8', 'backslashreplace') |
---|
1419 | n/a | self.assertNotIn("Exception ", err) |
---|
1420 | n/a | self.assertIn("ResourceWarning: Implicitly cleaning up", err) |
---|
1421 | n/a | |
---|
1422 | n/a | def test_warnings_on_cleanup(self): |
---|
1423 | n/a | # ResourceWarning will be triggered by __del__ |
---|
1424 | n/a | with self.do_create() as dir: |
---|
1425 | n/a | d = self.do_create(dir=dir, recurse=3) |
---|
1426 | n/a | name = d.name |
---|
1427 | n/a | |
---|
1428 | n/a | # Check for the resource warning |
---|
1429 | n/a | with support.check_warnings(('Implicitly', ResourceWarning), quiet=False): |
---|
1430 | n/a | warnings.filterwarnings("always", category=ResourceWarning) |
---|
1431 | n/a | del d |
---|
1432 | n/a | support.gc_collect() |
---|
1433 | n/a | self.assertFalse(os.path.exists(name), |
---|
1434 | n/a | "TemporaryDirectory %s exists after __del__" % name) |
---|
1435 | n/a | |
---|
1436 | n/a | def test_multiple_close(self): |
---|
1437 | n/a | # Can be cleaned-up many times without error |
---|
1438 | n/a | d = self.do_create() |
---|
1439 | n/a | d.cleanup() |
---|
1440 | n/a | d.cleanup() |
---|
1441 | n/a | d.cleanup() |
---|
1442 | n/a | |
---|
1443 | n/a | def test_context_manager(self): |
---|
1444 | n/a | # Can be used as a context manager |
---|
1445 | n/a | d = self.do_create() |
---|
1446 | n/a | with d as name: |
---|
1447 | n/a | self.assertTrue(os.path.exists(name)) |
---|
1448 | n/a | self.assertEqual(name, d.name) |
---|
1449 | n/a | self.assertFalse(os.path.exists(name)) |
---|
1450 | n/a | |
---|
1451 | n/a | |
---|
1452 | n/a | if __name__ == "__main__": |
---|
1453 | n/a | unittest.main() |
---|