1 use serde::Deserialize;
2 use serde_derive::Deserialize;
3 use std::collections::{BTreeMap as Map, BTreeSet as Set};
4 use std::iter::FromIterator;
5
assert_ignored<'de, T>(json: &'de str, expected: &[&str]) -> T where T: Deserialize<'de>,6 fn assert_ignored<'de, T>(json: &'de str, expected: &[&str]) -> T
7 where
8 T: Deserialize<'de>,
9 {
10 let de = &mut serde_json::Deserializer::from_str(json);
11
12 let mut unused = Set::new();
13
14 let value: T = serde_ignored::deserialize(de, |path| {
15 unused.insert(path.to_string());
16 })
17 .unwrap();
18
19 let expected = Set::from_iter(expected.into_iter().cloned().map(str::to_owned));
20 assert_eq!(unused, expected);
21
22 value
23 }
24
25 #[derive(Debug, Deserialize)]
26 struct V {
27 used: (),
28 }
29
30 #[test]
test_readme()31 fn test_readme() {
32 #[derive(Debug, PartialEq, Deserialize)]
33 struct Package {
34 name: String,
35 dependencies: Map<String, Dependency>,
36 }
37
38 #[derive(Debug, PartialEq, Deserialize)]
39 struct Dependency {
40 version: String,
41 }
42
43 let json = r#"{
44 "name": "demo",
45 "dependencies": {
46 "serde": {
47 "version": "1.0",
48 "typo1": ""
49 }
50 },
51 "typo2": {
52 "inner": ""
53 },
54 "typo3": {}
55 }"#;
56
57 let ignored = &["dependencies.serde.typo1", "typo2", "typo3"];
58 let p: Package = assert_ignored(json, ignored);
59
60 let expected = Package {
61 name: "demo".to_owned(),
62 dependencies: {
63 let mut map = Map::new();
64 map.insert(
65 "serde".to_owned(),
66 Dependency {
67 version: "1.0".to_owned(),
68 },
69 );
70 map
71 },
72 };
73 assert_eq!(p, expected);
74 }
75
76 #[test]
test_int_key()77 fn test_int_key() {
78 #[derive(Debug, Deserialize)]
79 struct Test {
80 a: Map<usize, V>,
81 }
82
83 let json = r#"{
84 "a": {
85 "2": {
86 "used": null,
87 "unused": null
88 }
89 }
90 }"#;
91
92 let ignored = &["a.2.unused"];
93 assert_ignored::<Test>(json, ignored);
94 }
95
96 #[test]
test_newtype_key()97 fn test_newtype_key() {
98 type Test = Map<Key, V>;
99
100 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
101 struct Key(&'static str);
102
103 let json = r#"{
104 "k": {
105 "used": null,
106 "unused": null
107 }
108 }"#;
109
110 let ignored = &["k.unused"];
111 assert_ignored::<Test>(json, ignored);
112 }
113
114 #[test]
test_unit_variant_key()115 fn test_unit_variant_key() {
116 type Test = Map<Key, V>;
117
118 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
119 enum Key {
120 First,
121 Second,
122 }
123
124 let json = r#"{
125 "First": {
126 "used": null,
127 "unused": null
128 }
129 }"#;
130
131 let ignored = &["First.unused"];
132 assert_ignored::<Test>(json, ignored);
133 }
134