rstest_bdd_patterns/
hint.rs

1//! Placeholder type-hint helpers used during regex compilation.
2
3/// Translate a placeholder type hint into a regular-expression fragment.
4///
5/// # Examples
6/// ```ignore
7/// use rstest_bdd_patterns::get_type_pattern;
8/// assert_eq!(get_type_pattern(Some("u32")), "\\d+");
9/// assert_eq!(get_type_pattern(Some("f64")), "(?i:(?:[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?|nan|inf|infinity))");
10/// assert_eq!(get_type_pattern(None), ".+?");
11/// ```
12#[must_use]
13pub fn get_type_pattern(type_hint: Option<&str>) -> &'static str {
14    match type_hint {
15        Some("u8" | "u16" | "u32" | "u64" | "u128" | "usize") => r"\d+",
16        Some("i8" | "i16" | "i32" | "i64" | "i128" | "isize") => r"[+-]?\d+",
17        Some("f32" | "f64") => {
18            r"(?i:(?:[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?|nan|inf|infinity))"
19        }
20        Some("string") => r#""(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'"#,
21        _ => r".+?",
22    }
23}
24
25/// Check whether a type hint requires quote stripping.
26///
27/// The `:string` type hint matches quoted strings and extracts only the content
28/// between the quotes, discarding the surrounding quote characters.
29#[must_use]
30pub fn requires_quote_stripping(type_hint: Option<&str>) -> bool {
31    matches!(type_hint, Some("string"))
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn returns_integer_pattern_for_unsigned_types() {
40        assert_eq!(get_type_pattern(Some("u64")), "\\d+");
41    }
42
43    #[test]
44    fn returns_signed_integer_pattern() {
45        assert_eq!(get_type_pattern(Some("i32")), r"[+-]?\d+");
46    }
47
48    #[test]
49    fn returns_float_pattern() {
50        assert_eq!(
51            get_type_pattern(Some("f32")),
52            r"(?i:(?:[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?|nan|inf|infinity))"
53        );
54    }
55
56    #[test]
57    fn defaults_to_lazy_match_for_unknown_types() {
58        assert_eq!(get_type_pattern(Some("String")), r".+?");
59    }
60
61    #[test]
62    fn defaults_to_lazy_match_when_hint_is_none() {
63        assert_eq!(get_type_pattern(None), r".+?");
64    }
65
66    #[test]
67    fn returns_quoted_string_pattern_for_string_type() {
68        assert_eq!(
69            get_type_pattern(Some("string")),
70            r#""(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'"#
71        );
72    }
73
74    #[test]
75    fn string_hint_requires_quote_stripping() {
76        assert!(requires_quote_stripping(Some("string")));
77    }
78
79    #[test]
80    fn other_hints_do_not_require_quote_stripping() {
81        assert!(!requires_quote_stripping(Some("u32")));
82        assert!(!requires_quote_stripping(Some("i64")));
83        assert!(!requires_quote_stripping(Some("f64")));
84        assert!(!requires_quote_stripping(Some("String")));
85        assert!(!requires_quote_stripping(None));
86    }
87}