data_alchemist_json/
writer.rs1use std::io::Error;
2
3use data_alchemist::writer::{OutputSink, OutputWriter};
4
5pub struct JsonWriter;
6
7pub struct JsonProperties {}
8
9impl<T> OutputWriter<T> for JsonWriter where T: serde::Serialize {
10 type Properties = JsonProperties;
11
12 fn write(data: T, sink: &dyn OutputSink, _: Self::Properties) -> Result<(), Error> {
13 let serialized = serde_json::to_vec(&data)?;
14 sink.write_data(&serialized)
15 }
16}
17
18
19#[cfg(test)]
20mod test {
21 use mockall::mock;
22 use mockall::predicate::eq;
23 use serde::Serialize;
24
25 use super::*;
26
27 mock! {
28 pub OutputSink {}
29
30 impl OutputSink for OutputSink {
31 fn write_data(&self, data: &[u8]) -> Result<(), Error>;
32 }
33 }
34
35 #[derive(Serialize, Debug, PartialEq)]
36 struct TestStruct {
37 name: String,
38 age: u32,
39 }
40
41 #[test]
42 fn given_valid_struct_should_serialize_and_write() {
43 let test_data = TestStruct {
45 name: "Alice".to_string(),
46 age: 30,
47 };
48 let expected_json = serde_json::to_vec(&test_data).unwrap();
49
50 let mut mock_sink = MockOutputSink::new();
51 mock_sink.expect_write_data()
52 .with(eq(expected_json.clone())) .times(1)
54 .returning(|_| Ok(()));
55
56 let result = JsonWriter::write(test_data, &mut mock_sink, JsonProperties {});
58
59 assert!(result.is_ok());
61 }
62
63 #[test]
64 fn given_sink_write_error_should_return_error() {
65 let test_data = TestStruct {
67 name: "Bob".to_string(),
68 age: 42,
69 };
70
71 let mut mock_sink = MockOutputSink::new();
72 mock_sink.expect_write_data()
73 .times(1)
74 .returning(|_| Err(std::io::Error::from(std::io::ErrorKind::Other)));
75
76 let result = JsonWriter::write(test_data, &mut mock_sink, JsonProperties {});
78
79 assert!(result.is_err());
81 }
82}