Skip to content

Commit

Permalink
chore: Add extract occurences test utility
Browse files Browse the repository at this point in the history
Extracts timestamps for logs with matching predicates.
  • Loading branch information
bgins committed Oct 29, 2023
1 parent 5a5266c commit 29d0527
Showing 1 changed file with 41 additions and 7 deletions.
48 changes: 41 additions & 7 deletions homestar-runtime/tests/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use anyhow::{Context, Result};
#[cfg(not(windows))]
use assert_cmd::prelude::*;
use chrono::{DateTime, FixedOffset};
#[cfg(not(windows))]
use nix::{
sys::signal::{self, Signal},
Expand Down Expand Up @@ -95,16 +96,49 @@ pub(crate) fn retrieve_output(proc: Child) -> String {
pub(crate) fn check_lines_for(output: String, predicates: Vec<&str>) -> bool {
output
.split("\n")
.map(|line| {
// Line contains all predicates
predicates
.iter()
.map(|pred| predicate::str::contains(*pred).eval(line))
.fold(true, |acc, curr| acc && curr)
})
.map(|line| check_line_for(line, &predicates))
.fold(false, |acc, curr| acc || curr)
}

/// Check process output line for all predicates
fn check_line_for(line: &str, predicates: &Vec<&str>) -> bool {
predicates
.iter()
.map(|pred| predicate::str::contains(*pred).eval(line))
.fold(true, |acc, curr| acc && curr)
}

/// Extract timestamps for process output lines with matching predicates
pub(crate) fn extract_occurences_where(
output: String,
predicates: Vec<&str>,
) -> Vec<DateTime<FixedOffset>> {
output.split("\n").fold(vec![], |mut occurences, line| {
if check_line_for(line, &predicates) {
match extract_label(&line, "ts=").and_then(|label| {
DateTime::parse_from_rfc3339(label).map_or(None, |datetime| Some(datetime))
}) {
Some(datetime) => {
occurences.push(datetime);
occurences
}
None => {
panic!("Encountered a log entry that was missing a timestamp label: {line}");
}
}
} else {
occurences
}
})
}

/// Extract label value from process output line
fn extract_label<'a>(line: &'a str, key: &str) -> Option<&'a str> {
line.split(' ')
.find(|label| predicate::str::contains(key).eval(label))
.and_then(|label| Some(&label[key.len()..]))
}

/// Wait for process to exit or kill after timeout.
pub(crate) fn kill_homestar(mut homestar_proc: Child, timeout: Option<Duration>) -> Child {
if let Ok(None) = homestar_proc.try_wait() {
Expand Down

0 comments on commit 29d0527

Please sign in to comment.