@@ -1312,13 +1312,17 @@ def __exit__(self, *exc_info):
13121312 d .clear ()
13131313 d .update (c )
13141314
1315+
13151316class TestTemporaryDirectory (BaseTestCase ):
13161317 """Test TemporaryDirectory()."""
13171318
1318- def do_create (self , dir = None , pre = "" , suf = "" , recurse = 1 ):
1319+ def do_create (self , dir = None , pre = "" , suf = "" , recurse = 1 , dirs = 1 , files = 1 ,
1320+ ignore_cleanup_errors = False ):
13191321 if dir is None :
13201322 dir = tempfile .gettempdir ()
1321- tmp = tempfile .TemporaryDirectory (dir = dir , prefix = pre , suffix = suf )
1323+ tmp = tempfile .TemporaryDirectory (
1324+ dir = dir , prefix = pre , suffix = suf ,
1325+ ignore_cleanup_errors = ignore_cleanup_errors )
13221326 self .nameCheck (tmp .name , dir , pre , suf )
13231327 # Create a subdirectory and some files
13241328 if recurse :
@@ -1351,7 +1355,31 @@ def test_explicit_cleanup(self):
13511355 finally :
13521356 os .rmdir (dir )
13531357
1354- @support .skip_unless_symlink
1358+ def test_explict_cleanup_ignore_errors (self ):
1359+ """Test that cleanup doesn't return an error when ignoring them."""
1360+ with tempfile .TemporaryDirectory () as working_dir :
1361+ temp_dir = self .do_create (
1362+ dir = working_dir , ignore_cleanup_errors = True )
1363+ temp_path = pathlib .Path (temp_dir .name )
1364+ self .assertTrue (temp_path .exists (),
1365+ f"TemporaryDirectory { temp_path !s} does not exist" )
1366+ with open (temp_path / "a_file.txt" , "w+t" ) as open_file :
1367+ open_file .write ("Hello world!\n " )
1368+ temp_dir .cleanup ()
1369+ self .assertEqual (len (list (temp_path .glob ("*" ))),
1370+ int (sys .platform .startswith ("win" )),
1371+ "Unexpected number of files in "
1372+ f"TemporaryDirectory { temp_path !s} " )
1373+ self .assertEqual (
1374+ temp_path .exists (),
1375+ sys .platform .startswith ("win" ),
1376+ f"TemporaryDirectory { temp_path !s} existance state unexpected" )
1377+ temp_dir .cleanup ()
1378+ self .assertFalse (
1379+ temp_path .exists (),
1380+ f"TemporaryDirectory { temp_path !s} exists after cleanup" )
1381+
1382+ @os_helper .skip_unless_symlink
13551383 def test_cleanup_with_symlink_to_a_directory (self ):
13561384 # cleanup() should not follow symlinks to directories (issue #12464)
13571385 d1 = self .do_create ()
@@ -1385,6 +1413,27 @@ def test_del_on_collection(self):
13851413 finally :
13861414 os .rmdir (dir )
13871415
1416+ @support .cpython_only
1417+ def test_del_on_collection_ignore_errors (self ):
1418+ """Test that ignoring errors works when TemporaryDirectory is gced."""
1419+ with tempfile .TemporaryDirectory () as working_dir :
1420+ temp_dir = self .do_create (
1421+ dir = working_dir , ignore_cleanup_errors = True )
1422+ temp_path = pathlib .Path (temp_dir .name )
1423+ self .assertTrue (temp_path .exists (),
1424+ f"TemporaryDirectory { temp_path !s} does not exist" )
1425+ with open (temp_path / "a_file.txt" , "w+t" ) as open_file :
1426+ open_file .write ("Hello world!\n " )
1427+ del temp_dir
1428+ self .assertEqual (len (list (temp_path .glob ("*" ))),
1429+ int (sys .platform .startswith ("win" )),
1430+ "Unexpected number of files in "
1431+ f"TemporaryDirectory { temp_path !s} " )
1432+ self .assertEqual (
1433+ temp_path .exists (),
1434+ sys .platform .startswith ("win" ),
1435+ f"TemporaryDirectory { temp_path !s} existance state unexpected" )
1436+
13881437 def test_del_on_shutdown (self ):
13891438 # A TemporaryDirectory may be cleaned up during shutdown
13901439 with self .do_create () as dir :
@@ -1417,6 +1466,43 @@ def test_del_on_shutdown(self):
14171466 self .assertNotIn ("Exception " , err )
14181467 self .assertIn ("ResourceWarning: Implicitly cleaning up" , err )
14191468
1469+ def test_del_on_shutdown_ignore_errors (self ):
1470+ """Test ignoring errors works when a tempdir is gc'ed on shutdown."""
1471+ with tempfile .TemporaryDirectory () as working_dir :
1472+ code = """if True:
1473+ import pathlib
1474+ import sys
1475+ import tempfile
1476+ import warnings
1477+
1478+ temp_dir = tempfile.TemporaryDirectory(
1479+ dir={working_dir!r}, ignore_cleanup_errors=True)
1480+ sys.stdout.buffer.write(temp_dir.name.encode())
1481+
1482+ temp_dir_2 = pathlib.Path(temp_dir.name) / "test_dir"
1483+ temp_dir_2.mkdir()
1484+ with open(temp_dir_2 / "test0.txt", "w") as test_file:
1485+ test_file.write("Hello world!")
1486+ open_file = open(temp_dir_2 / "open_file.txt", "w")
1487+ open_file.write("Hello world!")
1488+
1489+ warnings.filterwarnings("always", category=ResourceWarning)
1490+ """ .format (working_dir = working_dir )
1491+ __ , out , err = script_helper .assert_python_ok ("-c" , code )
1492+ temp_path = pathlib .Path (out .decode ().strip ())
1493+ self .assertEqual (len (list (temp_path .glob ("*" ))),
1494+ int (sys .platform .startswith ("win" )),
1495+ "Unexpected number of files in "
1496+ f"TemporaryDirectory { temp_path !s} " )
1497+ self .assertEqual (
1498+ temp_path .exists (),
1499+ sys .platform .startswith ("win" ),
1500+ f"TemporaryDirectory { temp_path !s} existance state unexpected" )
1501+ err = err .decode ('utf-8' , 'backslashreplace' )
1502+ self .assertNotIn ("Exception" , err )
1503+ self .assertNotIn ("Error" , err )
1504+ self .assertIn ("ResourceWarning: Implicitly cleaning up" , err )
1505+
14201506 def test_exit_on_shutdown (self ):
14211507 # Issue #22427
14221508 with self .do_create () as dir :
0 commit comments