@@ -1646,10 +1646,14 @@ def __exit__(self, *exc_info):
16461646class TestTemporaryDirectory (BaseTestCase ):
16471647 """Test TemporaryDirectory()."""
16481648
1649- def do_create (self , dir = None , pre = "" , suf = "" , recurse = 1 , dirs = 1 , files = 1 ,
1649+ def do_create (self , dir = None , pre = None , suf = None , recurse = 1 , dirs = 1 , files = 1 ,
16501650 ignore_cleanup_errors = False ):
16511651 if dir is None :
16521652 dir = tempfile .gettempdir ()
1653+ if pre is None :
1654+ pre = type (dir )()
1655+ if suf is None :
1656+ suf = type (dir )()
16531657 tmp = tempfile .TemporaryDirectory (
16541658 dir = dir , prefix = pre , suffix = suf ,
16551659 ignore_cleanup_errors = ignore_cleanup_errors )
@@ -1659,13 +1663,17 @@ def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
16591663
16601664 def do_create2 (self , path , recurse = 1 , dirs = 1 , files = 1 ):
16611665 # Create subdirectories and some files
1666+ def join (name ):
1667+ if isinstance (path , bytes ):
1668+ name = os .fsencode (name )
1669+ return os .path .join (path , name )
16621670 if recurse :
16631671 for i in range (dirs ):
1664- name = os . path . join (path , "dir%d" % i )
1672+ name = join ("dir%d" % i )
16651673 os .mkdir (name )
16661674 self .do_create2 (name , recurse - 1 , dirs , files )
16671675 for i in range (files ):
1668- with open (os . path . join (path , "test%d.txt" % i ), "wb" ) as f :
1676+ with open (join ("test%d.txt" % i ), "wb" ) as f :
16691677 f .write (b"Hello world!" )
16701678
16711679 def test_mkdtemp_failure (self ):
@@ -1691,6 +1699,15 @@ def test_explicit_cleanup(self):
16911699 finally :
16921700 os .rmdir (dir )
16931701
1702+ def test_explicit_cleanup_bytes (self ):
1703+ # A TemporaryDirectory with a bytes name is deleted when cleaned up
1704+ with tempfile .TemporaryDirectory () as working_dir :
1705+ d = self .do_create (dir = os .fsencode (working_dir ), recurse = 2 )
1706+ self .assertIsInstance (d .name , bytes )
1707+ self .assertTrue (os .path .exists (d .name ))
1708+ d .cleanup ()
1709+ self .assertFalse (os .path .exists (d .name ))
1710+
16941711 def test_explicit_cleanup_ignore_errors (self ):
16951712 """Test that cleanup doesn't return an error when ignoring them."""
16961713 with tempfile .TemporaryDirectory () as working_dir :
@@ -1906,6 +1923,87 @@ def hook(path, *, dir_fd=None):
19061923 self .assertTrue (os .path .exists (target_file ))
19071924 self .assertEqual (os .stat (target_file ).st_mode , target_mode )
19081925
1926+ def _make_unopenable_subdir (self ):
1927+ # Create the following structure:
1928+ # work/ - top-level
1929+ # <d>/ - tempdir to clean up (random name)
1930+ # sub/ - an unopenable dir
1931+ # subsub/
1932+ # file
1933+ # Return:
1934+ # - `work` name (str)
1935+ # - `d` (TemporaryDirectory)
1936+ # - `subsub` stat result
1937+ work = self .enterContext (os_helper .temp_dir ())
1938+ d = tempfile .TemporaryDirectory (dir = work )
1939+ sub = os .path .join (d .name , 'sub' )
1940+ subsub = os .path .join (sub , 'subsub' )
1941+ os .mkdir (sub )
1942+ os .mkdir (subsub )
1943+ subsub_stat = os .lstat (subsub )
1944+ with open (os .path .join (subsub , 'file' ), 'w' ) as f :
1945+ f .write ("rm me pls" )
1946+ os .chmod (sub , 0 )
1947+ # If the test fails, make sure everything can still be removed.
1948+ self .addCleanup (d .cleanup )
1949+ @self .addCleanup
1950+ def _clean ():
1951+ if os .path .isdir (sub ):
1952+ os .chmod (sub , 0o700 )
1953+ return work , d , subsub_stat
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_toplevel_error (self ):
1961+ # rmtree() reports errors relative to the correct parent directory
1962+ work , d , subsub_stat = self ._make_unopenable_subdir ()
1963+ # An unrelated directory with the same name; should not be touched
1964+ unrelated = os .path .join (work , 'sub' )
1965+ os .mkdir (unrelated )
1966+
1967+ rmdir = os .rmdir
1968+ failed_path = None
1969+ def failing_rmdir (path , * , dir_fd = None ):
1970+ nonlocal failed_path
1971+ if path == 'sub' and dir_fd is not None and failed_path is None :
1972+ failed_path = path
1973+ raise PermissionError (errno .EPERM , 'simulated' , path )
1974+ return rmdir (path , dir_fd = dir_fd )
1975+ with os_helper .change_cwd (work ), mock .patch ('os.rmdir' , failing_rmdir ):
1976+ d .cleanup ()
1977+ self .assertEqual (failed_path , 'sub' )
1978+ self .assertFalse (os .path .exists (d .name ))
1979+ self .assertTrue (os .path .exists (unrelated ))
1980+
1981+ @os_helper .skip_unless_working_chmod
1982+ @support .requires_non_root_user
1983+ @unittest .skipUnless (tempfile ._rmtree_use_dir_fd
1984+ and shutil .rmtree .avoids_symlink_attacks ,
1985+ 'requires the fd based cleanup' )
1986+ def test_cleanup_nested_scandir_error (self ):
1987+ # A scandir() error is reported relative to the parent directory.
1988+ work , d , subsub_stat = self ._make_unopenable_subdir ()
1989+
1990+ scandir = os .scandir
1991+ failed = False
1992+ def failing_scandir (path = '.' ):
1993+ nonlocal failed
1994+ if (
1995+ not failed
1996+ and isinstance (path , int )
1997+ and os .path .samestat (os .fstat (path ), subsub_stat )
1998+ ):
1999+ failed = True
2000+ raise PermissionError (errno .EACCES , 'simulated' )
2001+ return scandir (path )
2002+ with os_helper .change_cwd (work ), mock .patch ('os.scandir' , failing_scandir ):
2003+ d .cleanup ()
2004+ self .assertTrue (failed )
2005+ self .assertFalse (os .path .exists (d .name ))
2006+
19092007 @support .cpython_only
19102008 def test_del_on_collection (self ):
19112009 # A TemporaryDirectory is deleted when garbage collected
@@ -2064,11 +2162,17 @@ def test_context_manager(self):
20642162 self .assertEqual (name , d .name )
20652163 self .assertFalse (os .path .exists (name ))
20662164
2067- def test_modes (self ):
2165+ @support .subTests ('bytes_name' , (False , True ))
2166+ def test_modes (self , bytes_name ):
20682167 for mode in range (8 ):
20692168 mode <<= 6
20702169 with self .subTest (mode = format (mode , '03o' )):
2071- d = self .do_create (recurse = 3 , dirs = 2 , files = 2 )
2170+ if bytes_name :
2171+ d = self .do_create (recurse = 3 , dirs = 2 , files = 2 ,
2172+ dir = tempfile .gettempdirb ())
2173+ else :
2174+ d = self .do_create (recurse = 3 , dirs = 2 , files = 2 )
2175+ self .assertIsInstance (d .name , bytes if bytes_name else str )
20722176 with d :
20732177 # Change files and directories mode recursively.
20742178 for root , dirs , files in os .walk (d .name , topdown = False ):
@@ -2079,13 +2183,17 @@ def test_modes(self):
20792183 self .assertFalse (os .path .exists (d .name ))
20802184
20812185 @support .subTests ('ignore_errors' , (True , False ))
2082- def test_parent_mode_preserved (self , ignore_errors ):
2186+ @support .subTests ('bytes_name' , (False , True ))
2187+ def test_parent_mode_preserved (self , ignore_errors , bytes_name ):
20832188 # Test that cleanup does not touch the parent directory,
20842189 # even if that prevents removal.
20852190 for mode in range (8 ):
20862191 mode <<= 6
20872192 with self .subTest (mode = format (mode , '03o' )):
2088- outer = self .do_create ()
2193+ if bytes_name :
2194+ outer = self .do_create (dir = tempfile .gettempdirb ())
2195+ else :
2196+ outer = self .do_create ()
20892197 with outer :
20902198 d = self .do_create (dir = outer .name , dirs = 2 , files = 2 ,
20912199 ignore_cleanup_errors = ignore_errors )
0 commit comments