@@ -1981,6 +1981,13 @@ def test_walk_above_recursion_limit(self):
19811981 self .assertEqual (sorted (dirs ), ["SUB1" , "SUB2" , "d" ])
19821982 self .assertEqual (all , expected )
19831983
1984+ def test_walk_on_file_raises_not_a_directory (self ):
1985+ # gh-101420: os.walk() was silently returning [] when top is a
1986+ # regular file instead of raising NotADirectoryError.
1987+ with tempfile .NamedTemporaryFile () as f :
1988+ with self .assertRaises (NotADirectoryError ):
1989+ list (os .walk (f .name ))
1990+
19841991
19851992@unittest .skipUnless (hasattr (os , 'fwalk' ), "Test needs os.fwalk()" )
19861993class FwalkTests (WalkTests ):
@@ -2038,6 +2045,19 @@ def test_yields_correct_dir_fd(self):
20382045 # check that listdir() returns consistent information
20392046 self .assertEqual (set (os .listdir (rootfd )), set (dirs ) | set (files ))
20402047
2048+ def test_fwalk_on_file_raises_not_a_directory (self ):
2049+ with tempfile .NamedTemporaryFile () as f :
2050+ with self .assertRaises (NotADirectoryError ):
2051+ list (os .fwalk (f .name , follow_symlinks = False ))
2052+
2053+ # follow_symlinks=True: raised but with fd int as filename, must now have path
2054+ with self .assertRaises (NotADirectoryError ) as ctx :
2055+ list (os .fwalk (f .name , follow_symlinks = True ))
2056+ self .assertEqual (
2057+ ctx .exception .filename , f .name ,
2058+ "filename should be the path string, not a raw fd integer"
2059+ )
2060+
20412061 @unittest .skipIf (
20422062 support .is_android , "dup return value is unpredictable on Android"
20432063 )
0 commit comments