use std::path::{Path, PathBuf};
use pretty_assertions::assert_eq;
use rho_protocol::ClientEnvironment;
use super::{is_copy, newer, on_path};
#[test]
fn an_installed_rho_no_newer_than_the_running_one_is_an_error() {
let path = Path::new("/opt/rho/bin/rho");
let same = newer(path, "3.10.0".to_owned(), "3.10.0").unwrap_err();
let newer_one = newer(path, "3.11.0".to_owned(), "3.10.0").unwrap();
assert_eq!(
same.to_string(),
"the installer finished, but /opt/rho/bin/rho still reports rho 3.10.0"
);
assert_eq!(newer_one, "3.11.0");
}
#[cfg(unix)]
#[test]
fn the_login_path_finds_rho_in_its_first_absolute_entry_that_has_it() {
use std::path::Component;
let [relative_dir, without, first, second] =
std::array::from_fn::<_, 4, _>(|_| tempfile::tempdir().unwrap());
for dir in [&relative_dir, &first, &second] {
std::fs::write(dir.path().join("rho"), "").unwrap();
}
let up = std::env::current_dir()
.unwrap()
.components()
.filter(|component| matches!(component, Component::Normal(_)))
.count();
let relative = std::iter::repeat_n("..", up)
.collect::<PathBuf>()
.join(relative_dir.path().strip_prefix("/").unwrap());
assert!(relative.join("rho").is_file(), "{}", relative.display());
let entries = [
PathBuf::new(),
relative,
without.path().to_owned(),
first.path().to_owned(),
second.path().to_owned(),
];
let path = std::env::join_paths(entries).unwrap();
let environment =
ClientEnvironment::from_iter([("PATH".to_owned(), path.into_string().unwrap())]);
let found = on_path(&environment);
let none = on_path(&ClientEnvironment::default());
assert_eq!(found, Some(first.path().join("rho")));
assert_eq!(none, None);
}
#[test]
fn only_a_file_in_the_copies_directory_is_a_copy() {
let (state, elsewhere) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let copies = state.path().join("bin");
std::fs::create_dir(&copies).unwrap();
let copy = copies.join("rho-3.10.0");
std::fs::write(©, "").unwrap();
let installed = elsewhere.path().join("rho");
std::fs::write(&installed, "").unwrap();
let found = [
is_copy(©, &copies),
is_copy(&installed, &copies),
is_copy(©, &state.path().join("missing")),
];
assert_eq!(found, [true, false, false]);
}
#[cfg(not(windows))]
mod installer {
use std::time::Duration;
use pretty_assertions::assert_eq;
use super::super::{forward_lines, run_reporting, INSTALLER_DEADLINE, LINE_MAX_BYTES};
use crate::update::tests::{Recorded, Said};
fn sh(script: &str) -> tokio::process::Command {
let mut command = tokio::process::Command::new("sh");
command.args(["-c", script]);
command
}
#[tokio::test]
async fn the_installers_lines_are_reported_and_its_failure_is_an_error() {
let mut recorded = Recorded::default();
let error = run_reporting(
sh("echo out; echo err >&2; exit 3"),
"test",
INSTALLER_DEADLINE,
&mut recorded,
)
.await
.unwrap_err();
recorded.0.sort();
assert_eq!(
recorded.0,
[
Said::Stdout("err".to_owned()),
Said::Stdout("out".to_owned())
]
);
assert_eq!(
error.to_string(),
"test update command exited with exit status: 3"
);
}
#[tokio::test(start_paused = true)]
async fn an_installer_past_its_deadline_is_stopped_and_named() {
let error = run_reporting(
sh("sleep 30"),
"test",
INSTALLER_DEADLINE,
&mut Recorded::default(),
)
.await
.unwrap_err();
assert_eq!(
error.to_string(),
"test update command ran past INSTALLER_DEADLINE (60 min), so rho stopped it"
);
}
#[tokio::test]
async fn a_process_the_installer_left_running_does_not_hold_the_update() {
let mut recorded = Recorded::default();
let ran = tokio::time::timeout(
Duration::from_secs(20),
run_reporting(
sh("echo $$; sleep 30 & exit 0"),
"test",
INSTALLER_DEADLINE,
&mut recorded,
),
)
.await;
let group = match recorded.0.first() {
Some(Said::Stdout(group)) => group.parse::<libc::pid_t>().ok(),
_ => None,
};
if let Some(group) = group {
unsafe { libc::killpg(group, libc::SIGKILL) };
}
assert!(matches!(ran, Ok(Ok(()))), "{ran:?}");
assert!(group.is_some(), "{:?}", recorded.0);
}
#[tokio::test]
async fn a_line_without_an_end_is_split_at_line_max_bytes() {
let mut output = vec![b'a'; LINE_MAX_BYTES + 10];
output.extend_from_slice(b"\rdone\r\n");
let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
forward_lines(output.as_slice(), sender).await;
let mut lines = Vec::new();
while let Ok(line) = receiver.try_recv() {
lines.push(line);
}
assert_eq!(
lines,
[
"a".repeat(LINE_MAX_BYTES),
format!("{}\rdone", "a".repeat(10))
]
);
}
}
#[cfg(unix)]
mod login {
use std::time::Duration;
use pretty_assertions::assert_eq;
use rho_protocol::ClientEnvironment;
use tokio::runtime::Handle;
use super::super::{Login, LOOKUP_TIMEOUT};
use crate::installation::Probe as _;
fn environment(home: &std::path::Path) -> ClientEnvironment {
ClientEnvironment::from_iter([
("PATH".to_owned(), "/usr/bin:/bin".to_owned()),
("HOME".to_owned(), home.to_str().unwrap().to_owned()),
("ONLY".to_owned(), "login".to_owned()),
])
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn lookups_run_in_the_login_environment_alone() {
assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some());
let home = tempfile::tempdir().unwrap();
let login = Login::new(environment(home.path()), Handle::current(), LOOKUP_TIMEOUT);
let mut command = std::process::Command::new("sh");
command.args([
"-c",
r#"printf '%s|%s|%s' "$ONLY" "${CARGO_MANIFEST_DIR-unset}" "$(pwd -P)""#,
]);
let (output, only) =
tokio::task::spawn_blocking(move || (login.output(command), login.var("ONLY")))
.await
.unwrap();
let home = std::fs::canonicalize(home.path()).unwrap();
assert_eq!(
(String::from_utf8(output.unwrap().stdout).unwrap(), only),
(
format!("login|unset|{}", home.display()),
Some("login".into())
)
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_lookup_past_its_time_is_kept_to_fail_the_detection() {
let home = tempfile::tempdir().unwrap();
let login = Login::new(
environment(home.path()),
Handle::current(),
Duration::from_millis(100),
);
let mut command = std::process::Command::new("sleep");
command.arg("5");
let (ran, kept) = tokio::task::spawn_blocking(move || {
let ran = login
.output(command)
.map(|_| ())
.map_err(|error| error.kind());
(ran, login.timed_out())
})
.await
.unwrap();
assert_eq!(
(ran, kept.as_deref()),
(
Err(std::io::ErrorKind::TimedOut),
Some("`sleep 5` did not answer within LOOKUP_TIMEOUT (100ms)")
)
);
}
}