1 # tempfile.py unit tests.
11 from test
import test_support
13 warnings
.filterwarnings("ignore",
14 category
=RuntimeWarning,
15 message
="mktemp", module
=__name__
)
17 if hasattr(os
, 'stat'):
23 has_textmode
= (tempfile
._text
_openflags
!= tempfile
._bin
_openflags
)
24 has_spawnl
= hasattr(os
, 'spawnl')
26 # TEST_FILES may need to be tweaked for systems depending on the maximum
27 # number of files that can be opened at one time (see ulimit -n)
28 if sys
.platform
== 'mac':
33 # This is organized as one test for each chunk of code in tempfile.py,
34 # in order of their appearance in the file. Testing which requires
35 # threads is not done here.
37 # Common functionality.
38 class TC(unittest
.TestCase
):
40 str_check
= re
.compile(r
"[a-zA-Z0-9_-]{6}$")
42 def failOnException(self
, what
, ei
=None):
45 self
.fail("%s raised %s: %s" % (what
, ei
[0], ei
[1]))
47 def nameCheck(self
, name
, dir, pre
, suf
):
48 (ndir
, nbase
) = os
.path
.split(name
)
49 npre
= nbase
[:len(pre
)]
50 nsuf
= nbase
[len(nbase
)-len(suf
):]
52 self
.assertEqual(ndir
, dir,
53 "file '%s' not in directory '%s'" % (name
, dir))
54 self
.assertEqual(npre
, pre
,
55 "file '%s' does not begin with '%s'" % (nbase
, pre
))
56 self
.assertEqual(nsuf
, suf
,
57 "file '%s' does not end with '%s'" % (nbase
, suf
))
59 nbase
= nbase
[len(pre
):len(nbase
)-len(suf
)]
60 self
.assert_(self
.str_check
.match(nbase
),
61 "random string '%s' does not match /^[a-zA-Z0-9_-]{6}$/"
66 class test_exports(TC
):
67 def test_exports(self
):
68 # There are no surprising symbols in the tempfile module
69 dict = tempfile
.__dict
__
72 "NamedTemporaryFile" : 1,
86 if key
[0] != '_' and key
not in expected
:
88 self
.failUnless(len(unexp
) == 0,
89 "unexpected keys: %s" % unexp
)
91 test_classes
.append(test_exports
)
94 class test__RandomNameSequence(TC
):
95 """Test the internal iterator object _RandomNameSequence."""
98 self
.r
= tempfile
._RandomNameSequence
()
100 def test_get_six_char_str(self
):
101 # _RandomNameSequence returns a six-character string
103 self
.nameCheck(s
, '', '', '')
106 # _RandomNameSequence returns no duplicate strings (stochastic)
110 for i
in xrange(TEST_FILES
):
112 self
.nameCheck(s
, '', '', '')
113 self
.failIf(s
in dict)
116 def test_supports_iter(self
):
117 # _RandomNameSequence supports the iterator protocol
127 failOnException("iteration")
129 test_classes
.append(test__RandomNameSequence
)
132 class test__candidate_tempdir_list(TC
):
133 """Test the internal function _candidate_tempdir_list."""
135 def test_nonempty_list(self
):
136 # _candidate_tempdir_list returns a nonempty list of strings
138 cand
= tempfile
._candidate
_tempdir
_list
()
140 self
.failIf(len(cand
) == 0)
142 self
.assert_(isinstance(c
, basestring
),
143 "%s is not a string" % c
)
145 def test_wanted_dirs(self
):
146 # _candidate_tempdir_list contains the expected directories
148 # Make sure the interesting environment variables are all set.
151 for envname
in 'TMPDIR', 'TEMP', 'TMP':
152 dirname
= os
.getenv(envname
)
154 os
.environ
[envname
] = os
.path
.abspath(envname
)
155 added
.append(envname
)
157 cand
= tempfile
._candidate
_tempdir
_list
()
159 for envname
in 'TMPDIR', 'TEMP', 'TMP':
160 dirname
= os
.getenv(envname
)
161 if not dirname
: raise ValueError
162 self
.assert_(dirname
in cand
)
165 dirname
= os
.getcwd()
166 except (AttributeError, os
.error
):
169 self
.assert_(dirname
in cand
)
171 # Not practical to try to verify the presence of OS-specific
172 # paths in this list.
177 test_classes
.append(test__candidate_tempdir_list
)
180 # We test _get_default_tempdir by testing gettempdir.
183 class test__get_candidate_names(TC
):
184 """Test the internal function _get_candidate_names."""
186 def test_retval(self
):
187 # _get_candidate_names returns a _RandomNameSequence object
188 obj
= tempfile
._get
_candidate
_names
()
189 self
.assert_(isinstance(obj
, tempfile
._RandomNameSequence
))
191 def test_same_thing(self
):
192 # _get_candidate_names always returns the same object
193 a
= tempfile
._get
_candidate
_names
()
194 b
= tempfile
._get
_candidate
_names
()
198 test_classes
.append(test__get_candidate_names
)
201 class test__mkstemp_inner(TC
):
202 """Test the internal function _mkstemp_inner."""
205 _bflags
= tempfile
._bin
_openflags
206 _tflags
= tempfile
._text
_openflags
210 def __init__(self
, dir, pre
, suf
, bin
):
211 if bin
: flags
= self
._bflags
212 else: flags
= self
._tflags
214 (self
.fd
, self
.name
) = tempfile
._mkstemp
_inner
(dir, pre
, suf
, flags
)
216 def write(self
, str):
217 os
.write(self
.fd
, str)
221 self
._unlink
(self
.name
)
223 def do_create(self
, dir=None, pre
="", suf
="", bin
=1):
225 dir = tempfile
.gettempdir()
227 file = self
.mkstemped(dir, pre
, suf
, bin
)
229 self
.failOnException("_mkstemp_inner")
231 self
.nameCheck(file.name
, dir, pre
, suf
)
234 def test_basic(self
):
235 # _mkstemp_inner can create files
236 self
.do_create().write("blat")
237 self
.do_create(pre
="a").write("blat")
238 self
.do_create(suf
="b").write("blat")
239 self
.do_create(pre
="a", suf
="b").write("blat")
240 self
.do_create(pre
="aa", suf
=".txt").write("blat")
242 def test_basic_many(self
):
243 # _mkstemp_inner can create many files (stochastic)
244 extant
= range(TEST_FILES
)
246 extant
[i
] = self
.do_create(pre
="aa")
248 def test_choose_directory(self
):
249 # _mkstemp_inner can create files in a user-selected directory
250 dir = tempfile
.mkdtemp()
252 self
.do_create(dir=dir).write("blat")
256 def test_file_mode(self
):
257 # _mkstemp_inner creates files with the proper mode
259 return # ugh, can't use TestSkipped.
261 file = self
.do_create()
262 mode
= stat
.S_IMODE(os
.stat(file.name
).st_mode
)
264 if sys
.platform
in ('win32', 'os2emx', 'mac'):
265 # There's no distinction among 'user', 'group' and 'world';
266 # replicate the 'user' bits.
268 expected
= user
* (1 + 8 + 64)
269 self
.assertEqual(mode
, expected
)
271 def test_noinherit(self
):
272 # _mkstemp_inner file handles are not inherited by child processes
274 return # ugh, can't use TestSkipped.
276 if test_support
.verbose
:
281 file = self
.do_create()
289 # We have to exec something, so that FD_CLOEXEC will take
290 # effect. The core of this test is therefore in
291 # tf_inherit_check.py, which see.
292 tester
= os
.path
.join(os
.path
.dirname(os
.path
.abspath(me
)),
293 "tf_inherit_check.py")
295 retval
= os
.spawnl(os
.P_WAIT
, sys
.executable
,
296 sys
.executable
, tester
, v
, fd
)
297 self
.failIf(retval
< 0,
298 "child process caught fatal signal %d" % -retval
)
299 self
.failIf(retval
> 0, "child process reports failure")
301 def test_textmode(self
):
302 # _mkstemp_inner can create files in text mode
304 return # ugh, can't use TestSkipped.
306 self
.do_create(bin
=0).write("blat\n")
307 # XXX should test that the file really is a text file
309 test_classes
.append(test__mkstemp_inner
)
312 class test_gettempprefix(TC
):
313 """Test gettempprefix()."""
315 def test_sane_template(self
):
316 # gettempprefix returns a nonempty prefix string
317 p
= tempfile
.gettempprefix()
319 self
.assert_(isinstance(p
, basestring
))
320 self
.assert_(len(p
) > 0)
322 def test_usable_template(self
):
323 # gettempprefix returns a usable prefix string
325 # Create a temp directory, avoiding use of the prefix.
326 # Then attempt to create a file whose name is
327 # prefix + 'xxxxxx.xxx' in that directory.
328 p
= tempfile
.gettempprefix() + "xxxxxx.xxx"
329 d
= tempfile
.mkdtemp(prefix
="")
331 p
= os
.path
.join(d
, p
)
333 fd
= os
.open(p
, os
.O_RDWR | os
.O_CREAT
)
335 self
.failOnException("os.open")
341 test_classes
.append(test_gettempprefix
)
344 class test_gettempdir(TC
):
345 """Test gettempdir()."""
347 def test_directory_exists(self
):
348 # gettempdir returns a directory which exists
350 dir = tempfile
.gettempdir()
351 self
.assert_(os
.path
.isabs(dir) or dir == os
.curdir
,
352 "%s is not an absolute path" % dir)
353 self
.assert_(os
.path
.isdir(dir),
354 "%s is not a directory" % dir)
356 def test_directory_writable(self
):
357 # gettempdir returns a directory writable by the user
359 # sneaky: just instantiate a NamedTemporaryFile, which
360 # defaults to writing into the directory returned by
363 file = tempfile
.NamedTemporaryFile()
367 self
.failOnException("create file in %s" % tempfile
.gettempdir())
369 def test_same_thing(self
):
370 # gettempdir always returns the same object
371 a
= tempfile
.gettempdir()
372 b
= tempfile
.gettempdir()
376 test_classes
.append(test_gettempdir
)
379 class test_mkstemp(TC
):
380 """Test mkstemp()."""
382 def do_create(self
, dir=None, pre
="", suf
="", ):
384 dir = tempfile
.gettempdir()
386 (fd
, name
) = tempfile
.mkstemp(dir=dir, prefix
=pre
, suffix
=suf
)
388 self
.failOnException("mkstemp")
391 self
.nameCheck(name
, dir, pre
, suf
)
396 def test_basic(self
):
397 # mkstemp can create files
399 self
.do_create(pre
="a")
400 self
.do_create(suf
="b")
401 self
.do_create(pre
="a", suf
="b")
402 self
.do_create(pre
="aa", suf
=".txt")
404 def test_choose_directory(self
):
405 # mkstemp can create directories in a user-selected directory
406 dir = tempfile
.mkdtemp()
408 self
.do_create(dir=dir)
412 test_classes
.append(test_mkstemp
)
415 class test_mkdtemp(TC
):
416 """Test mkdtemp()."""
418 def do_create(self
, dir=None, pre
="", suf
=""):
420 dir = tempfile
.gettempdir()
422 name
= tempfile
.mkdtemp(dir=dir, prefix
=pre
, suffix
=suf
)
424 self
.failOnException("mkdtemp")
427 self
.nameCheck(name
, dir, pre
, suf
)
433 def test_basic(self
):
434 # mkdtemp can create directories
435 os
.rmdir(self
.do_create())
436 os
.rmdir(self
.do_create(pre
="a"))
437 os
.rmdir(self
.do_create(suf
="b"))
438 os
.rmdir(self
.do_create(pre
="a", suf
="b"))
439 os
.rmdir(self
.do_create(pre
="aa", suf
=".txt"))
441 def test_basic_many(self
):
442 # mkdtemp can create many directories (stochastic)
443 extant
= range(TEST_FILES
)
446 extant
[i
] = self
.do_create(pre
="aa")
449 if(isinstance(i
, basestring
)):
452 def test_choose_directory(self
):
453 # mkdtemp can create directories in a user-selected directory
454 dir = tempfile
.mkdtemp()
456 os
.rmdir(self
.do_create(dir=dir))
461 # mkdtemp creates directories with the proper mode
463 return # ugh, can't use TestSkipped.
465 dir = self
.do_create()
467 mode
= stat
.S_IMODE(os
.stat(dir).st_mode
)
469 if sys
.platform
in ('win32', 'os2emx', 'mac'):
470 # There's no distinction among 'user', 'group' and 'world';
471 # replicate the 'user' bits.
473 expected
= user
* (1 + 8 + 64)
474 self
.assertEqual(mode
, expected
)
478 test_classes
.append(test_mkdtemp
)
481 class test_mktemp(TC
):
484 # For safety, all use of mktemp must occur in a private directory.
485 # We must also suppress the RuntimeWarning it generates.
487 self
.dir = tempfile
.mkdtemp()
496 _bflags
= tempfile
._bin
_openflags
498 def __init__(self
, dir, pre
, suf
):
499 self
.name
= tempfile
.mktemp(dir=dir, prefix
=pre
, suffix
=suf
)
500 # Create the file. This will raise an exception if it's
501 # mysteriously appeared in the meanwhile.
502 os
.close(os
.open(self
.name
, self
._bflags
, 0600))
505 self
._unlink
(self
.name
)
507 def do_create(self
, pre
="", suf
=""):
509 file = self
.mktemped(self
.dir, pre
, suf
)
511 self
.failOnException("mktemp")
513 self
.nameCheck(file.name
, self
.dir, pre
, suf
)
516 def test_basic(self
):
517 # mktemp can choose usable file names
519 self
.do_create(pre
="a")
520 self
.do_create(suf
="b")
521 self
.do_create(pre
="a", suf
="b")
522 self
.do_create(pre
="aa", suf
=".txt")
525 # mktemp can choose many usable file names (stochastic)
526 extant
= range(TEST_FILES
)
528 extant
[i
] = self
.do_create(pre
="aa")
530 ## def test_warning(self):
531 ## # mktemp issues a warning when used
532 ## warnings.filterwarnings("error",
533 ## category=RuntimeWarning,
535 ## self.assertRaises(RuntimeWarning,
536 ## tempfile.mktemp, dir=self.dir)
538 test_classes
.append(test_mktemp
)
541 # We test _TemporaryFileWrapper by testing NamedTemporaryFile.
544 class test_NamedTemporaryFile(TC
):
545 """Test NamedTemporaryFile()."""
547 def do_create(self
, dir=None, pre
="", suf
=""):
549 dir = tempfile
.gettempdir()
551 file = tempfile
.NamedTemporaryFile(dir=dir, prefix
=pre
, suffix
=suf
)
553 self
.failOnException("NamedTemporaryFile")
555 self
.nameCheck(file.name
, dir, pre
, suf
)
559 def test_basic(self
):
560 # NamedTemporaryFile can create files
562 self
.do_create(pre
="a")
563 self
.do_create(suf
="b")
564 self
.do_create(pre
="a", suf
="b")
565 self
.do_create(pre
="aa", suf
=".txt")
567 def test_creates_named(self
):
568 # NamedTemporaryFile creates files with names
569 f
= tempfile
.NamedTemporaryFile()
570 self
.failUnless(os
.path
.exists(f
.name
),
571 "NamedTemporaryFile %s does not exist" % f
.name
)
573 def test_del_on_close(self
):
574 # A NamedTemporaryFile is deleted when closed
575 dir = tempfile
.mkdtemp()
577 f
= tempfile
.NamedTemporaryFile(dir=dir)
580 self
.failIf(os
.path
.exists(f
.name
),
581 "NamedTemporaryFile %s exists after close" % f
.name
)
585 def test_multiple_close(self
):
586 # A NamedTemporaryFile can be closed many times without error
588 f
= tempfile
.NamedTemporaryFile()
595 self
.failOnException("close")
597 # How to test the mode and bufsize parameters?
599 test_classes
.append(test_NamedTemporaryFile
)
602 class test_TemporaryFile(TC
):
603 """Test TemporaryFile()."""
605 def test_basic(self
):
606 # TemporaryFile can create files
607 # No point in testing the name params - the file has no name.
609 tempfile
.TemporaryFile()
611 self
.failOnException("TemporaryFile")
613 def test_has_no_name(self
):
614 # TemporaryFile creates files with no names (on this system)
615 dir = tempfile
.mkdtemp()
616 f
= tempfile
.TemporaryFile(dir=dir)
619 # Sneaky: because this file has no name, it should not prevent
620 # us from removing the directory it was created in.
628 self
.failOnException("rmdir", ei
)
630 def test_multiple_close(self
):
631 # A TemporaryFile can be closed many times without error
632 f
= tempfile
.TemporaryFile()
639 self
.failOnException("close")
641 # How to test the mode and bufsize parameters?
644 if tempfile
.NamedTemporaryFile
is not tempfile
.TemporaryFile
:
645 test_classes
.append(test_TemporaryFile
)
648 suite
= unittest
.TestSuite()
649 for c
in test_classes
:
650 suite
.addTest(unittest
.makeSuite(c
))
651 test_support
.run_suite(suite
)
653 if __name__
== "__main__":