use super::*;
use crate::command::EnvOp;
use crate::resolve::no_drive_dir;
use std::ffi::OsString;
use std::path::Path;
fn resolve_with(exe: &Path, cmd_cwd: Option<&Path>, ops: &[EnvOp]) -> Result<PathBuf, Error> {
let snapshot = EnvSnapshot::read().unwrap();
let block = EnvSnapshot::from_block(ChildEnv::capture(&snapshot, ops).into_block()?);
let base = effective_cwd(cmd_cwd, &DriveDirs::new(&snapshot), || {
std::env::current_dir().map_err(Error::Io)
})?;
let path = block.var(OsStr::new("PATH"));
resolve_executable(exe, Some(&base), &no_drive_dir, path.as_deref())
}
fn snapshot(base: &[(OsString, OsString)]) -> EnvSnapshot {
let mut block = Vec::new();
for (key, val) in base {
block.extend(key.encode_wide());
block.push(u16::from(b'='));
block.extend(val.encode_wide());
block.push(0);
}
block.push(0);
EnvSnapshot::from_block(block)
}
fn build_env_block_from(base: &[(OsString, OsString)], ops: &[EnvOp]) -> Result<Vec<u16>, Error> {
ChildEnv::capture(&snapshot(base), ops).into_block()
}
fn assert_not_found(got: Result<PathBuf, Error>) {
match got {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
other => panic!("a search miss must be Io(NotFound), got {other:?}"),
}
}
fn no_system_dirs() -> Result<Vec<PathBuf>, Error> {
Ok(Vec::new())
}
#[skuld::test]
fn resolve_an_absolute_path_to_an_existing_image_yields_that_path() {
let me = std::env::current_exe().unwrap();
assert_eq!(resolve_with(&me, None, &[]).unwrap(), me);
}
#[skuld::test]
fn resolve_bare_name_is_not_taken_from_base_cwd() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(std::env::current_exe().unwrap(), dir.path().join("sp_shadow.exe")).unwrap();
assert_not_found(resolve_executable_in(
std::path::Path::new("sp_shadow"),
Some(dir.path()),
&no_system_dirs,
&no_drive_dir,
None,
false,
));
}
#[skuld::test]
fn resolve_bare_extensionless_name_appends_exe() {
let p = resolve_with(std::path::Path::new("cmd"), None, &[]).unwrap();
assert!(
p.is_absolute() && p.exists() && p.extension().is_some_and(|e| e.eq_ignore_ascii_case("exe")),
"{p:?}"
);
}
#[skuld::test]
fn resolve_executable_honors_an_env_set_path_override() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(std::env::current_exe().unwrap(), dir.path().join("sp_env_path.exe")).unwrap();
let want = dir.path().join("sp_env_path.exe");
assert_not_found(resolve_with(std::path::Path::new("sp_env_path"), None, &[]));
let ops = [EnvOp::Set(
OsString::from("PATH"),
dir.path().as_os_str().to_os_string(),
)];
let got = resolve_with(std::path::Path::new("sp_env_path"), None, &ops);
assert_eq!(got.unwrap().canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn resolve_executable_path_key_match_is_case_insensitive() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(std::env::current_exe().unwrap(), dir.path().join("sp_env_path_ci.exe")).unwrap();
let want = dir.path().join("sp_env_path_ci.exe");
let ops = [EnvOp::Set(
OsString::from("Path"),
dir.path().as_os_str().to_os_string(),
)];
let got = resolve_with(std::path::Path::new("sp_env_path_ci"), None, &ops);
assert_eq!(got.unwrap().canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn resolve_executable_env_clear_defeats_ambient_path() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(std::env::current_exe().unwrap(), dir.path().join("sp_env_clear.exe")).unwrap();
let set = [EnvOp::Set(
OsString::from("PATH"),
dir.path().as_os_str().to_os_string(),
)];
assert!(resolve_with(std::path::Path::new("sp_env_clear"), None, &set).is_ok());
let got = resolve_with(
std::path::Path::new("sp_env_clear"),
None,
&[
EnvOp::Set(OsString::from("PATH"), dir.path().as_os_str().to_os_string()),
EnvOp::Clear,
],
);
assert_not_found(got);
}
#[skuld::test]
fn resolve_executable_env_remove_path_defeats_ambient_path() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(std::env::current_exe().unwrap(), dir.path().join("sp_env_remove.exe")).unwrap();
let set = [EnvOp::Set(
OsString::from("PATH"),
dir.path().as_os_str().to_os_string(),
)];
assert!(resolve_with(std::path::Path::new("sp_env_remove"), None, &set).is_ok());
let got = resolve_with(
std::path::Path::new("sp_env_remove"),
None,
&[
EnvOp::Set(OsString::from("PATH"), dir.path().as_os_str().to_os_string()),
EnvOp::Remove(OsString::from("path")),
],
);
assert_not_found(got);
}
#[skuld::test]
fn resolve_executable_uses_the_given_cwd_not_the_process_cwd() {
let cmd_dir = tempfile::tempdir().unwrap();
let want = std::fs::copy(
std::env::current_exe().unwrap(),
cmd_dir.path().join("sp_b1_helper.exe"),
)
.map(|_| cmd_dir.path().join("sp_b1_helper.exe"))
.unwrap();
let got = resolve_with(std::path::Path::new("./sp_b1_helper.exe"), Some(cmd_dir.path()), &[]);
assert_eq!(got.unwrap().canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn resolve_executable_falls_back_to_the_process_cwd_when_no_cwd_is_given() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(std::env::current_exe().unwrap(), dir.path().join("sp_b1_fallback.exe")).unwrap();
crate::test_child::run_fixture_with_cwd(
crate::test_child::fixture_path!(fixture_resolve_executable_falls_back_to_process_cwd),
dir.path(),
FIXTURE_RESOLVE_FALLBACK_MARKER,
);
}
const FIXTURE_RESOLVE_FALLBACK_MARKER: &str = "COSCA_FIXTURE_RESOLVE_FALLBACK";
#[skuld::test]
fn fixture_resolve_executable_falls_back_to_process_cwd() {
let Some(cwd) = crate::test_child::expected_cwd(FIXTURE_RESOLVE_FALLBACK_MARKER) else {
return; };
let want = cwd.join("sp_b1_fallback.exe");
assert!(
want.is_file(),
"the parent must have planted `sp_b1_fallback.exe` here: {want:?}"
);
let got = resolve_with(std::path::Path::new("./sp_b1_fallback.exe"), None, &[]);
assert_eq!(got.unwrap().canonicalize().unwrap(), want.canonicalize().unwrap());
}
#[skuld::test]
fn empty_ops_pass_the_snapshot_explicitly() {
let block = build_env_block_from(&[(OsString::from("A"), OsString::from("1"))], &[]).unwrap();
assert_eq!(String::from_utf16(&block).unwrap(), "A=1\0\0");
}
#[skuld::test]
fn set_sorts_ci_and_double_nul() {
let b = build_env_block_from(
&[],
&[
EnvOp::Set("Zeta".into(), "1".into()),
EnvOp::Set("alpha".into(), "2".into()),
],
)
.unwrap();
assert_eq!(&b[b.len() - 2..], &[0u16, 0u16]);
let s = String::from_utf16(&b).unwrap();
assert!(s.find("alpha=").unwrap() < s.find("Zeta=").unwrap(), "{s:?}");
}
#[skuld::test]
fn remove_is_case_insensitive() {
let b = build_env_block_from(
&[(OsString::from("SP_R"), OsString::from("x"))],
&[EnvOp::Remove("sp_r".into())],
)
.unwrap();
assert!(!String::from_utf16(&b).unwrap().to_uppercase().contains("SP_R="));
}
#[skuld::test]
fn clear_then_set_yields_only_the_set_var() {
let b = build_env_block_from(
&[(OsString::from("PATH"), OsString::from("x"))],
&[EnvOp::Clear, EnvOp::Set("ONLYME".into(), "1".into())],
)
.unwrap();
let s = String::from_utf16(&b).unwrap();
assert!(s.contains("ONLYME=1") && !s.to_uppercase().contains("PATH="));
}
#[skuld::test]
fn embedded_nul_is_rejected() {
let e = build_env_block_from(&[], &[EnvOp::Set("K".into(), OsString::from("a\u{0}b"))]).unwrap_err();
assert!(matches!(e, crate::error::Error::Io(_)));
}
#[skuld::test]
fn resolve_skips_directory_shadow_and_finds_path_exe() {
let base = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
let shadow_dir = tempfile::tempdir().unwrap();
std::fs::create_dir(shadow_dir.path().join("sp_dirtool.exe")).unwrap();
let path_copy = other.path().join("sp_dirtool.exe");
std::fs::copy(std::env::current_exe().unwrap(), &path_copy).unwrap();
let joined = std::env::join_paths([shadow_dir.path(), other.path()]).unwrap();
let got = resolve_executable_in(
std::path::Path::new("sp_dirtool"),
Some(base.path()),
&no_system_dirs,
&no_drive_dir,
Some(joined.as_os_str()),
false,
)
.unwrap();
assert_eq!(got.canonicalize().unwrap(), path_copy.canonicalize().unwrap());
}
#[skuld::test]
fn resolve_absolute_directory_is_not_returned() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sp_dir_shadow.exe");
std::fs::create_dir(&sub).unwrap();
assert_not_found(resolve_executable_in(
&sub,
Some(dir.path()),
&no_system_dirs,
&no_drive_dir,
None,
false,
));
}
#[skuld::test]
fn path_wins_over_base_cwd_when_both_have_exe() {
let base = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
let me = std::env::current_exe().unwrap();
let base_copy = base.path().join("sp_pref.exe");
std::fs::copy(&me, &base_copy).unwrap();
std::fs::copy(&me, other.path().join("sp_pref.exe")).unwrap();
let got = resolve_executable_in(
std::path::Path::new("sp_pref"),
Some(base.path()),
&no_system_dirs,
&no_drive_dir,
Some(other.path().as_os_str()),
false,
)
.unwrap();
let want = other.path().join("sp_pref.exe");
assert_eq!(got.canonicalize().unwrap(), want.canonicalize().unwrap());
assert_ne!(got.canonicalize().unwrap(), base_copy.canonicalize().unwrap());
}
#[skuld::test]
fn clear_only_yields_empty_double_nul_block() {
let b = build_env_block_from(&[(OsString::from("A"), OsString::from("1"))], &[EnvOp::Clear]).unwrap();
assert_eq!(b, vec![0u16, 0u16]);
}
#[skuld::test]
fn windows_system_dirs_are_real_existing_directories() {
let dirs = windows_system_dirs().unwrap();
for dir in &dirs {
assert!(dir.is_dir(), "{dir:?} is not a real, existing directory");
}
let sys32 = get_system_directory_via(|buf| {
unsafe { GetSystemDirectoryW(buf) }
});
let win = get_system_windows_directory_via(|buf| {
unsafe { GetSystemWindowsDirectoryW(buf) }
});
assert!(
sys32.is_ok(),
"GetSystemDirectoryW should succeed under the test runner, got {sys32:?}"
);
assert!(
win.is_ok(),
"GetSystemWindowsDirectoryW should succeed under the test runner, got {win:?}"
);
let (sys32, win) = (sys32.unwrap(), win.unwrap());
assert_eq!(
dirs,
vec![sys32, win],
"expected exactly [System32, Windows dir], got {dirs:?}"
);
let app_dir = std::env::current_exe().unwrap().parent().unwrap().to_path_buf();
assert!(
!dirs.contains(&app_dir),
"windows_system_dirs must never include the app directory {app_dir:?}, got {dirs:?}"
);
}
#[skuld::test]
fn the_system_dirs_ignore_systemroot_and_windir() {
let real = windows_system_dirs().unwrap();
let bogus = tempfile::tempdir().unwrap();
let mut cmd = crate::test_child::fixture_command(crate::test_child::fixture_path!(
fixture_the_system_dirs_ignore_systemroot_and_windir
));
cmd.env(FIXTURE_SYSTEM_DIRS_MARKER, std::process::id().to_string())
.env(FIXTURE_SYSTEM_DIRS_EXPECTED, std::env::join_paths(&real).unwrap())
.env("SystemRoot", bogus.path())
.env("windir", bogus.path());
crate::test_child::run_fixture_command(
crate::test_child::fixture_path!(fixture_the_system_dirs_ignore_systemroot_and_windir),
cmd,
);
}
const FIXTURE_SYSTEM_DIRS_MARKER: &str = "COSCA_FIXTURE_SYSTEM_DIRS";
const FIXTURE_SYSTEM_DIRS_EXPECTED: &str = "COSCA_FIXTURE_SYSTEM_DIRS_EXPECTED";
#[skuld::test]
fn fixture_the_system_dirs_ignore_systemroot_and_windir() {
if !crate::test_child::is_marked_fixture_reexec(FIXTURE_SYSTEM_DIRS_MARKER) {
return; }
let expected: Vec<PathBuf> = std::env::split_paths(
&std::env::var_os(FIXTURE_SYSTEM_DIRS_EXPECTED).expect("the driver sets the expectation"),
)
.collect();
assert_eq!(
expected.len(),
2,
"the driver passes System32 and the Windows directory"
);
for name in ["SystemRoot", "windir"] {
let value = PathBuf::from(std::env::var_os(name).unwrap_or_else(|| panic!("the driver sets {name}")));
assert!(
!expected.contains(&value),
"the bogus {name} {value:?} must differ from the real directories {expected:?}"
);
}
assert_eq!(windows_system_dirs().unwrap(), expected);
}
#[skuld::test]
fn a_system_directory_query_failure_is_not_silently_dropped() {
let err = query_wide_dir("GetSystemDirectoryW", |_buf| 0).unwrap_err();
let msg = match err {
Error::Io(e) => e.to_string(),
other => panic!("expected Io, got {other:?}"),
};
assert!(
msg.contains("GetSystemDirectoryW"),
"the error should name which query failed: {msg:?}"
);
}
#[skuld::test]
fn get_system_directory_via_names_its_own_api_on_failure() {
let err = get_system_directory_via(|_buf| 0).unwrap_err();
let msg = match err {
Error::Io(e) => e.to_string(),
other => panic!("expected Io, got {other:?}"),
};
assert!(msg.contains("GetSystemDirectoryW"), "{msg:?}");
assert!(!msg.contains("GetSystemWindowsDirectoryW"), "{msg:?}");
}
#[skuld::test]
fn get_system_windows_directory_via_names_its_own_api_on_failure() {
let err = get_system_windows_directory_via(|_buf| 0).unwrap_err();
let msg = match err {
Error::Io(e) => e.to_string(),
other => panic!("expected Io, got {other:?}"),
};
assert!(msg.contains("GetSystemWindowsDirectoryW"), "{msg:?}");
assert!(!msg.contains("GetSystemDirectoryW"), "{msg:?}");
}
#[skuld::test]
fn a_located_and_an_absolute_name_never_query_system_dirs_when_resolved_directly() {
let panics =
|| -> Result<Vec<PathBuf>, Error> { panic!("system_dirs must not be queried for a Located or absolute name") };
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("sp_via_located.exe");
std::fs::write(&file, b"x").unwrap();
let located = Path::new(".").join(file.file_name().unwrap());
let got = resolve_executable_in(&located, Some(dir.path()), &panics, &no_drive_dir, None, false).unwrap();
assert_eq!(got.canonicalize().unwrap(), file.canonicalize().unwrap());
let got = resolve_executable_in(&file, Some(dir.path()), &panics, &no_drive_dir, None, false).unwrap();
assert_eq!(got.canonicalize().unwrap(), file.canonicalize().unwrap());
}
#[skuld::test]
fn a_bare_name_names_get_system_directory_w_when_the_system_query_fails() {
let pathdir = tempfile::tempdir().unwrap();
std::fs::write(pathdir.path().join("sp_sysfail.exe"), b"x").unwrap();
let cwd = tempfile::tempdir().unwrap();
let system_dirs_fn = || {
windows_system_dirs_via(
|_buf| 0,
|buf| {
unsafe { GetSystemWindowsDirectoryW(buf) }
},
)
};
let err = resolve_executable_in(
Path::new("sp_sysfail"),
Some(cwd.path()),
&system_dirs_fn,
&no_drive_dir,
Some(pathdir.path().as_os_str()),
false,
)
.unwrap_err();
let msg = match err {
Error::Io(e) => e.to_string(),
other => panic!("expected Io, got {other:?}"),
};
assert!(msg.contains("GetSystemDirectoryW"), "{msg:?}");
assert!(!msg.contains("GetSystemWindowsDirectoryW"), "{msg:?}");
}
#[skuld::test]
fn a_bare_name_names_get_system_windows_directory_w_when_the_system_windows_query_fails() {
let pathdir = tempfile::tempdir().unwrap();
std::fs::write(pathdir.path().join("sp_winfail.exe"), b"x").unwrap();
let cwd = tempfile::tempdir().unwrap();
let system_dirs_fn = || {
windows_system_dirs_via(
|buf| {
unsafe { GetSystemDirectoryW(buf) }
},
|_buf| 0,
)
};
let err = resolve_executable_in(
Path::new("sp_winfail"),
Some(cwd.path()),
&system_dirs_fn,
&no_drive_dir,
Some(pathdir.path().as_os_str()),
false,
)
.unwrap_err();
let msg = match err {
Error::Io(e) => e.to_string(),
other => panic!("expected Io, got {other:?}"),
};
assert!(msg.contains("GetSystemWindowsDirectoryW"), "{msg:?}");
assert!(!msg.contains("GetSystemDirectoryW"), "{msg:?}");
}
#[skuld::test]
fn get_system_directory_via_keeps_the_os_error_reachable() {
let code: u32 = 87;
unsafe { windows::Win32::Foundation::SetLastError(windows::Win32::Foundation::WIN32_ERROR(code)) };
let err = get_system_directory_via(|_buf| 0).unwrap_err();
assert!(matches!(err, Error::Io(_)), "expected Io, got {err:?}");
assert_eq!(crate::error::first_os_code(&err), Some(code as i32), "{err:?}");
}
struct PlantedInAppDir(tempfile::NamedTempFile);
impl PlantedInAppDir {
fn new(prefix: &str) -> Self {
let app_dir = std::env::current_exe().unwrap().parent().unwrap().to_path_buf();
let mut file = tempfile::Builder::new()
.prefix(prefix)
.suffix(".exe")
.tempfile_in(&app_dir)
.unwrap();
let mut src = std::fs::File::open(std::env::current_exe().unwrap()).unwrap();
std::io::copy(&mut src, file.as_file_mut()).unwrap();
PlantedInAppDir(file)
}
fn dir(&self) -> PathBuf {
self.0.path().parent().unwrap().to_path_buf()
}
fn file_stem(&self) -> String {
self.0.path().file_stem().unwrap().to_str().unwrap().to_owned()
}
}
#[skuld::test]
fn the_app_directory_is_not_searched() {
let planted = PlantedInAppDir::new("sp_appdir_decoy");
let name = planted.file_stem();
let base = tempfile::tempdir().unwrap();
let empty_path = tempfile::tempdir().unwrap();
let app_dir_fn = || -> Result<Vec<PathBuf>, Error> { Ok(vec![planted.dir()]) };
let with_app_dir_searched = resolve_executable_in(
Path::new(&name),
Some(base.path()),
&app_dir_fn,
&no_drive_dir,
Some(empty_path.path().as_os_str()),
false,
);
assert_eq!(
with_app_dir_searched.unwrap().canonicalize().unwrap(),
planted.0.path().canonicalize().unwrap()
);
let app_dir_as_path = planted.dir().into_os_string();
let with_app_dir_on_path = resolve_executable(
Path::new(&name),
Some(base.path()),
&no_drive_dir,
Some(app_dir_as_path.as_os_str()),
);
assert_eq!(
with_app_dir_on_path.unwrap().canonicalize().unwrap(),
planted.0.path().canonicalize().unwrap()
);
let got = resolve_executable(
Path::new(&name),
Some(base.path()),
&no_drive_dir,
Some(empty_path.path().as_os_str()),
);
assert_not_found(got);
}
#[skuld::test]
fn resolve_finds_a_real_system32_binary_through_system_dirs() {
let cwd = tempfile::tempdir().unwrap();
let got = resolve_executable_in(
std::path::Path::new("notepad"),
Some(cwd.path()),
&windows_system_dirs,
&no_drive_dir,
None,
false,
)
.unwrap();
assert!(got.to_string_lossy().to_lowercase().contains("system32"), "{got:?}");
}
#[skuld::test]
fn embedded_nul_in_key_is_rejected_as_invalid_input() {
let e = build_env_block_from(&[], &[EnvOp::Set(OsString::from("a\u{0}b"), "1".into())]).unwrap_err();
assert!(
matches!(e, crate::error::Error::Io(ref io) if io.kind() == std::io::ErrorKind::InvalidInput),
"{e:?}"
);
}
#[skuld::test]
fn a_nul_refusal_names_the_field_that_carried_it() {
let said = |e: &crate::error::Error| crate::error::said(e);
let key = build_env_block_from(&[], &[EnvOp::Set(OsString::from("a\u{0}b"), "1".into())]).unwrap_err();
assert!(said(&key).contains("environment key"), "{key:?}");
let val = build_env_block_from(&[], &[EnvOp::Set("K".into(), OsString::from("a\u{0}b"))]).unwrap_err();
assert!(said(&val).contains("environment value"), "{val:?}");
let other = ensure_no_nul_wide("program token", OsStr::new("a\u{0}b")).unwrap_err();
assert!(said(&other).contains("program token"), "{other:?}");
assert!(
!said(&other).contains("environment"),
"a program token is not the environment: {other:?}"
);
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "program image contains an embedded NUL")]
fn debug_assert_no_nul_wide_panics_on_an_embedded_nul() {
debug_assert_no_nul_wide("program image", OsStr::new("a\u{0}b"));
}
fn wide(units: &[u16]) -> OsString {
OsString::from_wide(units)
}
fn block_entries(block: &[u16]) -> Vec<(OsString, OsString)> {
block[..block.len() - 1]
.split(|&u| u == 0)
.filter(|entry| !entry.is_empty())
.map(|entry| {
let eq = entry.iter().rposition(|&u| u == u16::from(b'=')).unwrap();
(wide(&entry[..eq]), wide(&entry[eq + 1..]))
})
.collect()
}
fn same_var(a: &OsStr, b: &OsStr) -> bool {
let block = build_env_block_from(&[(a.into(), "base".into())], &[EnvOp::Set(b.into(), "op".into())]).unwrap();
match block_entries(&block).len() {
1 => true,
2 => false,
n => panic!("{a:?} over {b:?} produced {n} entries"),
}
}
#[skuld::test]
fn full_case_mapping_does_not_merge_env_keys() {
for (a, b) in [("SS", "ß"), ("FI", "fi"), ("I", "ı"), ("\u{10400}", "\u{10428}")] {
assert!(
!same_var(OsStr::new(a), OsStr::new(b)),
"{a:?} and {b:?} are distinct on Windows"
);
}
}
#[skuld::test]
fn simple_case_pairs_are_the_same_env_key() {
for (a, b) in [("PATH", "path"), ("É", "é")] {
assert!(
same_var(OsStr::new(a), OsStr::new(b)),
"{a:?} and {b:?} are one variable"
);
}
}
#[skuld::test]
fn unpaired_surrogates_in_env_keys_compare_by_code_unit() {
let hi = 0xD800;
let a = u16::from(b'a');
let upper_a = u16::from(b'A');
assert!(same_var(&wide(&[hi]), &wide(&[hi])));
assert!(!same_var(&wide(&[hi]), &wide(&[0xDC00])));
assert!(same_var(&wide(&[hi, a]), &wide(&[hi, upper_a])));
}
#[skuld::test]
fn setting_eszett_keeps_an_inherited_ss() {
let block = build_env_block_from(
&[(OsString::from("SS"), OsString::from("inherited"))],
&[EnvOp::Set(OsString::from("ß"), OsString::from("set"))],
)
.unwrap();
let mut got = block_entries(&block);
got.sort();
assert_eq!(got, [("SS".into(), "inherited".into()), ("ß".into(), "set".into())]);
}
type Entries = Vec<(OsString, OsString)>;
fn block_vs_std(ops: &[EnvOp]) -> (Entries, Entries) {
let mut std_cmd = std::process::Command::new("unused");
crate::child::spawn::apply_env(&mut std_cmd, ops);
let ours = block_entries(&build_env_block_from(&[], ops).unwrap());
let std = std_cmd
.get_envs()
.filter_map(|(k, v)| Some((k.to_os_string(), v?.to_os_string())))
.collect();
(ours, std)
}
fn set_each(keys: &[OsString]) -> Vec<EnvOp> {
std::iter::once(EnvOp::Clear)
.chain(
keys.iter()
.enumerate()
.map(|(i, key)| EnvOp::Set(key.clone(), i.to_string().into())),
)
.collect()
}
#[skuld::test]
fn env_block_order_and_merges_match_std() {
let keys: Vec<OsString> = [
"T",
"ß",
"SS",
"sa",
"st",
"_x",
"a",
"Z",
"é",
"É",
"fi",
"FI",
"ı",
"I",
"\u{10428}",
"\u{10400}",
"\u{FFFF}",
]
.iter()
.map(OsString::from)
.chain([wide(&[0xD800]), wide(&[0xDC00, u16::from(b'a')])])
.collect();
let (ours, std) = block_vs_std(&set_each(&keys));
assert_eq!(ours, std);
}
#[skuld::test]
fn env_block_matches_std_over_every_code_unit() {
let keys: Vec<OsString> = (1..=u16::MAX).map(|u| wide(&[u])).collect();
let (ours, std) = block_vs_std(&set_each(&keys));
assert_eq!(ours.len(), std.len());
assert!(
ours == std,
"first divergence at {:?}",
ours.iter().zip(&std).position(|(a, b)| a != b)
);
}
#[skuld::test]
fn colliding_keys_keep_std_casing() {
let set = |k: &str, v: &str| EnvOp::Set(k.into(), v.into());
let remove = |k: &str| EnvOp::Remove(k.into());
for (ops, name) in [
(vec![set("Path", "1"), set("PATH", "2")], "Path"),
(vec![remove("path"), set("PATH", "1")], "path"),
(vec![EnvOp::Clear, remove("path"), set("PATH", "1")], "PATH"),
(vec![set("a", "1"), EnvOp::Clear, set("A", "2")], "A"),
(vec![EnvOp::Clear, set("a", "1"), remove("A"), set("A", "2")], "A"),
] {
let (ours, std) = block_vs_std(&ops);
assert_eq!(ours, std, "{ops:?}");
assert_eq!(ours.len(), 1, "{ops:?}");
assert_eq!(ours[0].0, name, "{ops:?}");
}
}
#[skuld::test]
fn an_inherited_key_keeps_its_casing() {
let base = [(OsString::from("Path"), OsString::from("inherited"))];
for ops in [
vec![EnvOp::Set("PATH".into(), "x".into())],
vec![EnvOp::Remove("PATH".into()), EnvOp::Set("pAth".into(), "x".into())],
] {
let block = build_env_block_from(&base, &ops).unwrap();
assert_eq!(block_entries(&block), [("Path".into(), "x".into())], "{ops:?}");
}
}
#[skuld::test]
fn path_is_the_one_the_child_reads_from_its_block() {
let base = [
(OsString::from("PATH"), OsString::from("a")),
(OsString::from("Path"), OsString::from("b")),
];
for (env, want) in [
(ChildEnv::inherit(&snapshot(&base)), "a"),
(ChildEnv::capture(&snapshot(&base), &[]), "b"),
(
ChildEnv::capture(&snapshot(&base), &[EnvOp::Set("K".into(), "1".into())]),
"b",
),
] {
let block = EnvSnapshot::from_block(env.into_block().unwrap());
assert_eq!(block.var(OsStr::new("PATH")).as_deref(), Some(OsStr::new(want)));
}
}
#[skuld::test]
fn inherit_passes_the_snapshot_verbatim() {
let block: Vec<u16> = ["Path=a", "JUNK", "PATH=b", "=C:=C:\\x"]
.iter()
.flat_map(|e| e.encode_utf16().chain([0]))
.chain([0])
.collect();
let env = ChildEnv::inherit(&EnvSnapshot::from_block(block.clone()));
assert_eq!(env.into_block().unwrap(), block);
}
#[skuld::test]
fn capture_rebuilds_even_with_no_ops() {
let env = ChildEnv::capture(
&snapshot(&[("Path".into(), "a".into()), ("PATH".into(), "b".into())]),
&[],
);
assert_eq!(block_entries(&env.into_block().unwrap()), [("Path".into(), "b".into())]);
}
#[skuld::test]
fn ops_rebuild_from_the_snapshot_as_std_does() {
let block: Vec<u16> = ["Path=a", "JUNK", "PATH=b"]
.iter()
.flat_map(|e| e.encode_utf16().chain([0]))
.chain([0])
.collect();
let env = ChildEnv::capture(&EnvSnapshot::from_block(block), &[EnvOp::Set("K".into(), "1".into())]);
let got = block_entries(&env.into_block().unwrap());
assert_eq!(got, [("K".into(), "1".into()), ("Path".into(), "b".into())]);
}
#[skuld::test]
fn resolution_searches_the_given_snapshot() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(std::env::current_exe().unwrap(), dir.path().join("sp_snapshot.exe")).unwrap();
let base = [(OsString::from("PATH"), dir.path().as_os_str().to_os_string())];
let block = EnvSnapshot::from_block(ChildEnv::capture(&snapshot(&base), &[]).into_block().unwrap());
let path = block.var(OsStr::new("PATH"));
let got = resolve_executable(Path::new("sp_snapshot"), None, &no_drive_dir, path.as_deref()).unwrap();
assert_eq!(
got.canonicalize().unwrap(),
dir.path().join("sp_snapshot.exe").canonicalize().unwrap()
);
}
fn exact_on(program: &Path, cwd: &str) -> Result<PathBuf, Error> {
let cwd = PathBuf::from(cwd);
absolutise_exact_on(program, || Ok(cwd), |_| Ok(None)).map(|c| c.path)
}
fn exact_reading_nothing(program: &Path) -> Result<PathBuf, Error> {
absolutise_exact_on(
program,
|| panic!("must not read the process cwd"),
|_| panic!("must not read a drive's directory"),
)
.map(|c| c.path)
}
#[skuld::test]
fn absolutise_exact_completes_a_bare_name_against_the_processes_cwd() {
let got = exact_on(Path::new("tool"), r"C:\base").unwrap();
assert_eq!(got, PathBuf::from(r"C:\base\tool"), "{got:?}");
assert!(got.is_absolute());
}
#[skuld::test]
fn absolutise_exact_never_appends_an_extension() {
let got = exact_on(Path::new("tool"), r"C:\base").unwrap();
assert_eq!(got.file_name().unwrap(), std::ffi::OsStr::new("tool"), "{got:?}");
}
#[skuld::test]
fn absolutise_exact_succeeds_for_a_file_that_does_not_exist() {
let dir = tempfile::tempdir().unwrap();
let got = exact_on(Path::new("no-such-file-983471.tmp"), dir.path().to_str().unwrap()).unwrap();
assert!(got.is_absolute(), "{got:?}");
assert!(!got.exists(), "the probe name must genuinely not exist: {got:?}");
}
#[skuld::test]
fn absolutise_exact_leaves_an_absolute_path_absolute() {
let me = std::env::current_exe().unwrap();
assert_eq!(exact_reading_nothing(&me).unwrap(), me);
}
#[skuld::test]
fn absolutise_exact_refuses_an_empty_program() {
match exact_reading_nothing(Path::new("")) {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!("an empty program must be Io(InvalidInput), got {other:?}"),
}
}
#[skuld::test]
fn absolutise_exact_refuses_a_program_that_names_no_file() {
for n in [
r"C:\t\dir\",
r"C:\t\.",
r"C:\t\..",
".",
"..",
r"C:\",
"C:",
r"C:\t\...",
r"C:\t\. ",
] {
match exact_on(Path::new(n), r"C:\base") {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!("{n:?} names no file and must be Io(InvalidInput), got {other:?}"),
}
}
}
#[skuld::test]
fn absolutise_exact_refuses_an_interior_nul() {
use std::os::windows::ffi::OsStringExt;
for units in [vec![0u16], "a.exe\0b".encode_utf16().collect::<Vec<u16>>()] {
let p = std::ffi::OsString::from_wide(&units);
match exact_reading_nothing(Path::new(&p)) {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!("an interior NUL must be Io(InvalidInput), not truncated: {p:?}, got {other:?}"),
}
}
}
#[skuld::test]
fn absolutise_exact_reports_an_interior_nul_ahead_of_the_shape() {
use std::os::windows::ffi::OsStringExt;
let p = std::ffi::OsString::from_wide(&"x\0\\".encode_utf16().collect::<Vec<u16>>());
match exact_reading_nothing(Path::new(&p)) {
Err(Error::Io(e)) => {
assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e:?}");
assert!(e.to_string().contains("embedded NUL"), "the NUL must be named: {e}");
}
other => panic!("expected Io(InvalidInput), got {other:?}"),
}
}