1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use std::fmt;
use crate::reflection;
use crate::utils;
use crate::Predicate;
pub type RegexError = regex::Error;
#[derive(Debug, Clone)]
pub struct RegexPredicate {
re: regex::Regex,
}
impl RegexPredicate {
pub fn count(self, count: usize) -> RegexMatchesPredicate {
RegexMatchesPredicate { re: self.re, count }
}
}
impl Predicate<str> for RegexPredicate {
fn eval(&self, variable: &str) -> bool {
self.re.is_match(variable)
}
fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> {
utils::default_find_case(self, expected, variable)
}
}
impl reflection::PredicateReflection for RegexPredicate {}
impl fmt::Display for RegexPredicate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "var.is_match({})", self.re)
}
}
#[derive(Debug, Clone)]
pub struct RegexMatchesPredicate {
re: regex::Regex,
count: usize,
}
impl Predicate<str> for RegexMatchesPredicate {
fn eval(&self, variable: &str) -> bool {
self.re.find_iter(variable).count() == self.count
}
fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> {
let actual_count = self.re.find_iter(variable).count();
let result = self.count == actual_count;
if result == expected {
Some(
reflection::Case::new(Some(self), result)
.add_product(reflection::Product::new("actual count", actual_count)),
)
} else {
None
}
}
}
impl reflection::PredicateReflection for RegexMatchesPredicate {
fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> {
let params = vec![reflection::Parameter::new("count", &self.count)];
Box::new(params.into_iter())
}
}
impl fmt::Display for RegexMatchesPredicate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "var.is_match({})", self.re)
}
}
pub fn is_match<S>(pattern: S) -> Result<RegexPredicate, RegexError>
where
S: AsRef<str>,
{
regex::Regex::new(pattern.as_ref()).map(|re| RegexPredicate { re })
}