Skip to content

Commit 57cf05d

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

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed

src/uu/vmstat/src/picker.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55

66
#[cfg(target_os = "linux")]
77
use crate::{CpuLoad, Meminfo, ProcData};
8+
#[cfg(target_os = "linux")]
89
use clap::ArgMatches;
9-
use uucore::error::USimpleError;
1010

1111
#[cfg(target_os = "linux")]
1212
pub type Picker = (
@@ -65,17 +65,15 @@ pub fn get_pickers(matches: &ArgMatches) -> Vec<Picker> {
6565
]
6666
}
6767

68+
#[cfg(target_os = "linux")]
6869
fn with_unit(x: u64, arg: &ArgMatches) -> u64 {
6970
if let Some(unit) = arg.get_one::<String>("unit") {
7071
return match unit.as_str() {
7172
"k" => x / bytesize::KB,
7273
"K" => x / bytesize::KIB,
7374
"m" => x / bytesize::MB,
7475
"M" => x / bytesize::MIB,
75-
_ => panic!(
76-
"{:?}",
77-
USimpleError::new(1, "-S requires k, K, m or M (default is KiB)",)
78-
),
76+
_ => x, // impossible
7977
};
8078
}
8179
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)