From 9a33f81ab5dbefdc54b0b2faec068c4675930031 Mon Sep 17 00:00:00 2001 From: Lars T Hansen Date: Wed, 3 Apr 2024 13:18:07 +0200 Subject: [PATCH] Test cases --- src/sysinfo.rs | 17 ++++++++++++----- src/util.rs | 11 +++++++++++ tests/sysinfo-syntax.sh | 13 +++++++++++++ 3 files changed, 36 insertions(+), 5 deletions(-) create mode 100755 tests/sysinfo-syntax.sh diff --git a/src/sysinfo.rs b/src/sysinfo.rs index 34e5fbb..04c7895 100644 --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -7,11 +7,12 @@ use crate::procfs; use crate::procfsapi; use crate::util; -use std::io::{self, Write}; +use std::io; pub fn show_system(timestamp: &str) { let fs = procfsapi::RealFS::new(); - match do_show_system(&fs, timestamp) { + let mut writer = io::stdout(); + match do_show_system(&mut writer, &fs, timestamp) { Ok(_) => {} Err(e) => { log::error!("sysinfo failed: {e}"); @@ -21,7 +22,7 @@ pub fn show_system(timestamp: &str) { const GIB: usize = 1024 * 1024 * 1024; -fn do_show_system(fs: &dyn procfsapi::ProcfsAPI, timestamp: &str) -> Result<(), String> { +fn do_show_system(writer: &mut dyn io::Write, fs: &dyn procfsapi::ProcfsAPI, timestamp: &str) -> Result<(), String> { let (model, sockets, cores_per_socket, threads_per_core) = procfs::get_cpu_info(fs)?; let mem_by = procfs::get_memtotal_kib(fs)? * 1024; let mem_gib = (mem_by as f64 / GIB as f64).round() as i64; @@ -93,7 +94,13 @@ fn do_show_system(fs: &dyn procfsapi::ProcfsAPI, timestamp: &str) -> Result<(), }} "#); - let _ = io::stdout().write(s.as_bytes()); - let _ = io::stdout().flush(); + // Ignore I/O errors. + + let _ = writer.write(s.as_bytes()); + let _ = writer.flush(); Ok(()) } + +// Currently the test for do_show_system() is whitebox, see ../tests. The reason for this is partly +// that not all the system interfaces used by that function are virtualized at this time, and partly +// that we only care that the output syntax looks right. diff --git a/src/util.rs b/src/util.rs index 1262865..ab6f359 100644 --- a/src/util.rs +++ b/src/util.rs @@ -102,3 +102,14 @@ pub fn json_quote(s: &str) -> String { } t } + +#[test] +pub fn json_quote_test() { + assert!(&json_quote("abcde") == "abcde"); + assert!(&json_quote(r#"abc\de"#) == r#"abc\\de"#); + assert!(&json_quote(r#"abc"de"#) == r#"abc\"de"#); + assert!(&json_quote("abc\nde") == r#"abc\nde"#); + assert!(&json_quote("abc\rde") == r#"abc\rde"#); + assert!(&json_quote("abc de") == r#"abc\tde"#); + assert!(&json_quote("abc\u{0008}de") == r#"abc de"#); +} diff --git a/tests/sysinfo-syntax.sh b/tests/sysinfo-syntax.sh new file mode 100755 index 0000000..2769281 --- /dev/null +++ b/tests/sysinfo-syntax.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# +# Check that sysinfo produces properly formatted JSON. +# Requirement: the `jq` utility. + +set -e +( cd .. ; cargo build ) +if [[ $(command -v jq) == "" ]]; then + echo "Install jq first" + exit 1 +fi +output=$(../target/debug/sonar sysinfo) +jq . <<< $output > /dev/null