use std::{
fs,
io::Write,
path::{Path, PathBuf},
};
use pretty_assertions::assert_eq;
use super::{
extract_executable, install, remove_update_leftovers, sibling, swap, verify_checksum,
SwapError, ARCHIVE_EXECUTABLE,
};
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
fn sorted<const N: usize>(mut names: [String; N]) -> Vec<String> {
names.sort();
names.into()
}
fn file_name(path: &Path) -> String {
path.file_name().unwrap().to_string_lossy().into_owned()
}
#[tokio::test]
async fn install_refuses_a_rho_that_does_not_run() {
let dir = tempfile::tempdir().unwrap();
let installed = dir.path().join("rho.exe");
fs::write(&installed, "old").unwrap();
install(&installed, b"not a program", "3.10.0")
.await
.expect_err("a file that cannot run is refused");
assert_eq!(fs::read_to_string(&installed).unwrap(), "old");
assert_eq!(names(dir.path()), ["rho.exe"]);
}
fn installed_and_staged(dir: &Path) -> (PathBuf, PathBuf) {
let installed = dir.join("rho.exe");
fs::write(&installed, "old").unwrap();
let staged = sibling(&installed, "new-1");
fs::write(&staged, "new").unwrap();
fs::write(dir.join("rho.txt"), "kept").unwrap();
fs::write(dir.join("rho.old-mine.exe"), "kept").unwrap();
(installed, staged)
}
#[test]
fn swap_puts_the_new_rho_in_place_and_keeps_the_old_beside_it() {
let dir = tempfile::tempdir().unwrap();
let (installed, staged) = installed_and_staged(dir.path());
let aside = swap(&installed, &staged).expect("the swap succeeds");
assert_eq!(fs::read_to_string(&installed).unwrap(), "new");
assert_eq!(fs::read_to_string(&aside).unwrap(), "old");
assert_eq!(
names(dir.path()),
sorted([
file_name(&aside),
"rho.exe".into(),
"rho.txt".into(),
"rho.old-mine.exe".into()
])
);
}
fn exited_pid() -> u32 {
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
.arg("--help")
.stdout(std::process::Stdio::null())
.spawn()
.unwrap();
child.wait().unwrap();
child.id()
}
#[test]
fn the_sweep_removes_only_what_ended_updates_left() {
let dir = tempfile::tempdir().unwrap();
let installed = dir.path().join("rho.exe");
fs::write(&installed, "rho").unwrap();
let running = std::process::id();
let ended = exited_pid();
let kept = [
format!("rho.old-1796147852247597900-{running}.exe"),
format!("rho.new-{running}.exe"),
"rho.old-2026-12-01.exe".to_owned(),
"rho.old-mine.exe".to_owned(),
"rho.new-+1.exe".to_owned(),
];
let removed = [
format!("rho.old-1796147852247597900-{ended}.exe"),
format!("rho.new-{ended}.exe"),
];
for name in kept.iter().chain(&removed) {
fs::write(dir.path().join(name), "left").unwrap();
}
remove_update_leftovers(&installed);
let mut expected = kept.to_vec();
expected.push("rho.exe".to_owned());
expected.sort();
assert_eq!(names(dir.path()), expected);
}
#[test]
fn failed_swap_leaves_the_installed_rho() {
let dir = tempfile::tempdir().unwrap();
let (installed, staged) = installed_and_staged(dir.path());
let missing = dir.path().join("missing");
let error = swap(&installed, &missing).expect_err("there is nothing to place");
assert!(matches!(error, SwapError::Place { .. }), "{error:?}");
assert_eq!(fs::read_to_string(&installed).unwrap(), "old");
assert_eq!(
names(dir.path()),
sorted([
file_name(&staged),
"rho.exe".into(),
"rho.txt".into(),
"rho.old-mine.exe".into(),
])
);
let error = swap(&missing, &staged).expect_err("there is nothing to move aside");
assert!(matches!(error, SwapError::MoveAside { .. }), "{error:?}");
assert_eq!(
names(dir.path()),
sorted([
file_name(&staged),
"rho.exe".into(),
"rho.txt".into(),
"rho.old-mine.exe".into(),
])
);
}
#[cfg(windows)]
#[test]
fn swap_moves_a_running_program_aside_and_removes_it_once_it_exits() {
let dir = tempfile::tempdir().unwrap();
let (installed, staged) = installed_and_staged(dir.path());
let system = std::env::var_os("SystemRoot").expect("Windows names its directory");
fs::copy(
Path::new(&system).join("System32").join("ping.exe"),
&installed,
)
.unwrap();
struct Running(std::process::Child);
impl Drop for Running {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let mut running = Running(
std::process::Command::new(&installed)
.args(["-n", "600", "127.0.0.1"])
.stdout(std::process::Stdio::null())
.spawn()
.unwrap(),
);
assert!(fs::write(&installed, "new").is_err());
let aside = swap(&installed, &staged).expect("a running program's file moves aside");
assert_eq!(fs::read_to_string(&installed).unwrap(), "new");
assert_eq!(
running.0.try_wait().unwrap(),
None,
"the program still runs"
);
let ended = sibling(&installed, &format!("old-1-{}", exited_pid()));
fs::rename(&aside, &ended).unwrap();
remove_update_leftovers(&installed);
assert!(ended.exists(), "a running program's file is kept");
drop(running);
remove_update_leftovers(&installed);
assert!(!ended.exists(), "removed once nothing runs it");
}
#[test]
fn verifies_the_archive_against_the_published_checksum() {
let actual = hex::encode(<sha2::Sha256 as sha2::Digest>::digest(b"rho"));
let cases = [
(
format!("{actual} rho-x86_64-pc-windows-msvc.zip\r\n"),
true,
),
(actual.to_uppercase(), true),
(format!("{}0", &actual[..63]), false),
(String::new(), false),
(" \n".to_owned(), false),
];
for (checksum, verified) in cases {
assert_eq!(
verify_checksum(b"rho", &checksum).is_ok(),
verified,
"{checksum:?}"
);
}
}
#[test]
fn extracts_rho_exe_from_the_release_archive() {
let zip = |name: &str| {
let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
writer
.start_file(name, zip::write::SimpleFileOptions::default())
.unwrap();
writer.write_all(b"MZ rho").unwrap();
writer.finish().unwrap().into_inner()
};
assert_eq!(
extract_executable(&zip(ARCHIVE_EXECUTABLE)).unwrap(),
b"MZ rho"
);
assert!(extract_executable(&zip("other.exe")).is_err());
assert!(extract_executable(b"not a zip").is_err());
}