|
1 | | -#[derive(Serialize, Deserialize, Clone)] |
| 1 | +#[derive(Deserialize, Serialize, Clone)] |
2 | 2 | pub struct Item { |
3 | 3 | pub domain: String, |
4 | | - pub directive: Vec<String>, |
| 4 | + pub directives: Vec<String>, |
5 | 5 | } |
6 | 6 |
|
7 | 7 | pub type Collection = Vec<Item>; |
8 | 8 |
|
| 9 | +pub trait ToJson { |
| 10 | + fn to_json(&self) -> String; |
| 11 | +} |
| 12 | + |
| 13 | +impl ToJson for Collection { |
| 14 | + fn to_json(&self) -> String { |
| 15 | + let mut json = "[".to_string(); |
| 16 | + |
| 17 | + for item in self { |
| 18 | + json.push_str(serde_json::to_string(&item).unwrap().as_str()); |
| 19 | + } |
| 20 | + |
| 21 | + json.push_str("]"); |
| 22 | + |
| 23 | + json |
| 24 | + } |
| 25 | +} |
| 26 | + |
9 | 27 | // ----- |
10 | 28 | // Tests |
11 | 29 | // ----- |
12 | 30 | #[cfg(test)] |
13 | 31 | mod item_test { |
| 32 | + use super::{Collection, Item, ToJson}; |
| 33 | + |
14 | 34 | #[test] |
15 | 35 | fn test_item_struct() { |
16 | 36 | let directives: Vec<String> = vec![String::from("connect-src"), String::from("script-src")]; |
17 | 37 |
|
18 | | - let item = super::Item { |
| 38 | + let item = Item { |
19 | 39 | domain: String::from("*.example.com"), |
20 | | - directive: directives, |
| 40 | + directives, |
21 | 41 | }; |
22 | 42 |
|
23 | 43 | assert_eq!(item.domain, "*.example.com"); |
24 | | - assert_eq!(item.directive[1], "script-src"); |
| 44 | + assert_eq!(item.directives[1], "script-src"); |
25 | 45 | } |
26 | 46 |
|
27 | 47 | #[test] |
28 | 48 | fn test_collection() { |
29 | 49 | let directives: Vec<String> = vec![String::from("connect-src"), String::from("script-src")]; |
30 | 50 |
|
31 | | - let item = super::Item { |
| 51 | + let item = Item { |
32 | 52 | domain: String::from("*.example.com"), |
33 | | - directive: directives, |
| 53 | + directives, |
34 | 54 | }; |
35 | 55 |
|
36 | | - let mut domains: super::Collection = vec![]; |
| 56 | + let mut domains: Collection = Collection::new(); |
37 | 57 | domains.push(item); |
38 | 58 |
|
39 | 59 | assert_eq!(domains[0].domain, "*.example.com"); |
40 | | - assert_eq!(domains[0].directive[1], "script-src"); |
| 60 | + assert_eq!(domains[0].directives[1], "script-src"); |
| 61 | + } |
| 62 | + |
| 63 | + #[test] |
| 64 | + fn test_to_json() { |
| 65 | + let directives: Vec<String> = vec![String::from("connect-src"), String::from("script-src")]; |
| 66 | + |
| 67 | + let item = super::Item { |
| 68 | + domain: String::from("*.example.com"), |
| 69 | + directives, |
| 70 | + }; |
| 71 | + |
| 72 | + let mut domains: Collection = Collection::new(); |
| 73 | + domains.push(item); |
| 74 | + |
| 75 | + assert_eq!( |
| 76 | + domains.to_json(), |
| 77 | + r#"[{"domain":"*.example.com","directives":["connect-src","script-src"]}]"# |
| 78 | + ); |
41 | 79 | } |
42 | 80 | } |
0 commit comments