@@ -1639,10 +1639,14 @@ def __exit__(self, *exc_info):
16391639class TestTemporaryDirectory (BaseTestCase ):
16401640 """Test TemporaryDirectory()."""
16411641
1642- def do_create (self , dir = None , pre = "" , suf = "" , recurse = 1 , dirs = 1 , files = 1 ,
1642+ def do_create (self , dir = None , pre = None , suf = None , recurse = 1 , dirs = 1 , files = 1 ,
16431643 ignore_cleanup_errors = False ):
16441644 if dir is None :
16451645 dir = tempfile .gettempdir ()
1646+ if pre is None :
1647+ pre = type (dir )()
1648+ if suf is None :
1649+ suf = type (dir )()
16461650 tmp = tempfile .TemporaryDirectory (
16471651 dir = dir , prefix = pre , suffix = suf ,
16481652 ignore_cleanup_errors = ignore_cleanup_errors )
@@ -1652,13 +1656,17 @@ def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
16521656
16531657 def do_create2 (self , path , recurse = 1 , dirs = 1 , files = 1 ):
16541658 # Create subdirectories and some files
1659+ def join (name ):
1660+ if isinstance (path , bytes ):
1661+ name = os .fsencode (name )
1662+ return os .path .join (path , name )
16551663 if recurse :
16561664 for i in range (dirs ):
1657- name = os . path . join (path , "dir%d" % i )
1665+ name = join ("dir%d" % i )
16581666 os .mkdir (name )
16591667 self .do_create2 (name , recurse - 1 , dirs , files )
16601668 for i in range (files ):
1661- with open (os . path . join (path , "test%d.txt" % i ), "wb" ) as f :
1669+ with open (join ("test%d.txt" % i ), "wb" ) as f :
16621670 f .write (b"Hello world!" )
16631671
16641672 def test_mkdtemp_failure (self ):
@@ -1684,6 +1692,15 @@ def test_explicit_cleanup(self):
16841692 finally :
16851693 os .rmdir (dir )
16861694
1695+ def test_explicit_cleanup_bytes (self ):
1696+ # A TemporaryDirectory with a bytes name is deleted when cleaned up
1697+ with tempfile .TemporaryDirectory () as working_dir :
1698+ d = self .do_create (dir = os .fsencode (working_dir ), recurse = 2 )
1699+ self .assertIsInstance (d .name , bytes )
1700+ self .assertTrue (os .path .exists (d .name ))
1701+ d .cleanup ()
1702+ self .assertFalse (os .path .exists (d .name ))
1703+
16871704 def test_explicit_cleanup_ignore_errors (self ):
16881705 """Test that cleanup doesn't return an error when ignoring them."""
16891706 with tempfile .TemporaryDirectory () as working_dir :
@@ -1896,6 +1913,87 @@ def hook(path, *, dir_fd=None):
18961913 self .assertTrue (os .path .exists (target_file ))
18971914 self .assertEqual (os .stat (target_file ).st_mode , target_mode )
18981915
1916+ def _make_unopenable_subdir (self ):
1917+ # Create the following structure:
1918+ # work/ - top-level
1919+ # <d>/ - tempdir to clean up (random name)
1920+ # sub/ - an unopenable dir
1921+ # subsub/
1922+ # file
1923+ # Return:
1924+ # - `work` name (str)
1925+ # - `d` (TemporaryDirectory)
1926+ # - `subsub` stat result
1927+ work = self .enterContext (os_helper .temp_dir ())
1928+ d = tempfile .TemporaryDirectory (dir = work )
1929+ sub = os .path .join (d .name , 'sub' )
1930+ subsub = os .path .join (sub , 'subsub' )
1931+ os .mkdir (sub )
1932+ os .mkdir (subsub )
1933+ subsub_stat = os .lstat (subsub )
1934+ with open (os .path .join (subsub , 'file' ), 'w' ) as f :
1935+ f .write ("rm me pls" )
1936+ os .chmod (sub , 0 )
1937+ # If the test fails, make sure everything can still be removed.
1938+ self .addCleanup (d .cleanup )
1939+ @self .addCleanup
1940+ def _clean ():
1941+ if os .path .isdir (sub ):
1942+ os .chmod (sub , 0o700 )
1943+ return work , d , subsub_stat
1944+
1945+ @os_helper .skip_unless_working_chmod
1946+ @support .requires_non_root_user
1947+ @unittest .skipUnless (tempfile ._rmtree_use_dir_fd
1948+ and shutil .rmtree .avoids_symlink_attacks ,
1949+ 'requires the fd based cleanup' )
1950+ def test_cleanup_nested_toplevel_error (self ):
1951+ # rmtree() reports errors relative to the correct parent directory
1952+ work , d , subsub_stat = self ._make_unopenable_subdir ()
1953+ # An unrelated directory with the same name; should not be touched
1954+ unrelated = os .path .join (work , 'sub' )
1955+ os .mkdir (unrelated )
1956+
1957+ rmdir = os .rmdir
1958+ failed_path = None
1959+ def failing_rmdir (path , * , dir_fd = None ):
1960+ nonlocal failed_path
1961+ if path == 'sub' and dir_fd is not None and failed_path is None :
1962+ failed_path = path
1963+ raise PermissionError (errno .EPERM , 'simulated' , path )
1964+ return rmdir (path , dir_fd = dir_fd )
1965+ with os_helper .change_cwd (work ), mock .patch ('os.rmdir' , failing_rmdir ):
1966+ d .cleanup ()
1967+ self .assertEqual (failed_path , 'sub' )
1968+ self .assertFalse (os .path .exists (d .name ))
1969+ self .assertTrue (os .path .exists (unrelated ))
1970+
1971+ @os_helper .skip_unless_working_chmod
1972+ @support .requires_non_root_user
1973+ @unittest .skipUnless (tempfile ._rmtree_use_dir_fd
1974+ and shutil .rmtree .avoids_symlink_attacks ,
1975+ 'requires the fd based cleanup' )
1976+ def test_cleanup_nested_scandir_error (self ):
1977+ # A scandir() error is reported relative to the parent directory.
1978+ work , d , subsub_stat = self ._make_unopenable_subdir ()
1979+
1980+ scandir = os .scandir
1981+ failed = False
1982+ def failing_scandir (path = '.' ):
1983+ nonlocal failed
1984+ if (
1985+ not failed
1986+ and isinstance (path , int )
1987+ and os .path .samestat (os .fstat (path ), subsub_stat )
1988+ ):
1989+ failed = True
1990+ raise PermissionError (errno .EACCES , 'simulated' )
1991+ return scandir (path )
1992+ with os_helper .change_cwd (work ), mock .patch ('os.scandir' , failing_scandir ):
1993+ d .cleanup ()
1994+ self .assertTrue (failed )
1995+ self .assertFalse (os .path .exists (d .name ))
1996+
18991997 @support .cpython_only
19001998 def test_del_on_collection (self ):
19011999 # A TemporaryDirectory is deleted when garbage collected
@@ -2054,11 +2152,17 @@ def test_context_manager(self):
20542152 self .assertEqual (name , d .name )
20552153 self .assertFalse (os .path .exists (name ))
20562154
2057- def test_modes (self ):
2155+ @support .subTests ('bytes_name' , (False , True ))
2156+ def test_modes (self , bytes_name ):
20582157 for mode in range (8 ):
20592158 mode <<= 6
20602159 with self .subTest (mode = format (mode , '03o' )):
2061- d = self .do_create (recurse = 3 , dirs = 2 , files = 2 )
2160+ if bytes_name :
2161+ d = self .do_create (recurse = 3 , dirs = 2 , files = 2 ,
2162+ dir = tempfile .gettempdirb ())
2163+ else :
2164+ d = self .do_create (recurse = 3 , dirs = 2 , files = 2 )
2165+ self .assertIsInstance (d .name , bytes if bytes_name else str )
20622166 with d :
20632167 # Change files and directories mode recursively.
20642168 for root , dirs , files in os .walk (d .name , topdown = False ):
@@ -2069,13 +2173,17 @@ def test_modes(self):
20692173 self .assertFalse (os .path .exists (d .name ))
20702174
20712175 @support .subTests ('ignore_errors' , (True , False ))
2072- def test_parent_mode_preserved (self , ignore_errors ):
2176+ @support .subTests ('bytes_name' , (False , True ))
2177+ def test_parent_mode_preserved (self , ignore_errors , bytes_name ):
20732178 # Test that cleanup does not touch the parent directory,
20742179 # even if that prevents removal.
20752180 for mode in range (8 ):
20762181 mode <<= 6
20772182 with self .subTest (mode = format (mode , '03o' )):
2078- outer = self .do_create ()
2183+ if bytes_name :
2184+ outer = self .do_create (dir = tempfile .gettempdirb ())
2185+ else :
2186+ outer = self .do_create ()
20792187 with outer :
20802188 d = self .do_create (dir = outer .name , dirs = 2 , files = 2 ,
20812189 ignore_cleanup_errors = ignore_errors )
0 commit comments