Debian Codegraph @

tests/number_range.rs

raw symbols SCIP
1 use clap::Parser;
2 use clap_num::number_range;
3
4 // standalone basic tests
5 #[cfg(test)]
6 mod basic {
7 use super::*;
8
9 macro_rules! pos {
10 ($NAME:ident, $VAL:expr, $MIN:expr, $MAX:expr, $RESULT:expr) => {
11 #[test]
12 fn $NAME() {
13 assert_eq!(number_range($VAL, $MIN, $MAX), Ok($RESULT));
14 }
15 };
16 }
17
18 macro_rules! neg {
19 ($NAME:ident, $VAL:expr, $MIN:expr, $MAX:expr, $RESULT:expr) => {
20 #[test]
21 fn $NAME() {
22 assert_eq!(number_range($VAL, $MIN, $MAX), Err(String::from($RESULT)));
23 }
24 };
25 }
26
27 pos!(simple, "123", 12u8, 200u8, 123u8);
28 pos!(zero, "0", 0u8, 0u8, 0u8);
29 pos!(neg, "-1", -10i8, 10i8, -1);
30 pos!(min_limit, "-5", -5i8, -5i8, -5i8);
31 pos!(max_limit, "65535", 0, u16::MAX, u16::MAX);
32
33 neg!(decimal, "1.1", -10i8, 10i8, "invalid digit found in string");
34 neg!(min, "-1", 0i8, 0i8, "less than minimum of 0");
35 neg!(max, "1", 0i8, 0i8, "exceeds maximum of 0");
36 neg!(
37 overflow,
38 "256",
39 0,
40 std::u8::MAX,
41 "number too large to fit in target type"
42 );
43 neg!(nan, "nan", 0, 0, "invalid digit found in string");
44
45 #[test]
46 #[should_panic]
47 fn min_max_debug_assert() {
48 let _ = number_range("", 2, 1);
49 }
50 }
51
52 // integration tests with clap
53 #[cfg(test)]
54 mod integration {
55 use super::*;
56
57 fn human_livable_temperature(s: &str) -> Result<i8, String> {
58 number_range(s, -40, 60)
59 }
60
61 #[derive(Parser, Debug)]
62 struct Thermostat {
63 #[clap(
64 long,
65 value_parser=human_livable_temperature,
66 allow_hyphen_values=true
67 )]
68 temperature: i8,
69 }
70
71 // positive path
72 macro_rules! pos {
73 ($NAME:ident, $VAL:expr, $RESULT:expr) => {
74 #[test]
75 fn $NAME() {
76 let opt = Thermostat::parse_from(&["", "--temperature", $VAL]);
77 assert_eq!(opt.temperature, $RESULT);
78 }
79 };
80 }
81
82 // negative path
83 macro_rules! neg {
84 ($NAME:ident, $VAL:expr, $RESULT:expr) => {
85 #[test]
86 fn $NAME() {
87 let opt = Thermostat::try_parse_from(&["", "--temperature", $VAL]);
88 match opt {
89 Err(e) => {
90 assert!(format!("{:?}", e).contains($RESULT));
91 }
92 _ => unreachable!(),
93 };
94 }
95 };
96 }
97
98 pos!(simple, "50", 50);
99 pos!(zero, "0", 0);
100 pos!(negative, "-30", -30);
101 pos!(positive_limit, "60", 60);
102 pos!(negative_limit, "-40", -40);
103
104 neg!(too_small, "-41", "less than minimum of -40");
105 neg!(too_large, "61", "exceeds maximum of 60");
106 }