1 #![warn(rust_2018_idioms)]
2 #![cfg(all(feature = "full", not(target_os = "wasi")))] // WASI does not support all fs operations
3
4 use std::io::Write;
5 use tempfile::NamedTempFile;
6 use tokio::fs::OpenOptions;
7 use tokio::io::AsyncReadExt;
8
9 const HELLO: &[u8] = b"hello world...";
10
11 #[tokio::test]
open_with_open_options_and_read()12 async fn open_with_open_options_and_read() {
13 let mut tempfile = NamedTempFile::new().unwrap();
14 tempfile.write_all(HELLO).unwrap();
15
16 let mut file = OpenOptions::new().read(true).open(tempfile).await.unwrap();
17
18 let mut buf = [0; 1024];
19 let n = file.read(&mut buf).await.unwrap();
20
21 assert_eq!(n, HELLO.len());
22 assert_eq!(&buf[..n], HELLO);
23 }
24
25 #[tokio::test]
open_options_write()26 async fn open_options_write() {
27 // TESTING HACK: use Debug output to check the stored data
28 assert!(format!("{:?}", OpenOptions::new().write(true)).contains("write: true"));
29 }
30
31 #[tokio::test]
open_options_append()32 async fn open_options_append() {
33 // TESTING HACK: use Debug output to check the stored data
34 assert!(format!("{:?}", OpenOptions::new().append(true)).contains("append: true"));
35 }
36
37 #[tokio::test]
open_options_truncate()38 async fn open_options_truncate() {
39 // TESTING HACK: use Debug output to check the stored data
40 assert!(format!("{:?}", OpenOptions::new().truncate(true)).contains("truncate: true"));
41 }
42
43 #[tokio::test]
open_options_create()44 async fn open_options_create() {
45 // TESTING HACK: use Debug output to check the stored data
46 assert!(format!("{:?}", OpenOptions::new().create(true)).contains("create: true"));
47 }
48
49 #[tokio::test]
open_options_create_new()50 async fn open_options_create_new() {
51 // TESTING HACK: use Debug output to check the stored data
52 assert!(format!("{:?}", OpenOptions::new().create_new(true)).contains("create_new: true"));
53 }
54
55 #[tokio::test]
56 #[cfg(unix)]
open_options_mode()57 async fn open_options_mode() {
58 let mode = format!("{:?}", OpenOptions::new().mode(0o644));
59 // TESTING HACK: use Debug output to check the stored data
60 assert!(
61 mode.contains("mode: 420 ") || mode.contains("mode: 0o000644 "),
62 "mode is: {mode}"
63 );
64 }
65
66 #[tokio::test]
67 #[cfg(target_os = "linux")]
open_options_custom_flags_linux()68 async fn open_options_custom_flags_linux() {
69 // TESTING HACK: use Debug output to check the stored data
70 assert!(
71 format!("{:?}", OpenOptions::new().custom_flags(libc::O_TRUNC))
72 .contains("custom_flags: 512,")
73 );
74 }
75
76 #[tokio::test]
77 #[cfg(any(target_os = "freebsd", target_os = "macos"))]
open_options_custom_flags_bsd_family()78 async fn open_options_custom_flags_bsd_family() {
79 // TESTING HACK: use Debug output to check the stored data
80 assert!(
81 format!("{:?}", OpenOptions::new().custom_flags(libc::O_NOFOLLOW))
82 .contains("custom_flags: 256,")
83 );
84 }
85