Debian Codegraph @

third_party/rust/serde_with/tests/serde_as/serde_conv.rs

raw
1 use super::*;
2 use serde_with::serde_conv;
3
4 #[test]
5 fn test_bool_as_string() {
6 serde_conv!(BoolAsString, bool, |x: &bool| x.to_string(), |x: String| x
7 .parse());
8
9 #[derive(Debug, PartialEq, Serialize, Deserialize)]
10 struct SWith(#[serde(with = "BoolAsString")] bool);
11
12 is_equal(SWith(false), expect![[r#""false""#]]);
13 is_equal(SWith(true), expect![[r#""true""#]]);
14 check_error_deserialization::<SWith>(
15 "123",
16 expect![[r#"invalid type: integer `123`, expected a string at line 1 column 3"#]],
17 );
18
19 #[serde_as]
20 #[derive(Debug, PartialEq, Serialize, Deserialize)]
21 struct SAs(#[serde_as(as = "BoolAsString")] bool);
22
23 is_equal(SAs(false), expect![[r#""false""#]]);
24 is_equal(SAs(true), expect![[r#""true""#]]);
25 check_error_deserialization::<SAs>(
26 "123",
27 expect![[r#"invalid type: integer `123`, expected a string at line 1 column 3"#]],
28 );
29
30 #[serde_as]
31 #[derive(Debug, PartialEq, Serialize, Deserialize)]
32 struct SAsVec(#[serde_as(as = "Vec<BoolAsString>")] Vec<bool>);
33
34 is_equal(
35 SAsVec(vec![false]),
36 expect![[r#"
37 [
38 "false"
39 ]"#]],
40 );
41 is_equal(
42 SAsVec(vec![true]),
43 expect![[r#"
44 [
45 "true"
46 ]"#]],
47 );
48 check_error_deserialization::<SAsVec>(
49 "123",
50 expect![[r#"invalid type: integer `123`, expected a sequence at line 1 column 3"#]],
51 );
52 }