File: test_dir.rs

package info (click to toggle)
thin-provisioning-tools 1.1.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,300 kB
  • sloc: xml: 544; sh: 521; makefile: 133
file content (67 lines) | stat: -rw-r--r-- 1,722 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use anyhow::{anyhow, Result};
use rand::prelude::*;
use std::fs;
use std::path::PathBuf;

//---------------------------------------

pub struct TestDir {
    dir: PathBuf,
    files: Vec<PathBuf>,
    clean_up: bool,
    file_count: usize,
}

fn mk_dir(prefix: &str) -> Result<PathBuf> {
    for _n in 0..100 {
        let mut p = PathBuf::new();
        let nr = rand::thread_rng().gen_range(1000000..9999999);
        p.push(format!("./{}_{}", prefix, nr));
        if let Ok(()) = fs::create_dir(&p) {
            return Ok(p);
        }
    }

    Err(anyhow!("Couldn't create test directory"))
}

impl TestDir {
    pub fn new() -> Result<TestDir> {
        let dir = mk_dir("test_fixture")?;
        Ok(TestDir {
            dir,
            files: Vec::new(),
            clean_up: true,
            file_count: 0,
        })
    }

    pub fn dont_clean_up(&mut self) {
        self.clean_up = false;
    }

    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)));
        self.files.push(p.clone());
        self.file_count += 1;
        p
    }
}

impl Drop for TestDir {
    fn drop(&mut self) {
        if !std::thread::panicking() && 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");
        } else {
            eprintln!("leaving test directory: {:?}", self.dir);
        }
    }
}

//---------------------------------------