@@ -1623,10 +1623,14 @@ def __exit__(self, *exc_info):
16231623class TestTemporaryDirectory (BaseTestCase ):
16241624 """Test TemporaryDirectory()."""
16251625
1626- def do_create (self , dir = None , pre = "" , suf = "" , recurse = 1 , dirs = 1 , files = 1 ,
1626+ def do_create (self , dir = None , pre = None , suf = None , recurse = 1 , dirs = 1 , files = 1 ,
16271627 ignore_cleanup_errors = False ):
16281628 if dir is None :
16291629 dir = tempfile .gettempdir ()
1630+ if pre is None :
1631+ pre = type (dir )()
1632+ if suf is None :
1633+ suf = type (dir )()
16301634 tmp = tempfile .TemporaryDirectory (
16311635 dir = dir , prefix = pre , suffix = suf ,
16321636 ignore_cleanup_errors = ignore_cleanup_errors )
@@ -1636,13 +1640,17 @@ def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
16361640
16371641 def do_create2 (self , path , recurse = 1 , dirs = 1 , files = 1 ):
16381642 # Create subdirectories and some files
1643+ def join (name ):
1644+ if isinstance (path , bytes ):
1645+ name = os .fsencode (name )
1646+ return os .path .join (path , name )
16391647 if recurse :
16401648 for i in range (dirs ):
1641- name = os . path . join (path , "dir%d" % i )
1649+ name = join ("dir%d" % i )
16421650 os .mkdir (name )
16431651 self .do_create2 (name , recurse - 1 , dirs , files )
16441652 for i in range (files ):
1645- with open (os . path . join (path , "test%d.txt" % i ), "wb" ) as f :
1653+ with open (join ("test%d.txt" % i ), "wb" ) as f :
16461654 f .write (b"Hello world!" )
16471655
16481656 def test_mkdtemp_failure (self ):
@@ -1668,6 +1676,15 @@ def test_explicit_cleanup(self):
16681676 finally :
16691677 os .rmdir (dir )
16701678
1679+ def test_explicit_cleanup_bytes (self ):
1680+ # A TemporaryDirectory with a bytes name is deleted when cleaned up
1681+ with tempfile .TemporaryDirectory () as working_dir :
1682+ d = self .do_create (dir = os .fsencode (working_dir ), recurse = 2 )
1683+ self .assertIsInstance (d .name , bytes )
1684+ self .assertTrue (os .path .exists (d .name ))
1685+ d .cleanup ()
1686+ self .assertFalse (os .path .exists (d .name ))
1687+
16711688 def test_explicit_cleanup_ignore_errors (self ):
16721689 """Test that cleanup doesn't return an error when ignoring them."""
16731690 with tempfile .TemporaryDirectory () as working_dir :
@@ -1880,6 +1897,87 @@ def hook(path, *, dir_fd=None):
18801897 self .assertTrue (os .path .exists (target_file ))
18811898 self .assertEqual (os .stat (target_file ).st_mode , target_mode )
18821899
1900+ def _make_unopenable_subdir (self ):
1901+ # Create the following structure:
1902+ # work/ - top-level
1903+ # <d>/ - tempdir to clean up (random name)
1904+ # sub/ - an unopenable dir
1905+ # subsub/
1906+ # file
1907+ # Return:
1908+ # - `work` name (str)
1909+ # - `d` (TemporaryDirectory)
1910+ # - `subsub` stat result
1911+ work = self .enterContext (os_helper .temp_dir ())
1912+ d = tempfile .TemporaryDirectory (dir = work )
1913+ sub = os .path .join (d .name , 'sub' )
1914+ subsub = os .path .join (sub , 'subsub' )
1915+ os .mkdir (sub )
1916+ os .mkdir (subsub )
1917+ subsub_stat = os .lstat (subsub )
1918+ with open (os .path .join (subsub , 'file' ), 'w' ) as f :
1919+ f .write ("rm me pls" )
1920+ os .chmod (sub , 0 )
1921+ # If the test fails, make sure everything can still be removed.
1922+ self .addCleanup (d .cleanup )
1923+ @self .addCleanup
1924+ def _clean ():
1925+ if os .path .isdir (sub ):
1926+ os .chmod (sub , 0o700 )
1927+ return work , d , subsub_stat
1928+
1929+ @os_helper .skip_unless_working_chmod
1930+ @support .requires_non_root_user
1931+ @unittest .skipUnless (tempfile ._rmtree_use_dir_fd
1932+ and shutil .rmtree .avoids_symlink_attacks ,
1933+ 'requires the fd based cleanup' )
1934+ def test_cleanup_nested_toplevel_error (self ):
1935+ # rmtree() reports errors relative to the correct parent directory
1936+ work , d , subsub_stat = self ._make_unopenable_subdir ()
1937+ # An unrelated directory with the same name; should not be touched
1938+ unrelated = os .path .join (work , 'sub' )
1939+ os .mkdir (unrelated )
1940+
1941+ rmdir = os .rmdir
1942+ failed_path = None
1943+ def failing_rmdir (path , * , dir_fd = None ):
1944+ nonlocal failed_path
1945+ if path == 'sub' and dir_fd is not None and failed_path is None :
1946+ failed_path = path
1947+ raise PermissionError (errno .EPERM , 'simulated' , path )
1948+ return rmdir (path , dir_fd = dir_fd )
1949+ with os_helper .change_cwd (work ), mock .patch ('os.rmdir' , failing_rmdir ):
1950+ d .cleanup ()
1951+ self .assertEqual (failed_path , 'sub' )
1952+ self .assertFalse (os .path .exists (d .name ))
1953+ self .assertTrue (os .path .exists (unrelated ))
1954+
1955+ @os_helper .skip_unless_working_chmod
1956+ @support .requires_non_root_user
1957+ @unittest .skipUnless (tempfile ._rmtree_use_dir_fd
1958+ and shutil .rmtree .avoids_symlink_attacks ,
1959+ 'requires the fd based cleanup' )
1960+ def test_cleanup_nested_scandir_error (self ):
1961+ # A scandir() error is reported relative to the parent directory.
1962+ work , d , subsub_stat = self ._make_unopenable_subdir ()
1963+
1964+ scandir = os .scandir
1965+ failed = False
1966+ def failing_scandir (path = '.' ):
1967+ nonlocal failed
1968+ if (
1969+ not failed
1970+ and isinstance (path , int )
1971+ and os .path .samestat (os .fstat (path ), subsub_stat )
1972+ ):
1973+ failed = True
1974+ raise PermissionError (errno .EACCES , 'simulated' )
1975+ return scandir (path )
1976+ with os_helper .change_cwd (work ), mock .patch ('os.scandir' , failing_scandir ):
1977+ d .cleanup ()
1978+ self .assertTrue (failed )
1979+ self .assertFalse (os .path .exists (d .name ))
1980+
18831981 @support .cpython_only
18841982 def test_del_on_collection (self ):
18851983 # A TemporaryDirectory is deleted when garbage collected
@@ -2038,11 +2136,17 @@ def test_context_manager(self):
20382136 self .assertEqual (name , d .name )
20392137 self .assertFalse (os .path .exists (name ))
20402138
2041- def test_modes (self ):
2139+ @support .subTests ('bytes_name' , (False , True ))
2140+ def test_modes (self , bytes_name ):
20422141 for mode in range (8 ):
20432142 mode <<= 6
20442143 with self .subTest (mode = format (mode , '03o' )):
2045- d = self .do_create (recurse = 3 , dirs = 2 , files = 2 )
2144+ if bytes_name :
2145+ d = self .do_create (recurse = 3 , dirs = 2 , files = 2 ,
2146+ dir = tempfile .gettempdirb ())
2147+ else :
2148+ d = self .do_create (recurse = 3 , dirs = 2 , files = 2 )
2149+ self .assertIsInstance (d .name , bytes if bytes_name else str )
20462150 with d :
20472151 # Change files and directories mode recursively.
20482152 for root , dirs , files in os .walk (d .name , topdown = False ):
@@ -2053,13 +2157,17 @@ def test_modes(self):
20532157 self .assertFalse (os .path .exists (d .name ))
20542158
20552159 @support .subTests ('ignore_errors' , (True , False ))
2056- def test_parent_mode_preserved (self , ignore_errors ):
2160+ @support .subTests ('bytes_name' , (False , True ))
2161+ def test_parent_mode_preserved (self , ignore_errors , bytes_name ):
20572162 # Test that cleanup does not touch the parent directory,
20582163 # even if that prevents removal.
20592164 for mode in range (8 ):
20602165 mode <<= 6
20612166 with self .subTest (mode = format (mode , '03o' )):
2062- outer = self .do_create ()
2167+ if bytes_name :
2168+ outer = self .do_create (dir = tempfile .gettempdirb ())
2169+ else :
2170+ outer = self .do_create ()
20632171 with outer :
20642172 d = self .do_create (dir = outer .name , dirs = 2 , files = 2 ,
20652173 ignore_cleanup_errors = ignore_errors )
0 commit comments