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:
parent
2b2c2b64c2
commit
a629bb3076
1 changed files with 42 additions and 4 deletions
38
tests/common/util.rs
Normal file → Executable file
38
tests/common/util.rs
Normal file → Executable file
|
@ -5,6 +5,7 @@ extern crate tempdir;
|
|||
use std::env;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Write, Result};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::symlink as symlink_file;
|
||||
#[cfg(windows)]
|
||||
|
@ -122,6 +123,40 @@ pub fn recursive_copy(src: &Path, dest: &Path) -> Result<()> {
|
|||
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 subdir: PathBuf,
|
||||
}
|
||||
|
@ -185,6 +220,9 @@ impl AtPath {
|
|||
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) {
|
||||
log_info("touch", self.plus_as_string(file));
|
||||
File::create(&self.plus(file)).unwrap();
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue