Debian Codegraph @

tests/test.rs

raw symbols SCIP
1 use std::borrow::Cow;
2 use std::str::CharIndices;
3 use descape::*;
4
5 macro_rules! ensure_err {
6 ($($name: ident),+) => {$(
7 assert_eq!($name.to_unescaped().map_err(|err| err.index), Err(0), "{} parsed successfully when invalid", stringify!($name));
8 )+};
9 }
10
11 #[test]
12 fn test_escapes() {
13 static ESCAPED: &str =
14 r#"\a \b \t \n \v❤️\f \r \e \' \" \` \\ \u{0} \u{21}❤️\u{433} \u{FFFD} \u0000 \u0021 \uFFFD \x7E \xFF \0 \11 \100"#;
15 static UNESCAPED: &str =
16 "\x07 \x08 \t \n \x0B❤️\x0C \x0D \x1B \' \" ` \\ \u{0} \u{21}❤️\u{433} \u{FFFD} \u{0000} \u{0021} \u{FFFD} \x7E \u{FF} \0 \t @";
17 static NO_ESCAPES: &str = "No escapes here!";
18 static BAD_ESCAPE: &str = r"\Z";
19 static CUT_ESCAPE: &str = r"\";
20 static BAD_UNICODE: &str = r"\u{This is definitely not hexadecimal}";
21 static EMPTY_UNICODE: &str = r"\u{}";
22 static CUT_UNICODE: &str = r"\u{03";
23 static BAD_HEX: &str = r"\xGG";
24 static CUT_HEX: &str = r"\xA";
25 static EMPTY_HEX: &str = r"\x";
26 static NON_UNICODE: &str = r"\u{D800}";
27
28 assert_eq!(
29 ESCAPED.to_unescaped()
30 .map_err(|err| &ESCAPED[..err.index])
31 .expect("should not reject legal escaped string"),
32 Cow::Owned::<'_, str>(UNESCAPED.to_string())
33 );
34
35 assert_eq!(
36 NO_ESCAPES.to_unescaped()
37 .map_err(|err| &ESCAPED[..err.index])
38 .expect("should not reject legal escaped string"),
39 Cow::Borrowed(NO_ESCAPES)
40 );
41
42 ensure_err!(
43 BAD_ESCAPE,
44 CUT_ESCAPE,
45 BAD_UNICODE,
46 EMPTY_UNICODE,
47 CUT_UNICODE,
48 BAD_HEX,
49 CUT_HEX,
50 EMPTY_HEX,
51 NON_UNICODE
52 );
53 }
54
55 fn custom_esc<'a>(_: usize, chr: char, iter: &mut CharIndices<'a>) -> Result<EscapeValue<'a>, ()> {
56 if chr == 'T' {
57 let (_, next) = iter.next().ok_or(())?;
58 return Ok((match next {
59 'a' => 'g',
60 'o' => 'p',
61 _ => Err(())?
62 }).into());
63 }
64 Ok(EscapeValue::Remove)
65 }
66
67 #[test]
68 fn test_customs() {
69 r"Hello \T world".to_unescaped_with(custom_esc)
70 .expect_err(r"custom escape should fail for \T");
71 r"Foo \Tg bar".to_unescaped_with(custom_esc)
72 .expect_err(r"custom escape should fail for \Tg");
73 assert_eq!(
74 r"Spam E\Tags".to_unescaped_with(custom_esc).expect(r"custom escape should succeed for \Ta"),
75 Cow::<'static, str>::Owned(String::from("Spam Eggs")),
76 "custom escape gave incorrect result"
77 );
78 assert_eq!(
79 r"Bee\To \n Boop".to_unescaped_with(custom_esc).expect(r"custom escape should succeed for \To"),
80 Cow::<'static, str>::Owned(String::from("Beep Boop")),
81 "custom escape gave incorrect result"
82 );
83 }
84
85