Skip to content

Commit

Permalink
Add EventMatcher::with_message_regex
Browse files Browse the repository at this point in the history
  • Loading branch information
rukai committed Oct 9, 2024
1 parent b78abde commit f6dbbf8
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 1 deletion.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion tokio-bin-process/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ itertools = "0.13.0"
once_cell = "1.17.1"
chrono = "0.4.24"
cargo_metadata = "0.18.0"
regex-lite = "0.1.6"

[dev-dependencies]
tokio = { version = "1.25.0", features = ["macros", "rt-multi-thread", "time"] }
tokio = { version = "1.25.0", features = ["macros", "rt-multi-thread", "time"] }
7 changes: 7 additions & 0 deletions tokio-bin-process/single-crate-test/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions tokio-bin-process/src/event_matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::fmt::Display;

use crate::event::{Event, Level};
use itertools::Itertools;
use regex_lite::Regex;

/// Use to check for any matching [`Event`]'s among a list of events.
#[derive(Debug)]
Expand Down Expand Up @@ -63,6 +64,7 @@ impl Display for Events {
pub struct EventMatcher {
level: Matcher<Level>,
message: Matcher<String>,
message_regex: RegexMatcher,
target: Matcher<String>,
pub(crate) count: Count,
}
Expand Down Expand Up @@ -91,6 +93,12 @@ impl EventMatcher {
self
}

/// Sets the matcher to only match an [`Event`] when it has the exact provided message
pub fn with_message_regex(mut self, message: &str) -> EventMatcher {
self.message_regex = RegexMatcher::new(message);
self
}

/// Defines how many times the matcher must match to pass an assertion
///
/// This is not used internally i.e. it has no effect on [`EventMatcher::matches`]
Expand All @@ -104,6 +112,7 @@ impl EventMatcher {
pub fn matches(&self, event: &Event) -> bool {
self.level.matches(&event.level)
&& self.message.matches(&event.fields.message)
&& self.message_regex.matches(&event.fields.message)
&& self.target.matches(&event.target)
}
}
Expand Down Expand Up @@ -145,3 +154,25 @@ impl<T: PartialEq> Matcher<T> {
}
}
}

#[derive(Debug, Default)]
enum RegexMatcher {
Matches(Regex),
#[default]
Any,
}

impl RegexMatcher {
fn new(pattern: &str) -> Self {
RegexMatcher::Matches(regex_lite::Regex::new(pattern).unwrap())
}
}

impl RegexMatcher {
fn matches(&self, value: &str) -> bool {
match self {
RegexMatcher::Matches(regex) => regex.is_match(value),
RegexMatcher::Any => true,
}
}
}

0 comments on commit f6dbbf8

Please sign in to comment.