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
//! Shared URL matcher used by `expect_*` and the network `monitor`.
/// URL match predicate used by request/response expectations.
///
/// `From<&str>` / `From<String>` build a [`UrlMatcher::Substring`], while
/// `From<regex::Regex>` builds a [`UrlMatcher::Regex`] — so callers can pass
/// any of the three to [`crate::Tab::expect_request`] /
/// [`crate::Tab::expect_response`].
///
/// # Examples
///
/// ```
/// use zendriver::UrlMatcher;
/// let m: UrlMatcher = "/api/".into();
/// assert!(m.matches("https://example.com/api/users"));
/// assert!(!m.matches("https://example.com/static/app.js"));
/// ```
#[derive(Debug, Clone)]
pub enum UrlMatcher {
/// Matches if the URL contains the needle anywhere.
Substring(String),
/// Matches via `regex::Regex::is_match`.
Regex(regex::Regex),
}
impl UrlMatcher {
/// Returns `true` if `url` matches this matcher.
///
/// # Examples
///
/// ```
/// use zendriver::UrlMatcher;
/// let re = regex::Regex::new(r"^https://example\.com/api/").unwrap();
/// let m: UrlMatcher = re.into();
/// assert!(m.matches("https://example.com/api/v1/users"));
/// assert!(!m.matches("https://example.com/static/app.js"));
/// ```
pub fn matches(&self, url: &str) -> bool {
match self {
Self::Substring(s) => url.contains(s.as_str()),
Self::Regex(re) => re.is_match(url),
}
}
}
impl From<&str> for UrlMatcher {
fn from(s: &str) -> Self {
Self::Substring(s.to_string())
}
}
impl From<String> for UrlMatcher {
fn from(s: String) -> Self {
Self::Substring(s)
}
}
impl From<regex::Regex> for UrlMatcher {
fn from(re: regex::Regex) -> Self {
Self::Regex(re)
}
}
#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn substring_matches_when_url_contains_needle() {
let m = UrlMatcher::Substring("/api/".to_string());
assert!(m.matches("https://example.com/api/users"));
assert!(!m.matches("https://example.com/static/app.js"));
}
#[test]
fn regex_matches_pattern() {
let re = regex::Regex::new(r"^https://example\.com/api/v\d+/").unwrap();
let m = UrlMatcher::Regex(re);
assert!(m.matches("https://example.com/api/v1/users"));
assert!(m.matches("https://example.com/api/v42/orders"));
assert!(!m.matches("https://example.com/api/users"));
}
#[test]
fn from_str_builds_substring_variant() {
let m: UrlMatcher = "/api/".into();
match m {
UrlMatcher::Substring(s) => assert_eq!(s, "/api/"),
UrlMatcher::Regex(_) => panic!("expected Substring variant"),
}
}
}