batch_mode_json/
write_json_to_file.rs1crate::ix!();
3
4pub async fn write_to_file(target_path: impl AsRef<Path>, serialized_json: &str)
16 -> Result<(), io::Error>
17{
18 info!("writing some json content to the file {:?}", target_path.as_ref());
19
20 let mut target_file = File::create(target_path).await?;
22
23 target_file.write_all(serialized_json.as_bytes()).await?;
25
26 target_file.flush().await?;
28
29 Ok(())
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35 use tokio::fs;
36 use std::path::PathBuf;
37
38 #[tokio::test]
39 async fn test_write_to_file_success() {
40 let temp_path = PathBuf::from("test_output.json");
42
43 let json_content = r#"{"key": "value"}"#;
45
46 let result = write_to_file(&temp_path, json_content).await;
48 assert!(result.is_ok());
49
50 let written_content = fs::read_to_string(&temp_path).await.unwrap();
52 assert_eq!(written_content, json_content);
53
54 fs::remove_file(temp_path).await.unwrap();
56 }
57
58 #[tokio::test]
59 async fn test_write_to_file_invalid_path() {
60 let invalid_path = PathBuf::from("/invalid_path/test_output.json");
62 let json_content = r#"{"key": "value"}"#;
63
64 let result = write_to_file(&invalid_path, json_content).await;
66
67 assert!(result.is_err());
69 }
70}