forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdadd2f4Tahinli3 months ago372 commits

scratch.rs130 lines, 4.9 KiBHistoryRawDownload
1//! Throwaway paths for the tests, and the one rule about them: everything a
2//! test writes goes inside a directory that deletes itself.
3//!
4//! [`Scratch`] is that directory. It derefs to a path -- the directory itself,
5//! or the one file inside it -- so a helper that used to hand back a `PathBuf`
6//! hands back one of these instead and its call sites do not change. `Drop` is
7//! what cleans up, which is the whole point: unwinding runs it, so a *failing*
8//! test leaves nothing behind either. The suites used to litter `/tmp` with a
9//! fresh `ve_*` directory per run and never take one back; on this machine that
10//! reached 2907 of them.
11//!
12//! Nothing outside a test has any use for this. It lives in the library rather
13//! than in a test file because the integration suites, the unit tests here and
14//! the app's own tests all need the same guard, and none of them can see each
15//! other's modules.
16
17use std::ffi::OsStr;
18use std::ops::Deref;
19use std::path::{Path, PathBuf};
20use std::sync::atomic::{AtomicU64, Ordering};
21
22/// A temporary directory and the path a test uses inside it, gone when the
23/// value is.
24#[derive(Debug)]
25pub struct Scratch {
26 dir: PathBuf,
27 path: PathBuf,
28}
29
30/// A fresh, empty directory under the system temporary one. `name` leads it so
31/// it is recognisable while a test is stopped in it; the process id and a
32/// counter follow, because two suites (or two tests of one suite, in parallel)
33/// must not write each other's files. Canonical, because saved projects hold
34/// paths relative to their own directory and `Project` canonicalises what it is
35/// handed.
36fn fresh(name: &str) -> PathBuf {
37 static NTH: AtomicU64 = AtomicU64::new(0);
38 let dir = std::env::temp_dir().join(format!(
39 "{name}_{}_{}",
40 std::process::id(),
41 NTH.fetch_add(1, Ordering::Relaxed)
42 ));
43 let _ = std::fs::remove_dir_all(&dir);
44 std::fs::create_dir_all(&dir).expect("scratch dir");
45 std::fs::canonicalize(&dir).expect("canonical scratch dir")
46}
47
48impl Scratch {
49 /// A directory to litter: the value *is* the directory.
50 pub fn dir(name: &str) -> Self {
51 let dir = fresh(name);
52 Self {
53 path: dir.clone(),
54 dir,
55 }
56 }
57
58 /// A path for the one file a test writes, `name.ext`, alone in a directory
59 /// of its own. Nothing creates it -- what is under test is what writes it,
60 /// and several of these tests are about a file that must *not* appear.
61 pub fn file(name: &str, ext: &str) -> Self {
62 let dir = fresh(name);
63 let path = dir.join(format!("{name}.{ext}"));
64 Self { dir, path }
65 }
66}
67
68impl Deref for Scratch {
69 type Target = Path;
70
71 fn deref(&self) -> &Path {
72 &self.path
73 }
74}
75
76impl AsRef<Path> for Scratch {
77 fn as_ref(&self) -> &Path {
78 &self.path
79 }
80}
81
82/// So one of these can be handed to a `Command` as an argument, which is how
83/// the suites that check our output with ffmpeg name the file.
84impl AsRef<OsStr> for Scratch {
85 fn as_ref(&self) -> &OsStr {
86 self.path.as_os_str()
87 }
88}
89
90impl Drop for Scratch {
91 fn drop(&mut self) {
92 let _ = std::fs::remove_dir_all(&self.dir);
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::Scratch;
99
100 /// The guard's whole job, both shapes: what it hands back is usable, and
101 /// what it made is gone once it is -- including when a test panicked, which
102 /// is the case that leaked.
103 #[test]
104 fn a_scratch_takes_its_directory_with_it() {
105 let (dir, file) = (Scratch::dir("ve_scratch_dir"), Scratch::file("ve_scratch", "mp4"));
106 assert!(dir.is_dir(), "a directory to litter, ready to use");
107 std::fs::write(dir.join("a.txt"), b"litter").expect("write into it");
108 assert!(!file.exists(), "the file itself is the test's to write");
109 assert!(file.parent().expect("inside a directory").is_dir());
110 assert_eq!(file.extension().and_then(|e| e.to_str()), Some("mp4"));
111
112 let (left, right) = (dir.to_path_buf(), file.parent().unwrap().to_path_buf());
113 assert_ne!(left, right, "one directory each, never shared");
114 drop((dir, file));
115 assert!(!left.exists(), "the directory went with the guard");
116 assert!(!right.exists(), "and so did the file's");
117
118 // Unwinding runs `Drop`, so a failing test cleans up like a passing one.
119 // The panic below is this test's own and is meant to reach stderr.
120 let seen = std::sync::Mutex::new(None);
121 let _ = std::panic::catch_unwind(|| {
122 let dir = Scratch::dir("ve_scratch_panic");
123 std::fs::write(dir.join("a.txt"), b"litter").expect("write into it");
124 *seen.lock().expect("the lock") = Some(dir.to_path_buf());
125 panic!("a test failing with a scratch directory in hand");
126 });
127 let path = seen.lock().expect("the lock").clone().expect("it ran");
128 assert!(!path.exists(), "a panicking test leaves nothing behind");
129 }
130}