1use std::{
2 fmt::Debug,
3 fs::File,
4 io::{Read, Write},
5 path::Path,
6};
7
8use serde::{de::DeserializeOwned, Serialize};
9
10pub fn assert_equal_to_golden<
11 T: Serialize + DeserializeOwned + Debug + PartialEq,
12 P: AsRef<Path>,
13>(
14 file_path: P,
15 data: &T,
16) {
17 let file_path = file_path.as_ref();
18 let ci_mode = std::env::var("CI").is_ok();
19
20 if !ci_mode {
21 let file_exists = std::fs::metadata(file_path).is_ok();
22 if !file_exists {
23 if let Some(parent_dir) = file_path.parent() {
24 std::fs::create_dir_all(parent_dir).expect("failed to create directory");
25 }
26 write_to_json_file(data, file_path).expect("failed to write data");
27 return;
28 }
29 }
30
31 let expected_data: T = read_from_json_file(file_path).expect("failed to read the data");
32 assert_eq!(data, &expected_data);
33}
34
35fn write_to_json_file<T: Serialize>(data: &T, file_path: &Path) -> std::io::Result<()> {
36 let json_data = serde_json::to_string_pretty(data).expect("failed to serialize data to JSON");
37
38 let mut file = File::create(file_path)?;
39 file.write_all(json_data.as_bytes())
40}
41
42fn read_from_json_file<T: DeserializeOwned>(file_path: &Path) -> std::io::Result<T> {
43 let mut file = File::open(file_path)?;
44 let mut json_data = String::new();
45 file.read_to_string(&mut json_data)?;
46
47 let deserialized_data: T = serde_json::from_str(&json_data)?;
48 Ok(deserialized_data)
49}
50
51pub fn assert_equal_to_string_golden<P: AsRef<Path>>(file_path: P, data: &String) {
52 let file_path = file_path.as_ref();
53 let ci_mode = std::env::var("CI").is_ok();
54
55 if !ci_mode {
56 let file_exists = std::fs::metadata(file_path).is_ok();
57 if !file_exists {
58 if let Some(parent_dir) = file_path.parent() {
59 std::fs::create_dir_all(parent_dir).expect("failed to create directory");
60 }
61 let mut file = File::create(file_path).expect("failed to create file");
62 file.write_all(data.as_bytes())
63 .expect("failed to write data");
64 return;
65 }
66 }
67
68 let mut file = File::open(file_path).expect("failed to open file");
69 let mut expected_data = String::new();
70 file.read_to_string(&mut expected_data)
71 .expect("failed to read to string");
72
73 assert_eq!(data, &expected_data);
74}