| 1 |
// This file is part of the uutils coreutils package. |
| 2 |
// |
| 3 |
// For the full copyright and license information, please view the LICENSE |
| 4 |
// file that was distributed with this source code. |
| 5 |
|
| 6 |
//spell-checker: ignore (linux) rlimit prlimit coreutil ggroups uchild uncaptured scmd SHLVL canonicalized openpty |
| 7 |
//spell-checker: ignore (linux) winsize xpixel ypixel setrlimit FSIZE SIGBUS SIGSEGV sigbus tmpfs mksocket |
| 8 |
//spell-checker: ignore (ToDO) ttyname |
| 9 |
|
| 10 |
#![allow(dead_code)] |
| 11 |
#![allow( |
| 12 |
clippy::too_many_lines, |
| 13 |
clippy::should_panic_without_expect, |
| 14 |
clippy::missing_errors_doc |
| 15 |
)] |
| 16 |
|
| 17 |
use core::str; |
| 18 |
#[cfg(unix)] |
| 19 |
use libc::mode_t; |
| 20 |
#[cfg(unix)] |
| 21 |
use nix::pty::OpenptyResult; |
| 22 |
#[cfg(unix)] |
| 23 |
use nix::sys; |
| 24 |
#[cfg(not(windows))] |
| 25 |
use nix::sys::stat::{self, SFlag}; |
| 26 |
use pretty_assertions::assert_eq; |
| 27 |
#[cfg(unix)] |
| 28 |
use rlimit::setrlimit; |
| 29 |
use std::borrow::Cow; |
| 30 |
use std::collections::VecDeque; |
| 31 |
use std::ffi::{OsStr, OsString}; |
| 32 |
use std::fs::{self, File, OpenOptions, hard_link, remove_file}; |
| 33 |
use std::io::{self, BufWriter, Read, Result, Write}; |
| 34 |
#[cfg(unix)] |
| 35 |
use std::os::fd::OwnedFd; |
| 36 |
#[cfg(unix)] |
| 37 |
use std::os::unix::fs::{PermissionsExt, symlink as symlink_dir, symlink as symlink_file}; |
| 38 |
#[cfg(unix)] |
| 39 |
use std::os::unix::net::UnixListener; |
| 40 |
#[cfg(unix)] |
| 41 |
use std::os::unix::process::CommandExt; |
| 42 |
#[cfg(unix)] |
| 43 |
use std::os::unix::process::ExitStatusExt; |
| 44 |
#[cfg(windows)] |
| 45 |
use std::os::windows::fs::{symlink_dir, symlink_file}; |
| 46 |
#[cfg(windows)] |
| 47 |
use std::path::MAIN_SEPARATOR_STR; |
| 48 |
use std::path::{Path, PathBuf}; |
| 49 |
use std::process::{Child, Command, ExitStatus, Output, Stdio}; |
| 50 |
use std::rc::Rc; |
| 51 |
use std::sync::mpsc::{self, RecvTimeoutError}; |
| 52 |
use std::thread::{JoinHandle, sleep}; |
| 53 |
use std::time::{Duration, Instant}; |
| 54 |
use std::{env, hint, mem, thread}; |
| 55 |
use tempfile::{Builder, TempDir}; |
| 56 |
|
| 57 |
use std::sync::OnceLock; |
| 58 |
|
| 59 |
static TESTS_DIR: &str = "tests"; |
| 60 |
static FIXTURES_DIR: &str = "fixtures"; |
| 61 |
|
| 62 |
static ALREADY_RUN: &str = " you have already run this UCommand, if you want to run \ |
| 63 |
another command in the same test, use TestScenario::new instead of \ |
| 64 |
testing();"; |
| 65 |
static MULTIPLE_STDIN_MEANINGLESS: &str = "Ucommand is designed around a typical use case of: provide args and input stream -> spawn process -> block until completion -> return output streams. For verifying that a particular section of the input stream is what causes a particular behavior, use the Command type directly."; |
| 66 |
|
| 67 |
static NO_STDIN_MEANINGLESS: &str = "Setting this flag has no effect if there is no stdin"; |
| 68 |
static END_OF_TRANSMISSION_SEQUENCE: &[u8] = b"\n\x04"; |
| 69 |
|
| 70 |
static TESTS_BINARY_PATH: OnceLock<PathBuf> = OnceLock::new(); |
| 71 |
/// This function needs the env variable UUTESTS_BINARY_PATH |
| 72 |
/// which will very probably be env!("`CARGO_BIN_EXE_<program>`") |
| 73 |
/// because here, we are in a crate but we need the name of the final binary |
| 74 |
pub fn get_tests_binary() -> &'static str { |
| 75 |
TESTS_BINARY_PATH.get_or_init(|| { |
| 76 |
if let Ok(path) = env::var("UUTESTS_BINARY_PATH") { |
| 77 |
return PathBuf::from(path); |
| 78 |
} |
| 79 |
panic!("Could not determine coreutils binary path. Please set UUTESTS_BINARY_PATH environment variable"); |
| 80 |
}) |
| 81 |
.to_str() |
| 82 |
.unwrap() |
| 83 |
} |
| 84 |
|
| 85 |
#[macro_export] |
| 86 |
macro_rules! get_tests_binary { |
| 87 |
() => { |
| 88 |
$crate::util::get_tests_binary() |
| 89 |
}; |
| 90 |
} |
| 91 |
|
| 92 |
pub const PATH: &str = env!("PATH"); |
| 93 |
|
| 94 |
/// Default environment variables to run the commands with |
| 95 |
const DEFAULT_ENV: [(&str, &str); 2] = [("LC_ALL", "C"), ("TZ", "UTC")]; |
| 96 |
|
| 97 |
/// Test if the program is running under CI |
| 98 |
pub fn is_ci() -> bool { |
| 99 |
env::var("CI").is_ok_and(|s| s.eq_ignore_ascii_case("true")) |
| 100 |
} |
| 101 |
|
| 102 |
/// Check if a locale is available on the system by verifying that |
| 103 |
/// `locale charmap` returns `"UTF-8"` when `LC_ALL` is set to the given locale. |
| 104 |
#[cfg(unix)] |
| 105 |
pub fn is_locale_available(locale: &str) -> bool { |
| 106 |
use std::process::Command; |
| 107 |
Command::new("locale") |
| 108 |
.env("LC_ALL", locale) |
| 109 |
.arg("charmap") |
| 110 |
.output() |
| 111 |
.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).trim() == "UTF-8") |
| 112 |
} |
| 113 |
|
| 114 |
/// Read a test scenario fixture, returning its bytes |
| 115 |
fn read_scenario_fixture<S: AsRef<OsStr>>(tmpd: Option<&Rc<TempDir>>, file_rel_path: S) -> Vec<u8> { |
| 116 |
let tmpdir_path = tmpd.as_ref().unwrap().as_ref().path(); |
| 117 |
AtPath::new(tmpdir_path).read_bytes(file_rel_path.as_ref().to_str().unwrap()) |
| 118 |
} |
| 119 |
|
| 120 |
/// A command result is the outputs of a command (streams and status code) |
| 121 |
/// within a struct which has convenience assertion functions about those outputs |
| 122 |
#[derive(Debug, Clone)] |
| 123 |
pub struct CmdResult { |
| 124 |
/// `bin_path` provided by `TestScenario` or `UCommand` |
| 125 |
bin_path: PathBuf, |
| 126 |
/// `util_name` provided by `TestScenario` or `UCommand` |
| 127 |
util_name: Option<String>, |
| 128 |
//tmpd is used for convenience functions for asserts against fixtures |
| 129 |
tmpd: Option<Rc<TempDir>>, |
| 130 |
/// exit status for command (if there is one) |
| 131 |
exit_status: Option<ExitStatus>, |
| 132 |
/// captured standard output after running the Command |
| 133 |
stdout: Vec<u8>, |
| 134 |
/// captured standard error after running the Command |
| 135 |
stderr: Vec<u8>, |
| 136 |
} |
| 137 |
|
| 138 |
impl CmdResult { |
| 139 |
pub fn new<S, T, U, V>( |
| 140 |
bin_path: S, |
| 141 |
util_name: Option<T>, |
| 142 |
tmpd: Option<Rc<TempDir>>, |
| 143 |
exit_status: Option<ExitStatus>, |
| 144 |
stdout: U, |
| 145 |
stderr: V, |
| 146 |
) -> Self |
| 147 |
where |
| 148 |
S: Into<PathBuf>, |
| 149 |
T: AsRef<str>, |
| 150 |
U: Into<Vec<u8>>, |
| 151 |
V: Into<Vec<u8>>, |
| 152 |
{ |
| 153 |
Self { |
| 154 |
bin_path: bin_path.into(), |
| 155 |
util_name: util_name.map(|s| s.as_ref().into()), |
| 156 |
tmpd, |
| 157 |
exit_status, |
| 158 |
stdout: stdout.into(), |
| 159 |
stderr: stderr.into(), |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
/// Apply a function to `stdout` as bytes and return a new [`CmdResult`] |
| 164 |
pub fn stdout_apply<'a, F, R>(&'a self, function: F) -> Self |
| 165 |
where |
| 166 |
F: Fn(&'a [u8]) -> R, |
| 167 |
R: Into<Vec<u8>>, |
| 168 |
{ |
| 169 |
Self::new( |
| 170 |
self.bin_path.clone(), |
| 171 |
self.util_name.clone(), |
| 172 |
self.tmpd.clone(), |
| 173 |
self.exit_status, |
| 174 |
function(&self.stdout), |
| 175 |
self.stderr.as_slice(), |
| 176 |
) |
| 177 |
} |
| 178 |
|
| 179 |
/// Apply a function to `stdout` as `&str` and return a new [`CmdResult`] |
| 180 |
pub fn stdout_str_apply<'a, F, R>(&'a self, function: F) -> Self |
| 181 |
where |
| 182 |
F: Fn(&'a str) -> R, |
| 183 |
R: Into<Vec<u8>>, |
| 184 |
{ |
| 185 |
Self::new( |
| 186 |
self.bin_path.clone(), |
| 187 |
self.util_name.clone(), |
| 188 |
self.tmpd.clone(), |
| 189 |
self.exit_status, |
| 190 |
function(self.stdout_str()), |
| 191 |
self.stderr.as_slice(), |
| 192 |
) |
| 193 |
} |
| 194 |
|
| 195 |
/// Apply a function to `stderr` as bytes and return a new [`CmdResult`] |
| 196 |
pub fn stderr_apply<'a, F, R>(&'a self, function: F) -> Self |
| 197 |
where |
| 198 |
F: Fn(&'a [u8]) -> R, |
| 199 |
R: Into<Vec<u8>>, |
| 200 |
{ |
| 201 |
Self::new( |
| 202 |
self.bin_path.clone(), |
| 203 |
self.util_name.clone(), |
| 204 |
self.tmpd.clone(), |
| 205 |
self.exit_status, |
| 206 |
self.stdout.as_slice(), |
| 207 |
function(&self.stderr), |
| 208 |
) |
| 209 |
} |
| 210 |
|
| 211 |
/// Apply a function to `stderr` as `&str` and return a new [`CmdResult`] |
| 212 |
pub fn stderr_str_apply<'a, F, R>(&'a self, function: F) -> Self |
| 213 |
where |
| 214 |
F: Fn(&'a str) -> R, |
| 215 |
R: Into<Vec<u8>>, |
| 216 |
{ |
| 217 |
Self::new( |
| 218 |
self.bin_path.clone(), |
| 219 |
self.util_name.clone(), |
| 220 |
self.tmpd.clone(), |
| 221 |
self.exit_status, |
| 222 |
self.stdout.as_slice(), |
| 223 |
function(self.stderr_str()), |
| 224 |
) |
| 225 |
} |
| 226 |
|
| 227 |
/// Assert `stdout` as bytes with a predicate function returning a `bool`. |
| 228 |
#[track_caller] |
| 229 |
pub fn stdout_check<'a, F>(&'a self, predicate: F) -> &'a Self |
| 230 |
where |
| 231 |
F: Fn(&'a [u8]) -> bool, |
| 232 |
{ |
| 233 |
assert!( |
| 234 |
predicate(&self.stdout), |
| 235 |
"Predicate for stdout as `bytes` evaluated to false.\nstdout='{:?}'\nstderr='{:?}'\n", |
| 236 |
self.stdout, |
| 237 |
self.stderr |
| 238 |
); |
| 239 |
self |
| 240 |
} |
| 241 |
|
| 242 |
/// Assert `stdout` as `&str` with a predicate function returning a `bool`. |
| 243 |
#[track_caller] |
| 244 |
pub fn stdout_str_check<'a, F>(&'a self, predicate: F) -> &'a Self |
| 245 |
where |
| 246 |
F: Fn(&'a str) -> bool, |
| 247 |
{ |
| 248 |
assert!( |
| 249 |
predicate(self.stdout_str()), |
| 250 |
"Predicate for stdout as `str` evaluated to false.\nstdout='{}'\nstderr='{}'\n", |
| 251 |
self.stdout_str(), |
| 252 |
self.stderr_str() |
| 253 |
); |
| 254 |
self |
| 255 |
} |
| 256 |
|
| 257 |
/// Assert `stderr` as bytes with a predicate function returning a `bool`. |
| 258 |
#[track_caller] |
| 259 |
pub fn stderr_check<'a, F>(&'a self, predicate: F) -> &'a Self |
| 260 |
where |
| 261 |
F: Fn(&'a [u8]) -> bool, |
| 262 |
{ |
| 263 |
assert!( |
| 264 |
predicate(&self.stderr), |
| 265 |
"Predicate for stderr as `bytes` evaluated to false.\nstdout='{:?}'\nstderr='{:?}'\n", |
| 266 |
self.stdout, |
| 267 |
self.stderr |
| 268 |
); |
| 269 |
self |
| 270 |
} |
| 271 |
|
| 272 |
/// Assert `stderr` as `&str` with a predicate function returning a `bool`. |
| 273 |
#[track_caller] |
| 274 |
pub fn stderr_str_check<'a, F>(&'a self, predicate: F) -> &'a Self |
| 275 |
where |
| 276 |
F: Fn(&'a str) -> bool, |
| 277 |
{ |
| 278 |
assert!( |
| 279 |
predicate(self.stderr_str()), |
| 280 |
"Predicate for stderr as `str` evaluated to false.\nstdout='{}'\nstderr='{}'\n", |
| 281 |
self.stdout_str(), |
| 282 |
self.stderr_str() |
| 283 |
); |
| 284 |
self |
| 285 |
} |
| 286 |
|
| 287 |
/// Return the exit status of the child process, if any. |
| 288 |
/// |
| 289 |
/// Returns None if the child process is still running or hasn't been started. |
| 290 |
pub fn try_exit_status(&self) -> Option<ExitStatus> { |
| 291 |
self.exit_status |
| 292 |
} |
| 293 |
|
| 294 |
/// Return the exit status of the child process. |
| 295 |
/// |
| 296 |
/// # Panics |
| 297 |
/// |
| 298 |
/// If the child process is still running or hasn't been started. |
| 299 |
pub fn exit_status(&self) -> ExitStatus { |
| 300 |
self.try_exit_status() |
| 301 |
.expect("Program must be run first or has not finished, yet") |
| 302 |
} |
| 303 |
|
| 304 |
/// Return the signal the child process received if any. |
| 305 |
/// |
| 306 |
/// # Platform specific behavior |
| 307 |
/// |
| 308 |
/// This method is only available on unix systems. |
| 309 |
#[cfg(unix)] |
| 310 |
pub fn signal(&self) -> Option<i32> { |
| 311 |
self.exit_status().signal() |
| 312 |
} |
| 313 |
|
| 314 |
/// Assert that the given signal `value` equals the signal the child process received. |
| 315 |
/// |
| 316 |
/// See also [`std::os::unix::process::ExitStatusExt::signal`]. |
| 317 |
/// |
| 318 |
/// # Platform specific behavior |
| 319 |
/// |
| 320 |
/// This assertion method is only available on unix systems. |
| 321 |
#[cfg(unix)] |
| 322 |
#[track_caller] |
| 323 |
pub fn signal_is(&self, value: i32) -> &Self { |
| 324 |
let actual = self.signal().unwrap_or_else(|| { |
| 325 |
panic!( |
| 326 |
"Expected process to be terminated by the '{value}' signal, but exit status is: '{}'", |
| 327 |
self.try_exit_status() |
| 328 |
.map_or("Not available".to_string(), |e| e.to_string()) |
| 329 |
) |
| 330 |
}); |
| 331 |
|
| 332 |
assert_eq!(actual, value); |
| 333 |
self |
| 334 |
} |
| 335 |
|
| 336 |
/// Assert that the given signal `name` equals the signal the child process received. |
| 337 |
/// |
| 338 |
/// Strings like `SIGINT`, `INT` or a number like `15` are all valid names. See also |
| 339 |
/// [`std::os::unix::process::ExitStatusExt::signal`] and |
| 340 |
/// [`uucore::signals::signal_by_name_or_value`] |
| 341 |
/// |
| 342 |
/// # Platform specific behavior |
| 343 |
/// |
| 344 |
/// This assertion method is only available on unix systems, except for fuchsia. |
| 345 |
#[cfg(all(unix, not(target_os = "fuchsia")))] |
| 346 |
#[track_caller] |
| 347 |
pub fn signal_name_is(&self, name: &str) -> &Self { |
| 348 |
use uucore::signals::signal_by_name_or_value; |
| 349 |
let expected: i32 = signal_by_name_or_value(name) |
| 350 |
.unwrap_or_else(|| panic!("Invalid signal name or value: '{name}'")) |
| 351 |
.try_into() |
| 352 |
.unwrap(); |
| 353 |
|
| 354 |
let actual = self.signal().unwrap_or_else(|| { |
| 355 |
panic!( |
| 356 |
"Expected process to be terminated by the '{name}' signal, but exit status is: '{}'", |
| 357 |
self.try_exit_status() |
| 358 |
.map_or("Not available".to_string(), |e| e.to_string()) |
| 359 |
) |
| 360 |
}); |
| 361 |
|
| 362 |
assert_eq!(actual, expected); |
| 363 |
self |
| 364 |
} |
| 365 |
|
| 366 |
/// Returns a reference to the program's standard output as a slice of bytes |
| 367 |
pub fn stdout(&self) -> &[u8] { |
| 368 |
&self.stdout |
| 369 |
} |
| 370 |
|
| 371 |
/// Returns the program's standard output as a string slice |
| 372 |
pub fn stdout_str(&self) -> &str { |
| 373 |
std::str::from_utf8(&self.stdout).unwrap() |
| 374 |
} |
| 375 |
|
| 376 |
/// Returns the program's standard output as a string, automatically handling invalid utf8 |
| 377 |
pub fn stdout_str_lossy(self) -> String { |
| 378 |
String::from_utf8_lossy(&self.stdout).to_string() |
| 379 |
} |
| 380 |
|
| 381 |
/// Returns the program's standard output as a string |
| 382 |
/// consumes self |
| 383 |
pub fn stdout_move_str(self) -> String { |
| 384 |
String::from_utf8(self.stdout).unwrap() |
| 385 |
} |
| 386 |
|
| 387 |
/// Returns the program's standard output as a vec of bytes |
| 388 |
/// consumes self |
| 389 |
pub fn stdout_move_bytes(self) -> Vec<u8> { |
| 390 |
self.stdout |
| 391 |
} |
| 392 |
|
| 393 |
/// Returns a reference to the program's standard error as a slice of bytes |
| 394 |
pub fn stderr(&self) -> &[u8] { |
| 395 |
&self.stderr |
| 396 |
} |
| 397 |
|
| 398 |
/// Returns the program's standard error as a string slice |
| 399 |
pub fn stderr_str(&self) -> &str { |
| 400 |
std::str::from_utf8(&self.stderr).unwrap() |
| 401 |
} |
| 402 |
|
| 403 |
/// Returns the program's standard error with the carriage returns a |
| 404 |
/// pseudo-terminal inserts and any trailing padding on each line removed. |
| 405 |
/// |
| 406 |
/// Diagnostics rendered under [`UCommand::terminal_sim_stderr`] pad their |
| 407 |
/// lines out to the width of the report, which makes them awkward to |
| 408 |
/// compare verbatim; this gives back the block as it reads on screen. |
| 409 |
pub fn stderr_as_displayed(&self) -> String { |
| 410 |
self.stderr_str() |
| 411 |
.lines() |
| 412 |
.map(str::trim_end) |
| 413 |
.collect::<Vec<_>>() |
| 414 |
.join("\n") |
| 415 |
} |
| 416 |
|
| 417 |
/// Returns the one-based column a caret diagnostic points at. |
| 418 |
/// |
| 419 |
/// A report opens with a header naming the utility and the position it |
| 420 |
/// points at — `â•─[ chmod:1:5 ]` — which is the only place the column is |
| 421 |
/// written out; the caret row itself is padded and drawn with box |
| 422 |
/// characters. Asserting on the column keeps a test to the one thing it |
| 423 |
/// cares about, where matching the block verbatim would break on every |
| 424 |
/// wording change. |
| 425 |
/// |
| 426 |
/// # Returns |
| 427 |
/// |
| 428 |
/// `None` when stderr carries no such header: the plain one-line message |
| 429 |
/// was printed, or the diagnostic pointed at another line. |
| 430 |
pub fn caret_column(&self) -> Option<usize> { |
| 431 |
let header = format!("{}:1:", self.util_name.as_ref()?); |
| 432 |
let line = self |
| 433 |
.stderr_str() |
| 434 |
.lines() |
| 435 |
.find(|line| line.contains(&header))?; |
| 436 |
line.rsplit(':').next()?.trim_end_matches(" ]").parse().ok() |
| 437 |
} |
| 438 |
|
| 439 |
/// Returns the program's standard error as a string slice, automatically handling invalid utf8 |
| 440 |
pub fn stderr_str_lossy(&self) -> Cow<'_, str> { |
| 441 |
String::from_utf8_lossy(&self.stderr) |
| 442 |
} |
| 443 |
|
| 444 |
/// Returns the program's standard error as a string |
| 445 |
/// consumes self |
| 446 |
pub fn stderr_move_str(self) -> String { |
| 447 |
String::from_utf8(self.stderr).unwrap() |
| 448 |
} |
| 449 |
|
| 450 |
/// Returns the program's standard error as a vec of bytes |
| 451 |
/// consumes self |
| 452 |
pub fn stderr_move_bytes(self) -> Vec<u8> { |
| 453 |
self.stderr |
| 454 |
} |
| 455 |
|
| 456 |
/// Returns the program's exit code |
| 457 |
/// Panics if not run or has not finished yet for example when run with `run_no_wait()` |
| 458 |
pub fn code(&self) -> i32 { |
| 459 |
self.exit_status().code().unwrap() |
| 460 |
} |
| 461 |
|
| 462 |
/// Verify the exit code of the program |
| 463 |
/// |
| 464 |
/// # Examples |
| 465 |
/// |
| 466 |
/// ```rust,ignore |
| 467 |
/// new_ucmd!().arg("--definitely-invalid").fails().code_is(1); |
| 468 |
/// ``` |
| 469 |
#[track_caller] |
| 470 |
pub fn code_is(&self, expected_code: i32) -> &Self { |
| 471 |
let fails = self.code() != expected_code; |
| 472 |
if fails { |
| 473 |
eprintln!( |
| 474 |
"stdout:\n{}\nstderr:\n{}", |
| 475 |
self.stdout_str(), |
| 476 |
self.stderr_str() |
| 477 |
); |
| 478 |
} |
| 479 |
assert_eq!(self.code(), expected_code); |
| 480 |
self |
| 481 |
} |
| 482 |
|
| 483 |
/// Returns the program's `TempDir` |
| 484 |
/// Panics if not present |
| 485 |
pub fn tmpd(&self) -> Rc<TempDir> { |
| 486 |
match &self.tmpd { |
| 487 |
Some(ptr) => ptr.clone(), |
| 488 |
None => panic!("Command not associated with a TempDir"), |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
/// Returns whether the program succeeded |
| 493 |
pub fn succeeded(&self) -> bool { |
| 494 |
self.exit_status.is_none_or(|e| e.success()) |
| 495 |
} |
| 496 |
|
| 497 |
/// asserts that the command resulted in a success (zero) status code |
| 498 |
#[track_caller] |
| 499 |
pub fn success(&self) -> &Self { |
| 500 |
assert!( |
| 501 |
self.succeeded(), |
| 502 |
"Command was expected to succeed. code: {}\nstdout = {}\n stderr = {}", |
| 503 |
self.code(), |
| 504 |
self.stdout_str(), |
| 505 |
self.stderr_str() |
| 506 |
); |
| 507 |
self |
| 508 |
} |
| 509 |
|
| 510 |
/// asserts that the command resulted in a failure (non-zero) status code |
| 511 |
#[track_caller] |
| 512 |
pub fn failure(&self) -> &Self { |
| 513 |
assert!( |
| 514 |
!self.succeeded(), |
| 515 |
"Command was expected to fail.\nstdout = {}\n stderr = {}", |
| 516 |
self.stdout_str(), |
| 517 |
self.stderr_str() |
| 518 |
); |
| 519 |
self |
| 520 |
} |
| 521 |
|
| 522 |
/// asserts that the command resulted in empty (zero-length) stderr stream output |
| 523 |
/// generally, it's better to use `stdout_only()` instead, |
| 524 |
/// but you might find yourself using this function if |
| 525 |
/// 1. you can not know exactly what stdout will be or |
| 526 |
/// 2. you know that stdout will also be empty |
| 527 |
/// |
| 528 |
/// # Examples |
| 529 |
/// |
| 530 |
/// ```rust,ignore |
| 531 |
/// scene.ucmd().fails().no_stderr(); |
| 532 |
/// ``` |
| 533 |
#[track_caller] |
| 534 |
pub fn no_stderr(&self) -> &Self { |
| 535 |
assert!( |
| 536 |
self.stderr.is_empty(), |
| 537 |
"Expected stderr to be empty, but it's:\n{}", |
| 538 |
self.stderr_str() |
| 539 |
); |
| 540 |
self |
| 541 |
} |
| 542 |
|
| 543 |
/// asserts that the command resulted in empty (zero-length) stderr stream output |
| 544 |
/// unless asserting there was neither stdout or stderr, `stderr_only` is usually a better choice |
| 545 |
/// generally, it's better to use `stderr_only()` instead, |
| 546 |
/// but you might find yourself using this function if |
| 547 |
/// 1. you can not know exactly what stderr will be or |
| 548 |
/// 2. you know that stderr will also be empty |
| 549 |
/// new_ucmd!() |
| 550 |
/// |
| 551 |
/// # Examples |
| 552 |
/// |
| 553 |
/// ```rust,ignore |
| 554 |
/// scene.ucmd().fails().no_stdout(); |
| 555 |
/// ``` |
| 556 |
#[track_caller] |
| 557 |
pub fn no_stdout(&self) -> &Self { |
| 558 |
assert!( |
| 559 |
self.stdout.is_empty(), |
| 560 |
"Expected stdout to be empty, but it's:\n{}", |
| 561 |
self.stdout_str() |
| 562 |
); |
| 563 |
self |
| 564 |
} |
| 565 |
|
| 566 |
/// Assert that there is output to neither stderr nor stdout. |
| 567 |
#[track_caller] |
| 568 |
pub fn no_output(&self) -> &Self { |
| 569 |
self.no_stdout().no_stderr() |
| 570 |
} |
| 571 |
|
| 572 |
/// asserts that the command resulted in stdout stream output that equals the |
| 573 |
/// passed in value, trailing whitespace are kept to force strict comparison (#1235) |
| 574 |
/// `stdout_only()` is a better choice unless stderr may or will be non-empty |
| 575 |
#[track_caller] |
| 576 |
pub fn stdout_is<T: AsRef<str>>(&self, msg: T) -> &Self { |
| 577 |
assert_eq!(self.stdout_str(), String::from(msg.as_ref())); |
| 578 |
self |
| 579 |
} |
| 580 |
|
| 581 |
/// like `stdout_is`, but succeeds if any elements of `expected` matches stdout. |
| 582 |
#[track_caller] |
| 583 |
pub fn stdout_is_any<T: AsRef<str> + std::fmt::Debug>(&self, expected: &[T]) -> &Self { |
| 584 |
assert!( |
| 585 |
expected.iter().any(|msg| self.stdout_str() == msg.as_ref()), |
| 586 |
"stdout was {}\nExpected any of {expected:#?}", |
| 587 |
self.stdout_str(), |
| 588 |
); |
| 589 |
self |
| 590 |
} |
| 591 |
|
| 592 |
/// Like `stdout_is` but newlines are normalized to `\n`. |
| 593 |
#[track_caller] |
| 594 |
pub fn normalized_newlines_stdout_is<T: AsRef<str>>(&self, msg: T) -> &Self { |
| 595 |
let msg = msg.as_ref().replace("\r\n", "\n"); |
| 596 |
assert_eq!(self.stdout_str().replace("\r\n", "\n"), msg); |
| 597 |
self |
| 598 |
} |
| 599 |
|
| 600 |
/// asserts that the command resulted in stdout stream output, |
| 601 |
/// whose bytes equal those of the passed in slice |
| 602 |
#[track_caller] |
| 603 |
pub fn stdout_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self { |
| 604 |
assert_eq!( |
| 605 |
self.stdout, |
| 606 |
msg.as_ref(), |
| 607 |
"stdout as bytes wasn't equal to expected bytes. Result as strings:\nstdout ='{:?}'\nexpected='{:?}'", |
| 608 |
std::str::from_utf8(&self.stdout), |
| 609 |
std::str::from_utf8(msg.as_ref()), |
| 610 |
); |
| 611 |
self |
| 612 |
} |
| 613 |
|
| 614 |
/// like `stdout_is()`, but expects the contents of the file at the provided relative path |
| 615 |
#[track_caller] |
| 616 |
pub fn stdout_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self { |
| 617 |
let contents = read_scenario_fixture(self.tmpd.as_ref(), file_rel_path); |
| 618 |
self.stdout_is(String::from_utf8(contents).unwrap()) |
| 619 |
} |
| 620 |
|
| 621 |
/// Assert that the bytes of stdout exactly match those of the given file. |
| 622 |
/// |
| 623 |
/// Contrast this with [`CmdResult::stdout_is_fixture`], which |
| 624 |
/// decodes the contents of the file as a UTF-8 [`String`] before |
| 625 |
/// comparison with stdout. |
| 626 |
/// |
| 627 |
/// # Examples |
| 628 |
/// |
| 629 |
/// Use this method in a unit test like this: |
| 630 |
/// |
| 631 |
/// ```rust,ignore |
| 632 |
/// #[test] |
| 633 |
/// fn test_something() { |
| 634 |
/// new_ucmd!().succeeds().stdout_is_fixture_bytes("expected.bin"); |
| 635 |
/// } |
| 636 |
/// ``` |
| 637 |
#[track_caller] |
| 638 |
pub fn stdout_is_fixture_bytes<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self { |
| 639 |
let contents = read_scenario_fixture(self.tmpd.as_ref(), file_rel_path); |
| 640 |
self.stdout_is_bytes(contents) |
| 641 |
} |
| 642 |
|
| 643 |
/// like `stdout_is_fixture()`, but replaces the data in fixture file based on values provided in `template_vars` |
| 644 |
/// command output |
| 645 |
#[track_caller] |
| 646 |
pub fn stdout_is_templated_fixture<T: AsRef<OsStr>>( |
| 647 |
&self, |
| 648 |
file_rel_path: T, |
| 649 |
template_vars: &[(&str, &str)], |
| 650 |
) -> &Self { |
| 651 |
let mut contents = |
| 652 |
String::from_utf8(read_scenario_fixture(self.tmpd.as_ref(), file_rel_path)).unwrap(); |
| 653 |
for kv in template_vars { |
| 654 |
contents = contents.replace(kv.0, kv.1); |
| 655 |
} |
| 656 |
self.stdout_is(contents) |
| 657 |
} |
| 658 |
|
| 659 |
/// like `stdout_is_templated_fixture`, but succeeds if any replacement by `template_vars` results in the actual stdout. |
| 660 |
#[track_caller] |
| 661 |
pub fn stdout_is_templated_fixture_any<T: AsRef<OsStr>>( |
| 662 |
&self, |
| 663 |
file_rel_path: T, |
| 664 |
template_vars: &[Vec<(String, String)>], |
| 665 |
) { |
| 666 |
let contents = |
| 667 |
String::from_utf8(read_scenario_fixture(self.tmpd.as_ref(), file_rel_path)).unwrap(); |
| 668 |
let possible_values = template_vars.iter().map(|vars| { |
| 669 |
let mut contents = contents.clone(); |
| 670 |
for kv in vars { |
| 671 |
contents = contents.replace(&kv.0, &kv.1); |
| 672 |
} |
| 673 |
contents |
| 674 |
}); |
| 675 |
self.stdout_is_any(&possible_values.collect::<Vec<_>>()); |
| 676 |
} |
| 677 |
|
| 678 |
/// assert that the command resulted in stderr stream output that equals the |
| 679 |
/// passed in value. |
| 680 |
/// |
| 681 |
/// `stderr_only` is a better choice unless stdout may or will be non-empty |
| 682 |
#[track_caller] |
| 683 |
pub fn stderr_is<T: AsRef<str>>(&self, msg: T) -> &Self { |
| 684 |
assert_eq!(self.stderr_str(), msg.as_ref()); |
| 685 |
self |
| 686 |
} |
| 687 |
|
| 688 |
/// asserts that the command resulted in stderr stream output, |
| 689 |
/// whose bytes equal those of the passed in slice |
| 690 |
#[track_caller] |
| 691 |
pub fn stderr_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self { |
| 692 |
assert_eq!( |
| 693 |
&self.stderr, |
| 694 |
msg.as_ref(), |
| 695 |
"stderr as bytes wasn't equal to expected bytes. Result as strings:\nstderr ='{:?}'\nexpected='{:?}'", |
| 696 |
std::str::from_utf8(&self.stderr), |
| 697 |
std::str::from_utf8(msg.as_ref()) |
| 698 |
); |
| 699 |
self |
| 700 |
} |
| 701 |
|
| 702 |
/// Like `stdout_is_fixture`, but for stderr |
| 703 |
#[track_caller] |
| 704 |
pub fn stderr_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self { |
| 705 |
let contents = read_scenario_fixture(self.tmpd.as_ref(), file_rel_path); |
| 706 |
self.stderr_is(String::from_utf8(contents).unwrap()) |
| 707 |
} |
| 708 |
|
| 709 |
/// asserts that |
| 710 |
/// 1. the command resulted in stdout stream output that equals the |
| 711 |
/// passed in value |
| 712 |
/// 2. the command resulted in empty (zero-length) stderr stream output |
| 713 |
#[track_caller] |
| 714 |
pub fn stdout_only<T: AsRef<str>>(&self, msg: T) -> &Self { |
| 715 |
self.no_stderr().stdout_is(msg) |
| 716 |
} |
| 717 |
|
| 718 |
/// asserts that |
| 719 |
/// 1. the command resulted in a stdout stream whose bytes |
| 720 |
/// equal those of the passed in value |
| 721 |
/// 2. the command resulted in an empty stderr stream |
| 722 |
#[track_caller] |
| 723 |
pub fn stdout_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self { |
| 724 |
self.no_stderr().stdout_is_bytes(msg) |
| 725 |
} |
| 726 |
|
| 727 |
/// like `stdout_only()`, but expects the contents of the file at the provided relative path |
| 728 |
#[track_caller] |
| 729 |
pub fn stdout_only_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self { |
| 730 |
let contents = read_scenario_fixture(self.tmpd.as_ref(), file_rel_path); |
| 731 |
self.stdout_only_bytes(contents) |
| 732 |
} |
| 733 |
|
| 734 |
/// asserts that |
| 735 |
/// 1. the command resulted in stderr stream output that equals the |
| 736 |
/// passed in value |
| 737 |
/// 2. the command resulted in empty (zero-length) stdout stream output |
| 738 |
#[track_caller] |
| 739 |
pub fn stderr_only<T: AsRef<str>>(&self, msg: T) -> &Self { |
| 740 |
self.no_stdout().stderr_is(msg) |
| 741 |
} |
| 742 |
|
| 743 |
/// asserts that |
| 744 |
/// 1. the command resulted in a stderr stream whose bytes equal the ones |
| 745 |
/// of the passed value |
| 746 |
/// 2. the command resulted in an empty stdout stream |
| 747 |
#[track_caller] |
| 748 |
pub fn stderr_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self { |
| 749 |
self.no_stdout().stderr_is_bytes(msg) |
| 750 |
} |
| 751 |
|
| 752 |
#[track_caller] |
| 753 |
pub fn fails_silently(&self) -> &Self { |
| 754 |
assert!(!self.succeeded()); |
| 755 |
assert!( |
| 756 |
self.stderr.is_empty(), |
| 757 |
"Expected stderr to be empty, but it's:\n{}", |
| 758 |
self.stderr_str() |
| 759 |
); |
| 760 |
self |
| 761 |
} |
| 762 |
|
| 763 |
/// asserts that |
| 764 |
/// 1. the command resulted in stderr stream output that equals the |
| 765 |
/// the following format |
| 766 |
/// `"{util_name}: {msg}\nTry '{bin_path} {util_name} --help' for more information."` |
| 767 |
/// This the expected format when a `UUsageError` is returned or when `show_error!` is called |
| 768 |
/// `msg` should be the same as the one provided to `UUsageError::new` or `show_error!` |
| 769 |
/// |
| 770 |
/// 2. the command resulted in empty (zero-length) stdout stream output |
| 771 |
#[track_caller] |
| 772 |
pub fn usage_error<T: AsRef<str>>(&self, msg: T) -> &Self { |
| 773 |
// When testing via a WASM runner, the binary sees only its filename |
| 774 |
// (via --argv0), not the full host path. |
| 775 |
let bin_display: Cow<'_, str> = if env::var("UUTESTS_WASM_RUNNER").is_ok() { |
| 776 |
self.bin_path |
| 777 |
.file_name() |
| 778 |
.unwrap_or(self.bin_path.as_os_str()) |
| 779 |
.to_string_lossy() |
| 780 |
} else { |
| 781 |
Cow::Owned(self.bin_path.display().to_string()) |
| 782 |
}; |
| 783 |
self.stderr_only(format!( |
| 784 |
"{0}: {2}\nTry '{1} {0} --help' for more information.\n", |
| 785 |
self.util_name.as_ref().unwrap(), // This shouldn't be called using a normal command |
| 786 |
bin_display, |
| 787 |
msg.as_ref() |
| 788 |
)) |
| 789 |
} |
| 790 |
|
| 791 |
/// Verify if stdout contains a specific string |
| 792 |
/// |
| 793 |
/// # Examples |
| 794 |
/// |
| 795 |
/// ```rust,ignore |
| 796 |
/// new_ucmd!() |
| 797 |
/// .arg("--help") |
| 798 |
/// .succeeds() |
| 799 |
/// .stdout_contains("Options:"); |
| 800 |
/// ``` |
| 801 |
#[track_caller] |
| 802 |
pub fn stdout_contains<T: AsRef<str>>(&self, cmp: T) -> &Self { |
| 803 |
assert!( |
| 804 |
self.stdout_str().contains(cmp.as_ref()), |
| 805 |
"'{}' does not contain '{}'", |
| 806 |
self.stdout_str(), |
| 807 |
cmp.as_ref() |
| 808 |
); |
| 809 |
self |
| 810 |
} |
| 811 |
|
| 812 |
/// Verify if stdout contains a specific line |
| 813 |
/// |
| 814 |
/// # Examples |
| 815 |
/// |
| 816 |
/// ```rust,ignore |
| 817 |
/// new_ucmd!() |
| 818 |
/// .arg("--help") |
| 819 |
/// .succeeds() |
| 820 |
/// .stdout_contains_line("Options:"); |
| 821 |
/// ``` |
| 822 |
#[track_caller] |
| 823 |
pub fn stdout_contains_line<T: AsRef<str>>(&self, cmp: T) -> &Self { |
| 824 |
assert!( |
| 825 |
self.stdout_str().lines().any(|line| line == cmp.as_ref()), |
| 826 |
"'{}' does not contain line '{}'", |
| 827 |
self.stdout_str(), |
| 828 |
cmp.as_ref() |
| 829 |
); |
| 830 |
self |
| 831 |
} |
| 832 |
|
| 833 |
/// Verify if stdout contains a byte sequence |
| 834 |
/// |
| 835 |
/// # Examples |
| 836 |
/// |
| 837 |
/// ```rust,ignore |
| 838 |
/// new_ucmd!() |
| 839 |
/// .arg("--help") |
| 840 |
/// .succeeds() |
| 841 |
/// .stdout_contains_bytes(b"hello \xff"); |
| 842 |
/// ``` |
| 843 |
#[track_caller] |
| 844 |
pub fn stdout_contains_bytes<T: AsRef<[u8]>>(&self, cmp: T) -> &Self { |
| 845 |
assert!( |
| 846 |
self.stdout() |
| 847 |
.windows(cmp.as_ref().len()) |
| 848 |
.any(|sub| sub == cmp.as_ref()), |
| 849 |
"'{:?}'\ndoes not contain\n'{:?}'", |
| 850 |
self.stdout(), |
| 851 |
cmp.as_ref() |
| 852 |
); |
| 853 |
self |
| 854 |
} |
| 855 |
|
| 856 |
/// Verify if stderr contains a specific string |
| 857 |
/// |
| 858 |
/// # Examples |
| 859 |
/// |
| 860 |
/// ```rust,ignore |
| 861 |
/// new_ucmd!() |
| 862 |
/// .arg("-l") |
| 863 |
/// .arg("IaMnOtAsIgNaL") |
| 864 |
/// .fails() |
| 865 |
/// .stderr_contains("IaMnOtAsIgNaL"); |
| 866 |
/// ``` |
| 867 |
#[track_caller] |
| 868 |
pub fn stderr_contains<T: AsRef<str>>(&self, cmp: T) -> &Self { |
| 869 |
assert!( |
| 870 |
self.stderr_str().contains(cmp.as_ref()), |
| 871 |
"'{}' does not contain '{}'", |
| 872 |
self.stderr_str(), |
| 873 |
cmp.as_ref() |
| 874 |
); |
| 875 |
self |
| 876 |
} |
| 877 |
|
| 878 |
/// Verify if stderr contains a byte sequence |
| 879 |
/// |
| 880 |
/// # Examples |
| 881 |
/// |
| 882 |
/// ```rust,ignore |
| 883 |
/// new_ucmd!() |
| 884 |
/// .arg("--help") |
| 885 |
/// .succeeds() |
| 886 |
/// .stdout_contains_bytes(b"hello \xff"); |
| 887 |
/// ``` |
| 888 |
#[track_caller] |
| 889 |
pub fn stderr_contains_bytes<T: AsRef<[u8]>>(&self, cmp: T) -> &Self { |
| 890 |
assert!( |
| 891 |
self.stderr() |
| 892 |
.windows(cmp.as_ref().len()) |
| 893 |
.any(|sub| sub == cmp.as_ref()), |
| 894 |
"'{:?}'\ndoes not contain\n'{:?}'", |
| 895 |
self.stderr(), |
| 896 |
cmp.as_ref() |
| 897 |
); |
| 898 |
self |
| 899 |
} |
| 900 |
|
| 901 |
/// Verify if stdout does not contain a specific string |
| 902 |
/// |
| 903 |
/// # Examples |
| 904 |
/// |
| 905 |
/// ```rust,ignore |
| 906 |
/// new_ucmd!() |
| 907 |
/// .arg("-l") |
| 908 |
/// .arg("IaMnOtAsIgNaL") |
| 909 |
/// .fails() |
| 910 |
/// .stdout_does_not_contain("Valid-signal"); |
| 911 |
/// ``` |
| 912 |
#[track_caller] |
| 913 |
pub fn stdout_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &Self { |
| 914 |
assert!( |
| 915 |
!self.stdout_str().contains(cmp.as_ref()), |
| 916 |
"'{}' contains '{}' but should not", |
| 917 |
self.stdout_str(), |
| 918 |
cmp.as_ref(), |
| 919 |
); |
| 920 |
self |
| 921 |
} |
| 922 |
|
| 923 |
/// Verify if st stderr does not contain a specific string |
| 924 |
/// |
| 925 |
/// # Examples |
| 926 |
/// |
| 927 |
/// ```rust,ignore |
| 928 |
/// new_ucmd!() |
| 929 |
/// .arg("-l") |
| 930 |
/// .arg("IaMnOtAsIgNaL") |
| 931 |
/// .fails() |
| 932 |
/// .stderr_does_not_contain("Valid-signal"); |
| 933 |
/// ``` |
| 934 |
#[track_caller] |
| 935 |
pub fn stderr_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &Self { |
| 936 |
assert!(!self.stderr_str().contains(cmp.as_ref())); |
| 937 |
self |
| 938 |
} |
| 939 |
|
| 940 |
#[track_caller] |
| 941 |
pub fn stdout_matches(&self, regex: ®ex::Regex) -> &Self { |
| 942 |
assert!( |
| 943 |
regex.is_match(self.stdout_str()), |
| 944 |
"Stdout does not match regex:\n{}", |
| 945 |
self.stdout_str() |
| 946 |
); |
| 947 |
self |
| 948 |
} |
| 949 |
|
| 950 |
#[track_caller] |
| 951 |
pub fn stderr_matches(&self, regex: ®ex::Regex) -> &Self { |
| 952 |
assert!( |
| 953 |
regex.is_match(self.stderr_str()), |
| 954 |
"Stderr does not match regex:\n{}", |
| 955 |
self.stderr_str() |
| 956 |
); |
| 957 |
self |
| 958 |
} |
| 959 |
|
| 960 |
#[track_caller] |
| 961 |
pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &Self { |
| 962 |
assert!( |
| 963 |
!regex.is_match(self.stdout_str()), |
| 964 |
"Stdout matches regex:\n{}", |
| 965 |
self.stdout_str() |
| 966 |
); |
| 967 |
self |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
pub fn log_info<T: AsRef<str>, U: AsRef<str>>(msg: T, par: U) { |
| 972 |
println!("{}: {}", msg.as_ref(), par.as_ref()); |
| 973 |
} |
| 974 |
|
| 975 |
pub fn recursive_copy(src: &Path, dest: &Path) -> Result<()> { |
| 976 |
if fs::metadata(src)?.is_dir() { |
| 977 |
for entry in fs::read_dir(src)? { |
| 978 |
let entry = entry?; |
| 979 |
let mut new_dest = PathBuf::from(dest); |
| 980 |
new_dest.push(entry.file_name()); |
| 981 |
if fs::metadata(entry.path())?.is_dir() { |
| 982 |
fs::create_dir(&new_dest)?; |
| 983 |
recursive_copy(&entry.path(), &new_dest)?; |
| 984 |
} else { |
| 985 |
fs::copy(entry.path(), new_dest)?; |
| 986 |
} |
| 987 |
} |
| 988 |
} |
| 989 |
Ok(()) |
| 990 |
} |
| 991 |
|
| 992 |
pub fn get_root_path() -> &'static str { |
| 993 |
if cfg!(windows) { "C:\\" } else { "/" } |
| 994 |
} |
| 995 |
|
| 996 |
/// Compares the extended attributes (xattrs) of two files or directories. |
| 997 |
/// |
| 998 |
/// # Returns |
| 999 |
/// |
| 1000 |
/// `true` if both paths have the same set of extended attributes, `false` otherwise. |
| 1001 |
#[cfg(all(unix, not(any(target_vendor = "apple", target_os = "openbsd"))))] |
| 1002 |
pub fn compare_xattrs<P: AsRef<Path>>(path1: P, path2: P) -> bool { |
| 1003 |
let get_sorted_xattrs = |path: P| { |
| 1004 |
xattr::list(path) |
| 1005 |
.map(|attrs| { |
| 1006 |
let mut attrs = attrs.collect::<Vec<_>>(); |
| 1007 |
attrs.sort(); |
| 1008 |
attrs |
| 1009 |
}) |
| 1010 |
.unwrap_or_default() |
| 1011 |
}; |
| 1012 |
|
| 1013 |
get_sorted_xattrs(path1) == get_sorted_xattrs(path2) |
| 1014 |
} |
| 1015 |
|
| 1016 |
/// Object-oriented path struct that represents and operates on |
| 1017 |
/// paths relative to the directory it was constructed for. |
| 1018 |
#[derive(Clone)] |
| 1019 |
pub struct AtPath { |
| 1020 |
pub subdir: PathBuf, |
| 1021 |
} |
| 1022 |
|
| 1023 |
impl AtPath { |
| 1024 |
pub fn new(subdir: &Path) -> Self { |
| 1025 |
Self { |
| 1026 |
subdir: PathBuf::from(subdir), |
| 1027 |
} |
| 1028 |
} |
| 1029 |
|
| 1030 |
pub fn as_string(&self) -> String { |
| 1031 |
self.subdir.to_str().unwrap().to_owned() |
| 1032 |
} |
| 1033 |
|
| 1034 |
pub fn plus<P: AsRef<Path>>(&self, name: P) -> PathBuf { |
| 1035 |
let mut pathbuf = self.subdir.clone(); |
| 1036 |
pathbuf.push(name); |
| 1037 |
pathbuf |
| 1038 |
} |
| 1039 |
|
| 1040 |
pub fn plus_as_string<P: AsRef<Path>>(&self, name: P) -> String { |
| 1041 |
self.plus(name).display().to_string() |
| 1042 |
} |
| 1043 |
|
| 1044 |
fn minus(&self, name: &str) -> PathBuf { |
| 1045 |
let prefixed = PathBuf::from(name); |
| 1046 |
if prefixed.starts_with(&self.subdir) { |
| 1047 |
let mut unprefixed = PathBuf::new(); |
| 1048 |
for component in prefixed.components().skip(self.subdir.components().count()) { |
| 1049 |
unprefixed.push(component.as_os_str().to_str().unwrap()); |
| 1050 |
} |
| 1051 |
unprefixed |
| 1052 |
} else { |
| 1053 |
prefixed |
| 1054 |
} |
| 1055 |
} |
| 1056 |
|
| 1057 |
pub fn minus_as_string(&self, name: &str) -> String { |
| 1058 |
String::from(self.minus(name).to_str().unwrap()) |
| 1059 |
} |
| 1060 |
|
| 1061 |
pub fn set_readonly(&self, name: &str) { |
| 1062 |
let metadata = fs::metadata(self.plus(name)).unwrap(); |
| 1063 |
let mut permissions = metadata.permissions(); |
| 1064 |
permissions.set_readonly(true); |
| 1065 |
fs::set_permissions(self.plus(name), permissions).unwrap(); |
| 1066 |
} |
| 1067 |
|
| 1068 |
pub fn open(&self, name: &str) -> File { |
| 1069 |
log_info("open", self.plus_as_string(name)); |
| 1070 |
File::open(self.plus(name)).unwrap() |
| 1071 |
} |
| 1072 |
|
| 1073 |
pub fn read(&self, name: &str) -> String { |
| 1074 |
let mut f = self.open(name); |
| 1075 |
let mut contents = String::new(); |
| 1076 |
f.read_to_string(&mut contents) |
| 1077 |
.unwrap_or_else(|e| panic!("Couldn't read {name}: {e}")); |
| 1078 |
contents |
| 1079 |
} |
| 1080 |
|
| 1081 |
pub fn read_bytes(&self, name: &str) -> Vec<u8> { |
| 1082 |
let mut f = self.open(name); |
| 1083 |
let mut contents = Vec::new(); |
| 1084 |
f.read_to_end(&mut contents) |
| 1085 |
.unwrap_or_else(|e| panic!("Couldn't read {name}: {e}")); |
| 1086 |
contents |
| 1087 |
} |
| 1088 |
|
| 1089 |
pub fn write(&self, name: &str, contents: &str) { |
| 1090 |
log_info("write(default)", self.plus_as_string(name)); |
| 1091 |
fs::write(self.plus(name), contents) |
| 1092 |
.unwrap_or_else(|e| panic!("Couldn't write {name}: {e}")); |
| 1093 |
} |
| 1094 |
|
| 1095 |
pub fn write_bytes(&self, name: &str, contents: &[u8]) { |
| 1096 |
log_info("write(default)", self.plus_as_string(name)); |
| 1097 |
fs::write(self.plus(name), contents) |
| 1098 |
.unwrap_or_else(|e| panic!("Couldn't write {name}: {e}")); |
| 1099 |
} |
| 1100 |
|
| 1101 |
pub fn append(&self, name: impl AsRef<Path>, contents: &str) { |
| 1102 |
let name = name.as_ref(); |
| 1103 |
log_info("write(append)", self.plus_as_string(name)); |
| 1104 |
let mut f = OpenOptions::new() |
| 1105 |
.append(true) |
| 1106 |
.create(true) |
| 1107 |
.open(self.plus(name)) |
| 1108 |
.unwrap(); |
| 1109 |
f.write_all(contents.as_bytes()) |
| 1110 |
.unwrap_or_else(|e| panic!("Couldn't write(append) {}: {e}", name.display())); |
| 1111 |
} |
| 1112 |
|
| 1113 |
pub fn append_bytes(&self, name: &str, contents: &[u8]) { |
| 1114 |
log_info("write(append)", self.plus_as_string(name)); |
| 1115 |
let mut f = OpenOptions::new() |
| 1116 |
.append(true) |
| 1117 |
.create(true) |
| 1118 |
.open(self.plus(name)) |
| 1119 |
.unwrap(); |
| 1120 |
f.write_all(contents) |
| 1121 |
.unwrap_or_else(|e| panic!("Couldn't write(append) to {name}: {e}")); |
| 1122 |
} |
| 1123 |
|
| 1124 |
pub fn truncate(&self, name: &str, contents: &str) { |
| 1125 |
log_info("write(truncate)", self.plus_as_string(name)); |
| 1126 |
let mut f = OpenOptions::new() |
| 1127 |
.write(true) |
| 1128 |
.truncate(true) |
| 1129 |
.create(true) |
| 1130 |
.open(self.plus(name)) |
| 1131 |
.unwrap(); |
| 1132 |
f.write_all(contents.as_bytes()) |
| 1133 |
.unwrap_or_else(|e| panic!("Couldn't write(truncate) {name}: {e}")); |
| 1134 |
} |
| 1135 |
|
| 1136 |
pub fn rename(&self, source: &str, target: &str) { |
| 1137 |
let source = self.plus(source); |
| 1138 |
let target = self.plus(target); |
| 1139 |
log_info( |
| 1140 |
"rename", |
| 1141 |
format!("{} {}", source.display(), target.display()), |
| 1142 |
); |
| 1143 |
fs::rename(&source, &target).unwrap_or_else(|e| { |
| 1144 |
panic!( |
| 1145 |
"Couldn't rename {} -> {}: {e}", |
| 1146 |
source.display(), |
| 1147 |
target.display() |
| 1148 |
) |
| 1149 |
}); |
| 1150 |
} |
| 1151 |
|
| 1152 |
pub fn remove(&self, source: &str) { |
| 1153 |
let source = self.plus(source); |
| 1154 |
log_info("remove", format!("{}", source.display())); |
| 1155 |
remove_file(&source) |
| 1156 |
.unwrap_or_else(|e| panic!("Couldn't remove {}: {e}", source.display())); |
| 1157 |
} |
| 1158 |
|
| 1159 |
pub fn copy(&self, source: &str, target: &str) { |
| 1160 |
let source = self.plus(source); |
| 1161 |
let target = self.plus(target); |
| 1162 |
log_info("copy", format!("{} {}", source.display(), target.display())); |
| 1163 |
fs::copy(&source, &target).unwrap_or_else(|e| { |
| 1164 |
panic!( |
| 1165 |
"Couldn't copy {} -> {}: {e}", |
| 1166 |
source.display(), |
| 1167 |
target.display() |
| 1168 |
) |
| 1169 |
}); |
| 1170 |
} |
| 1171 |
|
| 1172 |
pub fn rmdir(&self, dir: &str) { |
| 1173 |
log_info("rmdir", self.plus_as_string(dir)); |
| 1174 |
fs::remove_dir(self.plus(dir)).unwrap(); |
| 1175 |
} |
| 1176 |
|
| 1177 |
pub fn mkdir<P: AsRef<Path>>(&self, dir: P) { |
| 1178 |
let dir = dir.as_ref(); |
| 1179 |
log_info("mkdir", self.plus_as_string(dir)); |
| 1180 |
fs::create_dir(self.plus(dir)).unwrap(); |
| 1181 |
} |
| 1182 |
|
| 1183 |
pub fn mkdir_all(&self, dir: &str) { |
| 1184 |
log_info("mkdir_all", self.plus_as_string(dir)); |
| 1185 |
fs::create_dir_all(self.plus(dir)).unwrap(); |
| 1186 |
} |
| 1187 |
|
| 1188 |
pub fn make_file(&self, name: &str) -> File { |
| 1189 |
match File::create(self.plus(name)) { |
| 1190 |
Ok(f) => f, |
| 1191 |
Err(e) => panic!("{e}"), |
| 1192 |
} |
| 1193 |
} |
| 1194 |
|
| 1195 |
pub fn touch<P: AsRef<Path>>(&self, file: P) { |
| 1196 |
let file = file.as_ref(); |
| 1197 |
log_info("touch", self.plus_as_string(file)); |
| 1198 |
File::create(self.plus(file)).unwrap(); |
| 1199 |
} |
| 1200 |
|
| 1201 |
#[cfg(not(windows))] |
| 1202 |
pub fn mkfifo(&self, fifo: &str) { |
| 1203 |
// rustix::fs::mkfifoat is linux only |
| 1204 |
use nix::sys::stat::Mode; |
| 1205 |
let full_path = self.plus_as_string(fifo); |
| 1206 |
log_info("mkfifo", &full_path); |
| 1207 |
|
| 1208 |
let mode = Mode::S_IRUSR | Mode::S_IWUSR; |
| 1209 |
nix::unistd::mkfifo(Path::new(&full_path), mode).expect("mkfifo failed"); |
| 1210 |
} |
| 1211 |
|
| 1212 |
#[cfg(unix)] |
| 1213 |
pub fn mksocket(&self, socket: &str) { |
| 1214 |
let full_path = self.plus_as_string(socket); |
| 1215 |
log_info("mksocket", &full_path); |
| 1216 |
UnixListener::bind(full_path).expect("Socket file creation failed."); |
| 1217 |
} |
| 1218 |
|
| 1219 |
#[cfg(not(windows))] |
| 1220 |
pub fn is_fifo(&self, fifo: &str) -> bool { |
| 1221 |
stat::stat(&self.plus(fifo)) |
| 1222 |
.is_ok_and(|s| SFlag::from_bits_truncate(s.st_mode).contains(SFlag::S_IFIFO)) |
| 1223 |
} |
| 1224 |
|
| 1225 |
#[cfg(not(windows))] |
| 1226 |
pub fn is_char_device(&self, char_dev: &str) -> bool { |
| 1227 |
stat::stat(&self.plus(char_dev)) |
| 1228 |
.is_ok_and(|s| SFlag::from_bits_truncate(s.st_mode).contains(SFlag::S_IFCHR)) |
| 1229 |
} |
| 1230 |
|
| 1231 |
pub fn hard_link(&self, original: &str, link: &str) { |
| 1232 |
log_info( |
| 1233 |
"hard_link", |
| 1234 |
format!( |
| 1235 |
"{},{}", |
| 1236 |
self.plus_as_string(original), |
| 1237 |
self.plus_as_string(link) |
| 1238 |
), |
| 1239 |
); |
| 1240 |
hard_link(self.plus(original), self.plus(link)).unwrap(); |
| 1241 |
} |
| 1242 |
|
| 1243 |
pub fn symlink_file(&self, original: &str, link: &str) { |
| 1244 |
log_info( |
| 1245 |
"symlink", |
| 1246 |
format!( |
| 1247 |
"{},{}", |
| 1248 |
self.plus_as_string(original), |
| 1249 |
self.plus_as_string(link) |
| 1250 |
), |
| 1251 |
); |
| 1252 |
symlink_file(self.plus(original), self.plus(link)).unwrap(); |
| 1253 |
} |
| 1254 |
|
| 1255 |
pub fn relative_symlink_file(&self, original: &str, link: &str) { |
| 1256 |
#[cfg(windows)] |
| 1257 |
let original = original.replace('/', MAIN_SEPARATOR_STR); |
| 1258 |
log_info( |
| 1259 |
"symlink", |
| 1260 |
format!("{original},{}", self.plus_as_string(link)), |
| 1261 |
); |
| 1262 |
symlink_file(original, self.plus(link)).unwrap(); |
| 1263 |
} |
| 1264 |
|
| 1265 |
pub fn symlink_dir(&self, original: &str, link: &str) { |
| 1266 |
log_info( |
| 1267 |
"symlink", |
| 1268 |
format!( |
| 1269 |
"{},{}", |
| 1270 |
self.plus_as_string(original), |
| 1271 |
self.plus_as_string(link) |
| 1272 |
), |
| 1273 |
); |
| 1274 |
symlink_dir(self.plus(original), self.plus(link)).unwrap(); |
| 1275 |
} |
| 1276 |
|
| 1277 |
pub fn relative_symlink_dir(&self, original: &str, link: &str) { |
| 1278 |
#[cfg(windows)] |
| 1279 |
let original = original.replace('/', MAIN_SEPARATOR_STR); |
| 1280 |
log_info( |
| 1281 |
"symlink", |
| 1282 |
format!("{original},{}", self.plus_as_string(link)), |
| 1283 |
); |
| 1284 |
symlink_dir(original, self.plus(link)).unwrap(); |
| 1285 |
} |
| 1286 |
|
| 1287 |
pub fn is_symlink(&self, path: &str) -> bool { |
| 1288 |
log_info("is_symlink", self.plus_as_string(path)); |
| 1289 |
match fs::symlink_metadata(self.plus(path)) { |
| 1290 |
Ok(m) => m.file_type().is_symlink(), |
| 1291 |
Err(_) => false, |
| 1292 |
} |
| 1293 |
} |
| 1294 |
|
| 1295 |
pub fn resolve_link(&self, path: &str) -> String { |
| 1296 |
log_info("resolve_link", self.plus_as_string(path)); |
| 1297 |
match fs::read_link(self.plus(path)) { |
| 1298 |
Ok(p) => self.minus_as_string(p.to_str().unwrap()), |
| 1299 |
Err(_) => String::new(), |
| 1300 |
} |
| 1301 |
} |
| 1302 |
|
| 1303 |
pub fn read_symlink(&self, path: &str) -> String { |
| 1304 |
log_info("read_symlink", self.plus_as_string(path)); |
| 1305 |
fs::read_link(self.plus(path)) |
| 1306 |
.unwrap() |
| 1307 |
.to_str() |
| 1308 |
.unwrap() |
| 1309 |
.to_owned() |
| 1310 |
} |
| 1311 |
|
| 1312 |
pub fn symlink_metadata(&self, path: &str) -> fs::Metadata { |
| 1313 |
match fs::symlink_metadata(self.plus(path)) { |
| 1314 |
Ok(m) => m, |
| 1315 |
Err(e) => panic!("{e}"), |
| 1316 |
} |
| 1317 |
} |
| 1318 |
|
| 1319 |
pub fn metadata(&self, path: &str) -> fs::Metadata { |
| 1320 |
match fs::metadata(self.plus(path)) { |
| 1321 |
Ok(m) => m, |
| 1322 |
Err(e) => panic!("{e}"), |
| 1323 |
} |
| 1324 |
} |
| 1325 |
|
| 1326 |
pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool { |
| 1327 |
match fs::metadata(self.plus(path)) { |
| 1328 |
Ok(m) => m.is_file(), |
| 1329 |
Err(_) => false, |
| 1330 |
} |
| 1331 |
} |
| 1332 |
|
| 1333 |
/// Decide whether the named symbolic link exists in the test directory. |
| 1334 |
pub fn symlink_exists<P: AsRef<Path>>(&self, path: P) -> bool { |
| 1335 |
match fs::symlink_metadata(self.plus(path)) { |
| 1336 |
Ok(m) => m.file_type().is_symlink(), |
| 1337 |
Err(_) => false, |
| 1338 |
} |
| 1339 |
} |
| 1340 |
|
| 1341 |
pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool { |
| 1342 |
match fs::metadata(self.plus(path)) { |
| 1343 |
Ok(m) => m.is_dir(), |
| 1344 |
Err(_) => false, |
| 1345 |
} |
| 1346 |
} |
| 1347 |
|
| 1348 |
pub fn root_dir_resolved(&self) -> String { |
| 1349 |
log_info("current_directory_resolved", ""); |
| 1350 |
let s = self |
| 1351 |
.subdir |
| 1352 |
.canonicalize() |
| 1353 |
.unwrap() |
| 1354 |
.to_str() |
| 1355 |
.unwrap() |
| 1356 |
.to_owned(); |
| 1357 |
|
| 1358 |
// Due to canonicalize()'s use of GetFinalPathNameByHandleW() on Windows, the resolved path |
| 1359 |
// starts with '\\?\' to extend the limit of a given path to 32,767 wide characters. |
| 1360 |
// |
| 1361 |
// To address this issue, we remove this prepended string if available. |
| 1362 |
// |
| 1363 |
// Source: |
| 1364 |
// http://stackoverflow.com/questions/31439011/getfinalpathnamebyhandle-without-prepended |
| 1365 |
let prefix = "\\\\?\\"; |
| 1366 |
|
| 1367 |
if let Some(stripped) = s.strip_prefix(prefix) { |
| 1368 |
String::from(stripped) |
| 1369 |
} else { |
| 1370 |
s |
| 1371 |
} |
| 1372 |
} |
| 1373 |
|
| 1374 |
/// Set the permissions of the specified file. |
| 1375 |
/// |
| 1376 |
/// # Panics |
| 1377 |
/// |
| 1378 |
/// This function panics if there is an error loading the metadata |
| 1379 |
/// or setting the permissions of the file. |
| 1380 |
#[cfg(not(windows))] |
| 1381 |
pub fn set_mode(&self, filename: &str, mode: u32) { |
| 1382 |
let path = self.plus(filename); |
| 1383 |
let mut perms = fs::metadata(&path).unwrap().permissions(); |
| 1384 |
perms.set_mode(mode); |
| 1385 |
fs::set_permissions(&path, perms).unwrap(); |
| 1386 |
} |
| 1387 |
} |
| 1388 |
|
| 1389 |
/// An environment for running a single uutils test case, serves three functions: |
| 1390 |
/// 1. centralizes logic for locating the uutils binary and calling the utility |
| 1391 |
/// 2. provides a unique temporary directory for the test case |
| 1392 |
/// 3. copies over fixtures for the utility to the temporary directory |
| 1393 |
/// |
| 1394 |
/// Fixtures can be found under `tests/fixtures/$util_name/` |
| 1395 |
pub struct TestScenario { |
| 1396 |
pub bin_path: PathBuf, |
| 1397 |
pub util_name: String, |
| 1398 |
pub fixtures: AtPath, |
| 1399 |
tmpd: Rc<TempDir>, |
| 1400 |
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] |
| 1401 |
tmp_fs_mountpoint: Option<String>, |
| 1402 |
} |
| 1403 |
|
| 1404 |
impl TestScenario { |
| 1405 |
pub fn new<T>(util_name: T) -> Self |
| 1406 |
where |
| 1407 |
T: AsRef<str>, |
| 1408 |
{ |
| 1409 |
let tmpd = Rc::new(TempDir::new().unwrap()); |
| 1410 |
println!("bin: {:?}", get_tests_binary!()); |
| 1411 |
let ts = Self { |
| 1412 |
bin_path: PathBuf::from(get_tests_binary!()), |
| 1413 |
util_name: util_name.as_ref().into(), |
| 1414 |
fixtures: AtPath::new(tmpd.as_ref().path()), |
| 1415 |
tmpd, |
| 1416 |
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] |
| 1417 |
tmp_fs_mountpoint: None, |
| 1418 |
}; |
| 1419 |
let mut fixture_path_builder = env::current_dir().unwrap(); |
| 1420 |
fixture_path_builder.push(TESTS_DIR); |
| 1421 |
fixture_path_builder.push(FIXTURES_DIR); |
| 1422 |
fixture_path_builder.push(util_name.as_ref()); |
| 1423 |
if fs::metadata(&fixture_path_builder).is_ok_and(|m| m.is_dir()) { |
| 1424 |
recursive_copy(&fixture_path_builder, &ts.fixtures.subdir).unwrap(); |
| 1425 |
} |
| 1426 |
ts |
| 1427 |
} |
| 1428 |
|
| 1429 |
/// Returns builder for invoking the target uutils binary. Paths given are |
| 1430 |
/// treated relative to the environment's unique temporary test directory. |
| 1431 |
pub fn ucmd(&self) -> UCommand { |
| 1432 |
UCommand::from_test_scenario(self) |
| 1433 |
} |
| 1434 |
|
| 1435 |
/// Returns builder for invoking any system command. Paths given are treated |
| 1436 |
/// relative to the environment's unique temporary test directory. |
| 1437 |
pub fn cmd<S: Into<PathBuf>>(&self, bin_path: S) -> UCommand { |
| 1438 |
let mut command = UCommand::new(); |
| 1439 |
command.bin_path(bin_path); |
| 1440 |
command.temp_dir(self.tmpd.clone()); |
| 1441 |
command |
| 1442 |
} |
| 1443 |
|
| 1444 |
/// Returns builder for invoking a command in shell (e.g. sh -c 'cmd'). |
| 1445 |
/// Paths given are treated relative to the environment's unique temporary |
| 1446 |
/// test directory. |
| 1447 |
pub fn cmd_shell<S: AsRef<OsStr>>(&self, cmd: S) -> UCommand { |
| 1448 |
let mut command = UCommand::new(); |
| 1449 |
// Intentionally leave bin_path unset. |
| 1450 |
command.arg(cmd); |
| 1451 |
command.temp_dir(self.tmpd.clone()); |
| 1452 |
command |
| 1453 |
} |
| 1454 |
|
| 1455 |
/// Returns builder for invoking any uutils command. Paths given are treated |
| 1456 |
/// relative to the environment's unique temporary test directory. |
| 1457 |
pub fn ccmd<S: AsRef<str>>(&self, util_name: S) -> UCommand { |
| 1458 |
UCommand::with_util(util_name, self.tmpd.clone()) |
| 1459 |
} |
| 1460 |
|
| 1461 |
/// Mounts a temporary filesystem at the specified mount point. |
| 1462 |
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] |
| 1463 |
pub fn mount_temp_fs(&mut self, mount_point: &str) -> core::result::Result<(), String> { |
| 1464 |
if self.tmp_fs_mountpoint.is_some() { |
| 1465 |
return Err("already mounted".to_string()); |
| 1466 |
} |
| 1467 |
let cmd_result = self |
| 1468 |
.cmd("mount") |
| 1469 |
.arg("-t") |
| 1470 |
.arg("tmpfs") |
| 1471 |
.arg("-o") |
| 1472 |
.arg("size=640k") // ought to be enough |
| 1473 |
.arg("tmpfs") |
| 1474 |
.arg(mount_point) |
| 1475 |
.run(); |
| 1476 |
if !cmd_result.succeeded() { |
| 1477 |
return Err(format!("mount failed: {}", cmd_result.stderr_str())); |
| 1478 |
} |
| 1479 |
self.tmp_fs_mountpoint = Some(mount_point.to_string()); |
| 1480 |
Ok(()) |
| 1481 |
} |
| 1482 |
|
| 1483 |
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] |
| 1484 |
/// Unmounts the temporary filesystem if it is currently mounted. |
| 1485 |
pub fn umount_temp_fs(&mut self) { |
| 1486 |
if let Some(mount_point) = self.tmp_fs_mountpoint.as_ref() { |
| 1487 |
self.cmd("umount").arg(mount_point).succeeds(); |
| 1488 |
self.tmp_fs_mountpoint = None; |
| 1489 |
} |
| 1490 |
} |
| 1491 |
} |
| 1492 |
|
| 1493 |
impl Drop for TestScenario { |
| 1494 |
fn drop(&mut self) { |
| 1495 |
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] |
| 1496 |
self.umount_temp_fs(); |
| 1497 |
} |
| 1498 |
} |
| 1499 |
|
| 1500 |
#[cfg(unix)] |
| 1501 |
#[derive(Debug, Default)] |
| 1502 |
pub struct TerminalSimulation { |
| 1503 |
pub size: Option<libc::winsize>, |
| 1504 |
pub stdin: bool, |
| 1505 |
pub stdout: bool, |
| 1506 |
pub stderr: bool, |
| 1507 |
} |
| 1508 |
|
| 1509 |
/// A `UCommand` is a builder wrapping an individual Command that provides several additional features: |
| 1510 |
/// 1. it has convenience functions that are more ergonomic to use for piping in stdin, spawning the command |
| 1511 |
/// and asserting on the results. |
| 1512 |
/// 2. it tracks arguments provided so that in test cases which may provide variations of an arg in loops |
| 1513 |
/// the test failure can display the exact call which preceded an assertion failure. |
| 1514 |
/// 3. it provides convenience construction methods to set the Command uutils utility and temporary directory. |
| 1515 |
/// |
| 1516 |
/// Per default `UCommand` runs a command given as an argument in a shell, platform independently. |
| 1517 |
/// It does so with safety in mind, so the working directory is set to an individual temporary |
| 1518 |
/// directory and the environment variables are cleared per default. |
| 1519 |
/// |
| 1520 |
/// The default behavior can be changed with builder methods: |
| 1521 |
/// * [`UCommand::with_util`]: Run `coreutils UTIL_NAME` instead of the shell |
| 1522 |
/// * [`UCommand::from_test_scenario`]: Run `coreutils UTIL_NAME` instead of the shell in the |
| 1523 |
/// temporary directory of the [`TestScenario`] |
| 1524 |
/// * [`UCommand::current_dir`]: Sets the working directory |
| 1525 |
/// * ... |
| 1526 |
#[derive(Debug, Default)] |
| 1527 |
pub struct UCommand { |
| 1528 |
args: VecDeque<OsString>, |
| 1529 |
env_vars: Vec<(OsString, OsString)>, |
| 1530 |
current_dir: Option<PathBuf>, |
| 1531 |
bin_path: Option<PathBuf>, |
| 1532 |
util_name: Option<String>, |
| 1533 |
has_run: bool, |
| 1534 |
ignore_stdin_write_error: bool, |
| 1535 |
stdin: Option<Stdio>, |
| 1536 |
stdout: Option<Stdio>, |
| 1537 |
stderr: Option<Stdio>, |
| 1538 |
bytes_into_stdin: Option<Vec<u8>>, |
| 1539 |
#[cfg(unix)] |
| 1540 |
limits: Vec<(rlimit::Resource, u64, u64)>, |
| 1541 |
stderr_to_stdout: bool, |
| 1542 |
timeout: Option<Duration>, |
| 1543 |
#[cfg(unix)] |
| 1544 |
terminal_simulation: Option<TerminalSimulation>, |
| 1545 |
tmpd: Option<Rc<TempDir>>, // drop last |
| 1546 |
#[cfg(unix)] |
| 1547 |
umask: Option<mode_t>, |
| 1548 |
} |
| 1549 |
|
| 1550 |
impl UCommand { |
| 1551 |
/// Create a new plain [`UCommand`]. |
| 1552 |
/// |
| 1553 |
/// Executes a command that must be given as argument (for example with [`UCommand::arg`] in a |
| 1554 |
/// shell (`sh -c` on unix platforms or `cmd /C` on windows). |
| 1555 |
/// |
| 1556 |
/// Per default the environment is cleared and the working directory is set to an individual |
| 1557 |
/// temporary directory for safety purposes. |
| 1558 |
pub fn new() -> Self { |
| 1559 |
Self { |
| 1560 |
..Default::default() |
| 1561 |
} |
| 1562 |
} |
| 1563 |
|
| 1564 |
/// Create a [`UCommand`] for a specific uutils utility. |
| 1565 |
/// |
| 1566 |
/// Sets the temporary directory to `tmpd` and the execution binary to the path where |
| 1567 |
/// `coreutils` is found. |
| 1568 |
pub fn with_util<T>(util_name: T, tmpd: Rc<TempDir>) -> Self |
| 1569 |
where |
| 1570 |
T: AsRef<str>, |
| 1571 |
{ |
| 1572 |
let mut ucmd = Self::new(); |
| 1573 |
ucmd.util_name = Some(util_name.as_ref().into()); |
| 1574 |
ucmd.bin_path(&*get_tests_binary!()).temp_dir(tmpd); |
| 1575 |
ucmd |
| 1576 |
} |
| 1577 |
|
| 1578 |
/// Create a [`UCommand`] from a [`TestScenario`]. |
| 1579 |
/// |
| 1580 |
/// The temporary directory and uutils utility are inherited from the [`TestScenario`] and the |
| 1581 |
/// execution binary is set to `coreutils`. |
| 1582 |
pub fn from_test_scenario(scene: &TestScenario) -> Self { |
| 1583 |
Self::with_util(&scene.util_name, scene.tmpd.clone()) |
| 1584 |
} |
| 1585 |
|
| 1586 |
/// Set the execution binary. |
| 1587 |
/// |
| 1588 |
/// Make sure the binary found at this path is executable. It's safest to provide the |
| 1589 |
/// canonicalized path instead of just the name of the executable, since path resolution is not |
| 1590 |
/// guaranteed to work on all platforms. |
| 1591 |
fn bin_path<T>(&mut self, bin_path: T) -> &mut Self |
| 1592 |
where |
| 1593 |
T: Into<PathBuf>, |
| 1594 |
{ |
| 1595 |
self.bin_path = Some(bin_path.into()); |
| 1596 |
self |
| 1597 |
} |
| 1598 |
|
| 1599 |
/// Set the temporary directory. |
| 1600 |
/// |
| 1601 |
/// Per default an individual temporary directory is created for every [`UCommand`]. If not |
| 1602 |
/// specified otherwise with [`UCommand::current_dir`] the working directory is set to this |
| 1603 |
/// temporary directory. |
| 1604 |
fn temp_dir(&mut self, temp_dir: Rc<TempDir>) -> &mut Self { |
| 1605 |
self.tmpd = Some(temp_dir); |
| 1606 |
self |
| 1607 |
} |
| 1608 |
|
| 1609 |
/// Set the working directory for this [`UCommand`] |
| 1610 |
/// |
| 1611 |
/// Per default the working directory is set to the [`UCommand`] temporary directory. |
| 1612 |
/// |
| 1613 |
pub fn current_dir<T>(&mut self, current_dir: T) -> &mut Self |
| 1614 |
where |
| 1615 |
T: Into<PathBuf>, |
| 1616 |
{ |
| 1617 |
self.current_dir = Some(current_dir.into()); |
| 1618 |
self |
| 1619 |
} |
| 1620 |
|
| 1621 |
pub fn set_stdin<T: Into<Stdio>>(&mut self, stdin: T) -> &mut Self { |
| 1622 |
self.stdin = Some(stdin.into()); |
| 1623 |
self |
| 1624 |
} |
| 1625 |
|
| 1626 |
pub fn set_stdout<T: Into<Stdio>>(&mut self, stdout: T) -> &mut Self { |
| 1627 |
self.stdout = Some(stdout.into()); |
| 1628 |
self |
| 1629 |
} |
| 1630 |
|
| 1631 |
pub fn set_stderr<T: Into<Stdio>>(&mut self, stderr: T) -> &mut Self { |
| 1632 |
self.stderr = Some(stderr.into()); |
| 1633 |
self |
| 1634 |
} |
| 1635 |
|
| 1636 |
pub fn stderr_to_stdout(&mut self) -> &mut Self { |
| 1637 |
self.stderr_to_stdout = true; |
| 1638 |
self |
| 1639 |
} |
| 1640 |
|
| 1641 |
/// Add a parameter to the invocation. Path arguments are treated relative |
| 1642 |
/// to the test environment directory. |
| 1643 |
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self { |
| 1644 |
self.args.push_back(arg.as_ref().into()); |
| 1645 |
self |
| 1646 |
} |
| 1647 |
|
| 1648 |
/// Add multiple parameters to the invocation. Path arguments are treated relative |
| 1649 |
/// to the test environment directory. |
| 1650 |
pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut Self { |
| 1651 |
self.args.extend(args.iter().map(|s| s.as_ref().into())); |
| 1652 |
self |
| 1653 |
} |
| 1654 |
|
| 1655 |
/// provides standard input to feed in to the command when spawned |
| 1656 |
pub fn pipe_in<T: Into<Vec<u8>>>(&mut self, input: T) -> &mut Self { |
| 1657 |
assert!( |
| 1658 |
self.bytes_into_stdin.is_none(), |
| 1659 |
"{MULTIPLE_STDIN_MEANINGLESS}", |
| 1660 |
); |
| 1661 |
self.set_stdin(Stdio::piped()); |
| 1662 |
self.bytes_into_stdin = Some(input.into()); |
| 1663 |
self |
| 1664 |
} |
| 1665 |
|
| 1666 |
/// like `pipe_in()`, but uses the contents of the file at the provided relative path as the piped in data |
| 1667 |
pub fn pipe_in_fixture<S: AsRef<OsStr>>(&mut self, file_rel_path: S) -> &mut Self { |
| 1668 |
let contents = read_scenario_fixture(self.tmpd.as_ref(), file_rel_path); |
| 1669 |
self.pipe_in(contents) |
| 1670 |
} |
| 1671 |
|
| 1672 |
/// Ignores error caused by feeding stdin to the command. |
| 1673 |
/// This is typically useful to test non-standard workflows |
| 1674 |
/// like feeding something to a command that does not read it |
| 1675 |
pub fn ignore_stdin_write_error(&mut self) -> &mut Self { |
| 1676 |
self.ignore_stdin_write_error = true; |
| 1677 |
self |
| 1678 |
} |
| 1679 |
|
| 1680 |
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self |
| 1681 |
where |
| 1682 |
K: AsRef<OsStr>, |
| 1683 |
V: AsRef<OsStr>, |
| 1684 |
{ |
| 1685 |
self.env_vars |
| 1686 |
.push((key.as_ref().into(), val.as_ref().into())); |
| 1687 |
self |
| 1688 |
} |
| 1689 |
|
| 1690 |
pub fn envs<I, K, V>(&mut self, iter: I) -> &mut Self |
| 1691 |
where |
| 1692 |
I: IntoIterator<Item = (K, V)>, |
| 1693 |
K: AsRef<OsStr>, |
| 1694 |
V: AsRef<OsStr>, |
| 1695 |
{ |
| 1696 |
for (k, v) in iter { |
| 1697 |
self.env(k, v); |
| 1698 |
} |
| 1699 |
self |
| 1700 |
} |
| 1701 |
|
| 1702 |
#[cfg(unix)] |
| 1703 |
pub fn limit( |
| 1704 |
&mut self, |
| 1705 |
resource: rlimit::Resource, |
| 1706 |
soft_limit: u64, |
| 1707 |
hard_limit: u64, |
| 1708 |
) -> &mut Self { |
| 1709 |
self.limits.push((resource, soft_limit, hard_limit)); |
| 1710 |
self |
| 1711 |
} |
| 1712 |
|
| 1713 |
#[cfg(unix)] |
| 1714 |
/// The umask is a value that restricts the permissions of newly created files and directories. |
| 1715 |
pub fn umask(&mut self, umask: mode_t) -> &mut Self { |
| 1716 |
self.umask = Some(umask); |
| 1717 |
self |
| 1718 |
} |
| 1719 |
|
| 1720 |
/// Set the timeout for [`UCommand::run`] and similar methods in [`UCommand`]. |
| 1721 |
/// |
| 1722 |
/// After the timeout elapsed these `run` methods (besides [`UCommand::run_no_wait`]) will |
| 1723 |
/// panic. When [`UCommand::run_no_wait`] is used, this timeout is applied to |
| 1724 |
/// `wait_with_output` including all other waiting methods in [`UChild`] implicitly |
| 1725 |
/// using `wait_with_output()` and additionally [`UChild::kill`]. The default timeout of `kill` |
| 1726 |
/// will be overwritten by this `timeout`. |
| 1727 |
pub fn timeout(&mut self, timeout: Duration) -> &mut Self { |
| 1728 |
self.timeout = Some(timeout); |
| 1729 |
self |
| 1730 |
} |
| 1731 |
|
| 1732 |
/// Set if process should be run in a simulated terminal |
| 1733 |
/// |
| 1734 |
/// This is useful to test behavior that is only active if e.g. `stdout.is_terminal()` is `true`. |
| 1735 |
/// This function uses default terminal size and attaches stdin, stdout and stderr to that terminal. |
| 1736 |
/// For more control over the terminal simulation, use `terminal_sim_stdio` |
| 1737 |
/// (unix: pty, windows: `ConPTY`[not yet supported]) |
| 1738 |
#[cfg(unix)] |
| 1739 |
pub fn terminal_simulation(&mut self, enable: bool) -> &mut Self { |
| 1740 |
if enable { |
| 1741 |
self.terminal_simulation = Some(TerminalSimulation { |
| 1742 |
stdin: true, |
| 1743 |
stdout: true, |
| 1744 |
stderr: true, |
| 1745 |
..Default::default() |
| 1746 |
}); |
| 1747 |
} else { |
| 1748 |
self.terminal_simulation = None; |
| 1749 |
} |
| 1750 |
self |
| 1751 |
} |
| 1752 |
|
| 1753 |
/// Allows to simulate a terminal use-case with specific properties. |
| 1754 |
/// |
| 1755 |
/// This is useful to test behavior that is only active if e.g. `stdout.is_terminal()` is `true`. |
| 1756 |
/// This function allows to set a specific size and to attach the terminal to only parts of the in/out. |
| 1757 |
#[cfg(unix)] |
| 1758 |
pub fn terminal_sim_stdio(&mut self, config: TerminalSimulation) -> &mut Self { |
| 1759 |
self.terminal_simulation = Some(config); |
| 1760 |
self |
| 1761 |
} |
| 1762 |
|
| 1763 |
/// Attach stderr (and only stderr) to a simulated terminal, with colors |
| 1764 |
/// disabled through `NO_COLOR`. |
| 1765 |
/// |
| 1766 |
/// This is useful to test output that is only rendered when |
| 1767 |
/// `stderr.is_terminal()` is `true`, such as the rich error reports of |
| 1768 |
/// `chmod` or `test`, while letting assertions see plain text. |
| 1769 |
#[cfg(unix)] |
| 1770 |
pub fn terminal_sim_stderr(&mut self) -> &mut Self { |
| 1771 |
self.terminal_sim_stdio(TerminalSimulation { |
| 1772 |
stderr: true, |
| 1773 |
..Default::default() |
| 1774 |
}) |
| 1775 |
.env("NO_COLOR", "1") |
| 1776 |
} |
| 1777 |
|
| 1778 |
#[cfg(unix)] |
| 1779 |
fn read_from_pty(pty_fd: OwnedFd, out: File) { |
| 1780 |
let read_file = File::from(pty_fd); |
| 1781 |
let mut reader = io::BufReader::new(read_file); |
| 1782 |
let mut writer = BufWriter::new(out); |
| 1783 |
let result = io::copy(&mut reader, &mut writer); |
| 1784 |
match result { |
| 1785 |
Ok(_) => {} |
| 1786 |
// Input/output error (os error 5) is returned due to pipe closes. Buffer gets content anyway. |
| 1787 |
Err(e) if e.raw_os_error().unwrap_or_default() == 5 => {} |
| 1788 |
Err(e) => { |
| 1789 |
eprintln!("Unexpected error: {e:?}"); |
| 1790 |
panic!("error forwarding output of pty"); |
| 1791 |
} |
| 1792 |
} |
| 1793 |
} |
| 1794 |
|
| 1795 |
#[cfg(unix)] |
| 1796 |
fn spawn_reader_thread( |
| 1797 |
captured_output: Option<CapturedOutput>, |
| 1798 |
pty_fd_master: OwnedFd, |
| 1799 |
name: String, |
| 1800 |
) -> Option<CapturedOutput> { |
| 1801 |
if let Some(mut captured_output_i) = captured_output { |
| 1802 |
let fd = captured_output_i.try_clone().unwrap(); |
| 1803 |
|
| 1804 |
let handle = thread::Builder::new() |
| 1805 |
.name(name) |
| 1806 |
.spawn(move || { |
| 1807 |
Self::read_from_pty(pty_fd_master, fd); |
| 1808 |
}) |
| 1809 |
.unwrap(); |
| 1810 |
|
| 1811 |
captured_output_i.reader_thread_handle = Some(handle); |
| 1812 |
Some(captured_output_i) |
| 1813 |
} else { |
| 1814 |
None |
| 1815 |
} |
| 1816 |
} |
| 1817 |
|
| 1818 |
/// Build the `std::process::Command` and apply the defaults on fields which were not specified |
| 1819 |
/// by the user. |
| 1820 |
/// |
| 1821 |
/// These __defaults__ are: |
| 1822 |
/// * `bin_path`: Depending on the platform and os, the native shell (unix -> `/bin/sh` etc.). |
| 1823 |
/// This default also requires to set the first argument to `-c` on unix (`/C` on windows) if |
| 1824 |
/// this argument wasn't specified explicitly by the user. |
| 1825 |
/// * `util_name`: `None`. If neither `bin_path` nor `util_name` were given the arguments are |
| 1826 |
/// run in a shell (See `bin_path` above). |
| 1827 |
/// * `temp_dir`: If `current_dir` was not set, a new temporary directory will be created in |
| 1828 |
/// which this command will be run and `current_dir` will be set to this `temp_dir`. |
| 1829 |
/// * `current_dir`: The temporary directory given by `temp_dir`. |
| 1830 |
/// * `timeout`: `30 seconds` |
| 1831 |
/// * `stdin`: `Stdio::null()` |
| 1832 |
/// * `ignore_stdin_write_error`: `false` |
| 1833 |
/// * `stdout`, `stderr`: If not specified the output will be captured with [`CapturedOutput`] |
| 1834 |
/// * `stderr_to_stdout`: `false` |
| 1835 |
/// * `bytes_into_stdin`: `None` |
| 1836 |
/// * `limits`: `None`. |
| 1837 |
fn build( |
| 1838 |
&mut self, |
| 1839 |
) -> ( |
| 1840 |
Command, |
| 1841 |
Option<CapturedOutput>, |
| 1842 |
Option<CapturedOutput>, |
| 1843 |
Option<File>, |
| 1844 |
) { |
| 1845 |
if self.bin_path.is_some() { |
| 1846 |
if let Some(util_name) = &self.util_name { |
| 1847 |
self.args.push_front(util_name.into()); |
| 1848 |
} |
| 1849 |
} else if let Some(util_name) = &self.util_name { |
| 1850 |
self.bin_path = Some(PathBuf::from(&*get_tests_binary!())); |
| 1851 |
self.args.push_front(util_name.into()); |
| 1852 |
// neither `bin_path` nor `util_name` was set so we apply the default to run the arguments |
| 1853 |
// in a platform specific shell |
| 1854 |
} else if cfg!(unix) { |
| 1855 |
#[cfg(target_os = "android")] |
| 1856 |
let bin_path = PathBuf::from("/system/bin/sh"); |
| 1857 |
#[cfg(not(target_os = "android"))] |
| 1858 |
let bin_path = PathBuf::from("/bin/sh"); |
| 1859 |
|
| 1860 |
self.bin_path = Some(bin_path); |
| 1861 |
let c_arg = OsString::from("-c"); |
| 1862 |
if !self.args.contains(&c_arg) { |
| 1863 |
self.args.push_front(c_arg); |
| 1864 |
} |
| 1865 |
} else { |
| 1866 |
self.bin_path = Some(PathBuf::from("cmd")); |
| 1867 |
let c_arg = OsString::from("/C"); |
| 1868 |
let k_arg = OsString::from("/K"); |
| 1869 |
if !self |
| 1870 |
.args |
| 1871 |
.iter() |
| 1872 |
.any(|s| s.eq_ignore_ascii_case(&c_arg) || s.eq_ignore_ascii_case(&k_arg)) |
| 1873 |
{ |
| 1874 |
self.args.push_front(c_arg); |
| 1875 |
} |
| 1876 |
} |
| 1877 |
|
| 1878 |
// Resolve the working directory before building the command, since WASM |
| 1879 |
// runners need it as an absolute --dir argument. |
| 1880 |
let work_dir = if let Some(current_dir) = &self.current_dir { |
| 1881 |
std::path::absolute(current_dir).unwrap_or_else(|_| current_dir.clone()) |
| 1882 |
} else if let Some(temp_dir) = &self.tmpd { |
| 1883 |
temp_dir.path().to_path_buf() |
| 1884 |
} else { |
| 1885 |
let temp_dir = tempfile::tempdir().unwrap(); |
| 1886 |
let path = temp_dir.path().to_path_buf(); |
| 1887 |
self.current_dir = Some(path.clone()); |
| 1888 |
self.tmpd = Some(Rc::new(temp_dir)); |
| 1889 |
path |
| 1890 |
}; |
| 1891 |
|
| 1892 |
// If UUTESTS_WASM_RUNNER is set (e.g. "wasmtime"), run the binary through |
| 1893 |
// that runner so host-compiled tests can exercise a WASI binary. Only |
| 1894 |
// apply to the coreutils binary under test, not to helper commands like |
| 1895 |
// sh or seq that should run natively on the host. |
| 1896 |
let wasm_runner = env::var("UUTESTS_WASM_RUNNER").ok().filter(|_| { |
| 1897 |
self.bin_path.as_deref() |
| 1898 |
== env::var("UUTESTS_BINARY_PATH") |
| 1899 |
.ok() |
| 1900 |
.map(PathBuf::from) |
| 1901 |
.as_deref() |
| 1902 |
}); |
| 1903 |
|
| 1904 |
// Collect environment variables for the command. |
| 1905 |
let mut cmd_env: Vec<(OsString, OsString)> = Vec::new(); |
| 1906 |
cmd_env.extend( |
| 1907 |
DEFAULT_ENV |
| 1908 |
.iter() |
| 1909 |
.map(|(k, v)| (OsString::from(k), OsString::from(v))), |
| 1910 |
); |
| 1911 |
if let Some(path) = env::var_os("PATH") { |
| 1912 |
cmd_env.push(("PATH".into(), path)); |
| 1913 |
} |
| 1914 |
if cfg!(windows) { |
| 1915 |
// spell-checker:ignore (dll) rsaenh |
| 1916 |
// %SYSTEMROOT% is required on Windows to initialize crypto provider |
| 1917 |
if let Some(systemroot) = env::var_os("SYSTEMROOT") { |
| 1918 |
cmd_env.push(("SYSTEMROOT".into(), systemroot)); |
| 1919 |
} |
| 1920 |
} else if let Some(ld_preload) = env::var_os("LD_PRELOAD") { |
| 1921 |
cmd_env.push(("LD_PRELOAD".into(), ld_preload)); |
| 1922 |
} |
| 1923 |
if let Some(llvm_profile) = env::var_os("LLVM_PROFILE_FILE") { |
| 1924 |
cmd_env.push(("LLVM_PROFILE_FILE".into(), llvm_profile)); |
| 1925 |
} |
| 1926 |
cmd_env.extend(self.env_vars.iter().cloned()); |
| 1927 |
|
| 1928 |
let mut command = if let Some(ref runner) = wasm_runner { |
| 1929 |
let bin = self.bin_path.as_ref().unwrap(); |
| 1930 |
let mut cmd = Command::new(runner); |
| 1931 |
// Map the working directory as the WASI guest's root. Only files |
| 1932 |
// under this directory are visible to the guest; tests using |
| 1933 |
// absolute host paths outside it must be skipped. |
| 1934 |
cmd.arg(format!("--dir={}::/", work_dir.display())); |
| 1935 |
cmd.arg("--argv0"); |
| 1936 |
cmd.arg(bin.file_name().unwrap_or(bin.as_os_str())); |
| 1937 |
// Forward env vars to the WASI guest via --env flags |
| 1938 |
for (key, val) in &cmd_env { |
| 1939 |
if let (Some(k), Some(v)) = (key.to_str(), val.to_str()) { |
| 1940 |
cmd.arg("--env"); |
| 1941 |
cmd.arg(format!("{k}={v}")); |
| 1942 |
} |
| 1943 |
} |
| 1944 |
cmd.arg(bin); |
| 1945 |
cmd |
| 1946 |
} else { |
| 1947 |
Command::new(self.bin_path.as_ref().unwrap()) |
| 1948 |
}; |
| 1949 |
command.args(&self.args); |
| 1950 |
command.current_dir(&work_dir); |
| 1951 |
command.env_clear(); |
| 1952 |
command.envs(cmd_env); |
| 1953 |
|
| 1954 |
if self.timeout.is_none() { |
| 1955 |
self.timeout = Some(Duration::from_secs(30)); |
| 1956 |
} |
| 1957 |
|
| 1958 |
let mut captured_stdout = None; |
| 1959 |
let mut captured_stderr = None; |
| 1960 |
#[cfg(unix)] |
| 1961 |
let mut stdin_pty: Option<File> = None; |
| 1962 |
#[cfg(not(unix))] |
| 1963 |
let stdin_pty: Option<File> = None; |
| 1964 |
if self.stderr_to_stdout { |
| 1965 |
let mut output = CapturedOutput::default(); |
| 1966 |
|
| 1967 |
command |
| 1968 |
.stdin(self.stdin.take().unwrap_or_else(Stdio::null)) |
| 1969 |
.stdout(Stdio::from(output.try_clone().unwrap())) |
| 1970 |
.stderr(Stdio::from(output.try_clone().unwrap())); |
| 1971 |
captured_stdout = Some(output); |
| 1972 |
} else { |
| 1973 |
let stdout = if self.stdout.is_some() { |
| 1974 |
self.stdout.take().unwrap() |
| 1975 |
} else { |
| 1976 |
let mut stdout = CapturedOutput::default(); |
| 1977 |
let stdio = Stdio::from(stdout.try_clone().unwrap()); |
| 1978 |
captured_stdout = Some(stdout); |
| 1979 |
stdio |
| 1980 |
}; |
| 1981 |
|
| 1982 |
let stderr = if self.stderr.is_some() { |
| 1983 |
self.stderr.take().unwrap() |
| 1984 |
} else { |
| 1985 |
let mut stderr = CapturedOutput::default(); |
| 1986 |
let stdio = Stdio::from(stderr.try_clone().unwrap()); |
| 1987 |
captured_stderr = Some(stderr); |
| 1988 |
stdio |
| 1989 |
}; |
| 1990 |
|
| 1991 |
command |
| 1992 |
.stdin(self.stdin.take().unwrap_or_else(Stdio::null)) |
| 1993 |
.stdout(stdout) |
| 1994 |
.stderr(stderr); |
| 1995 |
} |
| 1996 |
|
| 1997 |
#[cfg(unix)] |
| 1998 |
if let Some(simulated_terminal) = &self.terminal_simulation { |
| 1999 |
let terminal_size = simulated_terminal.size.unwrap_or(libc::winsize { |
| 2000 |
ws_col: 80, |
| 2001 |
ws_row: 30, |
| 2002 |
ws_xpixel: 80 * 8, |
| 2003 |
ws_ypixel: 30 * 10, |
| 2004 |
}); |
| 2005 |
|
| 2006 |
if simulated_terminal.stdin { |
| 2007 |
let OpenptyResult { |
| 2008 |
slave: pi_slave, |
| 2009 |
master: pi_master, |
| 2010 |
} = nix::pty::openpty(&terminal_size, None).unwrap(); |
| 2011 |
stdin_pty = Some(File::from(pi_master)); |
| 2012 |
command.stdin(pi_slave); |
| 2013 |
} |
| 2014 |
|
| 2015 |
if simulated_terminal.stdout { |
| 2016 |
let OpenptyResult { |
| 2017 |
slave: po_slave, |
| 2018 |
master: po_master, |
| 2019 |
} = nix::pty::openpty(&terminal_size, None).unwrap(); |
| 2020 |
captured_stdout = Self::spawn_reader_thread( |
| 2021 |
captured_stdout, |
| 2022 |
po_master, |
| 2023 |
"stdout_reader".to_string(), |
| 2024 |
); |
| 2025 |
command.stdout(po_slave); |
| 2026 |
} |
| 2027 |
|
| 2028 |
if simulated_terminal.stderr { |
| 2029 |
let OpenptyResult { |
| 2030 |
slave: pe_slave, |
| 2031 |
master: pe_master, |
| 2032 |
} = nix::pty::openpty(&terminal_size, None).unwrap(); |
| 2033 |
captured_stderr = Self::spawn_reader_thread( |
| 2034 |
captured_stderr, |
| 2035 |
pe_master, |
| 2036 |
"stderr_reader".to_string(), |
| 2037 |
); |
| 2038 |
command.stderr(pe_slave); |
| 2039 |
} |
| 2040 |
} |
| 2041 |
|
| 2042 |
#[cfg(unix)] |
| 2043 |
if !self.limits.is_empty() { |
| 2044 |
// just to be safe: move a copy of the limits list into the closure. |
| 2045 |
// this way the closure is fully self-contained. |
| 2046 |
let limits_copy = self.limits.clone(); |
| 2047 |
let closure = move || -> Result<()> { |
| 2048 |
for &(resource, soft_limit, hard_limit) in &limits_copy { |
| 2049 |
setrlimit(resource, soft_limit, hard_limit)?; |
| 2050 |
} |
| 2051 |
Ok(()) |
| 2052 |
}; |
| 2053 |
// SAFETY: the closure is self-contained and doesn't do any memory |
| 2054 |
// writes that would need to be propagated back to the parent process. |
| 2055 |
// also, the closure doesn't access stdin, stdout and stderr. |
| 2056 |
unsafe { |
| 2057 |
command.pre_exec(closure); |
| 2058 |
} |
| 2059 |
} |
| 2060 |
|
| 2061 |
#[cfg(unix)] |
| 2062 |
if let Some(umask) = self.umask { |
| 2063 |
unsafe { |
| 2064 |
command.pre_exec(move || { |
| 2065 |
libc::umask(umask); |
| 2066 |
Ok(()) |
| 2067 |
}); |
| 2068 |
} |
| 2069 |
} |
| 2070 |
|
| 2071 |
(command, captured_stdout, captured_stderr, stdin_pty) |
| 2072 |
} |
| 2073 |
|
| 2074 |
/// Spawns the command, feeds the stdin if any, and returns the |
| 2075 |
/// child process immediately. |
| 2076 |
pub fn run_no_wait(&mut self) -> UChild { |
| 2077 |
assert!(!self.has_run, "{ALREADY_RUN}"); |
| 2078 |
self.has_run = true; |
| 2079 |
|
| 2080 |
let (mut command, captured_stdout, captured_stderr, stdin_pty) = self.build(); |
| 2081 |
log_info("run", self.to_string()); |
| 2082 |
let child = command.spawn().unwrap(); |
| 2083 |
|
| 2084 |
let mut child = UChild::from(self, child, captured_stdout, captured_stderr, stdin_pty); |
| 2085 |
|
| 2086 |
if let Some(input) = self.bytes_into_stdin.take() { |
| 2087 |
child.pipe_in(input); |
| 2088 |
} |
| 2089 |
|
| 2090 |
child |
| 2091 |
} |
| 2092 |
|
| 2093 |
/// Spawns the command, feeds the stdin if any, waits for the result |
| 2094 |
/// and returns a command result. |
| 2095 |
/// It is recommended that you instead use `succeeds()` or `fails()` |
| 2096 |
pub fn run(&mut self) -> CmdResult { |
| 2097 |
self.run_no_wait().wait().unwrap() |
| 2098 |
} |
| 2099 |
|
| 2100 |
/// Spawns the command, feeding the passed in stdin, waits for the result |
| 2101 |
/// and returns a command result. |
| 2102 |
/// It is recommended that, instead of this, you use a combination of `pipe_in()` |
| 2103 |
/// with `succeeds()` or `fails()` |
| 2104 |
pub fn run_piped_stdin<T: Into<Vec<u8>>>(&mut self, input: T) -> CmdResult { |
| 2105 |
self.pipe_in(input).run() |
| 2106 |
} |
| 2107 |
|
| 2108 |
/// Spawns the command, feeds the stdin if any, waits for the result, |
| 2109 |
/// asserts success, and returns a command result. |
| 2110 |
#[track_caller] |
| 2111 |
pub fn succeeds(&mut self) -> CmdResult { |
| 2112 |
let cmd_result = self.run(); |
| 2113 |
cmd_result.success(); |
| 2114 |
cmd_result |
| 2115 |
} |
| 2116 |
|
| 2117 |
/// Spawns the command, feeds the stdin if any, waits for the result, |
| 2118 |
/// asserts failure, and returns a command result. |
| 2119 |
#[track_caller] |
| 2120 |
pub fn fails(&mut self) -> CmdResult { |
| 2121 |
let cmd_result = self.run(); |
| 2122 |
cmd_result.failure(); |
| 2123 |
cmd_result |
| 2124 |
} |
| 2125 |
|
| 2126 |
#[track_caller] |
| 2127 |
pub fn fails_with_code(&mut self, expected_code: i32) -> CmdResult { |
| 2128 |
let cmd_result = self.run(); |
| 2129 |
cmd_result.failure(); |
| 2130 |
cmd_result.code_is(expected_code); |
| 2131 |
cmd_result |
| 2132 |
} |
| 2133 |
|
| 2134 |
pub fn get_full_fixture_path(&self, file_rel_path: &str) -> String { |
| 2135 |
let tmpdir_path = self.tmpd.as_ref().unwrap().path(); |
| 2136 |
format!("{}/{file_rel_path}", tmpdir_path.to_str().unwrap()) |
| 2137 |
} |
| 2138 |
|
| 2139 |
/// Runs the command, checks that the stdout starts with "expected", |
| 2140 |
/// then terminates the command. |
| 2141 |
#[track_caller] |
| 2142 |
pub fn run_stdout_starts_with(&mut self, expected: &[u8]) -> CmdResult { |
| 2143 |
let mut child = self.set_stdout(Stdio::piped()).run_no_wait(); |
| 2144 |
let buf = child.stdout_exact_bytes(expected.len()); |
| 2145 |
child.close_stdout(); |
| 2146 |
|
| 2147 |
assert_eq!(buf.as_slice(), expected); |
| 2148 |
child.wait().unwrap() |
| 2149 |
} |
| 2150 |
} |
| 2151 |
|
| 2152 |
impl std::fmt::Display for UCommand { |
| 2153 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 2154 |
let mut comm_string: Vec<String> = vec![ |
| 2155 |
self.bin_path |
| 2156 |
.as_ref() |
| 2157 |
.map_or(String::new(), |p| p.display().to_string()), |
| 2158 |
]; |
| 2159 |
comm_string.extend(self.args.iter().map(|s| s.to_string_lossy().to_string())); |
| 2160 |
f.write_str(&comm_string.join(" ")) |
| 2161 |
} |
| 2162 |
} |
| 2163 |
|
| 2164 |
/// Stored the captured output in a temporary file. The file is deleted as soon as |
| 2165 |
/// [`CapturedOutput`] is dropped. |
| 2166 |
#[derive(Debug)] |
| 2167 |
struct CapturedOutput { |
| 2168 |
current_file: File, |
| 2169 |
output: tempfile::NamedTempFile, // drop last |
| 2170 |
reader_thread_handle: Option<JoinHandle<()>>, |
| 2171 |
} |
| 2172 |
|
| 2173 |
impl CapturedOutput { |
| 2174 |
/// Creates a new instance of `CapturedOutput` |
| 2175 |
fn new(output: tempfile::NamedTempFile) -> Self { |
| 2176 |
Self { |
| 2177 |
current_file: output.reopen().unwrap(), |
| 2178 |
output, |
| 2179 |
reader_thread_handle: None, |
| 2180 |
} |
| 2181 |
} |
| 2182 |
|
| 2183 |
/// Try to clone the file pointer. |
| 2184 |
fn try_clone(&mut self) -> Result<File> { |
| 2185 |
self.output.as_file().try_clone() |
| 2186 |
} |
| 2187 |
|
| 2188 |
/// Return the captured output as [`String`]. |
| 2189 |
/// |
| 2190 |
/// Subsequent calls to any of the other output methods will operate on the subsequent output. |
| 2191 |
fn output(&mut self) -> String { |
| 2192 |
String::from_utf8(self.output_bytes()).unwrap() |
| 2193 |
} |
| 2194 |
|
| 2195 |
/// Return the exact amount of bytes as `String`. |
| 2196 |
/// |
| 2197 |
/// Subsequent calls to any of the other output methods will operate on the subsequent output. |
| 2198 |
/// |
| 2199 |
/// # Important |
| 2200 |
/// |
| 2201 |
/// This method blocks indefinitely if the amount of bytes given by `size` cannot be read |
| 2202 |
fn output_exact(&mut self, size: usize) -> String { |
| 2203 |
String::from_utf8(self.output_exact_bytes(size)).unwrap() |
| 2204 |
} |
| 2205 |
|
| 2206 |
/// Return the captured output as bytes. |
| 2207 |
/// |
| 2208 |
/// Subsequent calls to any of the other output methods will operate on the subsequent output. |
| 2209 |
fn output_bytes(&mut self) -> Vec<u8> { |
| 2210 |
let mut buffer = Vec::<u8>::new(); |
| 2211 |
self.current_file.read_to_end(&mut buffer).unwrap(); |
| 2212 |
buffer |
| 2213 |
} |
| 2214 |
|
| 2215 |
/// Return all captured output, so far. |
| 2216 |
/// |
| 2217 |
/// Subsequent calls to any of the other output methods will operate on the subsequent output. |
| 2218 |
fn output_all_bytes(&mut self) -> Vec<u8> { |
| 2219 |
let mut buffer = Vec::<u8>::new(); |
| 2220 |
let mut file = self.output.reopen().unwrap(); |
| 2221 |
|
| 2222 |
file.read_to_end(&mut buffer).unwrap(); |
| 2223 |
self.current_file = file; |
| 2224 |
|
| 2225 |
buffer |
| 2226 |
} |
| 2227 |
|
| 2228 |
/// Return the exact amount of bytes. |
| 2229 |
/// |
| 2230 |
/// Subsequent calls to any of the other output methods will operate on the subsequent output. |
| 2231 |
/// |
| 2232 |
/// # Important |
| 2233 |
/// |
| 2234 |
/// This method blocks indefinitely if the amount of bytes given by `size` cannot be read |
| 2235 |
fn output_exact_bytes(&mut self, size: usize) -> Vec<u8> { |
| 2236 |
let mut buffer = vec![0; size]; |
| 2237 |
self.current_file.read_exact(&mut buffer).unwrap(); |
| 2238 |
buffer |
| 2239 |
} |
| 2240 |
} |
| 2241 |
|
| 2242 |
impl Default for CapturedOutput { |
| 2243 |
fn default() -> Self { |
| 2244 |
let mut retries = 10; |
| 2245 |
let file = loop { |
| 2246 |
let file = Builder::new().rand_bytes(10).suffix(".out").tempfile(); |
| 2247 |
if file.is_ok() || retries <= 0 { |
| 2248 |
break file.unwrap(); |
| 2249 |
} |
| 2250 |
sleep(Duration::from_millis(100)); |
| 2251 |
retries -= 1; |
| 2252 |
}; |
| 2253 |
Self { |
| 2254 |
current_file: file.reopen().unwrap(), |
| 2255 |
output: file, |
| 2256 |
reader_thread_handle: None, |
| 2257 |
} |
| 2258 |
} |
| 2259 |
} |
| 2260 |
|
| 2261 |
impl Drop for CapturedOutput { |
| 2262 |
fn drop(&mut self) { |
| 2263 |
let _ = remove_file(self.output.path()); |
| 2264 |
} |
| 2265 |
} |
| 2266 |
|
| 2267 |
#[derive(Debug, Copy, Clone)] |
| 2268 |
pub enum AssertionMode { |
| 2269 |
All, |
| 2270 |
Current, |
| 2271 |
Exact(usize, usize), |
| 2272 |
} |
| 2273 |
pub struct UChildAssertion<'a> { |
| 2274 |
uchild: &'a mut UChild, |
| 2275 |
} |
| 2276 |
|
| 2277 |
impl<'a> UChildAssertion<'a> { |
| 2278 |
pub fn new(uchild: &'a mut UChild) -> Self { |
| 2279 |
Self { uchild } |
| 2280 |
} |
| 2281 |
|
| 2282 |
fn with_output(&mut self, mode: AssertionMode) -> CmdResult { |
| 2283 |
let exit_status = if self.uchild.is_alive() { |
| 2284 |
None |
| 2285 |
} else { |
| 2286 |
Some(self.uchild.raw.wait().unwrap()) |
| 2287 |
}; |
| 2288 |
let (stdout, stderr) = match mode { |
| 2289 |
AssertionMode::All => ( |
| 2290 |
self.uchild.stdout_all_bytes(), |
| 2291 |
self.uchild.stderr_all_bytes(), |
| 2292 |
), |
| 2293 |
AssertionMode::Current => (self.uchild.stdout_bytes(), self.uchild.stderr_bytes()), |
| 2294 |
AssertionMode::Exact(expected_stdout_size, expected_stderr_size) => ( |
| 2295 |
self.uchild.stdout_exact_bytes(expected_stdout_size), |
| 2296 |
self.uchild.stderr_exact_bytes(expected_stderr_size), |
| 2297 |
), |
| 2298 |
}; |
| 2299 |
CmdResult::new( |
| 2300 |
self.uchild.bin_path.clone(), |
| 2301 |
self.uchild.util_name.clone(), |
| 2302 |
self.uchild.tmpd.clone(), |
| 2303 |
exit_status, |
| 2304 |
stdout, |
| 2305 |
stderr, |
| 2306 |
) |
| 2307 |
} |
| 2308 |
|
| 2309 |
// Make assertions of [`CmdResult`] with all output from start of the process until now. |
| 2310 |
// |
| 2311 |
// This method runs [`UChild::stdout_all_bytes`] and [`UChild::stderr_all_bytes`] under the |
| 2312 |
// hood. See there for side effects |
| 2313 |
pub fn with_all_output(&mut self) -> CmdResult { |
| 2314 |
self.with_output(AssertionMode::All) |
| 2315 |
} |
| 2316 |
|
| 2317 |
// Make assertions of [`CmdResult`] with the current output. |
| 2318 |
// |
| 2319 |
// This method runs [`UChild::stdout_bytes`] and [`UChild::stderr_bytes`] under the hood. See |
| 2320 |
// there for side effects |
| 2321 |
pub fn with_current_output(&mut self) -> CmdResult { |
| 2322 |
self.with_output(AssertionMode::Current) |
| 2323 |
} |
| 2324 |
|
| 2325 |
// Make assertions of [`CmdResult`] with the exact output. |
| 2326 |
// |
| 2327 |
// This method runs [`UChild::stdout_exact_bytes`] and [`UChild::stderr_exact_bytes`] under the |
| 2328 |
// hood. See there for side effects |
| 2329 |
pub fn with_exact_output( |
| 2330 |
&mut self, |
| 2331 |
expected_stdout_size: usize, |
| 2332 |
expected_stderr_size: usize, |
| 2333 |
) -> CmdResult { |
| 2334 |
self.with_output(AssertionMode::Exact( |
| 2335 |
expected_stdout_size, |
| 2336 |
expected_stderr_size, |
| 2337 |
)) |
| 2338 |
} |
| 2339 |
|
| 2340 |
// Assert that the child process is alive |
| 2341 |
#[track_caller] |
| 2342 |
pub fn is_alive(&mut self) -> &mut Self { |
| 2343 |
match self.uchild.raw.try_wait() { |
| 2344 |
Ok(Some(status)) => panic!( |
| 2345 |
"Assertion failed. Expected '{}' to be running but exited with status={status}.\nstdout: {}\nstderr: {}", |
| 2346 |
uucore::util_name(), |
| 2347 |
self.uchild.stdout_all(), |
| 2348 |
self.uchild.stderr_all() |
| 2349 |
), |
| 2350 |
Ok(None) => {} |
| 2351 |
Err(error) => panic!("Assertion failed with error '{error:?}'"), |
| 2352 |
} |
| 2353 |
|
| 2354 |
self |
| 2355 |
} |
| 2356 |
|
| 2357 |
// Assert that the child process has exited |
| 2358 |
#[track_caller] |
| 2359 |
pub fn is_not_alive(&mut self) -> &mut Self { |
| 2360 |
match self.uchild.raw.try_wait() { |
| 2361 |
Ok(None) => panic!( |
| 2362 |
"Assertion failed. Expected '{}' to be not running but was alive.\nstdout: {}\nstderr: {}", |
| 2363 |
uucore::util_name(), |
| 2364 |
self.uchild.stdout_all(), |
| 2365 |
self.uchild.stderr_all() |
| 2366 |
), |
| 2367 |
Ok(_) => {} |
| 2368 |
Err(error) => panic!("Assertion failed with error '{error:?}'"), |
| 2369 |
} |
| 2370 |
|
| 2371 |
self |
| 2372 |
} |
| 2373 |
} |
| 2374 |
|
| 2375 |
/// Abstraction for a [`std::process::Child`] to handle the child process. |
| 2376 |
pub struct UChild { |
| 2377 |
raw: Child, |
| 2378 |
bin_path: PathBuf, |
| 2379 |
util_name: Option<String>, |
| 2380 |
captured_stdout: Option<CapturedOutput>, |
| 2381 |
captured_stderr: Option<CapturedOutput>, |
| 2382 |
stdin_pty: Option<File>, |
| 2383 |
ignore_stdin_write_error: bool, |
| 2384 |
stderr_to_stdout: bool, |
| 2385 |
join_handle: Option<JoinHandle<Result<()>>>, |
| 2386 |
timeout: Option<Duration>, |
| 2387 |
tmpd: Option<Rc<TempDir>>, // drop last |
| 2388 |
} |
| 2389 |
|
| 2390 |
impl UChild { |
| 2391 |
fn from( |
| 2392 |
ucommand: &UCommand, |
| 2393 |
child: Child, |
| 2394 |
captured_stdout: Option<CapturedOutput>, |
| 2395 |
captured_stderr: Option<CapturedOutput>, |
| 2396 |
stdin_pty: Option<File>, |
| 2397 |
) -> Self { |
| 2398 |
Self { |
| 2399 |
raw: child, |
| 2400 |
bin_path: ucommand.bin_path.clone().unwrap(), |
| 2401 |
util_name: ucommand.util_name.clone(), |
| 2402 |
captured_stdout, |
| 2403 |
captured_stderr, |
| 2404 |
stdin_pty, |
| 2405 |
ignore_stdin_write_error: ucommand.ignore_stdin_write_error, |
| 2406 |
stderr_to_stdout: ucommand.stderr_to_stdout, |
| 2407 |
join_handle: None, |
| 2408 |
timeout: ucommand.timeout, |
| 2409 |
tmpd: ucommand.tmpd.clone(), |
| 2410 |
} |
| 2411 |
} |
| 2412 |
|
| 2413 |
/// Convenience method for `sleep(Duration::from_millis(millis))` |
| 2414 |
pub fn delay(&mut self, millis: u64) -> &mut Self { |
| 2415 |
sleep(Duration::from_millis(millis)); |
| 2416 |
self |
| 2417 |
} |
| 2418 |
|
| 2419 |
/// Return the pid of the child process, similar to [`Child::id`]. |
| 2420 |
pub fn id(&self) -> u32 { |
| 2421 |
self.raw.id() |
| 2422 |
} |
| 2423 |
|
| 2424 |
/// Return true if the child process is still alive and false otherwise. |
| 2425 |
pub fn is_alive(&mut self) -> bool { |
| 2426 |
self.raw.try_wait().unwrap().is_none() |
| 2427 |
} |
| 2428 |
|
| 2429 |
/// Return true if the child process is exited and false otherwise. |
| 2430 |
#[allow(clippy::wrong_self_convention)] |
| 2431 |
pub fn is_not_alive(&mut self) -> bool { |
| 2432 |
!self.is_alive() |
| 2433 |
} |
| 2434 |
|
| 2435 |
/// Return a [`UChildAssertion`] |
| 2436 |
pub fn make_assertion(&mut self) -> UChildAssertion<'_> { |
| 2437 |
UChildAssertion::new(self) |
| 2438 |
} |
| 2439 |
|
| 2440 |
/// Convenience function for calling [`UChild::delay`] and then [`UChild::make_assertion`] |
| 2441 |
pub fn make_assertion_with_delay(&mut self, millis: u64) -> UChildAssertion<'_> { |
| 2442 |
self.delay(millis).make_assertion() |
| 2443 |
} |
| 2444 |
|
| 2445 |
/// Try to kill the child process and wait for its termination. |
| 2446 |
/// |
| 2447 |
/// This method blocks until the child process is killed, but returns an error if `self.timeout` |
| 2448 |
/// or the default of 60s was reached. If no such error happened, the process resources are |
| 2449 |
/// released, so there is usually no need to call `wait` or alike on unix systems although it's |
| 2450 |
/// still possible to do so. |
| 2451 |
/// |
| 2452 |
/// # Platform specific behavior |
| 2453 |
/// |
| 2454 |
/// On unix systems the child process resources will be released like a call to [`Child::wait`] |
| 2455 |
/// or alike would do. |
| 2456 |
/// |
| 2457 |
/// # Error |
| 2458 |
/// |
| 2459 |
/// If [`Child::kill`] returned an error or if the child process could not be terminated within |
| 2460 |
/// `self.timeout` or the default of 60s. |
| 2461 |
pub fn try_kill(&mut self) -> Result<()> { |
| 2462 |
let start = Instant::now(); |
| 2463 |
self.raw.kill()?; |
| 2464 |
|
| 2465 |
let timeout = self.timeout.unwrap_or(Duration::from_secs(60)); |
| 2466 |
// As a side effect, we're cleaning up the killed child process with the implicit call to |
| 2467 |
// `Child::try_wait` in `self.is_alive`, which reaps the process id on unix systems. We |
| 2468 |
// always fail with error on timeout if `self.timeout` is set to zero. |
| 2469 |
while self.is_alive() || timeout == Duration::ZERO { |
| 2470 |
if start.elapsed() < timeout { |
| 2471 |
self.delay(10); |
| 2472 |
} else { |
| 2473 |
return Err(io::Error::other(format!( |
| 2474 |
"kill: Timeout of '{}s' reached", |
| 2475 |
timeout.as_secs_f64() |
| 2476 |
))); |
| 2477 |
} |
| 2478 |
hint::spin_loop(); |
| 2479 |
} |
| 2480 |
|
| 2481 |
Ok(()) |
| 2482 |
} |
| 2483 |
|
| 2484 |
/// Terminate the child process unconditionally and wait for the termination. |
| 2485 |
/// |
| 2486 |
/// Ignores any errors happening during [`Child::kill`] (i.e. child process already exited) but |
| 2487 |
/// still panics on timeout. |
| 2488 |
/// |
| 2489 |
/// # Panics |
| 2490 |
/// If the child process could not be terminated within `self.timeout` or the default of 60s. |
| 2491 |
pub fn kill(&mut self) -> &mut Self { |
| 2492 |
self.try_kill() |
| 2493 |
.or_else(|error| { |
| 2494 |
// We still throw the error on timeout in the `try_kill` function |
| 2495 |
if error.kind() == io::ErrorKind::Other { |
| 2496 |
Err(error) |
| 2497 |
} else { |
| 2498 |
Ok(()) |
| 2499 |
} |
| 2500 |
}) |
| 2501 |
.unwrap(); |
| 2502 |
self |
| 2503 |
} |
| 2504 |
|
| 2505 |
/// Try to kill the child process and wait for its termination. |
| 2506 |
/// |
| 2507 |
/// This method blocks until the child process is killed, but returns an error if `self.timeout` |
| 2508 |
/// or the default of 60s was reached. If no such error happened, the process resources are |
| 2509 |
/// released, so there is usually no need to call `wait` or alike on unix systems although it's |
| 2510 |
/// still possible to do so. |
| 2511 |
/// |
| 2512 |
/// # Platform specific behavior |
| 2513 |
/// |
| 2514 |
/// On unix systems the child process resources will be released like a call to [`Child::wait`] |
| 2515 |
/// or alike would do. |
| 2516 |
/// |
| 2517 |
/// # Error |
| 2518 |
/// |
| 2519 |
/// If [`Child::kill`] returned an error or if the child process could not be terminated within |
| 2520 |
/// `self.timeout` or the default of 60s. |
| 2521 |
#[cfg(unix)] |
| 2522 |
pub fn try_kill_with_custom_signal(&mut self, signal_name: sys::signal::Signal) -> Result<()> { |
| 2523 |
let start = Instant::now(); |
| 2524 |
sys::signal::kill( |
| 2525 |
nix::unistd::Pid::from_raw(self.raw.id().try_into().unwrap()), |
| 2526 |
signal_name, |
| 2527 |
) |
| 2528 |
.unwrap(); |
| 2529 |
|
| 2530 |
let timeout = self.timeout.unwrap_or(Duration::from_secs(60)); |
| 2531 |
// As a side effect, we're cleaning up the killed child process with the implicit call to |
| 2532 |
// `Child::try_wait` in `self.is_alive`, which reaps the process id on unix systems. We |
| 2533 |
// always fail with error on timeout if `self.timeout` is set to zero. |
| 2534 |
while self.is_alive() || timeout == Duration::ZERO { |
| 2535 |
if start.elapsed() < timeout { |
| 2536 |
self.delay(10); |
| 2537 |
} else { |
| 2538 |
return Err(io::Error::other(format!( |
| 2539 |
"kill: Timeout of '{}s' reached", |
| 2540 |
timeout.as_secs_f64() |
| 2541 |
))); |
| 2542 |
} |
| 2543 |
hint::spin_loop(); |
| 2544 |
} |
| 2545 |
|
| 2546 |
Ok(()) |
| 2547 |
} |
| 2548 |
|
| 2549 |
/// Terminate the child process using custom signal parameter and wait for the termination. |
| 2550 |
/// |
| 2551 |
/// Ignores any errors happening during [`Child::kill`] (i.e. child process already exited) but |
| 2552 |
/// still panics on timeout. |
| 2553 |
/// |
| 2554 |
/// # Panics |
| 2555 |
/// If the child process could not be terminated within `self.timeout` or the default of 60s. |
| 2556 |
#[cfg(unix)] |
| 2557 |
pub fn kill_with_custom_signal(&mut self, signal_name: sys::signal::Signal) -> &mut Self { |
| 2558 |
self.try_kill_with_custom_signal(signal_name) |
| 2559 |
.or_else(|error| { |
| 2560 |
// We still throw the error on timeout in the `try_kill` function |
| 2561 |
if error.kind() == io::ErrorKind::Other { |
| 2562 |
Err(error) |
| 2563 |
} else { |
| 2564 |
Ok(()) |
| 2565 |
} |
| 2566 |
}) |
| 2567 |
.unwrap(); |
| 2568 |
self |
| 2569 |
} |
| 2570 |
|
| 2571 |
/// Wait for the child process to terminate and return a [`CmdResult`]. |
| 2572 |
/// |
| 2573 |
/// See `wait_with_output` for details on timeouts etc. This method can also be run if |
| 2574 |
/// the child process was killed with [`UChild::kill`]. |
| 2575 |
/// |
| 2576 |
/// # Errors |
| 2577 |
/// |
| 2578 |
/// Returns the error from the call to `wait_with_output` if any |
| 2579 |
pub fn wait(self) -> Result<CmdResult> { |
| 2580 |
let (bin_path, util_name, tmpd) = ( |
| 2581 |
self.bin_path.clone(), |
| 2582 |
self.util_name.clone(), |
| 2583 |
self.tmpd.clone(), |
| 2584 |
); |
| 2585 |
|
| 2586 |
let output = self.wait_with_output()?; |
| 2587 |
|
| 2588 |
Ok(CmdResult { |
| 2589 |
bin_path, |
| 2590 |
util_name, |
| 2591 |
tmpd, |
| 2592 |
exit_status: Some(output.status), |
| 2593 |
stdout: output.stdout, |
| 2594 |
stderr: output.stderr, |
| 2595 |
}) |
| 2596 |
} |
| 2597 |
|
| 2598 |
/// Wait for the child process to terminate and return an instance of [`Output`]. |
| 2599 |
/// |
| 2600 |
/// If `self.timeout` is reached while waiting, a [`io::ErrorKind::Other`] representing a |
| 2601 |
/// timeout error is returned. If no errors happened, we join with the thread created by |
| 2602 |
/// [`UChild::pipe_in`] if any. |
| 2603 |
/// |
| 2604 |
/// # Error |
| 2605 |
/// |
| 2606 |
/// If `self.timeout` is reached while waiting or [`Child::wait_with_output`] returned an |
| 2607 |
/// error. |
| 2608 |
fn wait_with_output(mut self) -> Result<Output> { |
| 2609 |
// some apps do not stop execution until their stdin gets closed. |
| 2610 |
// to prevent a endless waiting here, we close the stdin. |
| 2611 |
self.join(); // ensure that all pending async input is piped in |
| 2612 |
self.close_stdin(); |
| 2613 |
|
| 2614 |
let output = if let Some(timeout) = self.timeout { |
| 2615 |
let child = self.raw; |
| 2616 |
|
| 2617 |
let (sender, receiver) = mpsc::channel(); |
| 2618 |
let handle = thread::Builder::new() |
| 2619 |
.name("wait_with_output".to_string()) |
| 2620 |
.spawn(move || sender.send(child.wait_with_output())) |
| 2621 |
.unwrap(); |
| 2622 |
|
| 2623 |
match receiver.recv_timeout(timeout) { |
| 2624 |
Ok(result) => { |
| 2625 |
// unwraps are safe here because we got a result from the sender and there was no panic |
| 2626 |
// causing a disconnect. |
| 2627 |
handle.join().unwrap().unwrap(); |
| 2628 |
result |
| 2629 |
} |
| 2630 |
Err(RecvTimeoutError::Timeout) => Err(io::Error::other(format!( |
| 2631 |
"wait: Timeout of '{}s' reached", |
| 2632 |
timeout.as_secs_f64() |
| 2633 |
))), |
| 2634 |
Err(RecvTimeoutError::Disconnected) => { |
| 2635 |
handle.join().expect("Panic caused disconnect").unwrap(); |
| 2636 |
panic!("Error receiving from waiting thread because of unexpected disconnect"); |
| 2637 |
} |
| 2638 |
} |
| 2639 |
} else { |
| 2640 |
self.raw.wait_with_output() |
| 2641 |
}; |
| 2642 |
|
| 2643 |
let mut output = output?; |
| 2644 |
|
| 2645 |
if let Some(join_handle) = self.join_handle.take() { |
| 2646 |
join_handle |
| 2647 |
.join() |
| 2648 |
.expect("Error joining with the piping stdin thread") |
| 2649 |
.unwrap(); |
| 2650 |
} |
| 2651 |
|
| 2652 |
if let Some(stdout) = self.captured_stdout.as_mut() { |
| 2653 |
if let Some(handle) = stdout.reader_thread_handle.take() { |
| 2654 |
handle.join().unwrap(); |
| 2655 |
} |
| 2656 |
output.stdout = stdout.output_bytes(); |
| 2657 |
} |
| 2658 |
if let Some(stderr) = self.captured_stderr.as_mut() { |
| 2659 |
if let Some(handle) = stderr.reader_thread_handle.take() { |
| 2660 |
handle.join().unwrap(); |
| 2661 |
} |
| 2662 |
output.stderr = stderr.output_bytes(); |
| 2663 |
} |
| 2664 |
|
| 2665 |
Ok(output) |
| 2666 |
} |
| 2667 |
|
| 2668 |
/// Read, consume and return the output as [`String`] from [`Child`]'s stdout. |
| 2669 |
/// |
| 2670 |
/// See also [`UChild::stdout_bytes`] for side effects. |
| 2671 |
pub fn stdout(&mut self) -> String { |
| 2672 |
String::from_utf8(self.stdout_bytes()).unwrap() |
| 2673 |
} |
| 2674 |
|
| 2675 |
/// Read and return all child's output in stdout as String. |
| 2676 |
/// |
| 2677 |
/// Note, that a subsequent call of any of these functions |
| 2678 |
/// |
| 2679 |
/// * [`UChild::stdout`] |
| 2680 |
/// * [`UChild::stdout_bytes`] |
| 2681 |
/// * [`UChild::stdout_exact_bytes`] |
| 2682 |
/// |
| 2683 |
/// will operate on the subsequent output of the child process. |
| 2684 |
pub fn stdout_all(&mut self) -> String { |
| 2685 |
String::from_utf8(self.stdout_all_bytes()).unwrap() |
| 2686 |
} |
| 2687 |
|
| 2688 |
/// Read, consume and return the output as bytes from [`Child`]'s stdout. |
| 2689 |
/// |
| 2690 |
/// Each subsequent call to any of the functions below will operate on the subsequent output of |
| 2691 |
/// the child process: |
| 2692 |
/// |
| 2693 |
/// * [`UChild::stdout`] |
| 2694 |
/// * [`UChild::stdout_exact_bytes`] |
| 2695 |
/// * and the call to itself [`UChild::stdout_bytes`] |
| 2696 |
pub fn stdout_bytes(&mut self) -> Vec<u8> { |
| 2697 |
match self.captured_stdout.as_mut() { |
| 2698 |
Some(output) => output.output_bytes(), |
| 2699 |
None if self.raw.stdout.is_some() => { |
| 2700 |
let mut buffer: Vec<u8> = vec![]; |
| 2701 |
let stdout = self.raw.stdout.as_mut().unwrap(); |
| 2702 |
stdout.read_to_end(&mut buffer).unwrap(); |
| 2703 |
buffer |
| 2704 |
} |
| 2705 |
None => vec![], |
| 2706 |
} |
| 2707 |
} |
| 2708 |
|
| 2709 |
/// Read and return all output from start of the child process until now. |
| 2710 |
/// |
| 2711 |
/// Each subsequent call of any of the methods below will operate on the subsequent output of |
| 2712 |
/// the child process. This method will panic if the output wasn't captured (for example if |
| 2713 |
/// [`UCommand::set_stdout`] was used). |
| 2714 |
/// |
| 2715 |
/// * [`UChild::stdout`] |
| 2716 |
/// * [`UChild::stdout_bytes`] |
| 2717 |
/// * [`UChild::stdout_exact_bytes`] |
| 2718 |
pub fn stdout_all_bytes(&mut self) -> Vec<u8> { |
| 2719 |
match self.captured_stdout.as_mut() { |
| 2720 |
Some(output) => output.output_all_bytes(), |
| 2721 |
None => { |
| 2722 |
panic!("Usage error: This method cannot be used if the output wasn't captured.") |
| 2723 |
} |
| 2724 |
} |
| 2725 |
} |
| 2726 |
|
| 2727 |
/// Read, consume and return the exact amount of bytes from `stdout`. |
| 2728 |
/// |
| 2729 |
/// This method may block indefinitely if the `size` amount of bytes exceeds the amount of bytes |
| 2730 |
/// that can be read. See also [`UChild::stdout_bytes`] for side effects. |
| 2731 |
pub fn stdout_exact_bytes(&mut self, size: usize) -> Vec<u8> { |
| 2732 |
match self.captured_stdout.as_mut() { |
| 2733 |
Some(output) => output.output_exact_bytes(size), |
| 2734 |
None if self.raw.stdout.is_some() => { |
| 2735 |
let mut buffer = vec![0; size]; |
| 2736 |
let stdout = self.raw.stdout.as_mut().unwrap(); |
| 2737 |
stdout.read_exact(&mut buffer).unwrap(); |
| 2738 |
buffer |
| 2739 |
} |
| 2740 |
None => vec![], |
| 2741 |
} |
| 2742 |
} |
| 2743 |
|
| 2744 |
/// Read, consume and return the child's stderr as String. |
| 2745 |
/// |
| 2746 |
/// See also [`UChild::stdout_bytes`] for side effects. If stderr is redirected to stdout with |
| 2747 |
/// [`UCommand::stderr_to_stdout`] then always an empty string will be returned. |
| 2748 |
pub fn stderr(&mut self) -> String { |
| 2749 |
String::from_utf8(self.stderr_bytes()).unwrap() |
| 2750 |
} |
| 2751 |
|
| 2752 |
/// Read and return all child's output in stderr as String. |
| 2753 |
/// |
| 2754 |
/// Note, that a subsequent call of any of these functions |
| 2755 |
/// |
| 2756 |
/// * [`UChild::stderr`] |
| 2757 |
/// * [`UChild::stderr_bytes`] |
| 2758 |
/// * [`UChild::stderr_exact_bytes`] |
| 2759 |
/// |
| 2760 |
/// will operate on the subsequent output of the child process. If stderr is redirected to |
| 2761 |
/// stdout with [`UCommand::stderr_to_stdout`] then always an empty string will be returned. |
| 2762 |
pub fn stderr_all(&mut self) -> String { |
| 2763 |
String::from_utf8(self.stderr_all_bytes()).unwrap() |
| 2764 |
} |
| 2765 |
|
| 2766 |
/// Read, consume and return the currently available bytes from child's stderr. |
| 2767 |
/// |
| 2768 |
/// If stderr is redirected to stdout with [`UCommand::stderr_to_stdout`] then always zero bytes |
| 2769 |
/// are returned. See also [`UChild::stdout_bytes`] for side effects. |
| 2770 |
pub fn stderr_bytes(&mut self) -> Vec<u8> { |
| 2771 |
match self.captured_stderr.as_mut() { |
| 2772 |
Some(output) => output.output_bytes(), |
| 2773 |
None if self.raw.stderr.is_some() => { |
| 2774 |
let mut buffer: Vec<u8> = vec![]; |
| 2775 |
let stderr = self.raw.stderr.as_mut().unwrap(); |
| 2776 |
stderr.read_to_end(&mut buffer).unwrap(); |
| 2777 |
buffer |
| 2778 |
} |
| 2779 |
None => vec![], |
| 2780 |
} |
| 2781 |
} |
| 2782 |
|
| 2783 |
/// Read and return all output from start of the child process until now. |
| 2784 |
/// |
| 2785 |
/// Each subsequent call of any of the methods below will operate on the subsequent output of |
| 2786 |
/// the child process. This method will panic if the output wasn't captured (for example if |
| 2787 |
/// [`UCommand::set_stderr`] was used). If [`UCommand::stderr_to_stdout`] was used always zero |
| 2788 |
/// bytes are returned. |
| 2789 |
/// |
| 2790 |
/// * [`UChild::stderr`] |
| 2791 |
/// * [`UChild::stderr_bytes`] |
| 2792 |
/// * [`UChild::stderr_exact_bytes`] |
| 2793 |
pub fn stderr_all_bytes(&mut self) -> Vec<u8> { |
| 2794 |
match self.captured_stderr.as_mut() { |
| 2795 |
Some(output) => output.output_all_bytes(), |
| 2796 |
None if self.stderr_to_stdout => vec![], |
| 2797 |
None => { |
| 2798 |
panic!("Usage error: This method cannot be used if the output wasn't captured.") |
| 2799 |
} |
| 2800 |
} |
| 2801 |
} |
| 2802 |
|
| 2803 |
/// Read, consume and return the exact amount of bytes from stderr. |
| 2804 |
/// |
| 2805 |
/// If stderr is redirect to stdout with [`UCommand::stderr_to_stdout`] then always zero bytes |
| 2806 |
/// are returned. |
| 2807 |
/// |
| 2808 |
/// # Important |
| 2809 |
/// This method blocks indefinitely if the `size` amount of bytes cannot be read. |
| 2810 |
pub fn stderr_exact_bytes(&mut self, size: usize) -> Vec<u8> { |
| 2811 |
match self.captured_stderr.as_mut() { |
| 2812 |
Some(output) => output.output_exact_bytes(size), |
| 2813 |
None if self.raw.stderr.is_some() => { |
| 2814 |
let stderr = self.raw.stderr.as_mut().unwrap(); |
| 2815 |
let mut buffer = vec![0; size]; |
| 2816 |
stderr.read_exact(&mut buffer).unwrap(); |
| 2817 |
buffer |
| 2818 |
} |
| 2819 |
None => vec![], |
| 2820 |
} |
| 2821 |
} |
| 2822 |
|
| 2823 |
fn access_stdin_as_writer<'a>(&'a mut self) -> Box<dyn Write + Send + 'a> { |
| 2824 |
if let Some(stdin_fd) = &self.stdin_pty { |
| 2825 |
Box::new(BufWriter::new(stdin_fd.try_clone().unwrap())) |
| 2826 |
} else { |
| 2827 |
let stdin: &mut std::process::ChildStdin = self.raw.stdin.as_mut().unwrap(); |
| 2828 |
Box::new(BufWriter::new(stdin)) |
| 2829 |
} |
| 2830 |
} |
| 2831 |
|
| 2832 |
fn take_stdin_as_writer(&mut self) -> Box<dyn Write + Send> { |
| 2833 |
if let Some(stdin_fd) = mem::take(&mut self.stdin_pty) { |
| 2834 |
Box::new(BufWriter::new(stdin_fd)) |
| 2835 |
} else { |
| 2836 |
let stdin = self |
| 2837 |
.raw |
| 2838 |
.stdin |
| 2839 |
.take() |
| 2840 |
.expect("Could not pipe into child process. Was it set to Stdio::null()?"); |
| 2841 |
|
| 2842 |
Box::new(BufWriter::new(stdin)) |
| 2843 |
} |
| 2844 |
} |
| 2845 |
|
| 2846 |
/// Pipe data into [`Child`] stdin in a separate thread to avoid deadlocks. |
| 2847 |
/// |
| 2848 |
/// In contrast to [`UChild::write_in`], this method is designed to simulate a pipe on the |
| 2849 |
/// command line and can be used only once or else panics. Note, that [`UCommand::set_stdin`] |
| 2850 |
/// must be used together with [`Stdio::piped`] or else this method doesn't work as expected. |
| 2851 |
/// `Stdio::piped` is the current default when using [`UCommand::run_no_wait`]) without calling |
| 2852 |
/// `set_stdin`. This method stores a [`JoinHandle`] of the thread in which the writing to the |
| 2853 |
/// child processes' stdin is running. The associated thread is joined with the main process in |
| 2854 |
/// the methods below when exiting the child process. |
| 2855 |
/// |
| 2856 |
/// * [`UChild::wait`] |
| 2857 |
/// * [`UChild::pipe_in_and_wait`] |
| 2858 |
/// |
| 2859 |
/// Usually, there's no need to join manually but if needed, the [`UChild::join`] method can be |
| 2860 |
/// used . |
| 2861 |
/// |
| 2862 |
/// [`JoinHandle`]: std::thread::JoinHandle |
| 2863 |
pub fn pipe_in<T: Into<Vec<u8>>>(&mut self, content: T) -> &mut Self { |
| 2864 |
let ignore_stdin_write_error = self.ignore_stdin_write_error; |
| 2865 |
let mut content: Vec<u8> = content.into(); |
| 2866 |
if self.stdin_pty.is_some() { |
| 2867 |
content.append(&mut END_OF_TRANSMISSION_SEQUENCE.to_vec()); |
| 2868 |
} |
| 2869 |
let mut writer = self.take_stdin_as_writer(); |
| 2870 |
|
| 2871 |
let join_handle = thread::Builder::new() |
| 2872 |
.name("pipe_in".to_string()) |
| 2873 |
.spawn( |
| 2874 |
move || match writer.write_all(&content).and_then(|()| writer.flush()) { |
| 2875 |
Err(error) if !ignore_stdin_write_error => Err(io::Error::other(format!( |
| 2876 |
"failed to write to stdin of child: {error}" |
| 2877 |
))), |
| 2878 |
Ok(()) | Err(_) => Ok(()), |
| 2879 |
}, |
| 2880 |
) |
| 2881 |
.unwrap(); |
| 2882 |
|
| 2883 |
self.join_handle = Some(join_handle); |
| 2884 |
self |
| 2885 |
} |
| 2886 |
|
| 2887 |
/// Call join on the thread created by [`UChild::pipe_in`] and if the thread is still running. |
| 2888 |
/// |
| 2889 |
/// This method can be called multiple times but is a noop if already joined. |
| 2890 |
pub fn join(&mut self) -> &mut Self { |
| 2891 |
if let Some(join_handle) = self.join_handle.take() { |
| 2892 |
join_handle |
| 2893 |
.join() |
| 2894 |
.expect("Error joining with the piping stdin thread") |
| 2895 |
.unwrap(); |
| 2896 |
} |
| 2897 |
self |
| 2898 |
} |
| 2899 |
|
| 2900 |
/// Convenience method for [`UChild::pipe_in`] and then [`UChild::wait`] |
| 2901 |
pub fn pipe_in_and_wait<T: Into<Vec<u8>>>(mut self, content: T) -> CmdResult { |
| 2902 |
self.pipe_in(content); |
| 2903 |
self.wait().unwrap() |
| 2904 |
} |
| 2905 |
|
| 2906 |
/// Write some bytes to the child process stdin. |
| 2907 |
/// |
| 2908 |
/// This function is meant for small data and faking user input like typing a `yes` or `no`. |
| 2909 |
/// This function blocks until all data is written but can be used multiple times in contrast to |
| 2910 |
/// [`UChild::pipe_in`]. |
| 2911 |
/// |
| 2912 |
/// # Errors |
| 2913 |
/// If [`std::process::ChildStdin::write_all`] or [`std::process::ChildStdin::flush`] returned an error |
| 2914 |
pub fn try_write_in<T: Into<Vec<u8>>>(&mut self, data: T) -> Result<()> { |
| 2915 |
let ignore_stdin_write_error = self.ignore_stdin_write_error; |
| 2916 |
let mut writer = self.access_stdin_as_writer(); |
| 2917 |
|
| 2918 |
match writer.write_all(&data.into()).and_then(|()| writer.flush()) { |
| 2919 |
Err(error) if !ignore_stdin_write_error => Err(io::Error::other(format!( |
| 2920 |
"failed to write to stdin of child: {error}" |
| 2921 |
))), |
| 2922 |
Ok(()) | Err(_) => Ok(()), |
| 2923 |
} |
| 2924 |
} |
| 2925 |
|
| 2926 |
/// Convenience function for [`UChild::try_write_in`] and a following `unwrap`. |
| 2927 |
pub fn write_in<T: Into<Vec<u8>>>(&mut self, data: T) -> &mut Self { |
| 2928 |
self.try_write_in(data).unwrap(); |
| 2929 |
self |
| 2930 |
} |
| 2931 |
|
| 2932 |
/// Close the child process stdout. |
| 2933 |
/// |
| 2934 |
/// Note this will have no effect if the output was captured with CapturedOutput which is the |
| 2935 |
/// default if [`UCommand::set_stdout`] wasn't called. |
| 2936 |
pub fn close_stdout(&mut self) -> &mut Self { |
| 2937 |
self.raw.stdout.take(); |
| 2938 |
self |
| 2939 |
} |
| 2940 |
|
| 2941 |
/// Close the child process stderr. |
| 2942 |
/// |
| 2943 |
/// Note this will have no effect if the output was captured with CapturedOutput which is the |
| 2944 |
/// default if [`UCommand::set_stderr`] wasn't called. |
| 2945 |
pub fn close_stderr(&mut self) -> &mut Self { |
| 2946 |
self.raw.stderr.take(); |
| 2947 |
self |
| 2948 |
} |
| 2949 |
|
| 2950 |
/// Close the child process stdin. |
| 2951 |
/// |
| 2952 |
/// Note, this does not have any effect if using the [`UChild::pipe_in`] method. |
| 2953 |
pub fn close_stdin(&mut self) -> &mut Self { |
| 2954 |
self.raw.stdin.take(); |
| 2955 |
if self.stdin_pty.is_some() { |
| 2956 |
// a pty can not be closed. We need to send a EOT: |
| 2957 |
let _ = self.try_write_in(END_OF_TRANSMISSION_SEQUENCE); |
| 2958 |
self.stdin_pty.take(); |
| 2959 |
} |
| 2960 |
self |
| 2961 |
} |
| 2962 |
} |
| 2963 |
|
| 2964 |
pub fn vec_of_size(n: usize) -> Vec<u8> { |
| 2965 |
let result = vec![b'a'; n]; |
| 2966 |
assert_eq!(result.len(), n); |
| 2967 |
result |
| 2968 |
} |
| 2969 |
|
| 2970 |
pub fn whoami() -> String { |
| 2971 |
// Apparently some CI environments have configuration issues, e.g. with 'whoami' and 'id'. |
| 2972 |
// |
| 2973 |
// From the Logs: "Build (ubuntu-18.04, x86_64-unknown-linux-gnu, feat_os_unix, use-cross)" |
| 2974 |
// whoami: cannot find name for user ID 1001 |
| 2975 |
// id --name: cannot find name for user ID 1001 |
| 2976 |
// id --name: cannot find name for group ID 116 |
| 2977 |
// |
| 2978 |
// However, when running "id" from within "/bin/bash" it looks fine: |
| 2979 |
// id: "uid=1001(runner) gid=118(docker) groups=118(docker),4(adm),101(systemd-journal)" |
| 2980 |
// whoami: "runner" |
| 2981 |
|
| 2982 |
// Use environment variable to get current user instead of |
| 2983 |
// invoking `whoami` and fall back to user "nobody" on error. |
| 2984 |
env::var("USER") |
| 2985 |
.or_else(|_| env::var("USERNAME")) |
| 2986 |
.unwrap_or_else(|e| { |
| 2987 |
println!("{UUTILS_WARNING}: {e}, using \"nobody\" instead"); |
| 2988 |
"nobody".to_string() |
| 2989 |
}) |
| 2990 |
} |
| 2991 |
|
| 2992 |
/// Create a PTY (pseudo-terminal) for testing utilities that require a TTY. |
| 2993 |
/// |
| 2994 |
/// Returns a tuple of (path, controller, replica) where: |
| 2995 |
/// - path: The filesystem path to the PTY replica device |
| 2996 |
/// - controller: The controller file |
| 2997 |
/// - replica: The replica file |
| 2998 |
#[cfg(unix)] |
| 2999 |
pub fn pty_path() -> (String, File, File) { |
| 3000 |
use nix::pty::openpty; |
| 3001 |
use nix::unistd::ttyname; |
| 3002 |
let pty = openpty(None, None).expect("Failed to create PTY"); |
| 3003 |
let path = ttyname(&pty.slave) |
| 3004 |
.expect("Failed to get PTY path") |
| 3005 |
.to_string_lossy() |
| 3006 |
.to_string(); |
| 3007 |
(path, pty.master.into(), pty.slave.into()) |
| 3008 |
} |
| 3009 |
|
| 3010 |
/// Add prefix 'g' for `util_name` if not on linux |
| 3011 |
#[cfg(unix)] |
| 3012 |
pub fn host_name_for(util_name: &str) -> Cow<'_, str> { |
| 3013 |
// In some environments, e.g. macOS/freebsd, the GNU coreutils are prefixed with "g" |
| 3014 |
// to not interfere with the BSD counterparts already in `$PATH`. |
| 3015 |
#[cfg(not(target_os = "linux"))] |
| 3016 |
{ |
| 3017 |
// make call to `host_name_for` idempotent |
| 3018 |
if util_name.starts_with('g') && util_name != "groups" { |
| 3019 |
util_name.into() |
| 3020 |
} else { |
| 3021 |
format!("g{util_name}").into() |
| 3022 |
} |
| 3023 |
} |
| 3024 |
#[cfg(target_os = "linux")] |
| 3025 |
util_name.into() |
| 3026 |
} |
| 3027 |
|
| 3028 |
// Choose same coreutils version with ubuntu-latest runner: https://github.com/actions/runner-images/tree/main/images/ubuntu |
| 3029 |
const VERSION_MIN: &str = "9.4"; // minimum Version for the reference `coreutil` in `$PATH` |
| 3030 |
|
| 3031 |
const UUTILS_WARNING: &str = "uutils-tests-warning"; |
| 3032 |
const UUTILS_INFO: &str = "uutils-tests-info"; |
| 3033 |
|
| 3034 |
/// Run `util_name --version` and return Ok if the version is >= `version_expected`. |
| 3035 |
/// Returns an error if |
| 3036 |
/// * `util_name` cannot run |
| 3037 |
/// * the version cannot be parsed |
| 3038 |
/// * the version is too low |
| 3039 |
/// |
| 3040 |
/// This is used by `expected_result` to check if the coreutils version is >= `VERSION_MIN`. |
| 3041 |
/// It makes sense to use this manually in a test if a feature |
| 3042 |
/// is tested that was introduced after `VERSION_MIN` |
| 3043 |
/// |
| 3044 |
/// Example: |
| 3045 |
/// |
| 3046 |
/// ```no_run |
| 3047 |
/// use uutests::util::*; |
| 3048 |
/// const VERSION_MIN_MULTIPLE_USERS: &str = "8.31"; |
| 3049 |
/// |
| 3050 |
/// #[test] |
| 3051 |
/// fn test_xyz() { |
| 3052 |
/// unwrap_or_return!(check_coreutil_version( |
| 3053 |
/// util_name!(), |
| 3054 |
/// VERSION_MIN_MULTIPLE_USERS |
| 3055 |
/// )); |
| 3056 |
/// // proceed with the test... |
| 3057 |
/// } |
| 3058 |
/// ``` |
| 3059 |
#[cfg(unix)] |
| 3060 |
pub fn check_coreutil_version( |
| 3061 |
util_name: &str, |
| 3062 |
version_expected: &str, |
| 3063 |
) -> std::result::Result<String, String> { |
| 3064 |
// example: |
| 3065 |
// $ id --version | head -n 1 |
| 3066 |
// id (GNU coreutils) 8.32.162-4eda |
| 3067 |
|
| 3068 |
let util_name = &host_name_for(util_name); |
| 3069 |
log_info("run", format!("{util_name} --version")); |
| 3070 |
let version_check = match Command::new(util_name.as_ref()) |
| 3071 |
.env("LC_ALL", "C") |
| 3072 |
.arg("--version") |
| 3073 |
.output() |
| 3074 |
{ |
| 3075 |
Ok(s) => s, |
| 3076 |
Err(e) => return Err(format!("{UUTILS_WARNING}: '{util_name}' {e}")), |
| 3077 |
}; |
| 3078 |
std::str::from_utf8(&version_check.stdout).unwrap() |
| 3079 |
.split('\n') |
| 3080 |
.collect::<Vec<_>>() |
| 3081 |
.first() |
| 3082 |
.map_or_else( |
| 3083 |
|| Err(format!("{UUTILS_WARNING}: unexpected output format for reference coreutil: '{util_name} --version'")), |
| 3084 |
|s| { |
| 3085 |
if s.contains(&format!("(GNU coreutils) {version_expected}")) { |
| 3086 |
Ok(format!("{UUTILS_INFO}: {s}")) |
| 3087 |
} else if s.contains("(GNU coreutils)") { |
| 3088 |
let version_found = parse_coreutil_version(s); |
| 3089 |
let version_expected = version_expected.parse::<f32>().unwrap_or_default(); |
| 3090 |
if version_found > version_expected { |
| 3091 |
Ok(format!("{UUTILS_INFO}: version for the reference coreutil '{util_name}' is higher than expected; expected: {version_expected}, found: {version_found}")) |
| 3092 |
} else { |
| 3093 |
Err(format!("{UUTILS_WARNING}: version for the reference coreutil '{util_name}' does not match; expected: {version_expected}, found: {version_found}")) } |
| 3094 |
} else { |
| 3095 |
Err(format!("{UUTILS_WARNING}: no coreutils version string found for reference coreutils '{util_name} --version'")) |
| 3096 |
} |
| 3097 |
}, |
| 3098 |
) |
| 3099 |
} |
| 3100 |
|
| 3101 |
// simple heuristic to parse the coreutils SemVer string, e.g. "id (GNU coreutils) 8.32.263-0475" |
| 3102 |
fn parse_coreutil_version(version_string: &str) -> f32 { |
| 3103 |
version_string |
| 3104 |
.split_whitespace() |
| 3105 |
.last() |
| 3106 |
.unwrap() |
| 3107 |
.split('.') |
| 3108 |
.take(2) |
| 3109 |
.collect::<Vec<_>>() |
| 3110 |
.join(".") |
| 3111 |
.parse::<f32>() |
| 3112 |
.unwrap_or_default() |
| 3113 |
} |
| 3114 |
|
| 3115 |
/// This runs the GNU coreutils `util_name` binary in `$PATH` in order to |
| 3116 |
/// dynamically gather reference values on the system. |
| 3117 |
/// If the `util_name` in `$PATH` doesn't include a coreutils version string, |
| 3118 |
/// or the version is too low, this returns an error and the test should be skipped. |
| 3119 |
/// |
| 3120 |
/// Arguments: |
| 3121 |
/// - `ts`: The test context. |
| 3122 |
/// - `args`: Command-line variables applied to the command. |
| 3123 |
/// - `envs`: Environment variables applied to the command invocation. |
| 3124 |
/// |
| 3125 |
/// Example: |
| 3126 |
/// |
| 3127 |
/// ```no_run |
| 3128 |
/// use uutests::util::*; |
| 3129 |
/// #[test] |
| 3130 |
/// fn test_xyz() { |
| 3131 |
/// let ts = TestScenario::new(util_name!()); |
| 3132 |
/// let result = ts.ucmd().run(); |
| 3133 |
/// let exp_result = unwrap_or_return!(expected_result(&ts, &[])); |
| 3134 |
/// result |
| 3135 |
/// .stdout_is(exp_result.stdout_str()) |
| 3136 |
/// .stderr_is(exp_result.stderr_str()) |
| 3137 |
/// .code_is(exp_result.code()); |
| 3138 |
/// } |
| 3139 |
///``` |
| 3140 |
#[cfg(unix)] |
| 3141 |
pub fn gnu_cmd_result( |
| 3142 |
ts: &TestScenario, |
| 3143 |
args: &[&str], |
| 3144 |
envs: &[(&str, &str)], |
| 3145 |
) -> std::result::Result<CmdResult, String> { |
| 3146 |
let util_name = ts.util_name.as_str(); |
| 3147 |
println!("{}", check_coreutil_version(util_name, VERSION_MIN)?); |
| 3148 |
let util_name = host_name_for(util_name); |
| 3149 |
|
| 3150 |
let result = ts |
| 3151 |
.cmd(util_name.as_ref()) |
| 3152 |
.env("PATH", PATH) |
| 3153 |
.envs(DEFAULT_ENV) |
| 3154 |
.envs(envs.iter().copied()) |
| 3155 |
.args(args) |
| 3156 |
.run(); |
| 3157 |
|
| 3158 |
let (stdout, stderr): (String, String) = if cfg!(target_os = "linux") { |
| 3159 |
( |
| 3160 |
result.stdout_str().to_string(), |
| 3161 |
result.stderr_str_lossy().to_string(), |
| 3162 |
) |
| 3163 |
} else { |
| 3164 |
// `host_name_for` added prefix, strip 'g' prefix from results: |
| 3165 |
let from = util_name.to_string() + ":"; |
| 3166 |
let to = &from[1..]; |
| 3167 |
( |
| 3168 |
result.stdout_str().replace(&from, to), |
| 3169 |
result.stderr_str_lossy().replace(&from, to), |
| 3170 |
) |
| 3171 |
}; |
| 3172 |
|
| 3173 |
Ok(CmdResult::new( |
| 3174 |
ts.bin_path.as_os_str().to_str().unwrap().to_string(), |
| 3175 |
Some(ts.util_name.clone()), |
| 3176 |
Some(result.tmpd()), |
| 3177 |
result.exit_status, |
| 3178 |
stdout.as_bytes(), |
| 3179 |
stderr.as_bytes(), |
| 3180 |
)) |
| 3181 |
} |
| 3182 |
|
| 3183 |
/// This runs the GNU coreutils `util_name` binary in `$PATH` in order to |
| 3184 |
/// dynamically gather reference values on the system. |
| 3185 |
/// If the `util_name` in `$PATH` doesn't include a coreutils version string, |
| 3186 |
/// or the version is too low, this returns an error and the test should be skipped. |
| 3187 |
/// |
| 3188 |
/// Example: |
| 3189 |
/// |
| 3190 |
/// ```no_run |
| 3191 |
/// use uutests::util::*; |
| 3192 |
/// #[test] |
| 3193 |
/// fn test_xyz() { |
| 3194 |
/// let ts = TestScenario::new(util_name!()); |
| 3195 |
/// let result = ts.ucmd().run(); |
| 3196 |
/// let exp_result = unwrap_or_return!(expected_result(&ts, &[])); |
| 3197 |
/// result |
| 3198 |
/// .stdout_is(exp_result.stdout_str()) |
| 3199 |
/// .stderr_is(exp_result.stderr_str()) |
| 3200 |
/// .code_is(exp_result.code()); |
| 3201 |
/// } |
| 3202 |
///``` |
| 3203 |
#[cfg(unix)] |
| 3204 |
pub fn expected_result(ts: &TestScenario, args: &[&str]) -> std::result::Result<CmdResult, String> { |
| 3205 |
gnu_cmd_result(ts, args, &[]) |
| 3206 |
} |
| 3207 |
|
| 3208 |
/// This is a convenience wrapper to run a ucmd with root permissions. |
| 3209 |
/// It can be used to test programs when being root is needed |
| 3210 |
/// This runs `sudo -E --non-interactive target/debug/coreutils util_name args` |
| 3211 |
/// This is primarily designed to run in an environment where whoami is in $path |
| 3212 |
/// and where non-interactive sudo is possible. |
| 3213 |
/// To check if i) non-interactive sudo is possible and ii) if sudo works, this runs: |
| 3214 |
/// `sudo -E --non-interactive whoami` first. |
| 3215 |
/// |
| 3216 |
/// This return an `Err()` if run inside CICD because there's no 'sudo'. |
| 3217 |
/// |
| 3218 |
/// Example: |
| 3219 |
/// |
| 3220 |
/// ```no_run |
| 3221 |
/// use uutests::util::*; |
| 3222 |
/// #[test] |
| 3223 |
/// fn test_xyz() { |
| 3224 |
/// let ts = TestScenario::new("whoami"); |
| 3225 |
/// let expected = "root\n".to_string(); |
| 3226 |
/// if let Ok(result) = run_ucmd_as_root(&ts, &[]) { |
| 3227 |
/// result.stdout_is(expected); |
| 3228 |
/// } else { |
| 3229 |
/// println!("TEST SKIPPED"); |
| 3230 |
/// } |
| 3231 |
/// } |
| 3232 |
///``` |
| 3233 |
#[cfg(unix)] |
| 3234 |
pub fn run_ucmd_as_root( |
| 3235 |
ts: &TestScenario, |
| 3236 |
args: &[&str], |
| 3237 |
) -> std::result::Result<CmdResult, String> { |
| 3238 |
run_ucmd_as_root_with_stdin_stdout(ts, args, None, None) |
| 3239 |
} |
| 3240 |
|
| 3241 |
#[cfg(unix)] |
| 3242 |
pub fn run_ucmd_as_root_with_stdin_stdout( |
| 3243 |
ts: &TestScenario, |
| 3244 |
args: &[&str], |
| 3245 |
stdin: Option<&str>, |
| 3246 |
stdout: Option<&str>, |
| 3247 |
) -> std::result::Result<CmdResult, String> { |
| 3248 |
if is_ci() { |
| 3249 |
Err(format!("{UUTILS_INFO}: {}", "cannot run inside CI")) |
| 3250 |
} else { |
| 3251 |
// check if we can run 'sudo' |
| 3252 |
log_info("run", "sudo -E --non-interactive whoami"); |
| 3253 |
match Command::new("sudo") |
| 3254 |
.envs(DEFAULT_ENV) |
| 3255 |
.args(["-E", "--non-interactive", "whoami"]) |
| 3256 |
.output() |
| 3257 |
{ |
| 3258 |
Ok(output) if String::from_utf8_lossy(&output.stdout).eq("root\n") => { |
| 3259 |
// we can run sudo and we're root |
| 3260 |
// run ucmd as root: |
| 3261 |
let mut cmd = ts.cmd("sudo"); |
| 3262 |
cmd.env("PATH", PATH) |
| 3263 |
.envs(DEFAULT_ENV) |
| 3264 |
.arg("-E") |
| 3265 |
.arg("--non-interactive") |
| 3266 |
.arg(&ts.bin_path) |
| 3267 |
.arg(&ts.util_name) |
| 3268 |
.args(args); |
| 3269 |
if let Some(stdin) = stdin { |
| 3270 |
cmd.set_stdin(File::open(stdin).unwrap()); |
| 3271 |
} |
| 3272 |
if let Some(stdout) = stdout { |
| 3273 |
cmd.set_stdout(File::open(stdout).unwrap()); |
| 3274 |
} |
| 3275 |
Ok(cmd.run()) |
| 3276 |
} |
| 3277 |
Ok(output) |
| 3278 |
if String::from_utf8_lossy(&output.stderr).eq("sudo: a password is required\n") => |
| 3279 |
{ |
| 3280 |
Err("Cannot run non-interactive sudo".to_string()) |
| 3281 |
} |
| 3282 |
Ok(_output) => Err("\"sudo whoami\" didn't return \"root\"".to_string()), |
| 3283 |
Err(e) => Err(format!("{UUTILS_WARNING}: {e}")), |
| 3284 |
} |
| 3285 |
} |
| 3286 |
} |
| 3287 |
|
| 3288 |
/// Sanity checks for test utils |
| 3289 |
#[cfg(test)] |
| 3290 |
mod tests { |
| 3291 |
// spell-checker:ignore (tests) asdfsadfa |
| 3292 |
use super::*; |
| 3293 |
|
| 3294 |
// Create a init for the test with a fake value (not needed) |
| 3295 |
#[cfg(test)] |
| 3296 |
#[ctor::ctor(unsafe)] |
| 3297 |
fn init() { |
| 3298 |
unsafe { |
| 3299 |
env::set_var("UUTESTS_BINARY_PATH", ""); |
| 3300 |
} |
| 3301 |
} |
| 3302 |
|
| 3303 |
pub fn run_cmd<T: AsRef<OsStr>>(cmd: T) -> CmdResult { |
| 3304 |
UCommand::new().arg(cmd).run() |
| 3305 |
} |
| 3306 |
|
| 3307 |
#[test] |
| 3308 |
fn test_command_result_when_no_output_with_exit_32() { |
| 3309 |
let result = run_cmd("exit 32"); |
| 3310 |
|
| 3311 |
if cfg!(windows) { |
| 3312 |
std::assert!(result.bin_path.ends_with("cmd")); |
| 3313 |
} else { |
| 3314 |
std::assert!(result.bin_path.ends_with("sh")); |
| 3315 |
} |
| 3316 |
|
| 3317 |
std::assert!(result.util_name.is_none()); |
| 3318 |
std::assert!(result.tmpd.is_some()); |
| 3319 |
|
| 3320 |
assert!(result.exit_status.is_some()); |
| 3321 |
std::assert_eq!(result.code(), 32); |
| 3322 |
result.code_is(32); |
| 3323 |
assert!(!result.succeeded()); |
| 3324 |
result.failure(); |
| 3325 |
result.fails_silently(); |
| 3326 |
assert!(result.stderr.is_empty()); |
| 3327 |
assert!(result.stdout.is_empty()); |
| 3328 |
result.no_output(); |
| 3329 |
result.no_stderr(); |
| 3330 |
result.no_stdout(); |
| 3331 |
} |
| 3332 |
|
| 3333 |
#[test] |
| 3334 |
#[should_panic] |
| 3335 |
fn test_command_result_when_exit_32_then_success_panic() { |
| 3336 |
run_cmd("exit 32").success(); |
| 3337 |
} |
| 3338 |
|
| 3339 |
#[test] |
| 3340 |
fn test_command_result_when_no_output_with_exit_0() { |
| 3341 |
let result = run_cmd("exit 0"); |
| 3342 |
|
| 3343 |
assert!(result.exit_status.is_some()); |
| 3344 |
std::assert_eq!(result.code(), 0); |
| 3345 |
result.code_is(0); |
| 3346 |
assert!(result.succeeded()); |
| 3347 |
result.success(); |
| 3348 |
assert!(result.stderr.is_empty()); |
| 3349 |
assert!(result.stdout.is_empty()); |
| 3350 |
result.no_output(); |
| 3351 |
result.no_stderr(); |
| 3352 |
result.no_stdout(); |
| 3353 |
} |
| 3354 |
|
| 3355 |
#[test] |
| 3356 |
#[should_panic] |
| 3357 |
fn test_command_result_when_exit_0_then_failure_panics() { |
| 3358 |
run_cmd("exit 0").failure(); |
| 3359 |
} |
| 3360 |
|
| 3361 |
#[test] |
| 3362 |
#[should_panic] |
| 3363 |
fn test_command_result_when_exit_0_then_silent_failure_panics() { |
| 3364 |
run_cmd("exit 0").fails_silently(); |
| 3365 |
} |
| 3366 |
|
| 3367 |
#[test] |
| 3368 |
fn test_command_result_when_stdout_with_exit_0() { |
| 3369 |
#[cfg(windows)] |
| 3370 |
let (result, vector, string) = ( |
| 3371 |
run_cmd("echo hello& exit 0"), |
| 3372 |
vec![b'h', b'e', b'l', b'l', b'o', b'\r', b'\n'], |
| 3373 |
"hello\r\n", |
| 3374 |
); |
| 3375 |
#[cfg(not(windows))] |
| 3376 |
let (result, vector, string) = ( |
| 3377 |
run_cmd("echo hello; exit 0"), |
| 3378 |
vec![b'h', b'e', b'l', b'l', b'o', b'\n'], |
| 3379 |
"hello\n", |
| 3380 |
); |
| 3381 |
|
| 3382 |
assert!(result.exit_status.is_some()); |
| 3383 |
std::assert_eq!(result.code(), 0); |
| 3384 |
result.code_is(0); |
| 3385 |
assert!(result.succeeded()); |
| 3386 |
result.success(); |
| 3387 |
assert!(result.stderr.is_empty()); |
| 3388 |
std::assert_eq!(result.stdout, vector); |
| 3389 |
result.no_stderr(); |
| 3390 |
result.stdout_is(string); |
| 3391 |
result.stdout_is_bytes(&vector); |
| 3392 |
result.stdout_only(string); |
| 3393 |
result.stdout_only_bytes(&vector); |
| 3394 |
} |
| 3395 |
|
| 3396 |
#[test] |
| 3397 |
fn test_command_result_when_stderr_with_exit_0() { |
| 3398 |
#[cfg(windows)] |
| 3399 |
let (result, vector, string) = ( |
| 3400 |
run_cmd("echo hello>&2& exit 0"), |
| 3401 |
vec![b'h', b'e', b'l', b'l', b'o', b'\r', b'\n'], |
| 3402 |
"hello\r\n", |
| 3403 |
); |
| 3404 |
#[cfg(not(windows))] |
| 3405 |
let (result, vector, string) = ( |
| 3406 |
run_cmd("echo hello >&2; exit 0"), |
| 3407 |
vec![b'h', b'e', b'l', b'l', b'o', b'\n'], |
| 3408 |
"hello\n", |
| 3409 |
); |
| 3410 |
|
| 3411 |
assert!(result.exit_status.is_some()); |
| 3412 |
std::assert_eq!(result.code(), 0); |
| 3413 |
result.code_is(0); |
| 3414 |
assert!(result.succeeded()); |
| 3415 |
result.success(); |
| 3416 |
assert!(result.stdout.is_empty()); |
| 3417 |
result.no_stdout(); |
| 3418 |
std::assert_eq!(result.stderr, vector); |
| 3419 |
result.stderr_is(string); |
| 3420 |
result.stderr_is_bytes(&vector); |
| 3421 |
result.stderr_only(string); |
| 3422 |
result.stderr_only_bytes(&vector); |
| 3423 |
} |
| 3424 |
|
| 3425 |
#[test] |
| 3426 |
fn test_std_does_not_contain() { |
| 3427 |
#[cfg(windows)] |
| 3428 |
let res = run_cmd( |
| 3429 |
"(echo This is a likely error message& echo This is a likely error message>&2) & exit 0", |
| 3430 |
); |
| 3431 |
#[cfg(not(windows))] |
| 3432 |
let res = run_cmd( |
| 3433 |
"echo This is a likely error message; echo This is a likely error message >&2; exit 0", |
| 3434 |
); |
| 3435 |
res.stdout_does_not_contain("unlikely"); |
| 3436 |
res.stderr_does_not_contain("unlikely"); |
| 3437 |
} |
| 3438 |
|
| 3439 |
#[test] |
| 3440 |
#[should_panic] |
| 3441 |
fn test_stdout_does_not_contain_fail() { |
| 3442 |
#[cfg(windows)] |
| 3443 |
let res = run_cmd("echo This is a likely error message& exit 0"); |
| 3444 |
#[cfg(not(windows))] |
| 3445 |
let res = run_cmd("echo This is a likely error message; exit 0"); |
| 3446 |
|
| 3447 |
res.stdout_does_not_contain("likely"); |
| 3448 |
} |
| 3449 |
|
| 3450 |
#[test] |
| 3451 |
#[should_panic] |
| 3452 |
fn test_stderr_does_not_contain_fail() { |
| 3453 |
#[cfg(windows)] |
| 3454 |
let res = run_cmd("echo This is a likely error message>&2 & exit 0"); |
| 3455 |
#[cfg(not(windows))] |
| 3456 |
let res = run_cmd("echo This is a likely error message >&2; exit 0"); |
| 3457 |
|
| 3458 |
res.stderr_does_not_contain("likely"); |
| 3459 |
} |
| 3460 |
|
| 3461 |
#[test] |
| 3462 |
fn test_stdout_matches() { |
| 3463 |
#[cfg(windows)] |
| 3464 |
let res = run_cmd( |
| 3465 |
"(echo This is a likely error message& echo This is a likely error message>&2 ) & exit 0", |
| 3466 |
); |
| 3467 |
#[cfg(not(windows))] |
| 3468 |
let res = run_cmd( |
| 3469 |
"echo This is a likely error message; echo This is a likely error message >&2; exit 0", |
| 3470 |
); |
| 3471 |
|
| 3472 |
let positive = regex::Regex::new(".*likely.*").unwrap(); |
| 3473 |
let negative = regex::Regex::new(".*unlikely.*").unwrap(); |
| 3474 |
res.stdout_matches(&positive); |
| 3475 |
res.stdout_does_not_match(&negative); |
| 3476 |
} |
| 3477 |
|
| 3478 |
#[test] |
| 3479 |
#[should_panic] |
| 3480 |
fn test_stdout_matches_fail() { |
| 3481 |
#[cfg(windows)] |
| 3482 |
let res = run_cmd( |
| 3483 |
"(echo This is a likely error message& echo This is a likely error message>&2) & exit 0", |
| 3484 |
); |
| 3485 |
#[cfg(not(windows))] |
| 3486 |
let res = run_cmd( |
| 3487 |
"echo This is a likely error message; echo This is a likely error message >&2; exit 0", |
| 3488 |
); |
| 3489 |
|
| 3490 |
let negative = regex::Regex::new(".*unlikely.*").unwrap(); |
| 3491 |
res.stdout_matches(&negative); |
| 3492 |
} |
| 3493 |
|
| 3494 |
#[test] |
| 3495 |
#[should_panic] |
| 3496 |
fn test_stdout_not_matches_fail() { |
| 3497 |
#[cfg(windows)] |
| 3498 |
let res = run_cmd( |
| 3499 |
"(echo This is a likely error message& echo This is a likely error message>&2) & exit 0", |
| 3500 |
); |
| 3501 |
#[cfg(not(windows))] |
| 3502 |
let res = run_cmd( |
| 3503 |
"echo This is a likely error message; echo This is a likely error message >&2; exit 0", |
| 3504 |
); |
| 3505 |
|
| 3506 |
let positive = regex::Regex::new(".*likely.*").unwrap(); |
| 3507 |
res.stdout_does_not_match(&positive); |
| 3508 |
} |
| 3509 |
|
| 3510 |
#[test] |
| 3511 |
#[cfg(unix)] |
| 3512 |
fn test_parse_coreutil_version() { |
| 3513 |
use std::assert_eq; |
| 3514 |
assert_eq!( |
| 3515 |
parse_coreutil_version("id (GNU coreutils) 9.0.123-0123").to_string(), |
| 3516 |
"9" |
| 3517 |
); |
| 3518 |
assert_eq!( |
| 3519 |
parse_coreutil_version("id (GNU coreutils) 8.32.263-0475").to_string(), |
| 3520 |
"8.32" |
| 3521 |
); |
| 3522 |
assert_eq!( |
| 3523 |
parse_coreutil_version("id (GNU coreutils) 8.25.123-0123").to_string(), |
| 3524 |
"8.25" |
| 3525 |
); |
| 3526 |
assert_eq!( |
| 3527 |
parse_coreutil_version("id (GNU coreutils) 9.0").to_string(), |
| 3528 |
"9" |
| 3529 |
); |
| 3530 |
assert_eq!( |
| 3531 |
parse_coreutil_version("id (GNU coreutils) 8.32").to_string(), |
| 3532 |
"8.32" |
| 3533 |
); |
| 3534 |
assert_eq!( |
| 3535 |
parse_coreutil_version("id (GNU coreutils) 8.25").to_string(), |
| 3536 |
"8.25" |
| 3537 |
); |
| 3538 |
} |
| 3539 |
|
| 3540 |
#[test] |
| 3541 |
#[cfg(unix)] |
| 3542 |
fn test_check_coreutil_version() { |
| 3543 |
match check_coreutil_version("id", VERSION_MIN) { |
| 3544 |
Ok(s) => assert!(s.starts_with("uutils-tests-")), |
| 3545 |
Err(s) => assert!(s.starts_with("uutils-tests-warning")), |
| 3546 |
} |
| 3547 |
#[cfg(target_os = "linux")] |
| 3548 |
std::assert_eq!( |
| 3549 |
check_coreutil_version("no test name", VERSION_MIN), |
| 3550 |
Err("uutils-tests-warning: 'no test name' \ |
| 3551 |
No such file or directory (os error 2)" |
| 3552 |
.to_string()) |
| 3553 |
); |
| 3554 |
} |
| 3555 |
|
| 3556 |
#[test] |
| 3557 |
#[cfg(unix)] |
| 3558 |
fn test_expected_result() { |
| 3559 |
let ts = TestScenario::new("id"); |
| 3560 |
// assert!(expected_result(&ts, &[]).is_ok()); |
| 3561 |
match expected_result(&ts, &[]) { |
| 3562 |
Ok(r) => assert!(r.succeeded()), |
| 3563 |
Err(s) => assert!(s.starts_with("uutils-tests-warning")), |
| 3564 |
} |
| 3565 |
let ts = TestScenario::new("no test name"); |
| 3566 |
assert!(expected_result(&ts, &[]).is_err()); |
| 3567 |
} |
| 3568 |
|
| 3569 |
#[test] |
| 3570 |
#[cfg(unix)] |
| 3571 |
fn test_host_name_for() { |
| 3572 |
#[cfg(target_os = "linux")] |
| 3573 |
{ |
| 3574 |
std::assert_eq!(host_name_for("id"), "id"); |
| 3575 |
std::assert_eq!(host_name_for("groups"), "groups"); |
| 3576 |
std::assert_eq!(host_name_for("who"), "who"); |
| 3577 |
} |
| 3578 |
#[cfg(not(target_os = "linux"))] |
| 3579 |
{ |
| 3580 |
// spell-checker:ignore (strings) ggroups gwho |
| 3581 |
std::assert_eq!(host_name_for("id"), "gid"); |
| 3582 |
std::assert_eq!(host_name_for("groups"), "ggroups"); |
| 3583 |
std::assert_eq!(host_name_for("who"), "gwho"); |
| 3584 |
std::assert_eq!(host_name_for("gid"), "gid"); |
| 3585 |
std::assert_eq!(host_name_for("ggroups"), "ggroups"); |
| 3586 |
std::assert_eq!(host_name_for("gwho"), "gwho"); |
| 3587 |
} |
| 3588 |
} |
| 3589 |
|
| 3590 |
#[test] |
| 3591 |
#[cfg(unix)] |
| 3592 |
fn test_run_ucmd_as_root() { |
| 3593 |
if is_ci() { |
| 3594 |
println!("TEST SKIPPED (cannot run inside CI)"); |
| 3595 |
} else { |
| 3596 |
// Skip test if we can't guarantee non-interactive `sudo`, or if we're not "root" |
| 3597 |
if let Ok(output) = Command::new("sudo") |
| 3598 |
.env("LC_ALL", "C") |
| 3599 |
.args(["-E", "--non-interactive", "whoami"]) |
| 3600 |
.output() |
| 3601 |
{ |
| 3602 |
if output.status.success() && String::from_utf8_lossy(&output.stdout).eq("root\n") { |
| 3603 |
let ts = TestScenario::new("whoami"); |
| 3604 |
std::assert_eq!( |
| 3605 |
run_ucmd_as_root(&ts, &[]).unwrap().stdout_str().trim(), |
| 3606 |
"root" |
| 3607 |
); |
| 3608 |
} else { |
| 3609 |
println!("TEST SKIPPED (we're not root)"); |
| 3610 |
} |
| 3611 |
} else { |
| 3612 |
println!("TEST SKIPPED (cannot run sudo)"); |
| 3613 |
} |
| 3614 |
} |
| 3615 |
} |
| 3616 |
|
| 3617 |
#[cfg(all(unix, not(any(target_vendor = "apple", target_os = "openbsd"))))] |
| 3618 |
#[test] |
| 3619 |
fn test_compare_xattrs() { |
| 3620 |
use tempfile::tempdir; |
| 3621 |
|
| 3622 |
let temp_dir = tempdir().unwrap(); |
| 3623 |
let file_path1 = temp_dir.path().join("test_file1.txt"); |
| 3624 |
let file_path2 = temp_dir.path().join("test_file2.txt"); |
| 3625 |
|
| 3626 |
File::create(&file_path1).unwrap(); |
| 3627 |
File::create(&file_path2).unwrap(); |
| 3628 |
|
| 3629 |
let test_attr = "user.test_attr"; |
| 3630 |
let test_value = b"test value"; |
| 3631 |
xattr::set(&file_path1, test_attr, test_value).unwrap(); |
| 3632 |
|
| 3633 |
assert!(!compare_xattrs(&file_path1, &file_path2)); |
| 3634 |
|
| 3635 |
xattr::set(&file_path2, test_attr, test_value).unwrap(); |
| 3636 |
assert!(compare_xattrs(&file_path1, &file_path2)); |
| 3637 |
} |
| 3638 |
|
| 3639 |
#[cfg(unix)] |
| 3640 |
#[test] |
| 3641 |
fn test_application_of_process_resource_limits_unlimited_file_size() { |
| 3642 |
let ts = TestScenario::new("util"); |
| 3643 |
ts.cmd("sh") |
| 3644 |
.args(&["-c", "ulimit -Sf; ulimit -Hf"]) |
| 3645 |
.succeeds() |
| 3646 |
.no_stderr() |
| 3647 |
.stdout_is("unlimited\nunlimited\n"); |
| 3648 |
} |
| 3649 |
|
| 3650 |
#[cfg(unix)] |
| 3651 |
#[test] |
| 3652 |
fn test_application_of_process_resource_limits_limited_file_size() { |
| 3653 |
let unit_size_bytes = if cfg!(target_vendor = "apple") { |
| 3654 |
1024 |
| 3655 |
} else { |
| 3656 |
512 |
| 3657 |
}; |
| 3658 |
|
| 3659 |
let ts = TestScenario::new("util"); |
| 3660 |
ts.cmd("sh") |
| 3661 |
.args(&["-c", "ulimit -Sf; ulimit -Hf"]) |
| 3662 |
.limit( |
| 3663 |
rlimit::Resource::FSIZE, |
| 3664 |
8 * unit_size_bytes, |
| 3665 |
16 * unit_size_bytes, |
| 3666 |
) |
| 3667 |
.succeeds() |
| 3668 |
.no_stderr() |
| 3669 |
.stdout_is("8\n16\n"); |
| 3670 |
} |
| 3671 |
|
| 3672 |
#[cfg(unix)] |
| 3673 |
#[cfg(not(target_os = "openbsd"))] |
| 3674 |
#[test] |
| 3675 |
fn test_altering_umask() { |
| 3676 |
use uucore::mode::get_umask; |
| 3677 |
let p_umask = get_umask(); |
| 3678 |
// make sure we are not testing against the same umask |
| 3679 |
let c_umask = if p_umask == 0o002 { 0o007 } else { 0o002 }; |
| 3680 |
let expected = if cfg!(target_os = "android") { |
| 3681 |
if p_umask == 0o002 { "007\n" } else { "002\n" } |
| 3682 |
} else if p_umask == 0o002 { |
| 3683 |
"0007\n" |
| 3684 |
} else { |
| 3685 |
"0002\n" |
| 3686 |
}; |
| 3687 |
|
| 3688 |
let ts = TestScenario::new("util"); |
| 3689 |
ts.cmd_shell("umask") |
| 3690 |
.umask(c_umask) |
| 3691 |
.succeeds() |
| 3692 |
.stdout_is(expected); |
| 3693 |
std::assert_eq!(p_umask, get_umask()); // make sure parent umask didn't change |
| 3694 |
} |
| 3695 |
|
| 3696 |
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] |
| 3697 |
#[test] |
| 3698 |
fn test_mount_temp_fs() { |
| 3699 |
let mut scene = TestScenario::new("util"); |
| 3700 |
let at = &scene.fixtures; |
| 3701 |
// Test must be run as root (or with `sudo -E`) |
| 3702 |
if scene.cmd("whoami").run().stdout_str() != "root\n" { |
| 3703 |
return; |
| 3704 |
} |
| 3705 |
at.mkdir("mountpoint"); |
| 3706 |
let mountpoint = at.plus("mountpoint"); |
| 3707 |
scene.mount_temp_fs(mountpoint.to_str().unwrap()).unwrap(); |
| 3708 |
scene |
| 3709 |
.cmd("df") |
| 3710 |
.arg("-h") |
| 3711 |
.arg(mountpoint) |
| 3712 |
.succeeds() |
| 3713 |
.stdout_contains("tmpfs"); |
| 3714 |
} |
| 3715 |
} |