1use std::env;
3use std::path::{Path, PathBuf};
4
5use tempfile::TempDir;
6
7pub 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}