use extrasafe::builtins::SystemIO;
use extrasafe::*;
use std::fs::{File, OpenOptions};
use std::io::Write;
#[test]
fn allow_open_readonly() {
let dir = tempfile::tempdir().unwrap();
let mut path = dir.path().to_path_buf();
path.push("open_me.txt");
let mut file = File::create(&path).unwrap();
file.write_all(b"hello world").unwrap();
file.sync_all().unwrap();
drop(file);
SafetyContext::new()
.enable(
SystemIO::nothing()
.allow_open_readonly()
.allow_read()
.allow_metadata()
.allow_close(),
)
.unwrap()
.apply_to_current_thread()
.unwrap();
let res = OpenOptions::new().read(true).write(true).open(&path);
assert!(
res.is_err(),
"Successfully opened file for writing incorrectly"
);
let res = OpenOptions::new().read(true).append(true).open(&path);
assert!(
res.is_err(),
"Successfully opened file for append incorrectly"
);
let res = OpenOptions::new().read(true).create(true).open(&path);
assert!(
res.is_err(),
"Successfully opened file with create incorrectly"
);
let mut new_path = dir.path().to_path_buf();
new_path.push("new_path.txt");
let res = OpenOptions::new()
.read(true)
.create_new(true)
.open(&new_path);
assert!(
res.is_err(),
"Successfully opened file with create_new incorrectly"
);
let res = OpenOptions::new().read(true).write(false).open(&path);
assert!(
res.is_ok(),
"Failed to open file for reading: {:?}",
res.unwrap_err()
);
}