forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

scratch.rs190 lines, 7.6 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. A test the kernel *aborts* never unwinds and so never
11//! drops anything; [`reap_orphans`] takes those on the next run instead.
12//!
13//! Nothing outside a test has any use for this. It lives in the library rather
14//! than in a test file because the integration suites, the unit tests here and
15//! the app's own tests all need the same guard, and none of them can see each
16//! other's modules.
17
18use std::ffi::OsStr;
19use std::ops::Deref;
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicU64, Ordering};
22
23/// A temporary directory and the path a test uses inside it, gone when the
24/// value is.
25#[derive(Debug)]
26pub struct Scratch {
27 dir: PathBuf,
28 path: PathBuf,
29}
30
31/// A fresh, empty directory under the system temporary one. `name` leads it so
32/// it is recognisable while a test is stopped in it; the process id and a
33/// counter follow, because two suites (or two tests of one suite, in parallel)
34/// must not write each other's files. Canonical, because saved projects hold
35/// paths relative to their own directory and `Project` canonicalises what it is
36/// handed.
37fn fresh(name: &str) -> PathBuf {
38 static NTH: AtomicU64 = AtomicU64::new(0);
39 static REAP: std::sync::Once = std::sync::Once::new();
40 REAP.call_once(reap_orphans);
41 let dir = std::env::temp_dir().join(format!(
42 "{name}_{}_{}",
43 std::process::id(),
44 NTH.fetch_add(1, Ordering::Relaxed)
45 ));
46 let _ = std::fs::remove_dir_all(&dir);
47 std::fs::create_dir_all(&dir).expect("scratch dir");
48 std::fs::canonicalize(&dir).expect("canonical scratch dir")
49}
50
51/// The one leak `Drop` cannot reach: a test the kernel *aborts* -- the AV1
52/// hardware encoder does it whenever the driver's ring hangs -- never unwinds,
53/// so its directory outlives it. The name carries the process id that made it,
54/// so a later run can tell an orphan from a directory a live sibling suite is
55/// still writing into, and takes only the orphans. Once per process, before the
56/// first scratch directory of it: the suites are what fills `/tmp`, and they all
57/// come through here.
58fn reap_orphans() {
59 let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else {
60 return;
61 };
62 if !Path::new("/proc").is_dir() {
63 return; // No way to ask whether the owner is still running: take nothing.
64 }
65 for entry in entries.flatten() {
66 let name = entry.file_name();
67 let Some(name) = name.to_str() else { continue };
68 // `ve_<what>_<pid>_<nth>`, and nothing else, ever.
69 let mut tail = name.rsplitn(3, '_');
70 let (Some(nth), Some(pid), Some(head)) = (tail.next(), tail.next(), tail.next()) else {
71 continue;
72 };
73 if !head.starts_with("ve_") || nth.parse::<u64>().is_err() {
74 continue;
75 }
76 let Ok(pid) = pid.parse::<u64>() else { continue };
77 if Path::new("/proc").join(pid.to_string()).exists() {
78 continue; // Still running: its own `Drop` will do this.
79 }
80 let _ = std::fs::remove_dir_all(entry.path());
81 }
82}
83
84impl Scratch {
85 /// A directory to litter: the value *is* the directory.
86 pub fn dir(name: &str) -> Self {
87 let dir = fresh(name);
88 Self {
89 path: dir.clone(),
90 dir,
91 }
92 }
93
94 /// A path for the one file a test writes, `name.ext`, alone in a directory
95 /// of its own. Nothing creates it -- what is under test is what writes it,
96 /// and several of these tests are about a file that must *not* appear.
97 pub fn file(name: &str, ext: &str) -> Self {
98 let dir = fresh(name);
99 let path = dir.join(format!("{name}.{ext}"));
100 Self { dir, path }
101 }
102}
103
104impl Deref for Scratch {
105 type Target = Path;
106
107 fn deref(&self) -> &Path {
108 &self.path
109 }
110}
111
112impl AsRef<Path> for Scratch {
113 fn as_ref(&self) -> &Path {
114 &self.path
115 }
116}
117
118/// So one of these can be handed to a `Command` as an argument, which is how
119/// the suites that check our output with ffmpeg name the file.
120impl AsRef<OsStr> for Scratch {
121 fn as_ref(&self) -> &OsStr {
122 self.path.as_os_str()
123 }
124}
125
126impl Drop for Scratch {
127 fn drop(&mut self) {
128 let _ = std::fs::remove_dir_all(&self.dir);
129 }
130}
131
132#[cfg(test)]
133mod tests {
134 use super::{Scratch, reap_orphans};
135
136 /// What an aborted test leaves goes on the next run's account: its
137 /// directory is taken, a live process's is not, and nothing that is not
138 /// ours is touched whatever it is named.
139 #[test]
140 fn the_next_run_takes_what_an_aborted_one_left() {
141 let tmp = std::env::temp_dir();
142 // No process has this id: `pid_max` is an exclusive bound everywhere.
143 let orphan = tmp.join("ve_scratch_orphan_4294967295_0");
144 let mine = tmp.join(format!("ve_scratch_live_{}_9999", std::process::id()));
145 let theirs = tmp.join("someone_elses_4294967295_0");
146 for dir in [&orphan, &mine, &theirs] {
147 std::fs::create_dir_all(dir).expect("a directory to reap");
148 }
149
150 reap_orphans();
151
152 assert!(!orphan.exists(), "the aborted run's directory is gone");
153 assert!(mine.is_dir(), "a running suite's own directory is left alone");
154 assert!(theirs.is_dir(), "and so is everything that is not ours");
155 for dir in [&mine, &theirs] {
156 std::fs::remove_dir_all(dir).expect("cleanup");
157 }
158 }
159
160 /// The guard's whole job, both shapes: what it hands back is usable, and
161 /// what it made is gone once it is -- including when a test panicked, which
162 /// is the case that leaked.
163 #[test]
164 fn a_scratch_takes_its_directory_with_it() {
165 let (dir, file) = (Scratch::dir("ve_scratch_dir"), Scratch::file("ve_scratch", "mp4"));
166 assert!(dir.is_dir(), "a directory to litter, ready to use");
167 std::fs::write(dir.join("a.txt"), b"litter").expect("write into it");
168 assert!(!file.exists(), "the file itself is the test's to write");
169 assert!(file.parent().expect("inside a directory").is_dir());
170 assert_eq!(file.extension().and_then(|e| e.to_str()), Some("mp4"));
171
172 let (left, right) = (dir.to_path_buf(), file.parent().unwrap().to_path_buf());
173 assert_ne!(left, right, "one directory each, never shared");
174 drop((dir, file));
175 assert!(!left.exists(), "the directory went with the guard");
176 assert!(!right.exists(), "and so did the file's");
177
178 // Unwinding runs `Drop`, so a failing test cleans up like a passing one.
179 // The panic below is this test's own and is meant to reach stderr.
180 let seen = std::sync::Mutex::new(None);
181 let _ = std::panic::catch_unwind(|| {
182 let dir = Scratch::dir("ve_scratch_panic");
183 std::fs::write(dir.join("a.txt"), b"litter").expect("write into it");
184 *seen.lock().expect("the lock") = Some(dir.to_path_buf());
185 panic!("a test failing with a scratch directory in hand");
186 });
187 let path = seen.lock().expect("the lock").clone().expect("it ran");
188 assert!(!path.exists(), "a panicking test leaves nothing behind");
189 }
190}