1 # tempfile.py unit tests.
11 from test
import test_support
13 if hasattr(os
, 'stat'):
19 has_textmode
= (tempfile
._text
_openflags
!= tempfile
._bin
_openflags
)
20 has_spawnl
= hasattr(os
, 'spawnl')
22 # TEST_FILES may need to be tweaked for systems depending on the maximum
23 # number of files that can be opened at one time (see ulimit -n)
26 # This is organized as one test for each chunk of code in tempfile.py,
27 # in order of their appearance in the file. Testing which requires
28 # threads is not done here.
30 # Common functionality.
31 class TC(unittest
.TestCase
):
33 str_check
= re
.compile(r
"[a-zA-Z0-9_-]{6}$")
35 def failOnException(self
, what
, ei
=None):
38 self
.fail("%s raised %s: %s" % (what
, ei
[0], ei
[1]))
40 def nameCheck(self
, name
, dir, pre
, suf
):
41 (ndir
, nbase
) = os
.path
.split(name
)
42 npre
= nbase
[:len(pre
)]
43 nsuf
= nbase
[len(nbase
)-len(suf
):]
45 self
.assertEqual(ndir
, dir,
46 "file '%s' not in directory '%s'" % (name
, dir))
47 self
.assertEqual(npre
, pre
,
48 "file '%s' does not begin with '%s'" % (nbase
, pre
))
49 self
.assertEqual(nsuf
, suf
,
50 "file '%s' does not end with '%s'" % (nbase
, suf
))
52 nbase
= nbase
[len(pre
):len(nbase
)-len(suf
)]
53 self
.assert_(self
.str_check
.match(nbase
),
54 "random string '%s' does not match /^[a-zA-Z0-9_-]{6}$/"
59 class test_exports(TC
):
60 def test_exports(self
):
61 # There are no surprising symbols in the tempfile module
62 dict = tempfile
.__dict
__
65 "NamedTemporaryFile" : 1,
79 if key
[0] != '_' and key
not in expected
:
81 self
.failUnless(len(unexp
) == 0,
82 "unexpected keys: %s" % unexp
)
84 test_classes
.append(test_exports
)
87 class test__RandomNameSequence(TC
):
88 """Test the internal iterator object _RandomNameSequence."""
91 self
.r
= tempfile
._RandomNameSequence
()
93 def test_get_six_char_str(self
):
94 # _RandomNameSequence returns a six-character string
96 self
.nameCheck(s
, '', '', '')
99 # _RandomNameSequence returns no duplicate strings (stochastic)
103 for i
in xrange(TEST_FILES
):
105 self
.nameCheck(s
, '', '', '')
106 self
.failIf(s
in dict)
109 def test_supports_iter(self
):
110 # _RandomNameSequence supports the iterator protocol
120 failOnException("iteration")
122 test_classes
.append(test__RandomNameSequence
)
125 class test__candidate_tempdir_list(TC
):
126 """Test the internal function _candidate_tempdir_list."""
128 def test_nonempty_list(self
):
129 # _candidate_tempdir_list returns a nonempty list of strings
131 cand
= tempfile
._candidate
_tempdir
_list
()
133 self
.failIf(len(cand
) == 0)
135 self
.assert_(isinstance(c
, basestring
),
136 "%s is not a string" % c
)
138 def test_wanted_dirs(self
):
139 # _candidate_tempdir_list contains the expected directories
141 # Make sure the interesting environment variables are all set.
144 for envname
in 'TMPDIR', 'TEMP', 'TMP':
145 dirname
= os
.getenv(envname
)
147 os
.environ
[envname
] = os
.path
.abspath(envname
)
148 added
.append(envname
)
150 cand
= tempfile
._candidate
_tempdir
_list
()
152 for envname
in 'TMPDIR', 'TEMP', 'TMP':
153 dirname
= os
.getenv(envname
)
154 if not dirname
: raise ValueError
155 self
.assert_(dirname
in cand
)
158 dirname
= os
.getcwd()
159 except (AttributeError, os
.error
):
162 self
.assert_(dirname
in cand
)
164 # Not practical to try to verify the presence of OS-specific
165 # paths in this list.
170 test_classes
.append(test__candidate_tempdir_list
)
173 # We test _get_default_tempdir by testing gettempdir.
176 class test__get_candidate_names(TC
):
177 """Test the internal function _get_candidate_names."""
179 def test_retval(self
):
180 # _get_candidate_names returns a _RandomNameSequence object
181 obj
= tempfile
._get
_candidate
_names
()
182 self
.assert_(isinstance(obj
, tempfile
._RandomNameSequence
))
184 def test_same_thing(self
):
185 # _get_candidate_names always returns the same object
186 a
= tempfile
._get
_candidate
_names
()
187 b
= tempfile
._get
_candidate
_names
()
191 test_classes
.append(test__get_candidate_names
)
194 class test__mkstemp_inner(TC
):
195 """Test the internal function _mkstemp_inner."""
198 _bflags
= tempfile
._bin
_openflags
199 _tflags
= tempfile
._text
_openflags
203 def __init__(self
, dir, pre
, suf
, bin
):
204 if bin
: flags
= self
._bflags
205 else: flags
= self
._tflags
207 (self
.fd
, self
.name
) = tempfile
._mkstemp
_inner
(dir, pre
, suf
, flags
)
209 def write(self
, str):
210 os
.write(self
.fd
, str)
214 self
._unlink
(self
.name
)
216 def do_create(self
, dir=None, pre
="", suf
="", bin
=1):
218 dir = tempfile
.gettempdir()
220 file = self
.mkstemped(dir, pre
, suf
, bin
)
222 self
.failOnException("_mkstemp_inner")
224 self
.nameCheck(file.name
, dir, pre
, suf
)
227 def test_basic(self
):
228 # _mkstemp_inner can create files
229 self
.do_create().write("blat")
230 self
.do_create(pre
="a").write("blat")
231 self
.do_create(suf
="b").write("blat")
232 self
.do_create(pre
="a", suf
="b").write("blat")
233 self
.do_create(pre
="aa", suf
=".txt").write("blat")
235 def test_basic_many(self
):
236 # _mkstemp_inner can create many files (stochastic)
237 extant
= range(TEST_FILES
)
239 extant
[i
] = self
.do_create(pre
="aa")
241 def test_choose_directory(self
):
242 # _mkstemp_inner can create files in a user-selected directory
243 dir = tempfile
.mkdtemp()
245 self
.do_create(dir=dir).write("blat")
249 def test_file_mode(self
):
250 # _mkstemp_inner creates files with the proper mode
252 return # ugh, can't use TestSkipped.
254 file = self
.do_create()
255 mode
= stat
.S_IMODE(os
.stat(file.name
).st_mode
)
257 if sys
.platform
in ('win32', 'os2emx'):
258 # There's no distinction among 'user', 'group' and 'world';
259 # replicate the 'user' bits.
261 expected
= user
* (1 + 8 + 64)
262 self
.assertEqual(mode
, expected
)
264 def test_noinherit(self
):
265 # _mkstemp_inner file handles are not inherited by child processes
267 return # ugh, can't use TestSkipped.
269 if test_support
.verbose
:
274 file = self
.do_create()
282 # We have to exec something, so that FD_CLOEXEC will take
283 # effect. The core of this test is therefore in
284 # tf_inherit_check.py, which see.
285 tester
= os
.path
.join(os
.path
.dirname(os
.path
.abspath(me
)),
286 "tf_inherit_check.py")
288 retval
= os
.spawnl(os
.P_WAIT
, sys
.executable
,
289 sys
.executable
, tester
, v
, fd
)
290 self
.failIf(retval
< 0,
291 "child process caught fatal signal %d" % -retval
)
292 self
.failIf(retval
> 0, "child process reports failure")
294 def test_textmode(self
):
295 # _mkstemp_inner can create files in text mode
297 return # ugh, can't use TestSkipped.
299 self
.do_create(bin
=0).write("blat\n")
300 # XXX should test that the file really is a text file
302 test_classes
.append(test__mkstemp_inner
)
305 class test_gettempprefix(TC
):
306 """Test gettempprefix()."""
308 def test_sane_template(self
):
309 # gettempprefix returns a nonempty prefix string
310 p
= tempfile
.gettempprefix()
312 self
.assert_(isinstance(p
, basestring
))
313 self
.assert_(len(p
) > 0)
315 def test_usable_template(self
):
316 # gettempprefix returns a usable prefix string
318 # Create a temp directory, avoiding use of the prefix.
319 # Then attempt to create a file whose name is
320 # prefix + 'xxxxxx.xxx' in that directory.
321 p
= tempfile
.gettempprefix() + "xxxxxx.xxx"
322 d
= tempfile
.mkdtemp(prefix
="")
324 p
= os
.path
.join(d
, p
)
326 fd
= os
.open(p
, os
.O_RDWR | os
.O_CREAT
)
328 self
.failOnException("os.open")
334 test_classes
.append(test_gettempprefix
)
337 class test_gettempdir(TC
):
338 """Test gettempdir()."""
340 def test_directory_exists(self
):
341 # gettempdir returns a directory which exists
343 dir = tempfile
.gettempdir()
344 self
.assert_(os
.path
.isabs(dir) or dir == os
.curdir
,
345 "%s is not an absolute path" % dir)
346 self
.assert_(os
.path
.isdir(dir),
347 "%s is not a directory" % dir)
349 def test_directory_writable(self
):
350 # gettempdir returns a directory writable by the user
352 # sneaky: just instantiate a NamedTemporaryFile, which
353 # defaults to writing into the directory returned by
356 file = tempfile
.NamedTemporaryFile()
360 self
.failOnException("create file in %s" % tempfile
.gettempdir())
362 def test_same_thing(self
):
363 # gettempdir always returns the same object
364 a
= tempfile
.gettempdir()
365 b
= tempfile
.gettempdir()
369 test_classes
.append(test_gettempdir
)
372 class test_mkstemp(TC
):
373 """Test mkstemp()."""
375 def do_create(self
, dir=None, pre
="", suf
="", ):
377 dir = tempfile
.gettempdir()
379 (fd
, name
) = tempfile
.mkstemp(dir=dir, prefix
=pre
, suffix
=suf
)
381 self
.failOnException("mkstemp")
384 self
.nameCheck(name
, dir, pre
, suf
)
389 def test_basic(self
):
390 # mkstemp can create files
392 self
.do_create(pre
="a")
393 self
.do_create(suf
="b")
394 self
.do_create(pre
="a", suf
="b")
395 self
.do_create(pre
="aa", suf
=".txt")
397 def test_choose_directory(self
):
398 # mkstemp can create directories in a user-selected directory
399 dir = tempfile
.mkdtemp()
401 self
.do_create(dir=dir)
405 test_classes
.append(test_mkstemp
)
408 class test_mkdtemp(TC
):
409 """Test mkdtemp()."""
411 def do_create(self
, dir=None, pre
="", suf
=""):
413 dir = tempfile
.gettempdir()
415 name
= tempfile
.mkdtemp(dir=dir, prefix
=pre
, suffix
=suf
)
417 self
.failOnException("mkdtemp")
420 self
.nameCheck(name
, dir, pre
, suf
)
426 def test_basic(self
):
427 # mkdtemp can create directories
428 os
.rmdir(self
.do_create())
429 os
.rmdir(self
.do_create(pre
="a"))
430 os
.rmdir(self
.do_create(suf
="b"))
431 os
.rmdir(self
.do_create(pre
="a", suf
="b"))
432 os
.rmdir(self
.do_create(pre
="aa", suf
=".txt"))
434 def test_basic_many(self
):
435 # mkdtemp can create many directories (stochastic)
436 extant
= range(TEST_FILES
)
439 extant
[i
] = self
.do_create(pre
="aa")
442 if(isinstance(i
, basestring
)):
445 def test_choose_directory(self
):
446 # mkdtemp can create directories in a user-selected directory
447 dir = tempfile
.mkdtemp()
449 os
.rmdir(self
.do_create(dir=dir))
454 # mkdtemp creates directories with the proper mode
456 return # ugh, can't use TestSkipped.
458 dir = self
.do_create()
460 mode
= stat
.S_IMODE(os
.stat(dir).st_mode
)
462 if sys
.platform
in ('win32', 'os2emx'):
463 # There's no distinction among 'user', 'group' and 'world';
464 # replicate the 'user' bits.
466 expected
= user
* (1 + 8 + 64)
467 self
.assertEqual(mode
, expected
)
471 test_classes
.append(test_mkdtemp
)
474 class test_mktemp(TC
):
477 # For safety, all use of mktemp must occur in a private directory.
478 # We must also suppress the RuntimeWarning it generates.
480 self
.dir = tempfile
.mkdtemp()
481 warnings
.filterwarnings("ignore",
482 category
=RuntimeWarning,
489 # XXX This clobbers any -W options.
490 warnings
.resetwarnings()
494 _bflags
= tempfile
._bin
_openflags
496 def __init__(self
, dir, pre
, suf
):
497 self
.name
= tempfile
.mktemp(dir=dir, prefix
=pre
, suffix
=suf
)
498 # Create the file. This will raise an exception if it's
499 # mysteriously appeared in the meanwhile.
500 os
.close(os
.open(self
.name
, self
._bflags
, 0600))
503 self
._unlink
(self
.name
)
505 def do_create(self
, pre
="", suf
=""):
507 file = self
.mktemped(self
.dir, pre
, suf
)
509 self
.failOnException("mktemp")
511 self
.nameCheck(file.name
, self
.dir, pre
, suf
)
514 def test_basic(self
):
515 # mktemp can choose usable file names
517 self
.do_create(pre
="a")
518 self
.do_create(suf
="b")
519 self
.do_create(pre
="a", suf
="b")
520 self
.do_create(pre
="aa", suf
=".txt")
523 # mktemp can choose many usable file names (stochastic)
524 extant
= range(TEST_FILES
)
526 extant
[i
] = self
.do_create(pre
="aa")
528 def test_warning(self
):
529 # mktemp issues a warning when used
530 warnings
.filterwarnings("error",
531 category
=RuntimeWarning,
533 self
.assertRaises(RuntimeWarning,
534 tempfile
.mktemp
, (), { 'dir': self
.dir })
536 test_classes
.append(test_mktemp
)
539 # We test _TemporaryFileWrapper by testing NamedTemporaryFile.
542 class test_NamedTemporaryFile(TC
):
543 """Test NamedTemporaryFile()."""
545 def do_create(self
, dir=None, pre
="", suf
=""):
547 dir = tempfile
.gettempdir()
549 file = tempfile
.NamedTemporaryFile(dir=dir, prefix
=pre
, suffix
=suf
)
551 self
.failOnException("NamedTemporaryFile")
553 self
.nameCheck(file.name
, dir, pre
, suf
)
557 def test_basic(self
):
558 # NamedTemporaryFile can create files
560 self
.do_create(pre
="a")
561 self
.do_create(suf
="b")
562 self
.do_create(pre
="a", suf
="b")
563 self
.do_create(pre
="aa", suf
=".txt")
565 def test_creates_named(self
):
566 # NamedTemporaryFile creates files with names
567 f
= tempfile
.NamedTemporaryFile()
568 self
.failUnless(os
.path
.exists(f
.name
),
569 "NamedTemporaryFile %s does not exist" % f
.name
)
571 def test_del_on_close(self
):
572 # A NamedTemporaryFile is deleted when closed
573 dir = tempfile
.mkdtemp()
575 f
= tempfile
.NamedTemporaryFile(dir=dir)
578 self
.failIf(os
.path
.exists(f
.name
),
579 "NamedTemporaryFile %s exists after close" % f
.name
)
583 def test_multiple_close(self
):
584 # A NamedTemporaryFile can be closed many times without error
586 f
= tempfile
.NamedTemporaryFile()
593 self
.failOnException("close")
595 # How to test the mode and bufsize parameters?
597 test_classes
.append(test_NamedTemporaryFile
)
600 class test_TemporaryFile(TC
):
601 """Test TemporaryFile()."""
603 def test_basic(self
):
604 # TemporaryFile can create files
605 # No point in testing the name params - the file has no name.
607 tempfile
.TemporaryFile()
609 self
.failOnException("TemporaryFile")
611 def test_has_no_name(self
):
612 # TemporaryFile creates files with no names (on this system)
613 dir = tempfile
.mkdtemp()
614 f
= tempfile
.TemporaryFile(dir=dir)
617 # Sneaky: because this file has no name, it should not prevent
618 # us from removing the directory it was created in.
626 self
.failOnException("rmdir", ei
)
628 def test_multiple_close(self
):
629 # A TemporaryFile can be closed many times without error
630 f
= tempfile
.TemporaryFile()
637 self
.failOnException("close")
639 # How to test the mode and bufsize parameters?
642 if tempfile
.NamedTemporaryFile
is not tempfile
.TemporaryFile
:
643 test_classes
.append(test_TemporaryFile
)
646 suite
= unittest
.TestSuite()
647 for c
in test_classes
:
648 suite
.addTest(unittest
.makeSuite(c
))
649 test_support
.run_suite(suite
)
651 if __name__
== "__main__":