data_alchemist_json/
reader.rs

1use std::io::Error;
2
3use serde::de::DeserializeOwned;
4
5use data_alchemist::reader::{InputReader, InputSource};
6
7pub struct JsonReader;
8
9pub struct JsonProperties {}
10
11impl<T> InputReader<T> for JsonReader where T: DeserializeOwned {
12    type Properties = JsonProperties;
13
14    fn read(source: &dyn InputSource, _: Self::Properties) -> Result<T, Error> {
15        let raw_data = source.get_data()?;
16        let deserialized: T = serde_json::from_slice(&raw_data)?;
17        Ok(deserialized)
18    }
19}
20
21
22#[cfg(test)]
23mod test {
24    use mockall::*;
25    use mockall::predicate::*;
26    use serde_json::{json, Value};
27
28    use super::*;
29
30    mock! {
31        #[derive(Debug, Copy)]
32        pub InputSource {}
33
34        impl InputSource for InputSource {
35            fn get_data(&self) -> Result<Vec<u8>, Error>;
36        }
37    }
38
39    #[test]
40    fn given_valid_input_successful_deserializes() {
41        // given
42        let json_value = json!({"var1": "Alice", "var2": 30, "optional_var": "optional"});
43        let expected_output: TestStruct = json_value.to_owned().into();
44        let mut mock_source = MockInputSource::new();
45        mock_source.expect_get_data()
46            .times(1)
47            .returning(move || serde_json::to_vec(&json_value).map_err(|err| err.into()));
48
49        // when
50        let result: Result<TestStruct, Error> = JsonReader::read(&mock_source, JsonProperties {});
51
52        // then
53        assert!(result.is_ok());
54        assert_eq!(result.unwrap(), expected_output);
55    }
56
57    #[test]
58    fn given_unrecognized_var_should_fail() {
59        // given
60        let json_value = json!({"var1": "Alice", "var2": 30, "urecognized_var": 30, "optional_var": "optional"});
61        let mut mock_source = MockInputSource::new();
62        mock_source.expect_get_data()
63            .times(1)
64            .returning(move || serde_json::to_vec(&json_value).map_err(|err| err.into()));
65
66        // when
67        let result: Result<TestStruct, Error> = JsonReader::read(&mock_source, JsonProperties {});
68
69        // then
70        println!("{:?}", result.is_err());
71    }
72
73    #[test]
74    fn given_missing_required_field_should_fail() {
75        // given
76        let json_value = json!({"var2": 30, "optional_var": "optional"});
77        let mut mock_source = MockInputSource::new();
78        mock_source.expect_get_data()
79            .times(1)
80            .returning(move || serde_json::to_vec(&json_value).map_err(|err| err.into()));
81
82        // when
83        let result: Result<TestStruct, Error> = JsonReader::read(&mock_source, JsonProperties {});
84
85        // then
86        assert!(result.is_err());
87    }
88
89    #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
90    struct TestStruct {
91        var1: String,
92        var2: u32,
93        optional_var: Option<String>,
94    }
95
96    impl Into<Value> for TestStruct {
97        fn into(self) -> Value {
98            serde_json::to_value(self).unwrap()
99        }
100    }
101
102    impl From<Value> for TestStruct {
103        fn from(value: Value) -> Self {
104            serde_json::from_value(value).unwrap()
105        }
106    }
107}