1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

tests: Create the ScopedFile type for temporary files in tests

This commit adds the `ScopedFile` type, which wraps and derefs to a `File`. When
a `ScopedFile` is dropped, it removes the underlying file from the
filesystem. This is useful for temporary, generated files in tests.
This commit is contained in:
Nick Fitzgerald 2016-03-26 12:27:54 -07:00
parent 2b2c2b64c2
commit a629bb3076

38
tests/common/util.rs Normal file → Executable file
View file

@ -5,6 +5,7 @@ extern crate tempdir;
use std::env; use std::env;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::{Read, Write, Result}; use std::io::{Read, Write, Result};
use std::ops::{Deref, DerefMut};
#[cfg(unix)] #[cfg(unix)]
use std::os::unix::fs::symlink as symlink_file; use std::os::unix::fs::symlink as symlink_file;
#[cfg(windows)] #[cfg(windows)]
@ -122,6 +123,40 @@ pub fn recursive_copy(src: &Path, dest: &Path) -> Result<()> {
Ok(()) Ok(())
} }
/// A scoped, temporary file that is removed upon drop.
pub struct ScopedFile {
path: PathBuf,
file: File,
}
impl ScopedFile {
fn new(path: PathBuf, file: File) -> ScopedFile {
ScopedFile {
path: path,
file: file
}
}
}
impl Deref for ScopedFile {
type Target = File;
fn deref(&self) -> &File {
&self.file
}
}
impl DerefMut for ScopedFile {
fn deref_mut(&mut self) -> &mut File {
&mut self.file
}
}
impl Drop for ScopedFile {
fn drop(&mut self) {
fs::remove_file(&self.path).unwrap();
}
}
pub struct AtPath { pub struct AtPath {
pub subdir: PathBuf, pub subdir: PathBuf,
} }
@ -185,6 +220,9 @@ impl AtPath {
Err(e) => panic!("{}", e), Err(e) => panic!("{}", e),
} }
} }
pub fn make_scoped_file(&self, name: &str) -> ScopedFile {
ScopedFile::new(self.plus(name), self.make_file(name))
}
pub fn touch(&self, file: &str) { pub fn touch(&self, file: &str) {
log_info("touch", self.plus_as_string(file)); log_info("touch", self.plus_as_string(file));
File::create(&self.plus(file)).unwrap(); File::create(&self.plus(file)).unwrap();