@@ -3002,6 +3002,63 @@ def test_capabilities(self):
3002
3002
os .stat in os .supports_effective_ids ,
3003
3003
)
3004
3004
3005
+ def test_dup (self ):
3006
+ with self .assertRaises (OSError ) as cm :
3007
+ self .os .dup (500 )
3008
+ self .assertEqual (errno .EBADF , cm .exception .errno )
3009
+ file_path = self .make_path ("test.txt" )
3010
+ self .create_file (file_path , contents = "heythere" )
3011
+ fd1 = self .os .open (file_path , os .O_RDONLY )
3012
+ fd2 = self .os .dup (fd1 )
3013
+ self .assertEqual (b"hey" , self .os .read (fd1 , 3 ))
3014
+ self .assertEqual (b"there" , self .os .read (fd1 , 10 ))
3015
+ self .os .close (fd1 )
3016
+ self .os .close (fd2 )
3017
+
3018
+ def test_dup_uses_freed_fd (self ):
3019
+ file_path1 = self .make_path ("foo.txt" )
3020
+ file_path2 = self .make_path ("bar.txt" )
3021
+ self .create_file (file_path1 , contents = "foo here" )
3022
+ self .create_file (file_path2 , contents = "bar here" )
3023
+ fd1 = self .os .open (file_path1 , os .O_RDONLY )
3024
+ fd2 = self .os .open (file_path2 , os .O_RDONLY )
3025
+ self .os .close (fd1 )
3026
+ fd3 = self .os .dup (fd2 )
3027
+ self .assertEqual (fd1 , fd3 )
3028
+ self .os .close (fd2 )
3029
+
3030
+ def test_dup2_uses_existing_fd (self ):
3031
+ with self .assertRaises (OSError ) as cm :
3032
+ self .os .dup2 (500 , 501 )
3033
+ self .assertEqual (errno .EBADF , cm .exception .errno )
3034
+
3035
+ file_path1 = self .make_path ("foo.txt" )
3036
+ file_path2 = self .make_path ("bar.txt" )
3037
+ self .create_file (file_path1 , contents = "foo here" )
3038
+ self .create_file (file_path2 , contents = "bar here" )
3039
+ fd1 = self .os .open (file_path1 , os .O_RDONLY )
3040
+ fd2 = self .os .open (file_path2 , os .O_RDONLY )
3041
+ self .assertEqual (b"bar" , self .os .read (fd2 , 3 ))
3042
+ fd2 = self .os .dup2 (fd1 , fd2 )
3043
+ self .assertEqual (b"foo" , self .os .read (fd2 , 3 ))
3044
+ self .os .lseek (fd2 , 0 , 0 )
3045
+ self .assertEqual (b"foo" , self .os .read (fd1 , 3 ))
3046
+ self .os .close (fd2 )
3047
+
3048
+ def test_dup2_with_new_fd (self ):
3049
+ file_path1 = self .make_path ("foo.txt" )
3050
+ file_path2 = self .make_path ("bar.txt" )
3051
+ self .create_file (file_path1 )
3052
+ self .create_file (file_path2 )
3053
+ fd1 = self .os .open (file_path1 , os .O_RDONLY )
3054
+ fd2 = fd1 + 2
3055
+ self .assertEqual (fd2 , self .os .dup2 (fd1 , fd2 ))
3056
+ fd3 = self .os .open (file_path2 , os .O_RDONLY )
3057
+ self .os .close (fd3 )
3058
+ self .os .close (fd2 )
3059
+ # we have a free position before fd2 that is now filled
3060
+ self .assertEqual (fd1 + 1 , fd3 )
3061
+
3005
3062
3006
3063
class RealOsModuleTest (FakeOsModuleTest ):
3007
3064
def use_real_fs (self ):
0 commit comments