1#![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#[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#[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#[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
226pub struct Project {
230 root: PathBuf,
231}
232
233#[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 pub fn root(&self) -> PathBuf {
255 self.root.root()
256 }
257
258 pub fn target_debug_dir(&self) -> PathBuf {
262 self.root.target_debug_dir()
263 }
264
265 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 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 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 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 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 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 pub fn build(mut self) -> Project {
328 self.rm_root();
330
331 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 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 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 pub fn root(&self) -> PathBuf {
387 self.root.clone()
388 }
389
390 pub fn build_dir(&self) -> PathBuf {
394 self.root().join("target")
395 }
396
397 pub fn target_debug_dir(&self) -> PathBuf {
401 self.build_dir().join("debug")
402 }
403
404 pub fn url(&self) -> Url {
408 use paths::CargoPathExt;
409 self.root().to_url()
410 }
411
412 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 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 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 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 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 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 pub fn change_file(&self, path: impl AsRef<Path>, body: &str) {
478 FileBuilder::new(self.root().join(path), body, false).mk()
479 }
480
481 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 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 pub fn read_lockfile(&self) -> String {
522 self.read_file("Cargo.lock")
523 }
524
525 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 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
562pub fn project() -> ProjectBuilder {
564 ProjectBuilder::new(paths::root().join("foo"))
565}
566
567pub fn project_in(dir: impl AsRef<Path>) -> ProjectBuilder {
569 ProjectBuilder::new(paths::root().join(dir).join("foo"))
570}
571
572pub fn project_in_home(name: impl AsRef<Path>) -> ProjectBuilder {
574 ProjectBuilder::new(paths::home().join(name))
575}
576
577pub 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
607pub struct RawOutput {
615 pub code: Option<i32>,
616 pub stdout: Vec<u8>,
617 pub stderr: Vec<u8>,
618}
619
620#[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
651impl Execs {
653 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 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 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 pub fn with_status(&mut self, expected: i32) -> &mut Self {
781 self.expect_exit_code = Some(expected);
782 self
783 }
784
785 pub fn without_status(&mut self) -> &mut Self {
789 self.expect_exit_code = None;
790 self
791 }
792
793 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 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 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 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 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
913impl Execs {
915 #[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 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 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
1014impl Execs {
1016 pub fn exec_with_output(&mut self) -> Result<Output> {
1017 self.ran = true;
1018 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 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 #[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
1206pub 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
1225pub 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
1239pub 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
1258pub 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
1277pub 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
1329pub fn rustc_host() -> &'static str {
1331 &rustc_info().host
1332}
1333
1334pub 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 env::var("CARGO_TEST_DISABLE_NIGHTLY").is_err()
1346 && (vv.contains("-nightly") || vv.contains("-dev"))
1347}
1348
1349pub 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
1364pub trait ChannelChangerCommandExt {
1366 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
1384pub trait TestEnvCommandExt: Sized {
1386 fn test_env(mut self) -> Self {
1387 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 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 .env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "stable")
1431 .env("__CARGO_TEST_DISABLE_GLOBAL_KNOWN_HOST", "1")
1433 .env("__CARGO_TEST_FIXED_RETRY_SLEEP_MS", "1")
1435 .env("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS", "400")
1442 .env("CARGO_INCREMENTAL", "0")
1446 .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") .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") .env_remove("USER") .env_remove("XDG_CONFIG_HOME") .env_remove("OUT_DIR"); 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
1513pub 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
1550pub 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
1561pub fn is_coarse_mtime() -> bool {
1563 cfg!(emulate_second_only_system) ||
1566 cfg!(target_os = "macos") && is_ci()
1570}
1571
1572pub 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 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
1619pub fn no_such_file_err_msg() -> String {
1621 std::io::Error::from_raw_os_error(2).to_string()
1622}
1623
1624#[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#[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#[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#[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(|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 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 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 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}