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
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
55
#![warn(unnameable_types)]
56

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

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

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

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

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

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

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

            
168
203
        Self::from_complete_item_path(&path)
169
203
    }
170

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

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

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

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

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

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

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

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

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

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

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

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

            
309
25
            f(dir)
310
25
        })
311
25
    }
312
}
313

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

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

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

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