Skip to content

Commit

Permalink
Test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
Lars T Hansen committed Apr 4, 2024
1 parent 432d073 commit 9a33f81
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/sysinfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
Expand All @@ -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;
Expand Down Expand Up @@ -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.
11 changes: 11 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"#);
}
13 changes: 13 additions & 0 deletions tests/sysinfo-syntax.sh
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 9a33f81

Please sign in to comment.