use std::ffi::{OsStr, OsString}; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use tempfile::{env, tempdir, Builder, NamedTempFile, TempPath};
/// For the wasi platforms, `std::env::temp_dir` will panic. For those targets, configure the /tmp /// directory instead as the base directory for temp files. fn configure_wasi_temp_dir() { if cfg!(target_os = "wasi") { let _ = tempfile::env::override_temp_dir(Path::new("/tmp"));
}
}
let tmpfile = NamedTempFile::with_prefix("prefix").unwrap(); let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
assert!(name.starts_with("prefix"));
}
let tmpfile = NamedTempFile::with_suffix("suffix").unwrap(); let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
assert!(name.ends_with("suffix"));
}
{ // Try opening it at the new path. letmut f = File::open(&persist_path).unwrap();
f.seek(SeekFrom::Start(0)).unwrap(); letmut buf = String::new();
f.read_to_string(&mut buf).unwrap();
assert_eq!("abcde", buf);
}
std::fs::remove_file(&persist_path).unwrap();
}
{ // Try opening it at the new path. letmut f = File::open(&persist_path).unwrap();
f.seek(SeekFrom::Start(0)).unwrap(); letmut buf = String::new();
f.read_to_string(&mut buf).unwrap();
assert_eq!("abcde", buf);
}
// Try opening it at the new path. letmut f = File::open(&persist_path).unwrap();
f.seek(SeekFrom::Start(0)).unwrap(); letmut buf = String::new();
f.read_to_string(&mut buf).unwrap();
assert_eq!("abcde", buf);
std::fs::remove_file(&persist_path).unwrap();
}
let tmp_dir = tempdir().unwrap(); let tmp_file_path_1 = tmp_dir.path().join("testfile1"); let tmp_file_path_2 = tmp_dir.path().join("testfile2");
File::create(&tmp_file_path_1).unwrap();
assert!(tmp_file_path_1.exists(), "Test file 1 hasn't been created");
File::create(&tmp_file_path_2).unwrap();
assert!(tmp_file_path_2.exists(), "Test file 2 hasn't been created");
let tmp_path = TempPath::try_from_path(&tmp_file_path_1).unwrap();
assert!(
tmp_file_path_1.exists(), "Test file has been deleted before dropping TempPath"
);
drop(tmp_path);
assert!(
!tmp_file_path_1.exists(), "Test file exists after dropping TempPath"
);
assert!(
tmp_file_path_2.exists(), "Test file 2 has been deleted before dropping TempDir"
);
}
#[test] #[allow(unreachable_code)] fn temp_path_from_argument_types() { // This just has to compile return;
// This test only works on platforms where we can safely delete the current // working directory. #[test] #[cfg(not(any(target_os = "redox", target_os = "wasi", windows)))] fn test_temp_path_resolve_missing_cwd() {
configure_wasi_temp_dir(); let _guard = cwd_lock();
// Intentionally delete the current working directory let tmpdir = tempdir().unwrap();
std::env::set_current_dir(&tmpdir).expect("failed to change to the temporary directory");
tmpdir.close().unwrap();
#[allow(deprecated)] let path = TempPath::from_path("foo");
assert_eq!(&*path, Path::new("foo"));
TempPath::try_from_path("foo").expect_err("should have failed to make path absolute file");
}
#[test] fn test_temp_path_resolve_existing_cwd() {
configure_wasi_temp_dir(); let _guard = cwd_lock();
let tmpdir = tempdir().unwrap();
std::env::set_current_dir(&tmpdir).expect("failed to change to directory");
let cwd = if cfg!(target_os = "macos") { // MacOS has absolute paths and ABSOLUTE paths. `cd /var/tmp/...` actually changes to // /private/var/tmp...
std::env::current_dir().expect("failed to get the current directory")
} else {
tmpdir.path().to_owned()
};
#[allow(deprecated)] let path = TempPath::from_path("foo");
assert_eq!(&*path, cwd.join("foo"));
#[allow(deprecated)] let path = TempPath::from_path("");
assert_eq!(&*path, Path::new(""));
TempPath::try_from_path("").expect_err("empty paths should fail");
}
let path = NamedTempFile::new().unwrap().into_temp_path();
File::create(path).unwrap().write_all(b"test").unwrap();
}
#[test] fn test_change_dir() {
configure_wasi_temp_dir(); let _guard = cwd_lock();
let dir_a = tempdir().unwrap(); let dir_b = tempdir().unwrap();
std::env::set_current_dir(&dir_a).expect("failed to change to directory A"); let tmpfile = NamedTempFile::new_in(".").unwrap(); let path = std::env::current_dir().unwrap().join(tmpfile.path());
std::env::set_current_dir(&dir_b).expect("failed to change to directory B");
drop(tmpfile);
assert!(!exists(path));
drop(dir_a);
drop(dir_b);
}
#[test] fn test_change_dir_make() {
configure_wasi_temp_dir(); let _guard = cwd_lock();
let dir_a = tempdir().unwrap(); let dir_b = tempdir().unwrap();
std::env::set_current_dir(&dir_a).expect("failed to change to directory A"); let tmpfile = Builder::new().make_in(".", |p| File::create(p)).unwrap(); let path = std::env::current_dir().unwrap().join(tmpfile.path());
std::env::set_current_dir(&dir_b).expect("failed to change to directory B");
drop(tmpfile);
assert!(!exists(path));
// Case 0: never mark as "disable cleanup" // Case 1: enable "disable cleanup" in the builder, don't touch it after. // Case 2: enable "disable cleanup" in the builder, turn it off after. // Case 3: don't enable disable cleanup in the builder, turn it on after.
for case in0..4 { let in_builder = case & 1 > 0; let toggle = case & 2 > 0; letmut tmpfile = Builder::new()
.disable_cleanup(in_builder)
.tempfile()
.unwrap();
write!(tmpfile, "abcde").unwrap(); if toggle {
tmpfile.disable_cleanup(!in_builder);
}
let path = tmpfile.path().to_owned();
drop(tmpfile);
// Show that an FnMut can be used. let tmpfile = Builder::new()
.make(|path| {
count += 1;
File::create(path)
})
.unwrap();
assert!(tmpfile.path().is_file());
}
#[cfg(unix)] #[test] fn test_make_uds() { use std::os::unix::net::UnixListener;
let temp_sock = Builder::new()
.prefix("tmp")
.suffix(".sock")
.rand_bytes(12)
.make(|path| UnixListener::bind(path))
.unwrap();
assert!(temp_sock.path().exists());
}
// This works(ish) on redox, but it's really slow. #[cfg(all(unix, not(target_os = "redox")))] #[test] fn test_make_uds_conflict() { use std::io::ErrorKind; use std::os::unix::net::UnixListener;
let sockets = std::iter::repeat_with(|| {
Builder::new()
.prefix("tmp")
.suffix(".sock")
.rand_bytes(1)
.make(|path| UnixListener::bind(path))
})
.take_while(|r| match r {
Ok(_) => true,
Err(e) if matches!(e.kind(), ErrorKind::AddrInUse | ErrorKind::AlreadyExists) => false,
Err(e) => panic!("unexpected error {e}"),
})
.collect::<Result<Vec<_>, _>>()
.unwrap();
// Number of sockets we can create. Depends on whether or not the filesystem is case sensitive.
for socket in sockets {
assert!(socket.path().exists());
}
}
/// Make sure we re-seed with system randomness if we run into a conflict. #[test] fn test_reseed() {
configure_wasi_temp_dir();
// Deterministic seed.
fastrand::seed(42);
// I need to create 5 conflicts but I can't just make 5 temporary files because we fork the RNG // each time we create a file. letmut attempts = 0; letmut files: Vec<_> = Vec::new(); let _ = Builder::new().make(|path| -> io::Result<File> { if attempts == 5 { return Err(io::Error::new(io::ErrorKind::Other, "stop!"));
}
attempts += 1; let f = File::options()
.write(true)
.create_new(true)
.open(path)
.unwrap();
// Don't really need to run this. Only care if it compiles. iflet Ok(file) = File::open("i_do_not_exist") { letmut f; let _x = {
f = Foo::new(file);
&mut f
};
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.