use dever_runtime::io::File; fn fixture(name: &str) -> std::path::PathBuf { let path = std::env::temp_dir().join(format!("dever-stream-{}-{name}", std::process::id())); let mut output = std::fs::OpenOptions::new() .create_new(true) .write(true) .open(&path) .unwrap(); std::io::Write::write_all(&mut output, b"abc123").unwrap(); path } #[test] fn file_streams_are_lazy_share_one_cursor_and_preserve_external_files() { let path = fixture("cursor"); let file = File::open(path.to_str().unwrap()).unwrap(); let stream = file.chunks(2, std::convert::identity).unwrap(); let alias = stream.clone(); assert_eq!(file.read(1).unwrap().unwrap().as_ref(), b"a"); assert_eq!(stream.next().unwrap().unwrap().as_ref(), b"bc"); assert_eq!(alias.next().unwrap().unwrap().as_ref(), b"12"); stream.close(); assert!(alias.next().is_none()); assert_eq!(file.read(1).unwrap().unwrap().as_ref(), b"3"); file.close().unwrap(); std::fs::remove_file(path).unwrap(); } #[test] fn file_stream_failure_is_delivered_once_and_guards_close_every_alias() { let path = fixture("failure"); let file = File::open(path.to_str().unwrap()).unwrap(); assert!(file.chunks(0, std::convert::identity).is_err()); let stream = file.chunks(2, std::convert::identity).unwrap(); file.close().unwrap(); assert!(file.chunks(2, std::convert::identity).is_err()); assert_eq!( stream.next().unwrap().unwrap_err().kind(), std::io::ErrorKind::BrokenPipe ); assert!(stream.next().is_none()); let file = File::open(path.to_str().unwrap()).unwrap(); let stream = file.chunks(2, std::convert::identity).unwrap(); let alias = stream.clone(); let fault = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let _close = stream.close_on_drop(); assert!(stream.next().unwrap().is_ok()); std::panic::panic_any(42u32); })) .unwrap_err(); assert_eq!(fault.downcast_ref::(), Some(&42)); assert!(alias.next().is_none()); assert_eq!(file.read(4).unwrap().unwrap().as_ref(), b"c123"); file.close().unwrap(); std::fs::remove_file(path).unwrap(); }