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