assertables/assert_command/
assert_command_stderr_string_is_match.rs

1//! Assert a command stderr string is a match to a regex.
2//!
3//! Pseudocode:<br>
4//! (command ⇒ stderr ⇒ string) is match (expr into string)
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//! use std::process::Command;
11//! use regex::Regex;
12//!
13//! let mut command = Command::new("bin/printf-stderr");
14//! command.args(["%s", "alfa"]);
15//! let matcher = Regex::new(r"lf").expect("regex");
16//! assert_command_stderr_string_is_match!(command, &matcher);
17//! ```
18//!
19//! # Module macros
20//!
21//! * [`assert_command_stderr_string_is_match`](macro@crate::assert_command_stderr_string_is_match)
22//! * [`assert_command_stderr_string_is_match_as_result`](macro@crate::assert_command_stderr_string_is_match_as_result)
23//! * [`debug_assert_command_stderr_string_is_match`](macro@crate::debug_assert_command_stderr_string_is_match)
24
25/// Assert a command stderr string is a match to a regex.
26///
27/// Pseudocode:<br>
28/// (command ⇒ stderr ⇒ string) is match (expr into string)
29///
30/// * If true, return Result `Ok(command ⇒ stderr ⇒ string)`.
31///
32/// * Otherwise, return Result `Err(message)`.
33///
34/// This macro is useful for runtime checks, such as checking parameters,
35/// or sanitizing inputs, or handling different results in different ways.
36///
37/// # Module macros
38///
39/// * [`assert_command_stderr_string_is_match`](macro@crate::assert_command_stderr_string_is_match)
40/// * [`assert_command_stderr_string_is_match_as_result`](macro@crate::assert_command_stderr_string_is_match_as_result)
41/// * [`debug_assert_command_stderr_string_is_match`](macro@crate::debug_assert_command_stderr_string_is_match)
42///
43#[macro_export]
44macro_rules! assert_command_stderr_string_is_match_as_result {
45    ($command:expr, $matcher:expr $(,)?) => {
46        match ($command.output(), &$matcher) {
47            (Ok(a), matcher) => {
48                let a = String::from_utf8(a.stderr).unwrap();
49                if matcher.is_match(&a) {
50                    Ok(a)
51                } else {
52                    Err(
53                        format!(
54                            concat!(
55                                "assertion failed: `assert_command_stderr_string_is_match!(command, matcher)`\n",
56                                "https://docs.rs/assertables/9.5.4/assertables/macro.assert_command_stderr_string_is_match.html\n",
57                                " command label: `{}`,\n",
58                                " command debug: `{:?}`,\n",
59                                " command value: `{:?}`,\n",
60                                " matcher label: `{}`,\n",
61                                " matcher debug: `{:?}`,\n",
62                                " matcher value: `{:?}`"
63                            ),
64                            stringify!($command),
65                            $command,
66                            a,
67                            stringify!($matcher),
68                            $matcher,
69                            matcher
70                        )
71                    )
72                }
73            },
74            (a, matcher) => {
75                Err(
76                    format!(
77                        concat!(
78                            "assertion failed: `assert_command_stderr_string_is_match!(command, matcher)`\n",
79                            "https://docs.rs/assertables/9.5.4/assertables/macro.assert_command_stderr_string_is_match.html\n",
80                            "  command label: `{}`,\n",
81                            "  command debug: `{:?}`,\n",
82                            "  command value: `{:?}`,\n",
83                            "  matcher label: `{}`,\n",
84                            "  matcher debug: `{:?}`,\n",
85                            "  matcher value: `{:?}`,\n",
86                        ),
87                        stringify!($command),
88                        $command,
89                        a,
90                        stringify!($matcher),
91                        $matcher,
92                        matcher
93                    )
94                )
95            }
96        }
97    };
98}
99
100#[cfg(test)]
101mod test_assert_command_stderr_string_is_match_as_result {
102    use regex::Regex;
103    use std::process::Command;
104
105    #[test]
106    fn success() {
107        let mut a = Command::new("bin/printf-stderr");
108        a.args(["%s", "alfa"]);
109        let b = Regex::new(r"lf").expect("regex");
110        let actual = assert_command_stderr_string_is_match_as_result!(a, b);
111        assert_eq!(actual.unwrap(), "alfa");
112    }
113
114    #[test]
115    fn failure() {
116        let mut a = Command::new("bin/printf-stderr");
117        a.args(["%s", "alfa"]);
118        let b = Regex::new(r"zz").expect("regex");
119        let actual = assert_command_stderr_string_is_match_as_result!(a, b);
120        let message = concat!(
121            "assertion failed: `assert_command_stderr_string_is_match!(command, matcher)`\n",
122            "https://docs.rs/assertables/9.5.4/assertables/macro.assert_command_stderr_string_is_match.html\n",
123            " command label: `a`,\n",
124            " command debug: `\"bin/printf-stderr\" \"%s\" \"alfa\"`,\n",
125            " command value: `\"alfa\"`,\n",
126            " matcher label: `b`,\n",
127            " matcher debug: `Regex(\"zz\")`,\n",
128            " matcher value: `Regex(\"zz\")`"
129        );
130        assert_eq!(actual.unwrap_err(), message);
131    }
132}
133
134/// Assert a command stderr string is a match to a regex.
135///
136/// Pseudocode:<br>
137/// (command ⇒ stderr ⇒ string) is match (expr into string)
138///
139/// * If true, return (command ⇒ stderr ⇒ string).
140///
141/// * Otherwise, call [`panic!`] with a message and the values of the
142///   expressions with their debug representations.
143///
144/// # Examples
145///
146/// ```rust
147/// use assertables::*;
148/// # use std::panic;
149/// use std::process::Command;
150/// use regex::Regex;
151///
152/// # fn main() {
153/// let mut command = Command::new("bin/printf-stderr");
154/// command.args(["%s", "alfa"]);
155/// let matcher = Regex::new(r"lf").expect("regex");
156/// assert_command_stderr_string_is_match!(command, &matcher);
157///
158/// # let result = panic::catch_unwind(|| {
159/// // This will panic
160/// let mut command = Command::new("bin/printf-stderr");
161/// command.args(["%s", "alfa"]);
162/// let matcher = Regex::new(r"zz").expect("regex");
163/// assert_command_stderr_string_is_match!(command, &matcher);
164/// # });
165/// // assertion failed: `assert_command_stderr_string_is_match!(command, matcher)`
166/// // https://docs.rs/assertables/9.5.4/assertables/macro.assert_command_stderr_string_is_match.html
167/// //  command label: `command`,
168/// //  command debug: `\"bin/printf-stderr\" \"%s\" \"alfa\"`,
169/// //  command value: `\"alfa\"`,
170/// //  matcher label: `&matcher`,
171/// //  matcher debug: `Regex(\"zz\")`,
172/// //  matcher value: `Regex(\"zz\")`
173/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
174/// # let message = concat!(
175/// #     "assertion failed: `assert_command_stderr_string_is_match!(command, matcher)`\n",
176/// #     "https://docs.rs/assertables/9.5.4/assertables/macro.assert_command_stderr_string_is_match.html\n",
177/// #     " command label: `command`,\n",
178/// #     " command debug: `\"bin/printf-stderr\" \"%s\" \"alfa\"`,\n",
179/// #     " command value: `\"alfa\"`,\n",
180/// #     " matcher label: `&matcher`,\n",
181/// #     " matcher debug: `Regex(\"zz\")`,\n",
182/// #     " matcher value: `Regex(\"zz\")`"
183/// # );
184/// # assert_eq!(actual, message);
185/// # }
186/// ```
187///
188/// # Module macros
189///
190/// * [`assert_command_stderr_string_is_match`](macro@crate::assert_command_stderr_string_is_match)
191/// * [`assert_command_stderr_string_is_match_as_result`](macro@crate::assert_command_stderr_string_is_match_as_result)
192/// * [`debug_assert_command_stderr_string_is_match`](macro@crate::debug_assert_command_stderr_string_is_match)
193///
194#[macro_export]
195macro_rules! assert_command_stderr_string_is_match {
196    ($command:expr, $matcher:expr $(,)?) => {
197        match $crate::assert_command_stderr_string_is_match_as_result!($command, $matcher) {
198            Ok(x) => x,
199            Err(err) => panic!("{}", err),
200        }
201    };
202    ($command:expr, $matcher:expr, $($message:tt)+) => {
203        match $crate::assert_command_stderr_string_is_match_as_result!($command, $matcher) {
204            Ok(x) => x,
205            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
206        }
207    };
208}
209
210#[cfg(test)]
211mod test_assert_command_stderr_string_is_match {
212    use regex::Regex;
213    use std::panic;
214    use std::process::Command;
215
216    #[test]
217    fn success() {
218        let mut a = Command::new("bin/printf-stderr");
219        a.args(["%s", "alfa"]);
220        let b = Regex::new(r"lf").expect("regex");
221        let actual = assert_command_stderr_string_is_match!(a, b);
222        assert_eq!(actual, "alfa");
223    }
224
225    #[test]
226    fn failure() {
227        let result = panic::catch_unwind(|| {
228            let mut a = Command::new("bin/printf-stderr");
229            a.args(["%s", "alfa"]);
230            let b = Regex::new(r"zz").expect("regex");
231            let _actual = assert_command_stderr_string_is_match!(a, b);
232        });
233        let message = concat!(
234            "assertion failed: `assert_command_stderr_string_is_match!(command, matcher)`\n",
235            "https://docs.rs/assertables/9.5.4/assertables/macro.assert_command_stderr_string_is_match.html\n",
236            " command label: `a`,\n",
237            " command debug: `\"bin/printf-stderr\" \"%s\" \"alfa\"`,\n",
238            " command value: `\"alfa\"`,\n",
239            " matcher label: `b`,\n",
240            " matcher debug: `Regex(\"zz\")`,\n",
241            " matcher value: `Regex(\"zz\")`"
242        );
243        assert_eq!(
244            result
245                .unwrap_err()
246                .downcast::<String>()
247                .unwrap()
248                .to_string(),
249            message
250        );
251    }
252}
253
254/// Assert a command stderr string is a match to a regex.
255///
256/// Pseudocode:<br>
257/// (command ⇒ stderr ⇒ string) is match (expr into string)
258///
259/// This macro provides the same statements as [`assert_command_stderr_string_is_match`](macro.assert_command_stderr_string_is_match.html),
260/// except this macro's statements are only enabled in non-optimized
261/// builds by default. An optimized build will not execute this macro's
262/// statements unless `-C debug-assertions` is passed to the compiler.
263///
264/// This macro is useful for checks that are too expensive to be present
265/// in a release build but may be helpful during development.
266///
267/// The result of expanding this macro is always type checked.
268///
269/// An unchecked assertion allows a program in an inconsistent state to
270/// keep running, which might have unexpected consequences but does not
271/// introduce unsafety as long as this only happens in safe code. The
272/// performance cost of assertions, however, is not measurable in general.
273/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
274/// after thorough profiling, and more importantly, only in safe code!
275///
276/// This macro is intended to work in a similar way to
277/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
278///
279/// # Module macros
280///
281/// * [`assert_command_stderr_string_is_match`](macro@crate::assert_command_stderr_string_is_match)
282/// * [`assert_command_stderr_string_is_match`](macro@crate::assert_command_stderr_string_is_match)
283/// * [`debug_assert_command_stderr_string_is_match`](macro@crate::debug_assert_command_stderr_string_is_match)
284///
285#[macro_export]
286macro_rules! debug_assert_command_stderr_string_is_match {
287    ($($arg:tt)*) => {
288        if $crate::cfg!(debug_assertions) {
289            $crate::assert_command_stderr_string_is_match!($($arg)*);
290        }
291    };
292}