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
#![warn(clippy::cognitive_complexity)]
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
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
48

            
49
// We have a nonstandard test lint block
50
#![allow(clippy::print_stdout)]
51

            
52
use std::env::{self, VarError};
53
use std::fs;
54
use std::io::{self, ErrorKind};
55
use std::marker::PhantomData;
56
use std::path::{Path, PathBuf};
57

            
58
use anyhow::{Context as _, anyhow};
59
use derive_more::{Deref, DerefMut};
60
use educe::Educe;
61

            
62
/// The env var the user should set to control test temp dir handling
63
const RETAIN_VAR: &str = "TEST_TEMP_RETAIN";
64

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

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

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

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

            
163
175
        Self::from_complete_item_path(&path)
164
175
    }
165

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

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

            
179
        #[allow(clippy::needless_borrow)] // borrow not needed if we didn't rebind
180
175
        Self::from_stable_unique_subdir(&subdir)
181
175
    }
182

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

            
210
        let dir = {
211
            let mut dir = target;
212
            dir.push(subdir);
213
            dir
214
        };
215

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

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

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

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

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

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

            
298
48
            match fs::create_dir(&dir) {
299
14
                Err(e) if e.kind() == ErrorKind::AlreadyExists => Ok(()),
300
34
                other => other,
301
            }
302
48
            .expect("create subdir");
303

            
304
48
            f(dir)
305
48
        })
306
48
    }
307
}
308

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

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

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

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