Skip to main content

cargo_test_support/
lib.rs

1//! # Cargo test support.
2//!
3//! See <https://rust-lang.github.io/cargo/contrib/> for a guide on writing tests.
4//!
5//! There are two places you can find API documentation
6//!
7//! - <https://docs.rs/cargo-test-support>:
8//!   targeted at external tool developers testing cargo-related code
9//!   - Released with every rustc release
10//! - <https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_support>:
11//!   targeted at cargo contributors
12//!   - Updated on each update of the `cargo` submodule in `rust-lang/rust`
13//!
14//! > This crate is maintained by the Cargo team, primarily for use by Cargo
15//! > and not intended for external use. This
16//! > crate may make major changes to its APIs or be deprecated without warning.
17//!
18//! # Example
19//!
20//! ```rust,no_run
21//! use cargo_test_support::prelude::*;
22//! use cargo_test_support::str;
23//! use cargo_test_support::project;
24//!
25//! #[cargo_test]
26//! fn some_test() {
27//!     let p = project()
28//!         .file("src/main.rs", r#"fn main() { println!("hi!"); }"#)
29//!         .build();
30//!
31//!     p.cargo("run --bin foo")
32//!         .with_stderr_data(str![[r#"
33//! [COMPILING] foo [..]
34//! [FINISHED] [..]
35//! [RUNNING] `target/debug/foo`
36//! "#]])
37//!         .with_stdout_data(str![["hi!"]])
38//!         .run();
39//! }
40//! ```
41
42#![allow(clippy::disallowed_methods)]
43#![allow(clippy::disallowed_types)]
44#![allow(clippy::print_stderr)]
45#![allow(clippy::print_stdout)]
46
47use std::env;
48use std::ffi::OsStr;
49use std::fmt::Write;
50use std::fs;
51use std::os;
52use std::path::{Path, PathBuf};
53use std::process::{Command, Output};
54use std::sync::LazyLock;
55use std::sync::OnceLock;
56use std::thread::JoinHandle;
57use std::time::{self, Duration};
58
59use anyhow::{Result, bail};
60use cargo_util::{ProcessError, is_ci};
61use snapbox::IntoData as _;
62use url::Url;
63
64use self::paths::CargoPathExt;
65
66/// Unwrap a `Result` with a useful panic message
67///
68/// # Example
69///
70/// ```rust
71/// use cargo_test_support::t;
72/// t!(std::fs::read_to_string("Cargo.toml"));
73/// ```
74#[macro_export]
75macro_rules! t {
76    ($e:expr) => {
77        match $e {
78            Ok(e) => e,
79            Err(e) => $crate::panic_error(&format!("failed running {}", stringify!($e)), e),
80        }
81    };
82}
83
84pub use cargo_util::ProcessBuilder;
85#[doc(inline)]
86pub use snapbox;
87pub use snapbox::file;
88pub use snapbox::str;
89pub use snapbox::utils::current_dir;
90
91/// `panic!`, reporting the specified error , see also [`t!`]
92#[track_caller]
93pub fn panic_error(what: &str, err: impl Into<anyhow::Error>) -> ! {
94    let err = err.into();
95    pe(what, err);
96    #[track_caller]
97    fn pe(what: &str, err: anyhow::Error) -> ! {
98        let mut result = format!("{}\nerror: {}", what, err);
99        for cause in err.chain().skip(1) {
100            let _ = writeln!(result, "\nCaused by:");
101            let _ = write!(result, "{}", cause);
102        }
103        panic!("\n{}", result);
104    }
105}
106
107pub use cargo_test_macro::cargo_test;
108
109pub mod compare;
110pub mod containers;
111pub mod cross_compile;
112pub mod git;
113pub mod install;
114pub mod paths;
115pub mod publish;
116pub mod registry;
117
118pub mod prelude {
119    pub use crate::ArgLineCommandExt;
120    pub use crate::ChannelChangerCommandExt;
121    pub use crate::TestEnvCommandExt;
122    pub use crate::cargo_test;
123    pub use crate::paths::CargoPathExt;
124    pub use snapbox::IntoData;
125}
126
127/*
128 *
129 * ===== Builders =====
130 *
131 */
132
133#[derive(PartialEq, Clone)]
134struct FileBuilder {
135    path: PathBuf,
136    body: String,
137    executable: bool,
138}
139
140impl FileBuilder {
141    pub fn new(path: PathBuf, body: &str, executable: bool) -> FileBuilder {
142        FileBuilder {
143            path,
144            body: body.to_string(),
145            executable: executable,
146        }
147    }
148
149    fn mk(&mut self) {
150        if self.executable {
151            let mut path = self.path.clone().into_os_string();
152            write!(path, "{}", env::consts::EXE_SUFFIX).unwrap();
153            self.path = path.into();
154        }
155
156        self.dirname().mkdir_p();
157        fs::write(&self.path, &self.body)
158            .unwrap_or_else(|e| panic!("could not create file {}: {}", self.path.display(), e));
159
160        #[cfg(unix)]
161        if self.executable {
162            use std::os::unix::fs::PermissionsExt;
163
164            let mut perms = fs::metadata(&self.path).unwrap().permissions();
165            let mode = perms.mode();
166            perms.set_mode(mode | 0o111);
167            fs::set_permissions(&self.path, perms).unwrap();
168        }
169    }
170
171    fn dirname(&self) -> &Path {
172        self.path.parent().unwrap()
173    }
174}
175
176#[derive(PartialEq, Clone)]
177struct SymlinkBuilder {
178    dst: PathBuf,
179    src: PathBuf,
180    src_is_dir: bool,
181}
182
183impl SymlinkBuilder {
184    pub fn new(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
185        SymlinkBuilder {
186            dst,
187            src,
188            src_is_dir: false,
189        }
190    }
191
192    pub fn new_dir(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
193        SymlinkBuilder {
194            dst,
195            src,
196            src_is_dir: true,
197        }
198    }
199
200    #[cfg(unix)]
201    fn mk(&self) {
202        self.dirname().mkdir_p();
203        t!(os::unix::fs::symlink(&self.dst, &self.src));
204    }
205
206    #[cfg(windows)]
207    fn mk(&mut self) {
208        self.dirname().mkdir_p();
209        if self.src_is_dir {
210            t!(os::windows::fs::symlink_dir(&self.dst, &self.src));
211        } else {
212            if let Some(ext) = self.dst.extension() {
213                if ext == env::consts::EXE_EXTENSION {
214                    self.src.set_extension(ext);
215                }
216            }
217            t!(os::windows::fs::symlink_file(&self.dst, &self.src));
218        }
219    }
220
221    fn dirname(&self) -> &Path {
222        self.src.parent().unwrap()
223    }
224}
225
226/// A cargo project to run tests against.
227///
228/// See [`ProjectBuilder`] or [`Project::from_template`] to get started.
229pub struct Project {
230    root: PathBuf,
231}
232
233/// Create a project to run tests against
234///
235/// - Creates a [`basic_manifest`] if one isn't supplied
236///
237/// To get started, see:
238/// - [`project`]
239/// - [`project_in`]
240/// - [`project_in_home`]
241/// - [`Project::from_template`]
242#[must_use]
243pub struct ProjectBuilder {
244    root: Project,
245    files: Vec<FileBuilder>,
246    symlinks: Vec<SymlinkBuilder>,
247    no_manifest: bool,
248}
249
250impl ProjectBuilder {
251    /// Root of the project
252    ///
253    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo`
254    pub fn root(&self) -> PathBuf {
255        self.root.root()
256    }
257
258    /// Project's debug dir
259    ///
260    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target/debug`
261    pub fn target_debug_dir(&self) -> PathBuf {
262        self.root.target_debug_dir()
263    }
264
265    /// Create project in `root`
266    pub fn new(root: PathBuf) -> ProjectBuilder {
267        ProjectBuilder {
268            root: Project { root },
269            files: vec![],
270            symlinks: vec![],
271            no_manifest: false,
272        }
273    }
274
275    /// Create project, relative to [`paths::root`]
276    pub fn at<P: AsRef<Path>>(mut self, path: P) -> Self {
277        self.root = Project {
278            root: paths::root().join(path),
279        };
280        self
281    }
282
283    /// Adds a file to the project.
284    pub fn file<B: AsRef<Path>>(mut self, path: B, body: &str) -> Self {
285        self._file(path.as_ref(), body, false);
286        self
287    }
288
289    /// Adds an executable file to the project.
290    pub fn executable<B: AsRef<Path>>(mut self, path: B, body: &str) -> Self {
291        self._file(path.as_ref(), body, true);
292        self
293    }
294
295    fn _file(&mut self, path: &Path, body: &str, executable: bool) {
296        self.files.push(FileBuilder::new(
297            self.root.root().join(path),
298            body,
299            executable,
300        ));
301    }
302
303    /// Adds a symlink to a file to the project.
304    pub fn symlink(mut self, dst: impl AsRef<Path>, src: impl AsRef<Path>) -> Self {
305        self.symlinks.push(SymlinkBuilder::new(
306            self.root.root().join(dst),
307            self.root.root().join(src),
308        ));
309        self
310    }
311
312    /// Create a symlink to a directory
313    pub fn symlink_dir(mut self, dst: impl AsRef<Path>, src: impl AsRef<Path>) -> Self {
314        self.symlinks.push(SymlinkBuilder::new_dir(
315            self.root.root().join(dst),
316            self.root.root().join(src),
317        ));
318        self
319    }
320
321    pub fn no_manifest(mut self) -> Self {
322        self.no_manifest = true;
323        self
324    }
325
326    /// Creates the project.
327    pub fn build(mut self) -> Project {
328        // First, clean the directory if it already exists
329        self.rm_root();
330
331        // Create the empty directory
332        self.root.root().mkdir_p();
333
334        let manifest_path = self.root.root().join("Cargo.toml");
335        if !self.no_manifest && self.files.iter().all(|fb| fb.path != manifest_path) {
336            self._file(
337                Path::new("Cargo.toml"),
338                &basic_manifest("foo", "0.0.1"),
339                false,
340            )
341        }
342
343        let past = time::SystemTime::now() - Duration::new(1, 0);
344        let ftime = filetime::FileTime::from_system_time(past);
345        let times = fs::FileTimes::new()
346            .set_accessed(ftime.into())
347            .set_modified(ftime.into());
348
349        for file in self.files.iter_mut() {
350            file.mk();
351            if is_coarse_mtime() {
352                // Place the entire project 1 second in the past to ensure
353                // that if cargo is called multiple times, the 2nd call will
354                // see targets as "fresh". Without this, if cargo finishes in
355                // under 1 second, the second call will see the mtime of
356                // source == mtime of output and consider it dirty.
357                fs::set_times(&file.path, times).unwrap();
358            }
359        }
360
361        for symlink in self.symlinks.iter_mut() {
362            symlink.mk();
363        }
364
365        let ProjectBuilder { root, .. } = self;
366        root
367    }
368
369    fn rm_root(&self) {
370        self.root.root().rm_rf()
371    }
372}
373
374impl Project {
375    /// Copy the test project from a fixed state
376    pub fn from_template(template_path: impl AsRef<Path>) -> Self {
377        let root = paths::root();
378        let project_root = root.join("case");
379        snapbox::dir::copy_template(template_path.as_ref(), &project_root).unwrap();
380        Self { root: project_root }
381    }
382
383    /// Root of the project
384    ///
385    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo`
386    pub fn root(&self) -> PathBuf {
387        self.root.clone()
388    }
389
390    /// Project's target dir
391    ///
392    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target`
393    pub fn build_dir(&self) -> PathBuf {
394        self.root().join("target")
395    }
396
397    /// Project's debug dir
398    ///
399    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target/debug`
400    pub fn target_debug_dir(&self) -> PathBuf {
401        self.build_dir().join("debug")
402    }
403
404    /// File url for root
405    ///
406    /// ex: `file://$CARGO_TARGET_TMPDIR/cit/t0/foo`
407    pub fn url(&self) -> Url {
408        use paths::CargoPathExt;
409        self.root().to_url()
410    }
411
412    /// Path to an example built as a library.
413    ///
414    /// `kind` should be one of: "lib", "rlib", "staticlib", "dylib", "proc-macro"
415    ///
416    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target/debug/examples/libex.rlib`
417    pub fn example_lib(&self, name: &str, kind: &str) -> PathBuf {
418        self.target_debug_dir()
419            .join("examples")
420            .join(paths::get_lib_filename(name, kind))
421    }
422
423    /// Path to a dynamic library.
424    /// ex: `/path/to/cargo/target/cit/t0/foo/target/debug/examples/libex.dylib`
425    pub fn dylib(&self, name: &str) -> PathBuf {
426        self.target_debug_dir().join(format!(
427            "{}{name}{}",
428            env::consts::DLL_PREFIX,
429            env::consts::DLL_SUFFIX
430        ))
431    }
432
433    /// Path to a debug binary.
434    ///
435    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target/debug/foo`
436    pub fn bin(&self, b: &str) -> PathBuf {
437        self.build_dir()
438            .join("debug")
439            .join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
440    }
441
442    /// Path to a release binary.
443    ///
444    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target/release/foo`
445    pub fn release_bin(&self, b: &str) -> PathBuf {
446        self.build_dir()
447            .join("release")
448            .join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
449    }
450
451    /// Path to a debug binary for a specific target tuple.
452    ///
453    /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target/i686-apple-darwin/debug/foo`
454    pub fn target_bin(&self, target: &str, b: &str) -> PathBuf {
455        self.build_dir().join(target).join("debug").join(&format!(
456            "{}{}",
457            b,
458            env::consts::EXE_SUFFIX
459        ))
460    }
461
462    /// Returns an iterator of paths within [`Project::root`] matching the glob pattern
463    pub fn glob<P: AsRef<Path>>(&self, pattern: P) -> glob::Paths {
464        let pattern = self.root().join(pattern);
465        glob::glob(pattern.to_str().expect("failed to convert pattern to str"))
466            .expect("failed to glob")
467    }
468
469    /// Overwrite a file with new content
470    ///
471    // # Example:
472    ///
473    /// ```no_run
474    /// # let p = cargo_test_support::project().build();
475    /// p.change_file("src/lib.rs", "fn new_fn() {}");
476    /// ```
477    pub fn change_file(&self, path: impl AsRef<Path>, body: &str) {
478        FileBuilder::new(self.root().join(path), body, false).mk()
479    }
480
481    /// Creates a `ProcessBuilder` to run a program in the project
482    /// and wrap it in an Execs to assert on the execution.
483    ///
484    /// # Example:
485    ///
486    /// ```no_run
487    /// # use cargo_test_support::str;
488    /// # let p = cargo_test_support::project().build();
489    /// p.process(&p.bin("foo"))
490    ///     .with_stdout_data(str!["bar\n"])
491    ///     .run();
492    /// ```
493    pub fn process<T: AsRef<OsStr>>(&self, program: T) -> Execs {
494        let mut p = process(program);
495        p.cwd(self.root());
496        execs().with_process_builder(p)
497    }
498
499    /// Safely run a process after `cargo build`.
500    ///
501    /// Windows has a problem where a process cannot be reliably
502    /// be replaced, removed, or renamed immediately after executing it.
503    /// The action may fail (with errors like Access is denied), or
504    /// it may succeed, but future attempts to use the same filename
505    /// will fail with "Already Exists".
506    ///
507    /// If you have a test that needs to do `cargo run` multiple
508    /// times, you should instead use `cargo build` and use this
509    /// method to run the executable. Each time you call this,
510    /// use a new name for `dst`.
511    /// See rust-lang/cargo#5481.
512    pub fn rename_run(&self, src: &str, dst: &str) -> Execs {
513        let src = self.bin(src);
514        let dst = self.bin(dst);
515        fs::rename(&src, &dst)
516            .unwrap_or_else(|e| panic!("Failed to rename `{:?}` to `{:?}`: {}", src, dst, e));
517        self.process(dst)
518    }
519
520    /// Returns the contents of `Cargo.lock`.
521    pub fn read_lockfile(&self) -> String {
522        self.read_file("Cargo.lock")
523    }
524
525    /// Returns the contents of a path in the project root
526    pub fn read_file(&self, path: impl AsRef<Path>) -> String {
527        let full = self.root().join(path);
528        fs::read_to_string(&full)
529            .unwrap_or_else(|e| panic!("could not read file {}: {}", full.display(), e))
530    }
531
532    /// Modifies `Cargo.toml` to remove all commented lines.
533    pub fn uncomment_root_manifest(&self) {
534        let contents = self.read_file("Cargo.toml").replace("#", "");
535        fs::write(self.root().join("Cargo.toml"), contents).unwrap();
536    }
537
538    pub fn symlink(&self, src: impl AsRef<Path>, dst: impl AsRef<Path>) {
539        let src = self.root().join(src.as_ref());
540        let dst = self.root().join(dst.as_ref());
541        #[cfg(unix)]
542        {
543            if let Err(e) = os::unix::fs::symlink(&src, &dst) {
544                panic!("failed to symlink {:?} to {:?}: {:?}", src, dst, e);
545            }
546        }
547        #[cfg(windows)]
548        {
549            if src.is_dir() {
550                if let Err(e) = os::windows::fs::symlink_dir(&src, &dst) {
551                    panic!("failed to symlink {:?} to {:?}: {:?}", src, dst, e);
552                }
553            } else {
554                if let Err(e) = os::windows::fs::symlink_file(&src, &dst) {
555                    panic!("failed to symlink {:?} to {:?}: {:?}", src, dst, e);
556                }
557            }
558        }
559    }
560}
561
562/// Generates a project layout, see [`ProjectBuilder`]
563pub fn project() -> ProjectBuilder {
564    ProjectBuilder::new(paths::root().join("foo"))
565}
566
567/// Generates a project layout in given directory, see [`ProjectBuilder`]
568pub fn project_in(dir: impl AsRef<Path>) -> ProjectBuilder {
569    ProjectBuilder::new(paths::root().join(dir).join("foo"))
570}
571
572/// Generates a project layout inside our fake home dir, see [`ProjectBuilder`]
573pub fn project_in_home(name: impl AsRef<Path>) -> ProjectBuilder {
574    ProjectBuilder::new(paths::home().join(name))
575}
576
577// === Helpers ===
578
579/// Generate a `main.rs` printing the specified text
580///
581/// ```rust
582/// # use cargo_test_support::main_file;
583/// # mod dep {
584/// #     fn bar() -> &'static str {
585/// #         "world"
586/// #     }
587/// # }
588/// main_file(
589///     r#""hello {}", dep::bar()"#,
590///     &[]
591/// );
592/// ```
593pub fn main_file(println: &str, externed_deps: &[&str]) -> String {
594    let mut buf = String::new();
595
596    for dep in externed_deps.iter() {
597        buf.push_str(&format!("extern crate {};\n", dep));
598    }
599
600    buf.push_str("fn main() { println!(");
601    buf.push_str(println);
602    buf.push_str("); }\n");
603
604    buf
605}
606
607/// This is the raw output from the process.
608///
609/// This is similar to `std::process::Output`, however the `status` is
610/// translated to the raw `code`. This is necessary because `ProcessError`
611/// does not have access to the raw `ExitStatus` because `ProcessError` needs
612/// to be serializable (for the Rustc cache), and `ExitStatus` does not
613/// provide a constructor.
614pub struct RawOutput {
615    pub code: Option<i32>,
616    pub stdout: Vec<u8>,
617    pub stderr: Vec<u8>,
618}
619
620/// Run and verify a [`ProcessBuilder`]
621///
622/// Construct with
623/// - [`execs`]
624/// - [`Project`] methods
625/// - `cargo_process` in testsuite
626#[must_use]
627#[derive(Clone)]
628pub struct Execs {
629    ran: bool,
630    process_builder: Option<ProcessBuilder>,
631    expect_stdin: Option<String>,
632    expect_exit_code: Option<i32>,
633    expect_stdout_data: Option<snapbox::Data>,
634    expect_stderr_data: Option<snapbox::Data>,
635    expect_stdout_contains: Vec<String>,
636    expect_stderr_contains: Vec<String>,
637    expect_stdout_not_contains: Vec<String>,
638    expect_stderr_not_contains: Vec<String>,
639    expect_stderr_with_without: Vec<(Vec<String>, Vec<String>)>,
640    stream_output: bool,
641    assert: snapbox::Assert,
642}
643
644impl Execs {
645    pub fn with_process_builder(mut self, p: ProcessBuilder) -> Execs {
646        self.process_builder = Some(p);
647        self
648    }
649}
650
651/// # Configure assertions
652impl Execs {
653    /// Verifies that stdout is equal to the given lines.
654    ///
655    /// See [`compare::assert_e2e`] for assertion details.
656    ///
657    /// <div class="warning">
658    ///
659    /// Prefer passing in [`str!`] for `expected` to get snapshot updating.
660    ///
661    /// If `format!` is needed for content that changes from run to run that you don't care about,
662    /// consider whether you could have [`compare::assert_e2e`] redact the content.
663    /// If nothing else, a wildcard (`[..]`, `...`) may be useful.
664    ///
665    /// However, `""` may be preferred for intentionally empty output so people don't accidentally
666    /// bless a change.
667    ///
668    /// </div>
669    ///
670    /// # Examples
671    ///
672    /// ```no_run
673    /// use cargo_test_support::prelude::*;
674    /// use cargo_test_support::str;
675    /// use cargo_test_support::execs;
676    ///
677    /// execs().with_stdout_data(str![r#"
678    /// Hello world!
679    /// "#]);
680    /// ```
681    ///
682    /// Non-deterministic compiler output
683    /// ```no_run
684    /// use cargo_test_support::prelude::*;
685    /// use cargo_test_support::str;
686    /// use cargo_test_support::execs;
687    ///
688    /// execs().with_stdout_data(str![r#"
689    /// [COMPILING] foo
690    /// [COMPILING] bar
691    /// "#].unordered());
692    /// ```
693    ///
694    /// jsonlines
695    /// ```no_run
696    /// use cargo_test_support::prelude::*;
697    /// use cargo_test_support::str;
698    /// use cargo_test_support::execs;
699    ///
700    /// execs().with_stdout_data(str![r#"
701    /// [
702    ///   {},
703    ///   {}
704    /// ]
705    /// "#].is_json().against_jsonlines());
706    /// ```
707    pub fn with_stdout_data(&mut self, expected: impl snapbox::IntoData) -> &mut Self {
708        self.expect_stdout_data = Some(expected.into_data());
709        self
710    }
711
712    /// Verifies that stderr is equal to the given lines.
713    ///
714    /// See [`compare::assert_e2e`] for assertion details.
715    ///
716    /// <div class="warning">
717    ///
718    /// Prefer passing in [`str!`] for `expected` to get snapshot updating.
719    ///
720    /// If `format!` is needed for content that changes from run to run that you don't care about,
721    /// consider whether you could have [`compare::assert_e2e`] redact the content.
722    /// If nothing else, a wildcard (`[..]`, `...`) may be useful.
723    ///
724    /// However, `""` may be preferred for intentionally empty output so people don't accidentally
725    /// bless a change.
726    ///
727    /// </div>
728    ///
729    /// # Examples
730    ///
731    /// ```no_run
732    /// use cargo_test_support::prelude::*;
733    /// use cargo_test_support::str;
734    /// use cargo_test_support::execs;
735    ///
736    /// execs().with_stderr_data(str![r#"
737    /// Hello world!
738    /// "#]);
739    /// ```
740    ///
741    /// Non-deterministic compiler output
742    /// ```no_run
743    /// use cargo_test_support::prelude::*;
744    /// use cargo_test_support::str;
745    /// use cargo_test_support::execs;
746    ///
747    /// execs().with_stderr_data(str![r#"
748    /// [COMPILING] foo
749    /// [COMPILING] bar
750    /// "#].unordered());
751    /// ```
752    ///
753    /// jsonlines
754    /// ```no_run
755    /// use cargo_test_support::prelude::*;
756    /// use cargo_test_support::str;
757    /// use cargo_test_support::execs;
758    ///
759    /// execs().with_stderr_data(str![r#"
760    /// [
761    ///   {},
762    ///   {}
763    /// ]
764    /// "#].is_json().against_jsonlines());
765    /// ```
766    pub fn with_stderr_data(&mut self, expected: impl snapbox::IntoData) -> &mut Self {
767        self.expect_stderr_data = Some(expected.into_data());
768        self
769    }
770
771    /// Writes the given lines to stdin.
772    pub fn with_stdin<S: ToString>(&mut self, expected: S) -> &mut Self {
773        self.expect_stdin = Some(expected.to_string());
774        self
775    }
776
777    /// Verifies the exit code from the process.
778    ///
779    /// This is not necessary if the expected exit code is `0`.
780    pub fn with_status(&mut self, expected: i32) -> &mut Self {
781        self.expect_exit_code = Some(expected);
782        self
783    }
784
785    /// Removes exit code check for the process.
786    ///
787    /// By default, the expected exit code is `0`.
788    pub fn without_status(&mut self) -> &mut Self {
789        self.expect_exit_code = None;
790        self
791    }
792
793    /// Verifies that stdout contains the given contiguous lines somewhere in
794    /// its output.
795    ///
796    /// See [`compare`] for supported patterns.
797    ///
798    /// <div class="warning">
799    ///
800    /// Prefer [`Execs::with_stdout_data`] where possible.
801    /// - `expected` cannot be snapshotted
802    /// - `expected` can end up being ambiguous, causing the assertion to succeed when it should fail
803    ///
804    /// </div>
805    pub fn with_stdout_contains<S: ToString>(&mut self, expected: S) -> &mut Self {
806        self.expect_stdout_contains.push(expected.to_string());
807        self
808    }
809
810    /// Verifies that stderr contains the given contiguous lines somewhere in
811    /// its output.
812    ///
813    /// See [`compare`] for supported patterns.
814    ///
815    /// <div class="warning">
816    ///
817    /// Prefer [`Execs::with_stderr_data`] where possible.
818    /// - `expected` cannot be snapshotted
819    /// - `expected` can end up being ambiguous, causing the assertion to succeed when it should fail
820    ///
821    /// </div>
822    pub fn with_stderr_contains<S: ToString>(&mut self, expected: S) -> &mut Self {
823        self.expect_stderr_contains.push(expected.to_string());
824        self
825    }
826
827    /// Verifies that stdout does not contain the given contiguous lines.
828    ///
829    /// See [`compare`] for supported patterns.
830    ///
831    /// See note on [`Self::with_stderr_does_not_contain`].
832    ///
833    /// <div class="warning">
834    ///
835    /// Prefer [`Execs::with_stdout_data`] where possible.
836    /// - `expected` cannot be snapshotted
837    /// - The absence of `expected` can either mean success or that the string being looked for
838    ///   changed.
839    ///
840    /// To mitigate this, consider matching this up with
841    /// [`Execs::with_stdout_contains`].
842    ///
843    /// </div>
844    pub fn with_stdout_does_not_contain<S: ToString>(&mut self, expected: S) -> &mut Self {
845        self.expect_stdout_not_contains.push(expected.to_string());
846        self
847    }
848
849    /// Verifies that stderr does not contain the given contiguous lines.
850    ///
851    /// See [`compare`] for supported patterns.
852    ///
853    /// <div class="warning">
854    ///
855    /// Prefer [`Execs::with_stdout_data`] where possible.
856    /// - `expected` cannot be snapshotted
857    /// - The absence of `expected` can either mean success or that the string being looked for
858    ///   changed.
859    ///
860    /// To mitigate this, consider either matching this up with
861    /// [`Execs::with_stdout_contains`] or replace it
862    /// with [`Execs::with_stderr_line_without`].
863    ///
864    /// </div>
865    pub fn with_stderr_does_not_contain<S: ToString>(&mut self, expected: S) -> &mut Self {
866        self.expect_stderr_not_contains.push(expected.to_string());
867        self
868    }
869
870    /// Verify that a particular line appears in stderr with and without the
871    /// given substrings. Exactly one line must match.
872    ///
873    /// The substrings are matched as `contains`.
874    ///
875    /// <div class="warning">
876    ///
877    /// Prefer [`Execs::with_stdout_data`] where possible.
878    /// - `with` cannot be snapshotted
879    /// - The absence of `without` can either mean success or that the string being looked for
880    ///   changed.
881    ///
882    /// </div>
883    ///
884    /// # Example
885    ///
886    /// ```no_run
887    /// use cargo_test_support::execs;
888    ///
889    /// execs().with_stderr_line_without(
890    ///     &[
891    ///         "[RUNNING] `rustc --crate-name build_script_build",
892    ///         "-C opt-level=3",
893    ///     ],
894    ///     &["-C debuginfo", "-C incremental"],
895    /// );
896    /// ```
897    ///
898    /// This will check that a build line includes `-C opt-level=3` but does
899    /// not contain `-C debuginfo` or `-C incremental`.
900    ///
901    pub fn with_stderr_line_without<S: ToString>(
902        &mut self,
903        with: &[S],
904        without: &[S],
905    ) -> &mut Self {
906        let with = with.iter().map(|s| s.to_string()).collect();
907        let without = without.iter().map(|s| s.to_string()).collect();
908        self.expect_stderr_with_without.push((with, without));
909        self
910    }
911}
912
913/// # Configure the process
914impl Execs {
915    /// Forward subordinate process stdout/stderr to the terminal.
916    /// Useful for printf debugging of the tests.
917    /// CAUTION: CI will fail if you leave this in your test!
918    #[allow(unused)]
919    pub fn stream(&mut self) -> &mut Self {
920        self.stream_output = true;
921        self
922    }
923
924    pub fn arg<T: AsRef<OsStr>>(&mut self, arg: T) -> &mut Self {
925        if let Some(ref mut p) = self.process_builder {
926            p.arg(arg);
927        }
928        self
929    }
930
931    pub fn args<T: AsRef<OsStr>>(&mut self, args: &[T]) -> &mut Self {
932        if let Some(ref mut p) = self.process_builder {
933            p.args(args);
934        }
935        self
936    }
937
938    pub fn cwd<T: AsRef<OsStr>>(&mut self, path: T) -> &mut Self {
939        if let Some(ref mut p) = self.process_builder {
940            if let Some(cwd) = p.get_cwd() {
941                let new_path = cwd.join(path.as_ref());
942                p.cwd(new_path);
943            } else {
944                p.cwd(path);
945            }
946        }
947        self
948    }
949
950    pub fn env<T: AsRef<OsStr>>(&mut self, key: &str, val: T) -> &mut Self {
951        if let Some(ref mut p) = self.process_builder {
952            p.env(key, val);
953        }
954        self
955    }
956
957    pub fn env_remove(&mut self, key: &str) -> &mut Self {
958        if let Some(ref mut p) = self.process_builder {
959            p.env_remove(key);
960        }
961        self
962    }
963
964    /// Enables nightly features for testing
965    ///
966    /// The list of reasons should be why nightly cargo is needed. If it is
967    /// because of an unstable feature put the name of the feature as the reason,
968    /// e.g. `&["print-im-a-teapot"]`
969    pub fn masquerade_as_nightly_cargo(&mut self, reasons: &[&str]) -> &mut Self {
970        if let Some(ref mut p) = self.process_builder {
971            p.masquerade_as_nightly_cargo(reasons);
972        }
973        self
974    }
975
976    /// Overrides the crates.io URL for testing.
977    ///
978    /// Can be used for testing crates-io functionality where alt registries
979    /// cannot be used.
980    pub fn replace_crates_io(&mut self, url: &Url) -> &mut Self {
981        if let Some(ref mut p) = self.process_builder {
982            p.env("__CARGO_TEST_CRATES_IO_URL_DO_NOT_USE_THIS", url.as_str());
983        }
984        self
985    }
986
987    pub fn overlay_registry(&mut self, url: &Url, path: &str) -> &mut Self {
988        if let Some(ref mut p) = self.process_builder {
989            let env_value = format!("{}={}", url, path);
990            p.env(
991                "__CARGO_TEST_DEPENDENCY_CONFUSION_VULNERABILITY_DO_NOT_USE_THIS",
992                env_value,
993            );
994        }
995        self
996    }
997
998    pub fn enable_split_debuginfo_packed(&mut self) -> &mut Self {
999        self.env("CARGO_PROFILE_DEV_SPLIT_DEBUGINFO", "packed")
1000            .env("CARGO_PROFILE_TEST_SPLIT_DEBUGINFO", "packed")
1001            .env("CARGO_PROFILE_RELEASE_SPLIT_DEBUGINFO", "packed")
1002            .env("CARGO_PROFILE_BENCH_SPLIT_DEBUGINFO", "packed");
1003        self
1004    }
1005
1006    pub fn enable_mac_dsym(&mut self) -> &mut Self {
1007        if cfg!(target_os = "macos") {
1008            return self.enable_split_debuginfo_packed();
1009        }
1010        self
1011    }
1012}
1013
1014/// # Run and verify the process
1015impl Execs {
1016    pub fn exec_with_output(&mut self) -> Result<Output> {
1017        self.ran = true;
1018        // TODO avoid unwrap
1019        let p = (&self.process_builder).clone().unwrap();
1020        p.exec_with_output()
1021    }
1022
1023    pub fn build_command(&mut self) -> Command {
1024        self.ran = true;
1025        // TODO avoid unwrap
1026        let p = (&self.process_builder).clone().unwrap();
1027        p.build_command()
1028    }
1029
1030    #[track_caller]
1031    pub fn run(&mut self) -> RawOutput {
1032        self.ran = true;
1033        let mut p = (&self.process_builder).clone().unwrap();
1034        if let Some(stdin) = self.expect_stdin.take() {
1035            p.stdin(stdin);
1036        }
1037
1038        match self.match_process(&p) {
1039            Err(e) => panic_error(&format!("test failed running {}", p), e),
1040            Ok(output) => output,
1041        }
1042    }
1043
1044    /// Runs the process, checks the expected output, and returns the first
1045    /// JSON object on stdout.
1046    #[track_caller]
1047    pub fn run_json(&mut self) -> serde_json::Value {
1048        let output = self.run();
1049        serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
1050            panic!(
1051                "\nfailed to parse JSON: {}\n\
1052                     output was:\n{}\n",
1053                e,
1054                String::from_utf8_lossy(&output.stdout)
1055            );
1056        })
1057    }
1058
1059    #[track_caller]
1060    pub fn run_output(&mut self, output: &Output) {
1061        self.ran = true;
1062        if let Err(e) = self.match_output(output.status.code(), &output.stdout, &output.stderr) {
1063            panic_error("process did not return the expected result", e)
1064        }
1065    }
1066
1067    #[track_caller]
1068    fn verify_checks_output(&self, stdout: &[u8], stderr: &[u8]) {
1069        if self.expect_exit_code.unwrap_or(0) != 0
1070            && self.expect_stdin.is_none()
1071            && self.expect_stdout_data.is_none()
1072            && self.expect_stderr_data.is_none()
1073            && self.expect_stdout_contains.is_empty()
1074            && self.expect_stderr_contains.is_empty()
1075            && self.expect_stdout_not_contains.is_empty()
1076            && self.expect_stderr_not_contains.is_empty()
1077            && self.expect_stderr_with_without.is_empty()
1078        {
1079            panic!(
1080                "`with_status()` is used, but no output is checked.\n\
1081                 The test must check the output to ensure the correct error is triggered.\n\
1082                 --- stdout\n{}\n--- stderr\n{}",
1083                String::from_utf8_lossy(stdout),
1084                String::from_utf8_lossy(stderr),
1085            );
1086        }
1087    }
1088
1089    #[track_caller]
1090    fn match_process(&self, process: &ProcessBuilder) -> Result<RawOutput> {
1091        println!("running {}", process);
1092        let res = if self.stream_output {
1093            if is_ci() {
1094                panic!("`.stream()` is for local debugging")
1095            }
1096            process
1097                .exec_with_streaming(
1098                    &mut |out| {
1099                        println!("{}", out);
1100                        Ok(())
1101                    },
1102                    &mut |err| {
1103                        eprintln!("{}", err);
1104                        Ok(())
1105                    },
1106                    true,
1107                    false,
1108                )
1109                .1
1110        } else {
1111            process.exec_with_output()
1112        };
1113
1114        match res {
1115            Ok(out) => {
1116                self.match_output(out.status.code(), &out.stdout, &out.stderr)?;
1117                return Ok(RawOutput {
1118                    stdout: out.stdout,
1119                    stderr: out.stderr,
1120                    code: out.status.code(),
1121                });
1122            }
1123            Err(e) => {
1124                if let Some(ProcessError {
1125                    stdout: Some(stdout),
1126                    stderr: Some(stderr),
1127                    code,
1128                    ..
1129                }) = e.downcast_ref::<ProcessError>()
1130                {
1131                    self.match_output(*code, stdout, stderr)?;
1132                    return Ok(RawOutput {
1133                        stdout: stdout.to_vec(),
1134                        stderr: stderr.to_vec(),
1135                        code: *code,
1136                    });
1137                }
1138                bail!("could not exec process {}: {:?}", process, e)
1139            }
1140        }
1141    }
1142
1143    #[track_caller]
1144    fn match_output(&self, code: Option<i32>, stdout: &[u8], stderr: &[u8]) -> Result<()> {
1145        self.verify_checks_output(stdout, stderr);
1146        let stdout = std::str::from_utf8(stdout).expect("stdout is not utf8");
1147        let stderr = std::str::from_utf8(stderr).expect("stderr is not utf8");
1148
1149        match self.expect_exit_code {
1150            None => {}
1151            Some(expected) if code == Some(expected) => {}
1152            Some(expected) => bail!(
1153                "process exited with code {} (expected {})\n--- stdout\n{}\n--- stderr\n{}",
1154                code.unwrap_or(-1),
1155                expected,
1156                stdout,
1157                stderr
1158            ),
1159        }
1160
1161        if let Some(expect_stdout_data) = &self.expect_stdout_data {
1162            if let Err(err) = self.assert.try_eq(
1163                Some(&"stdout"),
1164                stdout.into_data(),
1165                expect_stdout_data.clone(),
1166            ) {
1167                panic!("{err}")
1168            }
1169        }
1170        if let Some(expect_stderr_data) = &self.expect_stderr_data {
1171            if let Err(err) = self.assert.try_eq(
1172                Some(&"stderr"),
1173                stderr.into_data(),
1174                expect_stderr_data.clone(),
1175            ) {
1176                panic!("{err}")
1177            }
1178        }
1179        for expect in self.expect_stdout_contains.iter() {
1180            compare::match_contains(expect, stdout, self.assert.redactions())?;
1181        }
1182        for expect in self.expect_stderr_contains.iter() {
1183            compare::match_contains(expect, stderr, self.assert.redactions())?;
1184        }
1185        for expect in self.expect_stdout_not_contains.iter() {
1186            compare::match_does_not_contain(expect, stdout, self.assert.redactions())?;
1187        }
1188        for expect in self.expect_stderr_not_contains.iter() {
1189            compare::match_does_not_contain(expect, stderr, self.assert.redactions())?;
1190        }
1191        for (with, without) in self.expect_stderr_with_without.iter() {
1192            compare::match_with_without(stderr, with, without, self.assert.redactions())?;
1193        }
1194        Ok(())
1195    }
1196}
1197
1198impl Drop for Execs {
1199    fn drop(&mut self) {
1200        if !self.ran && !std::thread::panicking() {
1201            panic!("forgot to run this command");
1202        }
1203    }
1204}
1205
1206/// Run and verify a process, see [`Execs`]
1207pub fn execs() -> Execs {
1208    Execs {
1209        ran: false,
1210        process_builder: None,
1211        expect_stdin: None,
1212        expect_exit_code: Some(0),
1213        expect_stdout_data: None,
1214        expect_stderr_data: None,
1215        expect_stdout_contains: Vec::new(),
1216        expect_stderr_contains: Vec::new(),
1217        expect_stdout_not_contains: Vec::new(),
1218        expect_stderr_not_contains: Vec::new(),
1219        expect_stderr_with_without: Vec::new(),
1220        stream_output: false,
1221        assert: compare::assert_e2e(),
1222    }
1223}
1224
1225/// Generate a basic `Cargo.toml`
1226pub fn basic_manifest(name: &str, version: &str) -> String {
1227    format!(
1228        r#"
1229        [package]
1230        name = "{}"
1231        version = "{}"
1232        authors = []
1233        edition = "2015"
1234    "#,
1235        name, version
1236    )
1237}
1238
1239/// Generate a `Cargo.toml` with the specified `bin.name`
1240pub fn basic_bin_manifest(name: &str) -> String {
1241    format!(
1242        r#"
1243        [package]
1244
1245        name = "{}"
1246        version = "0.5.0"
1247        authors = ["wycats@example.com"]
1248        edition = "2015"
1249
1250        [[bin]]
1251
1252        name = "{}"
1253    "#,
1254        name, name
1255    )
1256}
1257
1258/// Generate a `Cargo.toml` with the specified `lib.name`
1259pub fn basic_lib_manifest(name: &str) -> String {
1260    format!(
1261        r#"
1262        [package]
1263
1264        name = "{}"
1265        version = "0.5.0"
1266        authors = ["wycats@example.com"]
1267        edition = "2015"
1268
1269        [lib]
1270
1271        name = "{}"
1272    "#,
1273        name, name
1274    )
1275}
1276
1277/// Gets a valid target spec JSON from rustc.
1278///
1279/// To avoid any hardcoded value, this fetches `x86_64-unknown-none` target
1280/// spec JSON directly from `rustc`, as Cargo shouldn't know the JSON schema.
1281pub fn target_spec_json() -> &'static str {
1282    static TARGET_SPEC_JSON: LazyLock<String> = LazyLock::new(|| {
1283        let json = std::process::Command::new("rustc")
1284            .env("RUSTC_BOOTSTRAP", "1")
1285            .arg("--print")
1286            .arg("target-spec-json")
1287            .arg("-Zunstable-options")
1288            .arg("--target")
1289            .arg("x86_64-unknown-none")
1290            .output()
1291            .expect("rustc --print target-spec-json")
1292            .stdout;
1293        String::from_utf8(json).expect("utf8 target spec json")
1294    });
1295
1296    TARGET_SPEC_JSON.as_str()
1297}
1298
1299struct RustcInfo {
1300    verbose_version: String,
1301    host: String,
1302}
1303
1304impl RustcInfo {
1305    fn new() -> RustcInfo {
1306        let output = ProcessBuilder::new("rustc")
1307            .arg("-vV")
1308            .exec_with_output()
1309            .expect("rustc should exec");
1310        let verbose_version = String::from_utf8(output.stdout).expect("utf8 output");
1311        let host = verbose_version
1312            .lines()
1313            .filter_map(|line| line.strip_prefix("host: "))
1314            .next()
1315            .expect("verbose version has host: field")
1316            .to_string();
1317        RustcInfo {
1318            verbose_version,
1319            host,
1320        }
1321    }
1322}
1323
1324fn rustc_info() -> &'static RustcInfo {
1325    static RUSTC_INFO: OnceLock<RustcInfo> = OnceLock::new();
1326    RUSTC_INFO.get_or_init(RustcInfo::new)
1327}
1328
1329/// The rustc host such as `x86_64-unknown-linux-gnu`.
1330pub fn rustc_host() -> &'static str {
1331    &rustc_info().host
1332}
1333
1334/// The host tuple suitable for use in a cargo environment variable (uppercased).
1335pub fn rustc_host_env() -> String {
1336    rustc_host().to_uppercase().replace('-', "_")
1337}
1338
1339pub fn is_nightly() -> bool {
1340    let vv = &rustc_info().verbose_version;
1341    // CARGO_TEST_DISABLE_NIGHTLY is set in rust-lang/rust's CI so that all
1342    // nightly-only tests are disabled there. Otherwise, it could make it
1343    // difficult to land changes which would need to be made simultaneously in
1344    // rust-lang/cargo and rust-lan/rust, which isn't possible.
1345    env::var("CARGO_TEST_DISABLE_NIGHTLY").is_err()
1346        && (vv.contains("-nightly") || vv.contains("-dev"))
1347}
1348
1349/// Run `$bin` in the test's environment, see [`ProcessBuilder`]
1350///
1351/// For more on the test environment, see
1352/// - [`paths::root`]
1353/// - [`TestEnvCommandExt`]
1354pub fn process<T: AsRef<OsStr>>(bin: T) -> ProcessBuilder {
1355    _process(bin.as_ref())
1356}
1357
1358fn _process(t: &OsStr) -> ProcessBuilder {
1359    let mut p = ProcessBuilder::new(t);
1360    p.cwd(&paths::root()).test_env();
1361    p
1362}
1363
1364/// Enable nightly features for testing
1365pub trait ChannelChangerCommandExt {
1366    /// The list of reasons should be why nightly cargo is needed. If it is
1367    /// because of an unstable feature put the name of the feature as the reason,
1368    /// e.g. `&["print-im-a-teapot"]`.
1369    fn masquerade_as_nightly_cargo(self, _reasons: &[&str]) -> Self;
1370}
1371
1372impl ChannelChangerCommandExt for &mut ProcessBuilder {
1373    fn masquerade_as_nightly_cargo(self, _reasons: &[&str]) -> Self {
1374        self.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly")
1375    }
1376}
1377
1378impl ChannelChangerCommandExt for snapbox::cmd::Command {
1379    fn masquerade_as_nightly_cargo(self, _reasons: &[&str]) -> Self {
1380        self.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly")
1381    }
1382}
1383
1384/// Establish a process's test environment
1385pub trait TestEnvCommandExt: Sized {
1386    fn test_env(mut self) -> Self {
1387        // In general just clear out all cargo-specific configuration already in the
1388        // environment. Our tests all assume a "default configuration" unless
1389        // specified otherwise.
1390        for (k, _v) in env::vars() {
1391            if k.starts_with("CARGO_") {
1392                self = self.env_remove(&k);
1393            }
1394        }
1395        if env::var_os("RUSTUP_TOOLCHAIN").is_some() {
1396            // Override the PATH to avoid executing the rustup wrapper thousands
1397            // of times. This makes the testsuite run substantially faster.
1398            static RUSTC_DIR: OnceLock<PathBuf> = OnceLock::new();
1399            let rustc_dir = RUSTC_DIR.get_or_init(|| {
1400                match ProcessBuilder::new("rustup")
1401                    .args(&["which", "rustc"])
1402                    .exec_with_output()
1403                {
1404                    Ok(output) => {
1405                        let s = std::str::from_utf8(&output.stdout).expect("utf8").trim();
1406                        let mut p = PathBuf::from(s);
1407                        p.pop();
1408                        p
1409                    }
1410                    Err(e) => {
1411                        panic!("RUSTUP_TOOLCHAIN was set, but could not run rustup: {}", e);
1412                    }
1413                }
1414            });
1415            let path = env::var_os("PATH").unwrap_or_default();
1416            let paths = env::split_paths(&path);
1417            let new_path =
1418                env::join_paths(std::iter::once(rustc_dir.clone()).chain(paths)).unwrap();
1419            self = self.env("PATH", new_path);
1420        }
1421
1422        self = self
1423            .current_dir(&paths::root())
1424            .env("HOME", paths::home())
1425            .env("CARGO_HOME", paths::cargo_home())
1426            .env("__CARGO_TEST_ROOT", paths::global_root())
1427            // Force Cargo to think it's on the stable channel for all tests, this
1428            // should hopefully not surprise us as we add cargo features over time and
1429            // cargo rides the trains.
1430            .env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "stable")
1431            // Keeps cargo within its sandbox.
1432            .env("__CARGO_TEST_DISABLE_GLOBAL_KNOWN_HOST", "1")
1433            // Set retry sleep to 1 millisecond.
1434            .env("__CARGO_TEST_FIXED_RETRY_SLEEP_MS", "1")
1435            // Setting this to a large number helps avoid problems with long
1436            // paths getting trimmed in snapshot tests.
1437            //
1438            // When updating this value, keep in mind that the `CARGO_TARGET_DIR`
1439            // that gets set when Cargo's tests get run in `rust-lang/rust` can
1440            // easily cause path lengths to exceed 200 characters.
1441            .env("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS", "400")
1442            // Incremental generates a huge amount of data per test, which we
1443            // don't particularly need. Tests that specifically need to check
1444            // the incremental behavior should turn this back on.
1445            .env("CARGO_INCREMENTAL", "0")
1446            // Don't read the system git config which is out of our control.
1447            .env("GIT_CONFIG_NOSYSTEM", "1")
1448            .env_remove("CI")
1449            .env_remove("__CARGO_DEFAULT_LIB_METADATA")
1450            .env_remove("ALL_PROXY")
1451            .env_remove("EMAIL")
1452            .env_remove("GIT_AUTHOR_EMAIL")
1453            .env_remove("GIT_AUTHOR_NAME")
1454            .env_remove("GIT_COMMITTER_EMAIL")
1455            .env_remove("GIT_COMMITTER_NAME")
1456            .env_remove("http_proxy")
1457            .env_remove("HTTPS_PROXY")
1458            .env_remove("https_proxy")
1459            .env_remove("MAKEFLAGS")
1460            .env_remove("MFLAGS")
1461            .env_remove("MSYSTEM") // assume cmd.exe everywhere on windows
1462            .env_remove("MANPAGER")
1463            .env_remove("PAGER")
1464            .env_remove("LESS")
1465            .env_remove("RUSTC")
1466            .env_remove("RUST_BACKTRACE")
1467            .env_remove("RUSTC_WORKSPACE_WRAPPER")
1468            .env_remove("RUSTC_WRAPPER")
1469            .env_remove("RUSTDOC")
1470            .env_remove("RUSTDOCFLAGS")
1471            .env_remove("RUSTFLAGS")
1472            .env_remove("RUSTUP_TOOLCHAIN_SOURCE")
1473            .env_remove("SSH_AUTH_SOCK") // ensure an outer agent is never contacted
1474            .env_remove("USER") // not set on some rust-lang docker images
1475            .env_remove("XDG_CONFIG_HOME") // see #2345
1476            .env_remove("OUT_DIR"); // see #13204
1477        if cfg!(windows) {
1478            self = self.env("USERPROFILE", paths::home());
1479        }
1480        self
1481    }
1482
1483    fn current_dir<S: AsRef<std::path::Path>>(self, path: S) -> Self;
1484    fn env<S: AsRef<std::ffi::OsStr>>(self, key: &str, value: S) -> Self;
1485    fn env_remove(self, key: &str) -> Self;
1486}
1487
1488impl TestEnvCommandExt for &mut ProcessBuilder {
1489    fn current_dir<S: AsRef<std::path::Path>>(self, path: S) -> Self {
1490        let path = path.as_ref();
1491        self.cwd(path)
1492    }
1493    fn env<S: AsRef<std::ffi::OsStr>>(self, key: &str, value: S) -> Self {
1494        self.env(key, value)
1495    }
1496    fn env_remove(self, key: &str) -> Self {
1497        self.env_remove(key)
1498    }
1499}
1500
1501impl TestEnvCommandExt for snapbox::cmd::Command {
1502    fn current_dir<S: AsRef<std::path::Path>>(self, path: S) -> Self {
1503        self.current_dir(path)
1504    }
1505    fn env<S: AsRef<std::ffi::OsStr>>(self, key: &str, value: S) -> Self {
1506        self.env(key, value)
1507    }
1508    fn env_remove(self, key: &str) -> Self {
1509        self.env_remove(key)
1510    }
1511}
1512
1513/// Add a list of arguments as a line
1514pub trait ArgLineCommandExt: Sized {
1515    fn arg_line(mut self, s: &str) -> Self {
1516        for mut arg in s.split_whitespace() {
1517            if (arg.starts_with('"') && arg.ends_with('"'))
1518                || (arg.starts_with('\'') && arg.ends_with('\''))
1519            {
1520                arg = &arg[1..(arg.len() - 1).max(1)];
1521            } else if arg.contains(&['"', '\''][..]) {
1522                panic!("shell-style argument parsing is not supported")
1523            }
1524            self = self.arg(arg);
1525        }
1526        self
1527    }
1528
1529    fn arg<S: AsRef<std::ffi::OsStr>>(self, s: S) -> Self;
1530}
1531
1532impl ArgLineCommandExt for &mut ProcessBuilder {
1533    fn arg<S: AsRef<std::ffi::OsStr>>(self, s: S) -> Self {
1534        self.arg(s)
1535    }
1536}
1537
1538impl ArgLineCommandExt for &mut Execs {
1539    fn arg<S: AsRef<std::ffi::OsStr>>(self, s: S) -> Self {
1540        self.arg(s)
1541    }
1542}
1543
1544impl ArgLineCommandExt for snapbox::cmd::Command {
1545    fn arg<S: AsRef<std::ffi::OsStr>>(self, s: S) -> Self {
1546        self.arg(s)
1547    }
1548}
1549
1550/// Run `git $arg_line`, see [`ProcessBuilder`]
1551pub fn git_process(arg_line: &str) -> ProcessBuilder {
1552    let mut p = process("git");
1553    p.arg_line(arg_line);
1554    p
1555}
1556
1557pub fn sleep_ms(ms: u64) {
1558    ::std::thread::sleep(Duration::from_millis(ms));
1559}
1560
1561/// Returns `true` if the local filesystem has low-resolution mtimes.
1562pub fn is_coarse_mtime() -> bool {
1563    // If the filetime crate is being used to emulate HFS then
1564    // return `true`, without looking at the actual hardware.
1565    cfg!(emulate_second_only_system) ||
1566    // This should actually be a test that `$CARGO_TARGET_DIR` is on an HFS
1567    // filesystem, (or any filesystem with low-resolution mtimes). However,
1568    // that's tricky to detect, so for now just deal with CI.
1569    cfg!(target_os = "macos") && is_ci()
1570}
1571
1572/// A way for to increase the cut off for all the time based test.
1573///
1574/// Some CI setups are much slower then the equipment used by Cargo itself.
1575/// Architectures that do not have a modern processor, hardware emulation, etc.
1576pub fn slow_cpu_multiplier(main: u64) -> Duration {
1577    static SLOW_CPU_MULTIPLIER: OnceLock<u64> = OnceLock::new();
1578    let slow_cpu_multiplier = SLOW_CPU_MULTIPLIER.get_or_init(|| {
1579        env::var("CARGO_TEST_SLOW_CPU_MULTIPLIER")
1580            .ok()
1581            .and_then(|m| m.parse().ok())
1582            .unwrap_or(1)
1583    });
1584    Duration::from_secs(slow_cpu_multiplier * main)
1585}
1586
1587#[cfg(windows)]
1588pub fn symlink_supported() -> bool {
1589    if is_ci() {
1590        // We want to be absolutely sure this runs on CI.
1591        return true;
1592    }
1593    let src = paths::root().join("symlink_src");
1594    fs::write(&src, "").unwrap();
1595    let dst = paths::root().join("symlink_dst");
1596    let result = match os::windows::fs::symlink_file(&src, &dst) {
1597        Ok(_) => {
1598            fs::remove_file(&dst).unwrap();
1599            true
1600        }
1601        Err(e) => {
1602            eprintln!(
1603                "symlinks not supported: {:?}\n\
1604                 Windows 10 users should enable developer mode.",
1605                e
1606            );
1607            false
1608        }
1609    };
1610    fs::remove_file(&src).unwrap();
1611    return result;
1612}
1613
1614#[cfg(not(windows))]
1615pub fn symlink_supported() -> bool {
1616    true
1617}
1618
1619/// The error message for ENOENT.
1620pub fn no_such_file_err_msg() -> String {
1621    std::io::Error::from_raw_os_error(2).to_string()
1622}
1623
1624/// Helper to retry a function `n` times.
1625///
1626/// The function should return `Some` when it is ready.
1627#[track_caller]
1628pub fn retry<F, R>(n: u32, mut f: F) -> R
1629where
1630    F: FnMut() -> Option<R>,
1631{
1632    let mut count = 0;
1633    let start = std::time::Instant::now();
1634    loop {
1635        if let Some(r) = f() {
1636            return r;
1637        }
1638        count += 1;
1639        if count > n {
1640            panic!(
1641                "test did not finish within {n} attempts ({:?} total)",
1642                start.elapsed()
1643            );
1644        }
1645        sleep_ms(100);
1646    }
1647}
1648
1649#[test]
1650#[should_panic(expected = "test did not finish")]
1651fn retry_fails() {
1652    retry(2, || None::<()>);
1653}
1654
1655/// Helper that waits for a thread to finish, up to `n` tenths of a second.
1656#[track_caller]
1657pub fn thread_wait_timeout<T>(n: u32, thread: JoinHandle<T>) -> T {
1658    retry(n, || thread.is_finished().then_some(()));
1659    thread.join().unwrap()
1660}
1661
1662/// Helper that runs some function, and waits up to `n` tenths of a second for
1663/// it to finish.
1664#[track_caller]
1665pub fn threaded_timeout<F, R>(n: u32, f: F) -> R
1666where
1667    F: FnOnce() -> R + Send + 'static,
1668    R: Send + 'static,
1669{
1670    let thread = std::thread::spawn(|| f());
1671    thread_wait_timeout(n, thread)
1672}
1673
1674// Helper for testing dep-info files in the fingerprint dir.
1675#[track_caller]
1676pub fn assert_deps(project: &Project, fingerprint: &str, test_cb: impl Fn(&Path, &[(u8, &str)])) {
1677    let mut files = project
1678        .glob(fingerprint)
1679        .map(|f| f.expect("unwrap glob result"))
1680        // Filter out `.json` entries.
1681        .filter(|f| f.extension().is_none());
1682    let info_path = files
1683        .next()
1684        .unwrap_or_else(|| panic!("expected 1 dep-info file at {}, found 0", fingerprint));
1685    assert!(files.next().is_none(), "expected only 1 dep-info file");
1686    let dep_info = fs::read(&info_path).unwrap();
1687    let dep_info = &mut &dep_info[..];
1688
1689    // Consume the magic marker and version. Here they don't really matter.
1690    read_usize(dep_info);
1691    read_u8(dep_info);
1692    read_u8(dep_info);
1693
1694    let deps = (0..read_usize(dep_info))
1695        .map(|_| {
1696            let ty = read_u8(dep_info);
1697            let path = std::str::from_utf8(read_bytes(dep_info)).unwrap();
1698            let checksum_present = read_bool(dep_info);
1699            if checksum_present {
1700                // Read out the checksum info without using it
1701                let _file_len = read_u64(dep_info);
1702                let _checksum = read_bytes(dep_info);
1703            }
1704            (ty, path)
1705        })
1706        .collect::<Vec<_>>();
1707    test_cb(&info_path, &deps);
1708
1709    fn read_usize(bytes: &mut &[u8]) -> usize {
1710        let ret = &bytes[..4];
1711        *bytes = &bytes[4..];
1712
1713        u32::from_le_bytes(ret.try_into().unwrap()) as usize
1714    }
1715
1716    fn read_u8(bytes: &mut &[u8]) -> u8 {
1717        let ret = bytes[0];
1718        *bytes = &bytes[1..];
1719        ret
1720    }
1721
1722    fn read_bool(bytes: &mut &[u8]) -> bool {
1723        read_u8(bytes) != 0
1724    }
1725
1726    fn read_u64(bytes: &mut &[u8]) -> u64 {
1727        let ret = &bytes[..8];
1728        *bytes = &bytes[8..];
1729
1730        u64::from_le_bytes(ret.try_into().unwrap())
1731    }
1732
1733    fn read_bytes<'a>(bytes: &mut &'a [u8]) -> &'a [u8] {
1734        let n = read_usize(bytes);
1735        let ret = &bytes[..n];
1736        *bytes = &bytes[n..];
1737        ret
1738    }
1739}
1740
1741#[track_caller]
1742pub fn assert_deps_contains(project: &Project, fingerprint: &str, expected: &[(u8, &str)]) {
1743    assert_deps(project, fingerprint, |info_path, entries| {
1744        for (e_kind, e_path) in expected {
1745            let pattern = glob::Pattern::new(e_path).unwrap();
1746            let count = entries
1747                .iter()
1748                .filter(|(kind, path)| kind == e_kind && pattern.matches(path))
1749                .count();
1750            if count != 1 {
1751                panic!(
1752                    "Expected 1 match of {} {} in {:?}, got {}:\n{:#?}",
1753                    e_kind, e_path, info_path, count, entries
1754                );
1755            }
1756        }
1757    })
1758}
1759
1760#[track_caller]
1761pub fn assert_deterministic_mtime(path: impl AsRef<Path>) {
1762    // Hardcoded value be removed once alexcrichton/tar-rs#420 is merged and released.
1763    // See also rust-lang/cargo#16237
1764    const DETERMINISTIC_TIMESTAMP: u64 = 1153704088;
1765
1766    let path = path.as_ref();
1767    let mtime = path.metadata().unwrap().modified().unwrap();
1768    let timestamp = mtime
1769        .duration_since(std::time::UNIX_EPOCH)
1770        .unwrap()
1771        .as_secs();
1772    assert_eq!(
1773        timestamp, DETERMINISTIC_TIMESTAMP,
1774        "expected deterministic mtime for {path:?}, got {timestamp}"
1775    );
1776}