2020-08-14 15:24:31 +05:30
|
|
|
use anyhow::{anyhow, Result};
|
|
|
|
use rand::prelude::*;
|
|
|
|
use std::fs;
|
|
|
|
use std::path::PathBuf;
|
2020-08-07 19:00:00 +05:30
|
|
|
|
|
|
|
//---------------------------------------
|
|
|
|
|
|
|
|
pub struct TestDir {
|
2020-08-14 15:24:31 +05:30
|
|
|
dir: PathBuf,
|
|
|
|
files: Vec<PathBuf>,
|
|
|
|
clean_up: bool,
|
2020-08-07 19:00:00 +05:30
|
|
|
file_count: usize,
|
|
|
|
}
|
|
|
|
|
2020-08-14 15:24:31 +05:30
|
|
|
fn mk_dir(prefix: &str) -> Result<PathBuf> {
|
|
|
|
for _n in 0..100 {
|
|
|
|
let mut p = PathBuf::new();
|
2021-01-23 14:11:01 +05:30
|
|
|
let nr = rand::thread_rng().gen_range(1000000..9999999);
|
2020-08-14 15:24:31 +05:30
|
|
|
p.push(format!("./{}_{}", prefix, nr));
|
|
|
|
if let Ok(()) = fs::create_dir(&p) {
|
|
|
|
return Ok(p);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Err(anyhow!("Couldn't create test directory"))
|
|
|
|
}
|
|
|
|
|
2020-08-07 19:00:00 +05:30
|
|
|
impl TestDir {
|
|
|
|
pub fn new() -> Result<TestDir> {
|
2020-08-14 15:24:31 +05:30
|
|
|
let dir = mk_dir("test_fixture")?;
|
|
|
|
Ok(TestDir {
|
|
|
|
dir,
|
|
|
|
files: Vec::new(),
|
|
|
|
clean_up: true,
|
|
|
|
file_count: 0,
|
|
|
|
})
|
2020-08-07 19:00:00 +05:30
|
|
|
}
|
|
|
|
|
2021-10-18 21:29:17 +05:30
|
|
|
pub fn dont_clean_up(&mut self) {
|
|
|
|
self.clean_up = false;
|
|
|
|
}
|
|
|
|
|
2020-08-07 19:00:00 +05:30
|
|
|
pub fn mk_path(&mut self, file: &str) -> PathBuf {
|
|
|
|
let mut p = PathBuf::new();
|
|
|
|
p.push(&self.dir);
|
|
|
|
p.push(PathBuf::from(format!("{:02}_{}", self.file_count, file)));
|
2020-08-14 15:24:31 +05:30
|
|
|
self.files.push(p.clone());
|
2020-08-07 19:00:00 +05:30
|
|
|
self.file_count += 1;
|
|
|
|
p
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-14 15:24:31 +05:30
|
|
|
impl Drop for TestDir {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
if self.clean_up {
|
|
|
|
while let Some(f) = self.files.pop() {
|
|
|
|
// It's not guaranteed that the path generated was actually created.
|
|
|
|
let _ignore = fs::remove_file(f);
|
|
|
|
}
|
|
|
|
fs::remove_dir(&self.dir).expect("couldn't remove test directory");
|
2021-10-18 21:29:17 +05:30
|
|
|
} else {
|
|
|
|
eprintln!("leaving test directory: {:?}", self.dir);
|
2020-08-14 15:24:31 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-07 19:00:00 +05:30
|
|
|
//---------------------------------------
|