use std::path::PathBuf;
use serde_json::json;
use super::*;
#[test]
fn find_package_selects_by_name() {
let metadata = json!({ "packages": [
{ "name": "a", "targets": [] },
{ "name": "b", "targets": [] },
]});
assert_eq!(find_package(&metadata, "b").unwrap()["name"], json!("b"));
assert!(find_package(&metadata, "missing").is_none());
}
#[test]
fn crate_root_file_prefers_lib_then_proc_macro_then_bin() {
let lib_and_bin = json!({ "targets": [
{ "kind": ["bin"], "src_path": "/w/src/main.rs" },
{ "kind": ["lib"], "src_path": "/w/src/lib.rs" },
]});
assert_eq!(
crate_root_file(&lib_and_bin),
Some(PathBuf::from("/w/src/lib.rs")),
"the lib target wins over bin"
);
let bin_only = json!({ "targets": [{ "kind": ["bin"], "src_path": "/w/src/main.rs" }] });
assert_eq!(
crate_root_file(&bin_only),
Some(PathBuf::from("/w/src/main.rs"))
);
}
#[test]
fn crate_root_file_resolves_a_proc_macro_target() {
let package = json!({ "targets": [
{ "kind": ["proc-macro"], "src_path": "/w/src/lib.rs" }
]});
assert_eq!(
crate_root_file(&package),
Some(PathBuf::from("/w/src/lib.rs"))
);
}
#[test]
fn crate_root_file_skips_a_member_with_no_lib_proc_macro_or_bin() {
let bench_only = json!({ "targets": [{ "kind": ["bench"], "src_path": "/w/benches/b.rs" }] });
assert_eq!(crate_root_file(&bench_only), None);
let rootless = json!({ "targets": [] });
assert_eq!(crate_root_file(&rootless), None);
}
#[test]
fn crate_root_file_resolves_a_cdylib_staticlib_or_rlib_library() {
for kind in [["cdylib"], ["staticlib"], ["rlib"], ["dylib"]] {
let package = json!({ "targets": [{ "kind": kind, "src_path": "/w/src/lib.rs" }] });
assert_eq!(
crate_root_file(&package),
Some(PathBuf::from("/w/src/lib.rs")),
"a {kind:?} library must resolve its crate root"
);
}
let multi = json!({ "targets": [{ "kind": ["cdylib", "rlib"], "src_path": "/w/src/lib.rs" }] });
assert_eq!(
crate_root_file(&multi),
Some(PathBuf::from("/w/src/lib.rs"))
);
let lib_and_bin = json!({ "targets": [
{ "kind": ["bin"], "src_path": "/w/src/main.rs" },
{ "kind": ["cdylib"], "src_path": "/w/src/lib.rs" },
]});
assert_eq!(
crate_root_file(&lib_and_bin),
Some(PathBuf::from("/w/src/lib.rs"))
);
}
#[test]
fn member_src_dirs_resolves_from_src_path_including_a_custom_layout() {
let metadata = json!({
"packages": [
{ "name": "crate_a", "targets": [
{ "kind": ["lib"], "src_path": "/ws/crate_a/src/lib.rs" }
]},
{ "name": "crate_b", "targets": [
{ "kind": ["lib"], "src_path": "/ws/crate_b/lib.rs" }
]},
{ "name": "crate_c", "targets": [
{ "kind": ["bin"], "src_path": "/ws/crate_c/src/main.rs" }
]},
]
});
let dirs = member_src_dirs(&metadata);
assert!(dirs.contains(&PathBuf::from("/ws/crate_a/src")), "{dirs:?}");
assert!(
dirs.contains(&PathBuf::from("/ws/crate_b")),
"a custom [lib] path must resolve to its real root, not manifest_dir/src: {dirs:?}"
);
assert!(dirs.contains(&PathBuf::from("/ws/crate_c/src")), "{dirs:?}");
}
#[test]
fn member_src_dirs_prefers_lib_over_bin_and_skips_rootless_members() {
let metadata = json!({
"packages": [
{ "name": "both", "targets": [
{ "kind": ["bin"], "src_path": "/ws/both/src/main.rs" },
{ "kind": ["lib"], "src_path": "/ws/both/src/lib.rs" }
]},
{ "name": "rootless", "targets": [] },
]
});
let dirs = member_src_dirs(&metadata);
assert_eq!(dirs, vec![PathBuf::from("/ws/both/src")], "{dirs:?}");
}
#[test]
fn member_root_files_preserves_exact_custom_roots_and_is_deterministic() {
let metadata = json!({ "packages": [
{ "targets": [
{ "kind": ["lib"], "src_path": "/ws/z/src/lib.rs" },
{ "kind": ["bin"], "src_path": "/ws/z/src/main.rs" }
] },
{ "targets": [{ "kind": ["lib"], "src_path": "/ws/a/custom_root.rs" }] },
{ "targets": [{ "kind": ["lib"], "src_path": "/ws/a/custom_root.rs" }] },
{ "targets": [{ "kind": ["test"], "src_path": "/ws/t/test.rs" }] }
]});
assert_eq!(
member_root_files(&metadata),
[
PathBuf::from("/ws/a/custom_root.rs"),
PathBuf::from("/ws/z/src/lib.rs"),
PathBuf::from("/ws/z/src/main.rs")
]
);
}
#[test]
fn path_label_does_not_re_key_any_shape_that_occurs() {
for path in [
"src/lib.rs",
"src/main.rs",
"src/bin/conventional.rs",
"tools/outside.rs",
"single.rs",
"/abs/src/lib.rs",
"a/../b",
] {
assert_eq!(
path_label(Path::new(path)),
path,
"an ordinary path must label as itself, or every recorded baseline entry re-keys"
);
}
assert_eq!(
path_label(Path::new("with%pct/f.rs")),
"with%25pct/f.rs",
"a literal `%` escapes so no escaped label can be spelled by an unescaped one"
);
assert_eq!(path_label(Path::new("./a")), "a");
assert_eq!(path_label(Path::new("a//b")), "a/b");
assert_eq!(path_label(Path::new("/")), "/");
}
#[cfg(unix)]
#[test]
fn path_label_preserves_bytes_and_does_not_invent_separators() {
use std::os::unix::ffi::OsStrExt;
let bad = std::ffi::OsStr::from_bytes(b"src/ba\xffd.rs");
assert_eq!(
path_label(Path::new(bad)),
"src/ba%FFd.rs",
"an undecodable byte escapes rather than collapsing to U+FFFD"
);
let other = std::ffi::OsStr::from_bytes(b"src/ba\xfed.rs");
assert_ne!(
path_label(Path::new(bad)),
path_label(Path::new(other)),
"two paths differing only in undecodable bytes must keep two identities"
);
let backslash_in_name = std::ffi::OsStr::from_bytes(b"a\\b");
assert_eq!(
path_label(Path::new(backslash_in_name)),
"a\\b",
"on unix `\\` is a byte within one component, not a separator: labeling it as `a/b` would \
collide with the genuinely two-component path"
);
assert_ne!(
path_label(Path::new(backslash_in_name)),
path_label(Path::new("a/b")),
"the single file `a\\b` and the file `b` inside directory `a` are distinct observations"
);
}
#[cfg(windows)]
#[test]
fn a_windows_separator_labels_as_the_canonical_one() {
assert_eq!(path_label(Path::new("src\\lib.rs")), "src/lib.rs");
assert_eq!(path_label(Path::new("src\\bin\\x.rs")), "src/bin/x.rs");
assert_eq!(
path_label(Path::new("src/lib.rs")),
path_label(Path::new("src\\lib.rs")),
"both separators are separators on Windows, so both must reach one label"
);
}
#[test]
fn a_label_never_carries_a_platform_separator() {
for path in ["src/lib.rs", "a/b/c.rs", "/abs/x.rs"] {
let label = path_label(Path::new(path));
assert!(
std::path::MAIN_SEPARATOR == '/' || !label.contains(std::path::MAIN_SEPARATOR),
"a label must use `/` alone, so one commit yields one identity on every platform: {label:?}"
);
}
}
#[test]
fn crate_roots_are_unique_by_root_not_by_adjacency() {
let non_adjacent = json!({ "targets": [
{ "kind": ["bin"], "src_path": "/p/src/shared.rs" },
{ "kind": ["bin"], "src_path": "/p/src/between.rs" },
{ "kind": ["bin"], "src_path": "/p/src/shared.rs" }
]});
assert_eq!(
crate_roots(&non_adjacent).compiled(),
[
PathBuf::from("/p/src/shared.rs"),
PathBuf::from("/p/src/between.rs")
],
"a root reported twice is ONE compilation unit, and Cargo's reported order is preserved"
);
let adjacent = json!({ "targets": [
{ "kind": ["lib"], "src_path": "/p/src/shared.rs" },
{ "kind": ["bin"], "src_path": "/p/src/shared.rs" },
{ "kind": ["bin"], "src_path": "/p/src/other.rs" }
]});
assert_eq!(
crate_roots(&adjacent).compiled(),
[
PathBuf::from("/p/src/shared.rs"),
PathBuf::from("/p/src/other.rs")
],
"the adjacent arrangement collapses too — this half held before the fix, and is here so the \
test cannot be mistaken for pinning only it"
);
}
#[test]
fn crate_roots_tell_no_target_from_no_compiled_target() {
assert_eq!(crate_roots(&json!({})), CrateRoots::Unreported);
assert_eq!(
crate_roots(&json!({ "targets": [] })),
CrateRoots::Unreported
);
assert_eq!(
crate_roots(&json!({ "targets": [
{ "kind": ["example"], "src_path": "/p/examples/e.rs" },
{ "kind": ["custom-build"], "src_path": "/p/build.rs" }
]})),
CrateRoots::NoneCompiled,
"targets none of which is a library or a binary compile no root this reads"
);
assert_eq!(
crate_roots(&json!({ "targets": [
{ "kind": ["example"], "src_path": "/p/examples/e.rs" },
{ "kind": ["bin"], "src_path": "/p/src/main.rs" }
]})),
CrateRoots::Compiled(CompiledRoots(vec![PathBuf::from("/p/src/main.rs")]))
);
}
struct TempDir(ScratchRoot);
impl TempDir {
fn new(label: &str) -> Self {
Self(scratch_root(&format!("xingbiao-{label}")))
}
fn write(&self, name: &str, contents: &str) -> PathBuf {
let path = self.0.join(name);
std::fs::write(&path, contents).unwrap();
path
}
fn path(&self, name: &str) -> PathBuf {
self.0.join(name)
}
}
#[test]
fn canonicalize_or_fail_resolves_a_real_file_and_errors_on_a_missing_one() {
let dir = TempDir::new("canonicalize");
let file = dir.write("real.rs", "");
assert!(canonicalize_or_fail(&file).is_ok());
let missing = dir.path("does_not_exist.rs");
let err = canonicalize_or_fail(&missing).unwrap_err();
assert!(
err.contains("cannot resolve"),
"a missing path must fail loud, not silently skip: {err}"
);
}
#[test]
fn try_visit_reports_first_visit_then_repeat_and_fails_loud_on_an_unresolvable_path() {
let dir = TempDir::new("try-visit");
let file = dir.write("a.rs", "");
let mut visited = std::collections::HashSet::new();
assert_eq!(
try_visit(&mut visited, &file),
Ok(true),
"the first visit to a real file is new"
);
assert_eq!(
try_visit(&mut visited, &file),
Ok(false),
"a repeat visit to the same canonical file is not new"
);
assert!(try_visit(&mut visited, &dir.path("missing.rs")).is_err());
}
#[test]
fn claim_scratch_creates_a_fresh_root() {
let dir = TempDir::new("claim-fresh");
let root = dir.path("root");
assert!(claim_scratch(&root).is_ok());
assert!(root.is_dir());
}
#[test]
fn claim_scratch_refuses_an_existing_directory() {
let dir = TempDir::new("claim-existing");
let root = dir.path("root");
std::fs::create_dir(&root).expect("the fixture directory is writable");
assert!(
claim_scratch(&root).is_err(),
"a path that already exists must be refused, not silently adopted"
);
}
#[cfg(unix)]
#[test]
fn claim_scratch_refuses_a_pre_existing_symlink_that_create_dir_all_would_adopt() {
let dir = TempDir::new("claim-symlink");
let target = dir.path("elsewhere");
std::fs::create_dir(&target).expect("the symlink target is writable");
let root = dir.path("root");
std::os::unix::fs::symlink(&target, &root).expect("create the symlink");
assert!(
std::fs::create_dir_all(&root).is_ok(),
"control: create_dir_all silently adopts the symlink, which is exactly the defect claim_scratch exists \
to close"
);
assert!(
claim_scratch(&root).is_err(),
"a symlink at the path must be refused — mkdir cannot follow it, so adopting it would write through \
to whatever it points at"
);
}
#[test]
fn scratch_base_for_places_tmp_beside_the_profile_directory() {
for (exe, base) in [
("/w/target/debug/deps/t-1", "/w/target/tmp"),
(
"/w/target/x86_64-unknown-linux-gnu/release/deps/t-1",
"/w/target/x86_64-unknown-linux-gnu/tmp",
),
] {
assert_eq!(
scratch_base_for(Path::new(exe)),
Ok(PathBuf::from(base)),
"{exe}"
);
}
}
#[test]
fn scratch_base_for_refuses_a_layout_it_cannot_recognise_naming_the_executable() {
for exe in ["/usr/bin/t", "/w/target/debug/t", "/t", "deps/t"] {
let why = scratch_base_for(Path::new(exe)).expect_err(exe);
assert!(
why.contains(exe),
"the refusal names the executable's path: {why}"
);
}
}
#[test]
fn scratch_root_lives_under_the_base_and_is_removed_on_drop() {
let root = scratch_root("xingbiao-root-probe");
let path = root.path().to_path_buf();
assert!(path.starts_with(scratch_base()), "{}", path.display());
assert!(path.is_dir());
std::fs::write(path.join("f"), "x").unwrap();
drop(root);
assert!(
!path.exists(),
"the guard removes the root with what is in it"
);
}
#[test]
fn scratch_root_names_are_unique_per_call() {
let (a, b) = (
scratch_root("xingbiao-unique"),
scratch_root("xingbiao-unique"),
);
assert_ne!(a.path(), b.path());
}
#[test]
fn a_second_root_of_the_same_label_leaves_the_first_roots_files() {
let first = scratch_root("xingbiao-same-label");
let written = first.path().join("f");
std::fs::write(&written, "first").expect("write into the first root");
let second = scratch_root("xingbiao-same-label");
assert_eq!(
std::fs::read_to_string(&written).as_deref().ok(),
Some("first"),
"building a second root of the same label removed the first root's file"
);
assert_ne!(first.path(), second.path());
}
#[test]
fn scratch_root_refuses_a_label_the_base_would_not_contain() {
for label in ["/escaped", "../escaped", "nested/escaped"] {
let refused = std::panic::catch_unwind(|| scratch_root(label));
let why = refused.expect_err(label);
let message = why
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| why.downcast_ref::<&str>().copied())
.unwrap_or_else(|| panic!("the refusal carries a message: {label}"));
assert!(
message.contains(label),
"the refusal names the label it will not build a root from: {message}"
);
}
for label in [".", ".."] {
let root = scratch_root(label);
assert!(
root.path().starts_with(scratch_base()),
"a label the name contains is built, not refused: {}",
root.path().display()
);
}
}
#[test]
fn remove_if_present_tells_absence_from_a_failure() {
let root = scratch_root("xingbiao-remove-if-present");
let absent = root.path().join("never-created");
assert!(remove_if_present(&absent).is_ok(), "{}", absent.display());
let file = root.path().join("f");
std::fs::write(&file, "x").expect("write the file to remove as a directory");
let err = remove_if_present(&file).expect_err("a file is not a directory tree to remove");
assert_ne!(
err.kind(),
std::io::ErrorKind::NotFound,
"the error a caller must hear is not absence: {err}"
);
}