use std::cell::RefCell;
use toml_edit::Item;
use super::*;
fn unlaunched(_: &mut Command) -> io::Result<ExitStatus> {
unreachable!("this test fails or finishes before launching Cargo")
}
const SIMULATED_FAILURE: &str = "SIMULATED_CARGO_FAILURE";
thread_local! {
static SIMULATED_TEST_RUNS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
#[cfg(any(unix, windows))]
fn simulated_cargo(command: &mut Command) -> io::Result<ExitStatus> {
let args: Vec<&str> = command
.get_args()
.map(|arg| arg.to_str().expect("the simulated commands use only UTF-8 scratch paths"))
.collect();
let failure = command
.get_envs()
.find(|(key, _)| *key == SIMULATED_FAILURE)
.and_then(|(_, value)| value?.to_str());
let operation = if args[0] == "package" {
let archives = Path::new(args[3]).join("package");
fs::create_dir_all(&archives)?;
for selected in args[4..].iter().filter(|arg| **arg != "--package") {
let stem = selected.replace('@', "-");
write_crate_archive(&archives.join(format!("{stem}.crate")), &stem)?;
}
String::from("package")
} else {
let manifest = Path::new(args[args.len() - 1]);
assert_eq!(manifest.file_name(), Some(OsStr::new("Cargo.toml")), "{args:?}");
assert!(manifest.is_file(), "{args:?}");
let source = manifest.parent().expect("the manifest was checked to be a file in a directory");
let patch: DocumentMut = fs::read_to_string(args[1])?.parse().expect("the check writes its patch as TOML");
let patched = patch
.get("patch")
.and_then(|patch| patch.get("crates-io"))
.and_then(Item::as_table_like)
.is_some_and(|crates| {
crates
.iter()
.any(|(_, entry)| entry.get("path").and_then(Item::as_str) == source.to_str())
});
assert!(patched, "{patch}");
let mode = if args[3] == "--manifest-path" { "default" } else { args[3] };
let stem = source.file_name().and_then(OsStr::to_str).expect("archive stems are UTF-8");
SIMULATED_TEST_RUNS.with_borrow_mut(|runs| runs.push(format!("{stem} {mode}")));
mode.to_owned()
};
Ok(exit_status(failure == Some(operation.as_str())))
}
#[cfg(any(unix, windows))]
fn write_crate_archive(path: &Path, stem: &str) -> io::Result<()> {
const MANIFEST: &[u8] = b"[package]\n";
let mut header = tar::Header::new_gnu();
header.set_size(MANIFEST.len().try_into().expect("a ten-byte manifest fits in u64"));
header.set_mode(0o644);
let mut archive = tar::Builder::new(flate2::write::GzEncoder::new(File::create(path)?, flate2::Compression::fast()));
archive.append_data(&mut header, format!("{stem}/Cargo.toml"), MANIFEST)?;
archive.into_inner()?.finish()?;
Ok(())
}
#[cfg(unix)]
fn exit_status(failed: bool) -> ExitStatus {
use std::os::unix::process::ExitStatusExt;
ExitStatus::from_raw(i32::from(failed) << 8)
}
#[cfg(windows)]
fn exit_status(failed: bool) -> ExitStatus {
use std::os::windows::process::ExitStatusExt;
ExitStatus::from_raw(u32::from(failed))
}
#[cfg(any(unix, windows))]
fn simulated_check(failure: Option<&str>) -> Result<()> {
let report = r#"[{"name":"peer","new_version":"1.2.0"},{"name":"consumer","new_version":"0.3.0"}]"#;
let cargo = CargoInvoker {
root: PathBuf::from("workspace"),
child_env: failure
.map(|failure| (SIMULATED_FAILURE.into(), failure.into()))
.into_iter()
.collect(),
scratch: tempfile::tempdir()?,
run_status: simulated_cargo,
};
check(Candidates::from_report(report)?, cargo)
}
#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn check_tests_every_packaged_candidate_in_each_feature_mode() -> Result<()> {
simulated_check(None)?;
assert_eq!(
SIMULATED_TEST_RUNS.take(),
[
"consumer-0.3.0 --all-features",
"consumer-0.3.0 --no-default-features",
"consumer-0.3.0 default",
"peer-1.2.0 --all-features",
"peer-1.2.0 --no-default-features",
"peer-1.2.0 default",
]
);
Ok(())
}
#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn check_stops_when_packaging_fails() {
let error = simulated_check(Some("package")).unwrap_err().to_string();
assert!(error.starts_with("cargo package for release candidates failed ("), "{error}");
assert_eq!(SIMULATED_TEST_RUNS.take(), Vec::<String>::new());
}
#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn check_names_the_candidate_and_feature_mode_of_a_failing_test() {
let error = simulated_check(Some("default")).unwrap_err().to_string();
assert!(
error.starts_with("consumer: cargo test (default features) from package archive failed ("),
"{error}"
);
assert_eq!(
SIMULATED_TEST_RUNS.take(),
[
"consumer-0.3.0 --all-features",
"consumer-0.3.0 --no-default-features",
"consumer-0.3.0 default"
]
);
}
#[test]
fn preserves_the_selected_cargo_home_for_shipped_tests() -> Result<()> {
#[cfg(windows)]
let workspace = Path::new(r"\\?\C:\workspace");
#[cfg(not(windows))]
let workspace = Path::new("/workspace");
let key = OsStr::new("CARGO_HOME");
for (override_home, inherited, expected) in [
(None, None, None),
(None, Some("cache"), Some(workspace.join("cache").into_os_string())),
(Some("override"), Some("cache"), Some(workspace.join("override").into_os_string())),
(Some(""), Some("cache"), Some(OsString::new())),
] {
let mut child_env = override_home.into_iter().map(|home| (key.to_owned(), home.into())).collect();
resolve_cargo_home(workspace, &mut child_env, inherited.map(Into::into))?;
assert_eq!(child_env.get(key), expected.as_ref());
}
Ok(())
}
#[cfg(windows)]
#[test]
fn preserves_an_absolute_cargo_home_without_normalizing_it() -> Result<()> {
let root = Path::new(r"\\?\C:\workspace");
let home = OsString::from(r"C:\cache\..\shared");
let mut child_env = BTreeMap::new();
resolve_cargo_home(root, &mut child_env, Some(home.clone()))?;
assert_eq!(child_env.get(OsStr::new(CARGO_HOME)), Some(&home));
Ok(())
}
#[cfg(windows)]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_a_cargo_home_that_windows_cannot_resolve() -> Result<()> {
let parent = tempfile::tempdir()?;
let workspace = tempfile::tempdir_in(parent.path())?;
let child_env = BTreeMap::from([(CARGO_HOME.into(), "C:cache\0".into())]);
let error = CargoInvoker::new(workspace.path(), child_env, Some(parent.path())).unwrap_err();
assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::InvalidInput);
Ok(())
}
#[test]
fn reads_candidate_versions_and_ignores_discovery_metadata() -> Result<()> {
let report = r#"[{"name":"peer","new_version":"1.2.0","old_version":"1.1.0","classification":"compatible"}]"#;
assert_eq!(
Candidates::from_report(report)?.packages,
BTreeMap::from([("peer".into(), "1.2.0".into())])
);
assert!(Candidates::from_report("[]")?.is_empty());
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn an_empty_report_needs_no_workspace_and_releases_scratch() -> Result<()> {
let scratch = tempfile::tempdir()?;
let path = scratch.path().to_path_buf();
let cargo = CargoInvoker {
root: path.join("missing-workspace"),
child_env: BTreeMap::new(),
scratch,
run_status: unlaunched,
};
check(Candidates::from_report("[]")?, cargo)?;
assert!(!path.try_exists()?);
Ok(())
}
#[test]
fn deduplicates_candidates_with_the_same_name_and_version() -> Result<()> {
let report = r#"[
{"name":"peer","new_version":"1.2.0"},
{"name":"other","new_version":"1.2.0"},
{"name":"peer","new_version":"1.2.0"}
]"#;
assert_eq!(
Candidates::from_report(report)?.packages,
BTreeMap::from([("other".into(), "1.2.0".into()), ("peer".into(), "1.2.0".into())])
);
Ok(())
}
#[test]
fn rejects_invalid_candidate_reports() {
for report in ["", "{}"] {
assert!(Candidates::from_report(report).is_err(), "{report}");
}
for (report, diagnostic) in [
(r#"[{"new_version":"1.2.0"}]"#, "candidate is missing its name"),
(r#"[{"name":"peer","old_version":"1.1.0"}]"#, "candidate is missing its version"),
(
r#"[{"name":"peer","new_version":"1.1.0"},{"name":"peer","new_version":"1.2.0"}]"#,
"report lists two versions for `peer`: `1.1.0` and `1.2.0`; keep one",
),
] {
assert_eq!(Candidates::from_report(report).unwrap_err().to_string(), diagnostic);
}
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn validate_packages_reports_the_missing_candidate_archive() -> Result<()> {
let scratch = tempfile::tempdir()?;
let archives = tempfile::tempdir_in(scratch.path())?;
let candidates = BTreeMap::from([("peer".into(), "1.2.0".into())]);
let cargo = CargoInvoker {
root: PathBuf::from("workspace"),
child_env: BTreeMap::new(),
scratch,
run_status: unlaunched,
};
let error =
validate_packages(&cargo, archives.path(), candidates).expect_err("peer was reported as packaged, but its archive is missing");
let missing = archives.path().join("peer-1.2.0.crate");
assert!(
error.to_string().starts_with(&format!("extracting {}:", missing.display())),
"{error}"
);
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_a_missing_workspace_when_preparing_scratch() -> Result<()> {
let parent = tempfile::tempdir()?;
let error = CargoInvoker::new(&parent.path().join("missing-workspace"), BTreeMap::new(), Some(parent.path())).unwrap_err();
assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotFound);
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn rejects_scratch_at_or_inside_the_workspace() -> Result<()> {
let workspace = tempfile::tempdir()?;
let member = tempfile::tempdir_in(workspace.path())?;
for parent in [workspace.path(), member.path()] {
let error = CargoInvoker::new(workspace.path(), BTreeMap::new(), Some(parent)).unwrap_err();
assert_eq!(error.to_string(), "select a temporary directory outside the source workspace");
}
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_scratch_creation_failure_when_the_parent_is_a_file() -> Result<()> {
let workspace = tempfile::tempdir()?;
let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
let error = CargoInvoker::new(workspace.path(), BTreeMap::new(), Some(&manifest)).unwrap_err();
assert!(
error
.to_string()
.starts_with(&format!("preparing release scratch directory in {}: ", manifest.display())),
"{error}"
);
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn rejects_a_missing_scratch_parent() -> Result<()> {
let temp = tempfile::tempdir()?;
let workspace = tempfile::tempdir_in(temp.path())?;
let scratch_parent = temp.path().join("nonexistent");
let error =
CargoInvoker::new(workspace.path(), BTreeMap::new(), Some(&scratch_parent)).expect_err("the scratch parent must already exist");
assert!(error.to_string().starts_with("preparing release scratch directory in"), "{error}");
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_when_the_candidate_patch_cannot_be_written() -> Result<()> {
let temp = tempfile::tempdir()?;
let scratch = tempfile::tempdir_in(temp.path())?;
fs::remove_dir(scratch.path())?;
let cargo = CargoInvoker {
root: temp.path().to_path_buf(),
child_env: BTreeMap::new(),
scratch,
run_status: unlaunched,
};
let error = test_archives(&cargo, &BTreeMap::new()).unwrap_err();
assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotFound);
Ok(())
}
#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_paths_cargo_cannot_represent_in_patch_toml() {
#[cfg(unix)]
let directory = {
use std::os::unix::ffi::OsStringExt;
std::ffi::OsString::from_vec(vec![0xff])
};
#[cfg(windows)]
let directory = {
use std::os::windows::ffi::OsStringExt;
std::ffi::OsString::from_wide(&[0xd800])
};
let sources = BTreeMap::from([("candidate".into(), directory.into())]);
let temp = tempfile::tempdir();
let cargo = CargoInvoker {
root: PathBuf::from("workspace"),
child_env: BTreeMap::new(),
scratch: temp.unwrap(),
run_status: unlaunched,
};
assert_eq!(
test_archives(&cargo, &sources).unwrap_err().to_string(),
"candidate archive path must be UTF-8"
);
}
#[test]
fn reports_when_the_required_cargo_process_cannot_start() {
let mut command = Command::new("cargo");
let error = run(&mut command, "testing a candidate", |_| Err(io::ErrorKind::NotFound.into())).unwrap_err();
assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotFound);
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn commands_use_workspace_config_and_keep_builds_in_scratch() -> Result<()> {
let root = tempfile::tempdir()?;
let scratch = tempfile::tempdir()?;
let patch = scratch.path().join("patch.toml");
let manifest = scratch.path().join("Cargo.toml");
let cargo = CargoInvoker {
root: root.path().to_path_buf(),
child_env: BTreeMap::from([
("RUSTUP_TOOLCHAIN".into(), "workspace-toolchain".into()),
("CARGO_BUILD_BUILD_DIR".into(), "caller-build".into()),
]),
scratch,
run_status: unlaunched,
};
let command = archive_test_command(&cargo, &patch, &manifest, Some("--no-default-features"));
assert_eq!(command.get_program(), "cargo");
assert_eq!(command.get_current_dir(), Some(root.path()));
assert_eq!(
command.get_args().collect::<Vec<_>>(),
[
"--config".as_ref(),
patch.as_os_str(),
"test".as_ref(),
"--no-default-features".as_ref(),
"--manifest-path".as_ref(),
manifest.as_os_str(),
]
);
let env: BTreeMap<_, _> = command.get_envs().collect();
assert_eq!(
env.get(OsStr::new("RUSTUP_TOOLCHAIN")),
Some(&Some(OsStr::new("workspace-toolchain")))
);
for key in ["CARGO_TARGET_DIR", "CARGO_BUILD_BUILD_DIR"] {
let directory = env.get(OsStr::new(key)).copied().flatten().map(Path::new).unwrap();
assert!(directory.starts_with(cargo.scratch.path()) && directory != cargo.scratch.path());
}
assert!(!env.contains_key(OsStr::new("CARGO_HOME")));
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn package_command_selects_only_the_candidates() -> Result<()> {
let root = tempfile::tempdir()?;
let scratch = tempfile::tempdir()?;
let cargo = CargoInvoker::new(root.path(), BTreeMap::new(), Some(scratch.path()))?;
assert_eq!(cargo.scratch.path().parent(), Some(scratch.path().canonicalize()?.as_path()));
let candidates = BTreeMap::from([("consumer".to_owned(), "1.2.0".to_owned()), ("peer".to_owned(), "3.4.0".to_owned())]);
let command = cargo.package_command(&candidates);
let artifacts = cargo.scratch.path().join("artifacts");
assert_eq!(
command.get_args().collect::<Vec<_>>(),
[
"package".as_ref(),
"--allow-dirty".as_ref(),
"--target-dir".as_ref(),
artifacts.as_os_str(),
"--package".as_ref(),
"consumer@1.2.0".as_ref(),
"--package".as_ref(),
"peer@3.4.0".as_ref(),
]
);
Ok(())
}
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn archive_commands_cover_all_three_feature_modes() -> Result<()> {
let cargo = CargoInvoker {
root: PathBuf::from("workspace"),
child_env: BTreeMap::new(),
scratch: tempfile::tempdir()?,
run_status: unlaunched,
};
let patch = cargo.scratch.path().join("candidates.toml");
let manifest = cargo.scratch.path().join("candidate/Cargo.toml");
let args = ARCHIVE_FEATURE_MODES.map(|feature| {
archive_test_command(&cargo, &patch, &manifest, feature)
.get_args()
.map(OsStr::to_os_string)
.collect::<Vec<_>>()
});
assert!(args[0].iter().any(|arg| arg == "--all-features"));
assert!(args[1].iter().any(|arg| arg == "--no-default-features"));
assert!(args[2].iter().all(|arg| arg != "--all-features" && arg != "--no-default-features"));
Ok(())
}