use core::ops::Deref;
use regex::Regex;
pub fn contains_regex<PatternT: Deref<Target = str>>(
pattern: PatternT,
) -> __internal::ContainsRegexMatcher {
__internal::ContainsRegexMatcher { regex: Regex::new(pattern.deref()).unwrap() }
}
pub mod __internal {
use crate::description::Description;
use crate::matcher::{Describable, Matcher, MatcherResult};
use core::fmt::Debug;
use regex::Regex;
#[doc(hidden)]
pub struct ContainsRegexMatcher {
pub(super) regex: Regex,
}
impl<ActualT: AsRef<str> + Debug + ?Sized> Matcher<ActualT> for ContainsRegexMatcher {
fn matches(&self, actual: &ActualT) -> MatcherResult {
self.regex.is_match(actual.as_ref()).into()
}
}
impl Describable for ContainsRegexMatcher {
fn describe(&self, matcher_result: MatcherResult) -> Description {
match matcher_result {
MatcherResult::Match => {
format!("contains the regular expression {:#?}", self.regex.as_str()).into()
}
MatcherResult::NoMatch => {
format!("doesn't contain the regular expression {:#?}", self.regex.as_str())
.into()
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::contains_regex;
use crate::matcher::{Describable as _, Matcher, MatcherResult};
use crate::prelude::*;
use alloc::string::ToString;
#[test]
fn contains_regex_matches_string_reference_with_pattern() -> TestResult<()> {
let matcher = contains_regex("S.*val");
let result = matcher.matches("Some value");
verify_that!(result, eq(MatcherResult::Match))
}
#[test]
fn contains_regex_does_not_match_string_without_pattern() -> TestResult<()> {
let matcher = contains_regex("Another");
let result = matcher.matches("Some value");
verify_that!(result, eq(MatcherResult::NoMatch))
}
#[test]
fn contains_regex_matches_owned_string_with_pattern() -> TestResult<()> {
let matcher = contains_regex("value");
let result = matcher.matches(&"Some value".to_string());
verify_that!(result, eq(MatcherResult::Match))
}
#[test]
fn contains_regex_matches_string_reference_with_owned_string() -> TestResult<()> {
let matcher = contains_regex("value");
let result = matcher.matches("Some value");
verify_that!(result, eq(MatcherResult::Match))
}
#[test]
fn verify_that_works_with_owned_string() -> TestResult<()> {
verify_that!("Some value".to_string(), contains_regex("value"))
}
#[test]
fn contains_regex_displays_quoted_debug_of_pattern() -> TestResult<()> {
let matcher = contains_regex("\n");
verify_that!(
matcher.describe(MatcherResult::Match),
displays_as(eq("contains the regular expression \"\\n\""))
)
}
}