derive_deftly_tests/
tutils.rs

1//! utilities and common code for testingy
2
3use super::*;
4
5#[ext(DebugExt)]
6pub impl<T: Debug> T {
7    fn to_debug(&self) -> String {
8        format!("{:?}", self)
9    }
10}
11
12/// Compile `re` into a [`Regex`], with cacheing
13// Not using lazy_regex because we sometimes make our
14// regexps with format! so they aren't static
15#[cfg(feature = "recent")] // Doesn't work on 1.54; Mutex::new isn't const
16pub fn compile_re_cached(re: &str) -> Regex {
17    use std::sync::Mutex;
18    static CACHE: Mutex<Option<HashMap<String, Regex>>> = Mutex::new(None);
19
20    let mut guard = CACHE.lock().unwrap();
21    let cache = guard.get_or_insert_with(|| Default::default());
22    match cache.get(re) {
23        None => {
24            let re = Regex::new(re).expect(&format!("bad regexp {re}"));
25            cache.entry(re.to_string()).or_insert(re)
26        }
27        Some(re) => re,
28    }
29    .clone()
30}
31
32/// `fn re!(l: &str) -> Regex`
33#[macro_export]
34macro_rules! re { { $re:expr $(,)? } => {
35    compile_re_cached($re.as_ref())
36} }
37/// `fn m!(l: &str, re: &str) -> bool`: does regexp `re` match in `l` ?
38#[macro_export]
39macro_rules! m { { $l:expr, $re:expr $(,)? } => {
40    re!($re).is_match(&$l)
41} }
42/// `fn mc!(l: &str, re: &str) -> Option<(CAP,...)>`: regexp captures?
43///
44/// `(CAP,...)` is a tuple of `String`.
45#[macro_export]
46macro_rules! mc { { $l:expr, $re:expr $(,)? } => {
47    re!($re)
48        .captures(&$l)
49        .map(|caps| {
50            let caps = caps
51                .iter()
52                .map(|m| m.map(|m| m.as_str().to_owned()).unwrap_or_default())
53                .collect_vec();
54            let len = caps.len();
55            caps
56                .into_iter()
57                .skip(1)
58                .collect_tuple()
59                .unwrap_or_else(|| {
60                    panic!("wrong # matches: got {} from {}", len, $re)
61                })
62        })
63} }
64
65const EXPAND_TEST_GLOB: &str = "expand/*.rs";
66const EXPAND_MACROTEST_IGNORE_GLOB: &str = "*.expanded.rs";
67
68/// List the test cases in tests/expand/*.rs
69///
70/// Filters out tests with the word `recent` in,
71/// unless the `recent` cargo feature is enabled.
72/// These are tests that won't work with our MSRV.
73///
74/// Filters out *.expanded.rs.
75pub fn list_expand_test_paths() -> Vec<PathBuf> {
76    list_expand_general(&|_| false)
77}
78
79/// List the test cases in tests/expand/*.rs, for `macrotest`
80///
81/// Like `list_expand_test_paths`, but if the only thing we filter
82/// out is `*.expanded.rs`, simply returns the `expand/*.rs` glob.
83///
84/// Then macrotest will automatically ignore `*.expanded.rs`.
85/// We do this because macrotest is faster and less noisy
86/// if we run it once with a single glob.
87pub fn list_expand_test_paths_for_macrotest() -> Vec<PathBuf> {
88    list_expand_general(&|ign| ign == EXPAND_MACROTEST_IGNORE_GLOB)
89}
90
91fn list_expand_general(will_filter: &dyn Fn(&str) -> bool) -> Vec<PathBuf> {
92    let ignores = [
93        EXPAND_MACROTEST_IGNORE_GLOB,
94        #[cfg(not(feature = "recent"))]
95        "*recent*",
96    ];
97
98    if ignores.iter().cloned().all(will_filter) {
99        return iter::once(EXPAND_TEST_GLOB.into()).collect();
100    }
101
102    let ignores: Vec<_> = ignores
103        .iter()
104        .map(|pat| glob::Pattern::new(pat).unwrap())
105        .collect();
106
107    glob::glob(EXPAND_TEST_GLOB)
108        .unwrap()
109        .filter_map(move |path| {
110            let path = path.unwrap();
111            if ignores.iter().any(|pat| pat.matches_path(&path)) {
112                return None;
113            }
114            Some(path)
115        })
116        .collect()
117}