diff -r 6e2e5adc0400 Lib/tempfile.py --- a/Lib/tempfile.py Thu Dec 27 18:53:12 2012 -0800 +++ b/Lib/tempfile.py Fri Dec 28 07:37:16 2012 +0200 @@ -171,10 +171,12 @@ filename = _os.path.join(dir, name) try: fd = _os.open(filename, _bin_openflags, 0o600) - fp = _io.open(fd, 'wb') - fp.write(b'blat') - fp.close() - _os.unlink(filename) + try: + fp = _io.open(fd, 'wb') + fp.write(b'blat') + fp.close() + finally: + _os.unlink(filename) del fp, fd return dir except FileExistsError: diff -r 6e2e5adc0400 Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Thu Dec 27 18:53:12 2012 -0800 +++ b/Lib/test/test_tempfile.py Fri Dec 28 07:37:16 2012 +0200 @@ -197,7 +197,35 @@ # paths in this list. -# We test _get_default_tempdir by testing gettempdir. +# We test _get_default_tempdir some more by testing gettempdir. + +class TestGetDefaultTempdir(BaseTestCase): + """Test _get_default_tempdir().""" + + def test_no_files_left_behind(self): + # use a private empty directory + with tempfile.TemporaryDirectory() as our_temp_directory: + + # force _get_default_tempdir() to consider our empty directory + def our_candidate_list(): + return [our_temp_directory] + + with support.swap_attr(tempfile, "_candidate_tempdir_list", our_candidate_list): + + # verify our directory is empty after _get_default_tempdir() + tempfile._get_default_tempdir() + self.assertEqual(os.listdir(our_temp_directory), []) + + # make io.open() fail + import io + def raise_OSError(*args, **kwargs): + raise OSError() + + with support.swap_attr(io, "open", raise_OSError): + + # test again with failing io.open() + self.assertRaises(OSError, tempfile._get_default_tempdir) + self.assertEqual(os.listdir(our_temp_directory), []) class TestGetCandidateNames(BaseTestCase):