1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// We have a nonstandard test lint block
53
#![allow(clippy::print_stdout)]
54

            
55
use std::env::{self, VarError};
56
use std::fs;
57
use std::io::{self, ErrorKind};
58
use std::marker::PhantomData;
59
use std::path::{Path, PathBuf};
60

            
61
use anyhow::{Context as _, anyhow};
62
use derive_more::{Deref, DerefMut};
63
use educe::Educe;
64

            
65
/// The env var the user should set to control test temp dir handling
66
const RETAIN_VAR: &str = "TEST_TEMP_RETAIN";
67

            
68
/// Directory for a test to store temporary files
69
///
70
/// Automatically deleted (if appropriate) when dropped.
71
#[derive(Debug)]
72
#[non_exhaustive]
73
pub enum TestTempDir {
74
    /// An ephemeral directory
75
    Ephemeral(tempfile::TempDir),
76
    /// A directory which should persist after the test completes
77
    Persistent(PathBuf),
78
}
79

            
80
/// A `T` which relies on some temporary directory with lifetime `d`
81
///
82
/// Obtained from `TestTempDir::used_by`.
83
///
84
/// Using this type means that the `T` won't outlive the temporary directory.
85
/// (Typically, if it were to, things would malfunction.
86
/// There might even be security hazards!)
87
#[derive(Clone, Copy, Deref, DerefMut, Educe)]
88
#[educe(Debug(bound))]
89
pub struct TestTempDirGuard<'d, T> {
90
    /// The thing
91
    #[deref]
92
    #[deref_mut]
93
    thing: T,
94

            
95
    /// Placate the compiler
96
    ///
97
    /// We use a notional `()` since we don't want the compiler to infer drop glue.
98
    #[educe(Debug(ignore))]
99
    tempdir: PhantomData<&'d ()>,
