1
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![cfg_attr(not(ci_arti_stable), allow(renamed_and_removed_lints))]
5
#![cfg_attr(not(ci_arti_nightly), allow(unknown_lints))]
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_duration_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
38
#![allow(clippy::uninlined_format_args)]
39
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
40
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
41
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
42
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
43

            
44
// We have a nonstandard test lint block
45
#![allow(clippy::print_stdout)]
46

            
47
use std::env::{self, VarError};
48
use std::fs;
49
use std::io::{self, ErrorKind};
50
use std::marker::PhantomData;
51
use std::path::{Path, PathBuf};
52

            
53
use anyhow::{anyhow, Context as _};
54
use derive_more::{Deref, DerefMut};
55
use educe::Educe;
56

            
57
/// The env var the user should set to control test temp dir handling
58
const RETAIN_VAR: &str = "TEST_TEMP_RETAIN";
59

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

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

            
87
    /// Placate the compiler
88
    ///
89
    /// We use a notional `()` since we don't want the compiler to infer drop glue.
90
    #[educe(Debug(ignore))]
91
    tempdir: PhantomData<&'d ()>,
92
}
93

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

            
158
        Self::from_complete_item_path(&path)
159
    }
160

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

            
170
        // Operating systems that can't have `::` in pathnames
171
        #[cfg(target_os = "windows")]
172
        let subdir = subdir.replace("::", ",");
173

            
174
        #[allow(clippy::needless_borrow)] // borrow not needed if we didn't rebind
175
        Self::from_stable_unique_subdir(&subdir)
176
    }
177

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

            
205
        let dir = {
206
            let mut dir = target;
207
            dir.push(subdir);
208
            dir
209
        };
210

            
211
        let dir_display_lossy;
212
        #[allow(clippy::disallowed_methods)]
213
        {
214
            dir_display_lossy = dir.display();
215
        }
216
        println!("test {subdir}, temp dir is {}", dir_display_lossy);
217

            
218
        match fs::remove_dir_all(&dir) {
219
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
220
            other => other,
221
        }
222
        .expect("pre-remove temp dir");
223
        fs::create_dir_all(&dir).expect("create temp dir");
224
        TestTempDir::Persistent(dir)
225
    }
226

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

            
248
    /// Return a subdirectory, without lifetime tracking
249
    pub fn subdir_untracked(&self, subdir: &str) -> PathBuf {
250
        let mut r = self.as_path_untracked().to_owned();
251
        r.push(subdir);
252
        r
253
    }
254

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

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

            
293
            match fs::create_dir(&dir) {
294
                Err(e) if e.kind() == ErrorKind::AlreadyExists => Ok(()),
295
                other => other,
296
            }
297
            .expect("create subdir");
298

            
299
            f(dir)
300
        })
301
    }
302
}
303

            
304
impl<'d, T> TestTempDirGuard<'d, T> {
305
    /// Obtain the inner `T`
306
    ///
307
    /// It is up to you to ensure that `T` doesn't outlive
308
    /// the temp directory used to create it.
309
    pub fn into_untracked(self) -> T {
310
        self.thing
311
    }
312

            
313
    /// Create from a `T` and a `&Path` with the right lifetime
314
    pub fn with_path(thing: T, _path: &'d Path) -> Self {
315
        Self::new_untracked(thing)
316
    }
317

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

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