1 #![warn(rust_2018_idioms)] 2 #![cfg(feature = "full")] 3 4 use tokio::fs::File; 5 use tokio::prelude::*; 6 use tokio_test::task; 7 8 use std::io::prelude::*; 9 use tempfile::NamedTempFile; 10 11 const HELLO: &[u8] = b"hello world..."; 12 13 #[tokio::test] basic_read()14async fn basic_read() { 15 let mut tempfile = tempfile(); 16 tempfile.write_all(HELLO).unwrap(); 17 18 let mut file = File::open(tempfile.path()).await.unwrap(); 19 20 let mut buf = [0; 1024]; 21 let n = file.read(&mut buf).await.unwrap(); 22 23 assert_eq!(n, HELLO.len()); 24 assert_eq!(&buf[..n], HELLO); 25 } 26 27 #[tokio::test] basic_write()28async fn basic_write() { 29 let tempfile = tempfile(); 30 31 let mut file = File::create(tempfile.path()).await.unwrap(); 32 33 file.write_all(HELLO).await.unwrap(); 34 file.flush().await.unwrap(); 35 36 let file = std::fs::read(tempfile.path()).unwrap(); 37 assert_eq!(file, HELLO); 38 } 39 40 #[tokio::test] coop()41async fn coop() { 42 let mut tempfile = tempfile(); 43 tempfile.write_all(HELLO).unwrap(); 44 45 let mut task = task::spawn(async { 46 let mut file = File::open(tempfile.path()).await.unwrap(); 47 48 let mut buf = [0; 1024]; 49 50 loop { 51 file.read(&mut buf).await.unwrap(); 52 file.seek(std::io::SeekFrom::Start(0)).await.unwrap(); 53 } 54 }); 55 56 for _ in 0..1_000 { 57 if task.poll().is_pending() { 58 return; 59 } 60 } 61 62 panic!("did not yield"); 63 } 64 tempfile() -> NamedTempFile65fn tempfile() -> NamedTempFile { 66 NamedTempFile::new().unwrap() 67 } 68 69 #[tokio::test] 70 #[cfg(unix)] unix_fd()71async fn unix_fd() { 72 use std::os::unix::io::AsRawFd; 73 let tempfile = tempfile(); 74 75 let file = File::create(tempfile.path()).await.unwrap(); 76 assert!(file.as_raw_fd() as u64 > 0); 77 } 78 79 #[tokio::test] 80 #[cfg(windows)] windows_handle()81async fn windows_handle() { 82 use std::os::windows::io::AsRawHandle; 83 let tempfile = tempfile(); 84 85 let file = File::create(tempfile.path()).await.unwrap(); 86 assert!(file.as_raw_handle() as u64 > 0); 87 } 88