use super::*;
use std::ffi::OsString;
use std::path::Path;
const HOST_WINDOWS: bool = cfg!(windows);
fn path_var(dirs: &[&Path]) -> OsString {
std::env::join_paths(dirs).unwrap()
}
fn touch(dir: &Path, name: &str) -> std::path::PathBuf {
let p = dir.join(name);
std::fs::write(&p, b"x").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
}
p
}
fn exe_name(base: &str) -> String {
if HOST_WINDOWS {
format!("{base}.exe")
} else {
base.to_string()
}
}
fn go(program: &str, cwd: &Path, path: Option<&OsStr>) -> Result<std::path::PathBuf, Error> {
resolve(ResolveInput {
program: Path::new(program),
cwd: Some(cwd),
system_dirs: &no_system_dirs,
path_var: path,
windows: HOST_WINDOWS,
loadable_only: false,
normalise: &as_written,
})
}
fn path_var_for(dirs: &[&Path], windows: bool) -> OsString {
let sep = if windows { ";" } else { ":" };
OsString::from(
dirs.iter()
.map(|d| d.display().to_string())
.collect::<Vec<_>>()
.join(sep),
)
}
#[skuld::test]
fn path_var_is_split_on_the_simulated_platforms_separator() {
let win = split_path_var(Some(OsStr::new(r"C:\a;C:\b")), true);
assert_eq!(win.len(), 2, "{win:?}");
let nix = split_path_var(Some(OsStr::new("/a:/b")), false);
assert_eq!(nix.len(), 2, "{nix:?}");
let shredded = split_path_var(Some(OsStr::new(r"C:\a")), false);
assert_eq!(
shredded.len(),
2,
"a Windows path split POSIX-style is shredded: {shredded:?}"
);
}
#[skuld::test]
fn windows_path_var_quoting_protects_an_embedded_separator() {
let got = split_path_var(Some(OsStr::new(r#""C:\a;b";C:\c"#)), true);
assert_eq!(got, vec![PathBuf::from(r"C:\a;b"), PathBuf::from(r"C:\c")], "{got:?}");
}
#[skuld::test]
fn windows_path_var_quoting_strips_the_wrapping_quotes() {
let got = split_path_var(Some(OsStr::new(r#""C:\bin""#)), true);
assert_eq!(got, vec![PathBuf::from(r"C:\bin")], "{got:?}");
}
#[skuld::test]
fn posix_path_var_quotes_are_not_special() {
let got = split_path_var(Some(OsStr::new(r#""/a;b":/c"#)), false);
assert_eq!(got, vec![PathBuf::from(r#""/a;b""#), PathBuf::from("/c")], "{got:?}");
}
fn candidate(n: &str, w: bool) -> Vec<String> {
filename_candidates(OsStr::new(n), w, classify(OsStr::new(n), w))
.iter()
.map(|c| c.to_string_lossy().into_owned())
.collect()
}
#[skuld::test]
fn bare_extensionless_name_gets_only_the_exe_candidate() {
let got = candidate("tool", true);
assert_eq!(got, vec!["tool.exe"], "{got:?}");
}
#[skuld::test]
fn dotted_name_without_a_loadable_extension_still_gets_exe_appended() {
let got = candidate("python3.11", true);
assert_eq!(got, vec!["python3.11.exe"], "{got:?}");
}
#[skuld::test]
fn a_name_already_ending_in_exe_is_not_doubled() {
let got = candidate("tool.exe", true);
assert_eq!(got, vec!["tool.exe"], "{got:?}");
}
#[skuld::test]
fn the_exe_extension_check_is_case_insensitive() {
assert_eq!(candidate("TOOL.EXE", true), vec!["TOOL.EXE"]);
assert_eq!(candidate("Tool.Exe", true), vec!["Tool.Exe"]);
}
#[skuld::test]
fn a_com_extension_is_in_the_allowlist() {
let got = candidate("more.com", true);
assert_eq!(got, vec!["more.com"], "{got:?}");
}
#[skuld::test]
fn a_bat_extension_is_not_yet_in_the_allowlist() {
let got = candidate("tool.bat", true);
assert_eq!(got, vec!["tool.bat.exe"], "{got:?}");
}
#[skuld::test]
fn a_located_name_tries_the_exact_name_before_the_exe_one() {
let got = candidate("bin/my-program", true);
assert_eq!(got, vec!["bin/my-program", "bin/my-program.exe"], "{got:?}");
}
#[skuld::test]
fn a_located_dotted_name_gets_only_the_exact_candidate() {
let got = candidate(r"tools\thing.bin", true);
assert_eq!(got, vec![r"tools\thing.bin"], "{got:?}");
}
#[skuld::test]
fn a_located_name_with_only_a_leading_dot_still_gets_the_exe_fallback() {
let got = candidate(r"bin\.helper", true);
assert_eq!(got, vec![r"bin\.helper", r"bin\.helper.exe"], "{got:?}");
}
#[skuld::test]
fn a_located_name_already_ending_in_exe_or_com_gets_one_candidate() {
for n in [r"bin\tool.exe", r"bin\TOOL.EXE", r"bin\more.com"] {
let got = candidate(n, true);
assert_eq!(got.len(), 1, "{n:?} -> {got:?}");
assert_eq!(got[0], n, "{got:?}");
}
}
#[skuld::test]
fn posix_never_appends_exe_for_any_of_the_above() {
for n in [
"tool",
"python3.11",
"tool.exe",
"TOOL.EXE",
"more.com",
"tool.bat",
"bin/my-program",
] {
let got = candidate(n, false);
assert_eq!(
got,
vec![n.to_string()],
"POSIX must never append .exe: {n:?} -> {got:?}"
);
}
}
#[skuld::test]
fn every_searched_name_produces_exactly_one_candidate() {
for (n, w) in [
("tool", true),
("python3.11", true),
("tool.exe", true),
("TOOL.EXE", true),
("more.com", true),
("tool.bat", true),
("tool", false),
("python3.11", false),
] {
let got = filename_candidates(OsStr::new(n), w, classify(OsStr::new(n), w));
assert_eq!(got.len(), 1, "{n:?} (windows={w}) -> {got:?}");
}
}
#[skuld::test]
fn a_drive_relative_name_is_located_not_bare() {
assert_eq!(classify(OsStr::new("C:tool"), true), Shape::Located);
assert_eq!(classify(OsStr::new("tool"), true), Shape::BareName);
assert_eq!(classify(OsStr::new("C:tool"), false), Shape::BareName);
assert_eq!(classify(OsStr::new("1:tool"), true), Shape::Located);
assert_eq!(classify(OsStr::new(r"dir\tool"), true), Shape::Located);
assert_eq!(classify(OsStr::new("dir/tool"), true), Shape::Located);
assert_eq!(classify(OsStr::new(r"dir\tool"), false), Shape::BareName);
assert_eq!(classify(OsStr::new("dir/tool"), false), Shape::Located);
}
#[skuld::test]
fn bare_name_is_not_resolved_from_the_current_directory() {
let cwd = tempfile::tempdir().unwrap();
touch(cwd.path(), &exe_name("tool"));
assert_not_found("tool", go("tool", cwd.path(), None));
}
#[skuld::test]
fn bare_name_resolves_from_path() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let want = touch(bin.path(), &exe_name("tool"));
let p = path_var(&[bin.path()]);
assert_eq!(go("tool", cwd.path(), Some(&p)).unwrap(), want);
}
#[skuld::test]
fn path_wins_over_an_identically_named_file_in_cwd() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
touch(cwd.path(), &exe_name("tool"));
let want = touch(bin.path(), &exe_name("tool"));
let p = path_var(&[bin.path()]);
assert_eq!(go("tool", cwd.path(), Some(&p)).unwrap(), want);
}
#[skuld::test]
fn a_name_with_a_separator_resolves_against_cwd() {
let cwd = tempfile::tempdir().unwrap();
let want = touch(cwd.path(), &exe_name("tool"));
let got = go("./tool", cwd.path(), None).unwrap();
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
fn go_win_path(program: &str, cwd: &Path, path: Option<&OsStr>) -> Result<std::path::PathBuf, Error> {
resolve(ResolveInput {
program: Path::new(program),
cwd: Some(cwd),
system_dirs: &no_system_dirs,
path_var: path,
windows: true,
loadable_only: false,
normalise: &as_written,
})
}
fn go_win(program: &str, cwd: &Path) -> Result<std::path::PathBuf, Error> {
go_win_path(program, cwd, None)
}
#[skuld::test]
fn a_located_extensionless_image_resolves_on_windows() {
let cwd = tempfile::tempdir().unwrap();
let want = touch(cwd.path(), "myapp");
let got = go_win("./myapp", cwd.path()).expect("an extensionless pathed image must resolve");
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn a_located_image_with_an_unrelated_extension_resolves_on_windows() {
let cwd = tempfile::tempdir().unwrap();
let want = touch(cwd.path(), "thing.bin");
let got = go_win("./thing.bin", cwd.path()).expect("a .bin image must resolve");
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn a_located_name_prefers_the_exact_file_over_the_exe_one() {
let cwd = tempfile::tempdir().unwrap();
let want = touch(cwd.path(), "myapp");
touch(cwd.path(), "myapp.exe");
let got = go_win("./myapp", cwd.path()).unwrap();
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn a_located_name_still_falls_back_to_exe_when_only_that_exists() {
let cwd = tempfile::tempdir().unwrap();
let want = touch(cwd.path(), "my-program.exe");
let got = go_win("./my-program", cwd.path()).unwrap();
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn empty_path_elements_are_skipped() {
let cwd = tempfile::tempdir().unwrap();
touch(cwd.path(), &exe_name("tool"));
let bin = tempfile::tempdir().unwrap();
touch(bin.path(), &exe_name("tool"));
assert!(go("tool", cwd.path(), Some(&path_var(&[bin.path()]))).is_ok());
crate::test_child::run_fixture_with_cwd(
crate::test_child::fixture_path!(fixture_empty_path_elements_are_skipped),
cwd.path(),
FIXTURE_EMPTY_PATH_ELEMENTS_MARKER,
);
}
const FIXTURE_EMPTY_PATH_ELEMENTS_MARKER: &str = "COSCA_FIXTURE_EMPTY_PATH_ELEMENTS";
#[skuld::test]
fn fixture_empty_path_elements_are_skipped() {
let Some(cwd) = crate::test_child::expected_cwd(FIXTURE_EMPTY_PATH_ELEMENTS_MARKER) else {
return; };
assert!(
cwd.join(exe_name("tool")).is_file(),
"the parent must have planted `tool` in this directory: {cwd:?}"
);
let empty = if HOST_WINDOWS { ";;" } else { "::" };
assert_not_found("tool", go("tool", &cwd, Some(OsStr::new(empty))));
}
#[skuld::test]
fn relative_path_elements_are_skipped() {
let cwd = tempfile::tempdir().unwrap();
touch(cwd.path(), &exe_name("tool"));
let bin = tempfile::tempdir().unwrap();
touch(bin.path(), &exe_name("tool"));
assert!(
go("tool", cwd.path(), Some(&path_var(&[bin.path()]))).is_ok(),
"positive control"
);
crate::test_child::run_fixture_with_cwd(
crate::test_child::fixture_path!(fixture_relative_path_elements_are_skipped),
cwd.path(),
FIXTURE_RELATIVE_PATH_ELEMENTS_MARKER,
);
}
const FIXTURE_RELATIVE_PATH_ELEMENTS_MARKER: &str = "COSCA_FIXTURE_RELATIVE_PATH_ELEMENTS";
#[skuld::test]
fn fixture_relative_path_elements_are_skipped() {
let Some(cwd) = crate::test_child::expected_cwd(FIXTURE_RELATIVE_PATH_ELEMENTS_MARKER) else {
return; };
assert!(
cwd.join(exe_name("tool")).is_file(),
"the parent must have planted `tool` in this directory: {cwd:?}"
);
assert_not_found("tool", go("tool", &cwd, Some(OsStr::new("."))));
}
#[skuld::test]
fn the_exe_file_wins_over_an_extensionless_namesake_beside_it() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
touch(bin.path(), "tool"); let want = touch(bin.path(), "tool.exe");
let p = path_var_for(&[bin.path()], true);
assert_eq!(go_win_path("tool", cwd.path(), Some(&p)).unwrap(), want);
}
#[skuld::test]
fn an_extensionless_file_no_longer_resolves_even_with_no_exe_on_path() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
touch(bin.path(), "tool");
let p = path_var_for(&[bin.path()], true);
assert_not_found("tool", go_win_path("tool", cwd.path(), Some(&p)));
let want = touch(bin.path(), "tool.exe");
assert_eq!(go_win_path("tool", cwd.path(), Some(&p)).unwrap(), want);
}
#[skuld::test]
fn a_quoted_path_entry_with_an_embedded_semicolon_is_not_silently_dropped() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let semi_dir = bin.path().join("sub;dir");
std::fs::create_dir(&semi_dir).unwrap();
let want = touch(&semi_dir, "tool.exe");
let quoted = OsString::from(format!("\"{}\"", semi_dir.display()));
assert_eq!(go_win_path("tool", cwd.path(), Some("ed)).unwrap(), want);
}
#[skuld::test]
fn result_is_always_absolute() {
let cwd = tempfile::tempdir().unwrap();
touch(cwd.path(), &exe_name("tool"));
let got = go("./tool", cwd.path(), None).unwrap();
assert!(
got.is_absolute(),
"backends skip their own search only if this is absolute: {got:?}"
);
}
#[cfg(unix)]
#[skuld::test]
fn a_readable_but_non_executable_match_is_skipped() {
use std::os::unix::fs::PermissionsExt;
let cwd = tempfile::tempdir().unwrap();
let a = tempfile::tempdir().unwrap();
let b = tempfile::tempdir().unwrap();
let dud = touch(a.path(), "tool");
std::fs::set_permissions(&dud, std::fs::Permissions::from_mode(0o644)).unwrap();
let want = touch(b.path(), "tool");
std::fs::set_permissions(&want, std::fs::Permissions::from_mode(0o755)).unwrap();
let p = path_var(&[a.path(), b.path()]);
assert_eq!(go("tool", cwd.path(), Some(&p)).unwrap(), want);
}
#[skuld::test]
fn a_relative_cwd_is_absolutised_so_it_cannot_be_applied_twice() {
let tmp = tempfile::tempdir().unwrap();
let sub = tmp.path().join("sub");
std::fs::create_dir(&sub).unwrap();
#[cfg_attr(
not(unix),
allow(unused_variables, reason = "only cfg(unix) reads `want` (to set the execute bit)")
)]
let want = touch(&sub, &exe_name("tool"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&want, std::fs::Permissions::from_mode(0o755)).unwrap();
}
crate::test_child::run_fixture_with_cwd(
crate::test_child::fixture_path!(fixture_relative_cwd_is_absolutised),
tmp.path(),
FIXTURE_RELATIVE_CWD_MARKER,
);
}
const FIXTURE_RELATIVE_CWD_MARKER: &str = "COSCA_FIXTURE_RELATIVE_CWD";
#[skuld::test]
fn fixture_relative_cwd_is_absolutised() {
let Some(cwd) = crate::test_child::expected_cwd(FIXTURE_RELATIVE_CWD_MARKER) else {
return; };
let want = cwd.join("sub").join(exe_name("tool"));
assert!(want.is_file(), "the parent must have planted `tool` here: {want:?}");
#[cfg(windows)]
let got = {
use crate::child::spawn::windows_raw::{env_snapshot::EnvSnapshot, resolve};
let base = resolve::effective_cwd(
Some(Path::new("sub")),
&resolve::DriveDirs::new(&EnvSnapshot::read().unwrap()),
|| std::env::current_dir().map_err(Error::Io),
)
.unwrap();
resolve::resolve_executable(Path::new("./tool"), Some(&base), None).unwrap()
};
#[cfg(not(windows))]
let got = go("./tool", Path::new("sub"), None).unwrap();
assert!(got.is_absolute(), "{got:?}");
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[cfg(windows)]
#[skuld::test]
fn a_drive_relative_name_fails_closed() {
let cwd = tempfile::tempdir().unwrap();
touch(cwd.path(), "tool.exe");
crate::test_child::run_fixture_with_cwd(
crate::test_child::fixture_path!(fixture_drive_relative_name_fails_closed),
cwd.path(),
FIXTURE_DRIVE_RELATIVE_MARKER,
);
}
#[cfg(windows)]
const FIXTURE_DRIVE_RELATIVE_MARKER: &str = "COSCA_FIXTURE_DRIVE_RELATIVE";
#[cfg(windows)]
#[skuld::test]
fn fixture_drive_relative_name_fails_closed() {
let Some(cwd) = crate::test_child::expected_cwd(FIXTURE_DRIVE_RELATIVE_MARKER) else {
return; };
assert!(
cwd.join("tool.exe").is_file(),
"the parent must have planted `tool.exe` in this directory: {cwd:?}"
);
assert_refused_on_shape("C:tool", go("C:tool", &cwd, None));
}
#[skuld::test]
fn bare_name_in_a_system_dir_and_on_path_resolves_from_the_system_dir() {
let cwd = tempfile::tempdir().unwrap();
let sysdir = tempfile::tempdir().unwrap();
let pathdir = tempfile::tempdir().unwrap();
let want = touch(sysdir.path(), "tool.exe");
touch(pathdir.path(), "tool.exe"); let system_dirs = [sysdir.path().to_path_buf()];
let system_dirs_fn = || -> Result<Vec<PathBuf>, Error> { Ok(system_dirs.to_vec()) };
let path = path_var_for(&[pathdir.path()], true);
let got = resolve(ResolveInput {
program: Path::new("tool"),
cwd: Some(cwd.path()),
system_dirs: &system_dirs_fn,
path_var: Some(&path),
windows: true,
loadable_only: false,
normalise: &as_written,
})
.unwrap();
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn bare_name_only_on_path_still_resolves_from_path() {
let cwd = tempfile::tempdir().unwrap();
let sysdir = tempfile::tempdir().unwrap(); let pathdir = tempfile::tempdir().unwrap();
let want = touch(pathdir.path(), "tool.exe"); let system_dirs = [sysdir.path().to_path_buf()];
let system_dirs_fn = || -> Result<Vec<PathBuf>, Error> { Ok(system_dirs.to_vec()) };
let path = path_var_for(&[pathdir.path()], true);
let got = resolve(ResolveInput {
program: Path::new("tool"),
cwd: Some(cwd.path()),
system_dirs: &system_dirs_fn,
path_var: Some(&path),
windows: true,
loadable_only: false,
normalise: &as_written,
})
.unwrap();
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn empty_system_dirs_reproduces_the_pre_fix_path_only_search() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let want = touch(bin.path(), "tool.exe"); let path = path_var_for(&[bin.path()], true);
let got = resolve(ResolveInput {
program: Path::new("tool"),
cwd: Some(cwd.path()),
system_dirs: &no_system_dirs,
path_var: Some(&path),
windows: true,
loadable_only: false,
normalise: &as_written,
})
.unwrap();
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
let miss = resolve(ResolveInput {
program: Path::new("tool"),
cwd: Some(cwd.path()),
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &as_written,
});
assert_not_found("tool", miss);
}
#[skuld::test]
fn posix_ignores_system_dirs_entirely() {
let cwd = tempfile::tempdir().unwrap();
let sysdir = tempfile::tempdir().unwrap();
touch(sysdir.path(), "tool");
let system_dirs = [sysdir.path().to_path_buf()];
let system_dirs_fn = || -> Result<Vec<PathBuf>, Error> {
panic!("system_dirs must not be queried when windows is false: {system_dirs:?}")
};
let got = resolve(ResolveInput {
program: Path::new("tool"),
cwd: Some(cwd.path()),
system_dirs: &system_dirs_fn,
path_var: None,
windows: false,
loadable_only: false,
normalise: &as_written,
});
assert_not_found("tool", got);
}
#[skuld::test]
fn a_located_name_still_resolves_when_the_system_dirs_query_fails() {
let cwd = tempfile::tempdir().unwrap();
let want = touch(cwd.path(), "myapp");
let system_dirs_fn =
|| -> Result<Vec<PathBuf>, Error> { panic!("system_dirs must not be queried for a Located name") };
let got = resolve(ResolveInput {
program: Path::new("./myapp"),
cwd: Some(cwd.path()),
system_dirs: &system_dirs_fn,
path_var: None,
windows: true,
loadable_only: false,
normalise: &as_written,
})
.unwrap();
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn a_bare_name_fails_closed_when_the_system_dirs_query_fails() {
let cwd = tempfile::tempdir().unwrap();
let pathdir = tempfile::tempdir().unwrap();
touch(pathdir.path(), "tool.exe");
let path = path_var_for(&[pathdir.path()], true);
let system_dirs_fn =
|| -> Result<Vec<PathBuf>, Error> { Err(Error::Io(std::io::Error::other("system_dirs query failed"))) };
let got = resolve(ResolveInput {
program: Path::new("tool"),
cwd: Some(cwd.path()),
system_dirs: &system_dirs_fn,
path_var: Some(&path),
windows: true,
loadable_only: false,
normalise: &as_written,
});
match got {
Err(Error::Io(e)) => {
assert_eq!(e.to_string(), "system_dirs query failed", "{e}");
}
other => panic!("expected the system_dirs error to propagate verbatim, got {other:?}"),
}
}
#[skuld::test]
fn a_located_name_never_falls_back_to_a_search() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
touch(bin.path(), "helper");
touch(bin.path(), "helper.exe");
let pv = path_var_for(&[bin.path()], true);
assert_not_found("./helper", go_win_path("./helper", cwd.path(), Some(&pv)));
}
#[skuld::test]
fn a_miss_is_reported_as_not_found() {
let cwd = tempfile::tempdir().unwrap();
let err = go_win_path("no-such-program-41d9", cwd.path(), None).unwrap_err();
match err {
Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "{e:?}"),
other => panic!("a miss must be an Io(NotFound), got {other:?}"),
}
}
#[skuld::test]
fn a_directory_named_like_the_program_is_not_returned() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
std::fs::create_dir(bin.path().join(exe_name("tool"))).unwrap();
let p = path_var(&[bin.path()]);
assert_not_found("tool", go("tool", cwd.path(), Some(&p)));
let bin2 = tempfile::tempdir().unwrap();
let want = touch(bin2.path(), &exe_name("tool"));
let p2 = path_var(&[bin2.path()]);
assert_eq!(go("tool", cwd.path(), Some(&p2)).unwrap(), want);
}
#[skuld::test]
fn a_separator_terminated_located_name_gets_no_exe_fallback() {
for n in [r"tools\thing.bin\", r"bin\tool\", "bin/tool/", r"C:\"] {
let got = candidate(n, true);
assert_eq!(
got,
vec![n.to_string()],
"{n:?} must yield exactly one candidate: {got:?}"
);
}
}
#[skuld::test]
fn an_empty_program_never_resolves() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
touch(bin.path(), ".exe");
let pv = path_var_for(&[bin.path()], true);
assert_refused_on_shape("", go_win_path("", cwd.path(), Some(&pv)));
assert_refused_on_shape("", go_win_path("", cwd.path(), None));
}
fn assert_refused_on_shape(name: &str, got: Result<std::path::PathBuf, Error>) {
match got {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!("{name:?} names no file and must be refused on shape, got {other:?}"),
}
}
fn assert_not_found(name: &str, got: Result<std::path::PathBuf, Error>) {
match got {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
other => panic!("{name:?} was searched and missed, so it must be NotFound, got {other:?}"),
}
}
#[skuld::test]
fn a_drive_relative_name_is_refused_on_shape() {
let cwd = tempfile::tempdir().unwrap();
for n in ["C:tool", "D:sub/x", "C:tool.exe", r"Z:a\b", "1:tool", "\u{e9}:tool"] {
assert_refused_on_shape(n, go_win_path(n, cwd.path(), None));
}
}
#[skuld::test]
fn an_accepted_name_that_is_simply_absent_is_not_found() {
let cwd = tempfile::tempdir().unwrap();
for n in [
"tool",
r"\\?\C:/x",
"./missing",
r"C:\abs\missing.exe",
r"C:\dir\...\tool.exe",
r"sub\missing",
"sub/missing",
] {
assert_not_found(n, go_win_path(n, cwd.path(), None));
}
assert_not_found("tool", go(&exe_name("tool"), cwd.path(), None));
}
#[skuld::test]
fn a_program_with_no_stem_is_refused() {
let cwd = tempfile::tempdir().unwrap();
for n in [
"",
r"C:\t\thing.bin\",
r"C:\t\dir\",
"bin/",
r"C:\t\.",
r"C:\t\..",
".",
"..",
r"C:\",
"C:",
"C:.",
"C:..",
] {
assert_refused_on_shape(n, go_win_path(n, cwd.path(), None));
}
}
#[skuld::test]
fn a_stemless_program_is_refused_on_posix_too() {
let cwd = tempfile::tempdir().unwrap();
for n in ["", "bin/", ".", "..", "/"] {
assert_refused_on_shape(n, go(n, cwd.path(), None));
}
}
#[skuld::test]
fn a_dot_terminated_name_never_invents_a_planted_sibling() {
let cwd = tempfile::tempdir().unwrap();
let dir = cwd.path().join("t");
std::fs::create_dir(&dir).unwrap();
touch(&dir, "..exe");
let named = format!("{}/.", dir.display());
assert_refused_on_shape(&named, go_win_path(&named, cwd.path(), None));
}
#[skuld::test]
fn a_trailing_dot_or_space_is_an_ordinary_name_on_both_platforms() {
let cwd = tempfile::tempdir().unwrap();
for n in [
"...",
"....",
". ",
" .",
".. ",
" ",
"tool.",
"tool ",
r"C:\t\...",
r"C:\t\. ",
r"C:\t\dir\.. ",
] {
assert!(!names_no_file(OsStr::new(n), true), "{n:?} names a file on Windows");
assert_not_found(n, go_win_path(n, cwd.path(), None));
}
for n in ["tool.", "tool ", "...", ". ", " .", "....", "a.", "bin/tool."] {
assert!(!names_no_file(OsStr::new(n), false), "{n:?} names a file on POSIX");
assert_eq!(candidate(n, false), vec![n.to_string()], "POSIX never rewrites a name");
}
}
#[skuld::test]
fn a_dot_run_name_is_searched_for_like_any_other_bare_name() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let planted = touch(bin.path(), "....exe");
let pv = path_var_for(&[bin.path()], true);
let got = go_win_path("...", cwd.path(), Some(&pv)).expect("`...` names a file and must resolve");
assert_eq!(got, planted, "{got:?}");
}
#[skuld::test]
fn the_exe_rule_appends_to_the_name_as_written() {
assert_eq!(candidate("tool.", true), vec!["tool..exe"]);
assert_eq!(candidate("tool ", true), vec!["tool .exe"]);
assert_eq!(candidate("tool. ", true), vec!["tool. .exe"]);
assert_eq!(candidate("...", true), vec!["....exe"]);
assert_eq!(candidate("tool.exe.", true), vec!["tool.exe..exe"]);
assert_eq!(candidate(r"bin\tool ", true), vec![r"bin\tool ", r"bin\tool .exe"]);
assert_eq!(candidate(r"bin\tool.", true), vec![r"bin\tool."]);
assert_eq!(
candidate(r"C:\dir\...\tool ", true),
vec![r"C:\dir\...\tool ", r"C:\dir\...\tool .exe"]
);
}
#[skuld::test]
fn a_prefix_only_located_name_is_refused_like_a_drive_root() {
let cwd = tempfile::tempdir().unwrap();
for n in [
r"\\server\share",
r"\\server\share\",
"//server/share",
r"\\?\C:",
r"\\?\C:\",
r"\\?\UNC\server\share",
r"\\?\GLOBALROOT",
r"\\.\pipe",
r"\\",
r"\\?\",
] {
assert_refused_on_shape(n, go_win_path(n, cwd.path(), None));
}
}
#[skuld::test]
fn a_verbatim_prefix_is_split_on_the_same_separators_as_the_rest_of_the_string() {
for (n, want) in [
(r"\\?\UNC\srv/shr\a", "a"),
(r"\\?\UNC\srv\shr/a", "a"),
(r"\\?\UNC\srv/shr/a", "a"),
(r"\\?\ns/a", "a"),
(r"\\?\GLOBALROOT/Device/X/tool.exe", "tool.exe"),
(r"\\?\UNC/srv\tool.exe", "tool.exe"),
(r"\\?\UNC/server\share", "share"),
(r"\\?\UNC/srv/shr", "shr"),
] {
let got = final_component(OsStr::new(n), true);
assert_eq!(got, want.as_bytes(), "{n:?} -> {:?}", String::from_utf8_lossy(got));
assert!(!names_no_file(OsStr::new(n), true), "{n:?} names a file");
}
for n in [
r"\\?\UNC\srv/shr",
r"\\?\UNC\srv\shr",
r"\\?\unc\srv\shr",
r"\\?\ns",
r"\\?\GLOBALROOT",
] {
assert!(names_no_file(OsStr::new(n), true), "{n:?} names no file");
}
}
#[skuld::test]
fn a_prefix_only_located_name_never_grows_an_exe_candidate() {
for n in [r"\\server\share", r"\\?\C:", r"\\?\UNC\server\share", r"\\.\pipe"] {
let got = candidate(n, true);
assert_eq!(got, vec![n.to_string()], "{n:?} must not grow a candidate: {got:?}");
}
}
#[skuld::test]
fn a_name_that_names_no_file_grows_no_candidate_on_either_axis() {
for n in [
"",
".",
"..",
r"C:\t\.",
r"C:\t\..",
r"a\.",
"./.",
r"\\server\share\.",
r"\\?\C:\.",
r"\\.\pipe\.",
r"C:\t\dir\",
] {
assert_eq!(candidate(n, true), vec![n.to_string()], "{n:?}");
}
}
#[skuld::test]
fn a_name_under_a_windows_prefix_is_still_a_filename() {
for (n, want) in [
(
r"\\server\share\tool",
vec![r"\\server\share\tool", r"\\server\share\tool.exe"],
),
(r"\\?\C:\tools\thing.bin", vec![r"\\?\C:\tools\thing.bin"]),
(r"\\?\UNC\server\share\tool.exe", vec![r"\\?\UNC\server\share\tool.exe"]),
(r"\\.\pipe\x", vec![r"\\.\pipe\x", r"\\.\pipe\x.exe"]),
] {
assert!(!names_no_file(OsStr::new(n), true), "{n:?} names a file");
let got = candidate(n, true);
assert_eq!(got, want, "{n:?} -> {got:?}");
}
}
#[cfg(unix)]
#[skuld::test]
fn a_posix_name_with_a_stem_still_resolves() {
let cwd = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let pv = path_var_for(&[bin.path()], false);
for n in [r"bin\", r"a\.", ".helper", "..helper"] {
touch(bin.path(), n);
let got = go(n, cwd.path(), Some(&pv));
assert!(got.is_ok(), "{n:?} has a stem on POSIX and must resolve, got {got:?}");
}
}
#[skuld::test]
fn a_name_with_a_stem_still_resolves() {
let cwd = tempfile::tempdir().unwrap();
let bin = cwd.path().join("bin");
std::fs::create_dir(&bin).unwrap();
for n in [".helper", "..helper", "tool.exe"] {
touch(&bin, n);
let got = go_win_path(&format!("{}/{}", bin.display(), n), cwd.path(), None);
assert!(got.is_ok(), "{n:?} has a stem and must resolve, got {got:?}");
}
}
#[skuld::test]
fn an_image_without_a_loadable_extension_is_refused() {
for n in [
r"C:\dir\tool",
r"C:\dir\tool.bat",
r"C:\dir\tool.cmd",
r"C:\dir\tool.exe.bat",
r"C:\dir\tool.exe.",
r"C:\dir\tool.bin",
] {
assert!(
reject_unloadable_image(Path::new(n), true).is_err(),
"{n:?} is not a loadable image name and must be refused"
);
}
}
#[skuld::test]
fn the_elevated_allowlist_also_refuses_the_wider_association_surface() {
for n in [
r"C:\dir\shortcut.lnk",
r"C:\dir\script.vbs",
r"C:\dir\script.ps1",
r"C:\dir\script.js",
r"C:\dir\page.hta",
r"C:\dir\installer.msi",
] {
assert!(
reject_unloadable_image(Path::new(n), true).is_err(),
"{n:?} is a shell association, not a loadable image, and must be refused"
);
}
}
#[skuld::test]
fn a_loadable_image_name_is_accepted() {
for n in [
r"C:\dir\tool.exe",
r"C:\dir\TOOL.EXE",
r"C:\dir\Tool.Exe",
r"C:\dir\more.com",
r"C:\dir\MORE.COM",
r"C:\dir\tool.bat.exe",
] {
assert!(
reject_unloadable_image(Path::new(n), true).is_ok(),
"{n:?} is a loadable image name and must be accepted"
);
}
}
#[skuld::test]
fn a_prefix_ending_in_exe_is_not_an_image_name() {
for n in [r"\\server\share.exe", r"\\?\UNC\server\share.com"] {
assert!(
reject_unloadable_image(Path::new(n), true).is_err(),
"{n:?} names no file and must be refused"
);
}
}