100
}
101

            
102
impl TestTempDir {
103
    /// Obtain a temp dir named after our thread, and the module path `mod_path`
104
    ///
105
    /// Expects that the current thread name is the module path within the crate,
106
    /// followed by the test function name.
107
    /// (This is how Rust's builtin `#[test]` names its threads.)
108
    // This is also used by some other crates.
109
    // If it turns out not to be true, we'll end up panicking.
110
    //
111
    // This is rather a shonky approach.  We take it here for the following reasons:
112
    //
113
    // It is important that the persistent test output filename is stable,
114
    // even if the source code is edited.  For example, if we used the line number
115
    // of the macro call, editing the source would change the output filenames.
116
    // When the output filenames change willy-nilly, it is very easy to accidentally
117
    // look at an out-of-date filename containing out-of-date test data,
118
    // which can be very confusing.
119
    //
120
    // We could ask the user to supply a string, but we'd then need
121
    // some kind of contraption for verifying its uniqueness, since
122
    // non-unique test names would risk tests overwriting each others'
123
    // files, making for flaky or malfunctioning tests.
124
    //
125
    // So the test function name is the best stable identifier we have,
126
    // and the thread name is the only way we have of discovering it.
127
    // Happily this works with `cargo nextest` too.
128
    //
129
    // For the same reasons, it wouldn't be a good idea to fall back
130
    // from the stable name to some less stable but more reliably obtainable id.
131
    //
132
    // And, the code structure is deliberately arranged that we *always*
133
    // try to determine the test name, even if TEST_TEMP_RETAIN isn't set.
134
    // Otherwise a latent situation, where TEST_TEMP_RETAIN doesn't work, could develop.
135
    //
136
    /// And, expects that `mod_path` is the crate name,
137
    /// and then the module path within the crate.
138
    /// This is what Rust's builtin `module_path!` macro returns.
139
    ///
140
    /// The two instances of the module path within the crate must be the same!
141
    ///
142
    /// # Panics
143
    ///
144
    /// Panics if the thread name and `mod_path` do not correspond
145
    /// (see the [self](module-level documentation).)
146
203
    pub fn from_module_path_and_thread(mod_path: &str) -> TestTempDir {
147
203
        let path = (|| {
148
203
            let (crate_, m_mod) = mod_path
149
203
                .split_once("::")
150
203
                .ok_or_else(|| anyhow!("module path {:?} doesn't contain `::`", mod_path))?;
151
203
            let thread = std::thread::current();
152
203
            let thread = thread.name().context("get current thread name")?;
153
203
            let (t_mod, fn_) = thread
154
203
                .rsplit_once("::")
155
203
                .ok_or_else(|| anyhow!("current thread name {:?} doesn't contain `::`", thread))?;
156
203
            if m_mod != t_mod {
157
                return Err(anyhow!(
158
 "module path {:?} implies module name {:?} but thread name {:?} implies module name {:?}",
159
                    mod_path, m_mod, thread, t_mod
160
                ));
161
203
            }
162
203
            Ok::<_, anyhow::Error>(format!("{crate_}::{m_mod}::{fn_}"))
163
        })()
164
203
        .expect("unable to calculate complete test function path");
165

            
166
203
        Self::from_complete_item_path(&path)
167
203
    }
168

            
169
    /// Obtains a temp dir named after a complete item path
170
    ///
171
    /// The supplied `item_path` must be globally unique in the whole workspace,
172
    /// or it might collide with other tests from other crates.
173
    ///
174
    /// Handles the replacement of `::` with `,` on Windows.
175
203
    pub fn from_complete_item_path(item_path: &str) -> Self {
176
203
        let subdir = item_path;
177

            
178
        // Operating systems that can't have `::` in pathnames
179
        #[cfg(target_os = "windows")]
180
        let subdir = subdir.replace("::", ",");
181

            
182
        #[allow(clippy::needless_borrow)] // borrow not needed if we didn't rebind
183
203
        Self::from_stable_unique_subdir(&subdir)
184
203
    }
185

            
186
    /// Obtains a temp dir given a stable unique subdirectory name
187
    ///
188
    /// The supplied `subdir` must be globally unique
189
    /// across every test in the whole workspace,
190
    /// or it might collide with other tests.
191
203
    pub fn from_stable_unique_subdir(subdir: &str) -> Self {
192
203
        let retain = env::var(RETAIN_VAR);
193
203
        let retain = match &retain {
194
            Ok(y) => y,
195
            Err(VarError::NotPresent) => "0",
196
            Err(VarError::NotUnicode(_)) => panic!("{} not unicode", RETAIN_VAR),
197
        };
198
203
        let target: PathBuf = if retain == "0" {
199
203
            println!("test {subdir}: {RETAIN_VAR} not enabled, using ephemeral temp dir");
200
203
            let dir = tempfile::tempdir().expect("failed to create temp dir");
201
203
            return TestTempDir::Ephemeral(dir);
202
        } else if retain.starts_with('.') || retain.starts_with('/') {
203
            retain.into()
204
        } else if retain == "1" {
205
            let target = env::var_os("CARGO_TARGET_DIR").unwrap_or_else(|| "target".into());
206
            let mut dir = PathBuf::from(target);
207
            dir.push("test");
208
            dir
209
        } else {
210
            panic!("invalid value for {}: {:?}", RETAIN_VAR, retain)
211
        };
212

            
213
        let dir = {
214
            let mut dir = target;
215
            dir.push(subdir);
216
            dir
217
        };
218

            
219
        let dir_display_lossy;
220
        #[allow(clippy::disallowed_methods)]
221
        {
222
            dir_display_lossy = dir.display();
223
        }
224
        println!("test {subdir}, temp dir is {}", dir_display_lossy);
225

            
226
        match fs::remove_dir_all(&dir) {
227
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
228
            other => other,
229
        }
230
        .expect("pre-remove temp dir");
231
        fs::create_dir_all(&dir).expect("create temp dir");
232
        TestTempDir::Persistent(dir)
233
203
    }
234

            
235
    /// Obtain a reference to the `Path` of this temp directory
236
    ///
237
    /// Prefer to use [`.used_by()`](TestTempDir::used_by) where possible.
238
    ///
239
    /// The lifetime of the temporary directory will not be properly represented
240
    /// by Rust lifetimes.  For example, calling
241
    /// `.to_owned()`[ToOwned::to_owned]
242
    /// will get a `'static` value,
243
    /// which doesn't represent the fact that the directory will go away
244
    /// when the `TestTempDir` is dropped.
245
    ///
246
    /// So the resulting value can be passed to functions which
247
    /// store the path for later use, and might later malfunction because
248
    /// the `TestTempDir` is dropped too early.
249
819
    pub fn as_path_untracked(&self) -> &Path {
250
819
        match self {
251
819
            TestTempDir::Ephemeral(t) => t.as_ref(),
252
            TestTempDir::Persistent(t) => t.as_ref(),
253
        }
254
819
    }
255

            
256
    /// Return a subdirectory, without lifetime tracking
257
56
    pub fn subdir_untracked(&self, subdir: &str) -> PathBuf {
258
56
        let mut r = self.as_path_untracked().to_owned();
259
56
        r.push(subdir);
260
56
        r
261
56
    }
262

            
263
    /// Obtain a `T` which uses paths in `self`
264
    ///
265
    /// Within `f`, construct `T` using the supplied filesystem path,
266
    /// which is the full path to the test's temporary directory.
267
    ///
268
    /// Do not store or copy the path anywhere other than the return value;
269
    /// such copies would not be protected by Rust lifetimes against early deletion.
270
    ///
271
    /// Rust lifetime tracking ensures that the temporary directory
272
    /// won't be cleaned up until the `T` is destroyed.
273
    #[allow(clippy::needless_lifetimes)] // explicit lifetimes for clarity (and symmetry)
274
46
    pub fn used_by<'d, T>(&'d self, f: impl FnOnce(&Path) -> T) -> TestTempDirGuard<'d, T> {
