Skip to main content

hide_glue/
fixture.rs

1//! A temporary file fixture
2use std::env;
3use std::path::{Path, PathBuf};
4
5use tempfile::TempDir;
6
7// Thanks Andrew Radev!
8// https://andrewra.dev/2019/03/01/testing-in-rust-temporary-files/
9/// Create a temporary file in a temporary directory, optionally populating the file with the
10/// contents of a file in $CARGO_MANIFEST_DIR/tests/fixtures.
11pub struct TemporaryFileFixture {
12    path: PathBuf,
13    source: PathBuf,
14    _tempdir: TempDir,
15}
16
17impl TemporaryFileFixture {
18    pub fn blank(fixture_filename: &str) -> Self {
19        let tempdir =
20            tempfile::tempdir().expect("Failed to initialize a temporary directory for a fixture");
21        let mut path = PathBuf::from(&tempdir.path());
22        path.push(fixture_filename);
23
24        Self {
25            path,
26            source: PathBuf::new(),
27            _tempdir: tempdir,
28        }
29    }
30    pub fn copy(fixture_filename: &str) -> Self {
31        let mut fixture = Self::blank(fixture_filename);
32
33        let key = "CARGO_MANIFEST_DIR";
34        let root = env::var(key)
35            .unwrap_or_else(|_| format!("Failed to get the {} environment variable", key));
36        fixture.source.push(root);
37        fixture.source.push("tests/fixtures");
38        fixture.source.push(fixture_filename);
39
40        std::fs::copy(&fixture.source, &fixture.path)
41            .expect("Failed to copy a fixture file to the temporary directory");
42        fixture
43    }
44
45    pub fn get_path(&self) -> &Path {
46        &self.path
47    }
48}
49
50impl std::ops::Deref for TemporaryFileFixture {
51    type Target = Path;
52
53    fn deref(&self) -> &Self::Target {
54        self.path.deref()
55    }
56}