Skip to content

Commit b1eb5f9

Browse files
committed
vmstat: add tests
1 parent 995013e commit b1eb5f9

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

src/uu/vmstat/src/picker.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
#[cfg(target_os = "linux")]
77
use crate::{CpuLoad, Meminfo, ProcData};
88
use clap::ArgMatches;
9-
use uucore::error::USimpleError;
109

1110
#[cfg(target_os = "linux")]
1211
pub type Picker = (
@@ -65,17 +64,15 @@ pub fn get_pickers(matches: &ArgMatches) -> Vec<Picker> {
6564
]
6665
}
6766

67+
#[cfg(target_os = "linux")]
6868
fn with_unit(x: u64, arg: &ArgMatches) -> u64 {
6969
if let Some(unit) = arg.get_one::<String>("unit") {
7070
return match unit.as_str() {
7171
"k" => x / bytesize::KB,
7272
"K" => x / bytesize::KIB,
7373
"m" => x / bytesize::MB,
7474
"M" => x / bytesize::MIB,
75-
_ => panic!(
76-
"{:?}",
77-
USimpleError::new(1, "-S requires k, K, m or M (default is KiB)",)
78-
),
75+
_ => x, // impossible
7976
};
8077
}
8178
x / bytesize::KIB

src/uu/vmstat/src/vmstat.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ mod picker;
88

99
#[cfg(target_os = "linux")]
1010
use crate::picker::{get_pickers, Picker};
11+
#[allow(unused_imports)]
1112
use clap::{arg, crate_version, ArgMatches, Command};
1213
#[allow(unused_imports)]
1314
pub use parser::*;
@@ -24,6 +25,16 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
2425
let matches = uu_app().try_get_matches_from(args)?;
2526
#[cfg(target_os = "linux")]
2627
{
28+
// validate unit
29+
if let Some(unit) = matches.get_one::<String>("unit") {
30+
if !["k", "K", "m", "M"].contains(&unit.as_str()) {
31+
Err(USimpleError::new(
32+
1,
33+
"-S requires k, K, m or M (default is KiB)",
34+
))?
35+
}
36+
}
37+
2738
let one_header = matches.get_flag("one-header");
2839
let no_first = matches.get_flag("no-first");
2940
let delay = matches.get_one::<String>("delay");

tests/by-util/test_vmstat.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,14 @@ fn test_simple() {
1616
fn test_invalid_arg() {
1717
new_ucmd!().arg("--definitely-invalid").fails().code_is(1);
1818
}
19+
20+
#[test]
21+
fn test_unit() {
22+
new_ucmd!().args(&["-S", "M"]).succeeds();
23+
}
24+
25+
#[test]
26+
#[cfg(target_os = "linux")]
27+
fn test_invalid_unit() {
28+
new_ucmd!().args(&["-S", "x"]).fails().code_is(1);
29+
}

0 commit comments

Comments
 (0)