275
46
        let thing = f(self.as_path_untracked());
276
46
        TestTempDirGuard::with_path(thing, self.as_path_untracked())
277
46
    }
278

            
279
    /// Obtain a `T` which uses paths in a subdir of `self`
280
    ///
281
    /// The directory `subdir` will be created,
282
    /// within the test's temporary directory,
283
    /// if it doesn't already exist.
284
    ///
285
    /// Within `f`, construct `T` using the supplied filesystem path,
286
    /// which is the fuill path to the subdirectory.
287
    ///
288
    /// Do not store or copy the path anywhere other than the return value;
289
    /// such copies would not be protected by Rust lifetimes against early deletion.
290
    ///
291
    /// Rust lifetime tracking ensures that the temporary directory
292
    /// won't be cleaned up until the `T` is destroyed.
293
25
    pub fn subdir_used_by<'d, T>(
294
25
        &'d self,
295
25
        subdir: &str,
296
25
        f: impl FnOnce(PathBuf) -> T,
297
25
    ) -> TestTempDirGuard<'d, T> {
298
25
        self.used_by(|dir| {
299
25
            let dir = dir.join(subdir);
300

            
301
25
            match fs::create_dir(&dir) {
302
7
                Err(e) if e.kind() == ErrorKind::AlreadyExists => Ok(()),
303
18
                other => other,
304
            }
305
25
            .expect("create subdir");
306

            
307
25
            f(dir)
308
25
        })
309
25
    }
310
}
311

            
312
impl<'d, T> TestTempDirGuard<'d, T> {
313
    /// Obtain the inner `T`
314
    ///
315
    /// It is up to you to ensure that `T` doesn't outlive
316
    /// the temp directory used to create it.
317
5
    pub fn into_untracked(self) -> T {
318
5
        self.thing
319
5
    }
320

            
321
    /// Create from a `T` and a `&Path` with the right lifetime
322
46
    pub fn with_path(thing: T, _path: &'d Path) -> Self {
323
46
        Self::new_untracked(thing)
324
46
    }
325

            
326
    /// Create from a raw `T`
327
    ///
328
    /// The returned lifetime is unfounded!
329
    /// It is up to you to ensure that the inferred lifetime is correct!
330
46
    pub fn new_untracked(thing: T) -> Self {
331
46
        Self {
332
46
            thing,
333
46
            tempdir: PhantomData,
334
46
        }
335
46
    }
336
}
337

            
338
/// Obtain a `TestTempDir` for the current test
339
///
340
/// Must be called in the same thread as the actual `#[test]` entrypoint!
341
///
342
/// **`fn test_temp_dir() -> TestTempDir;`**
343
#[macro_export]
344
macro_rules! test_temp_dir { {} => {
345
    $crate::TestTempDir::from_module_path_and_thread(module_path!())
346
} }