batch_mode_json/
write_json_to_file.rs

1// ---------------- [ File: src/write_json_to_file.rs ]
2crate::ix!();
3
4/// Writes serialized JSON content to a file asynchronously.
5///
6/// # Arguments
7/// * `target_path` - A reference to the path where the file will be written.
8/// * `serialized_json` - The JSON content as a string to write to the file.
9///
10/// # Returns
11/// * `Result<(), io::Error>` - `Ok(())` if the write succeeds, or an `io::Error` otherwise.
12///
13/// # Errors
14/// * Returns an `io::Error` if file creation, writing, or flushing fails.
15pub 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    // Create or overwrite the target file
21    let mut target_file = File::create(target_path).await?;
22
23    // Write the serialized JSON content to the file
24    target_file.write_all(serialized_json.as_bytes()).await?;
25
26    // Ensure all data is written and flushed to the disk
27    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        // Create a temporary file path
41        let temp_path = PathBuf::from("test_output.json");
42
43        // JSON content to write
44        let json_content = r#"{"key": "value"}"#;
45
46        // Write to file
47        let result = write_to_file(&temp_path, json_content).await;
48        assert!(result.is_ok());
49
50        // Read back the file content to verify
51        let written_content = fs::read_to_string(&temp_path).await.unwrap();
52        assert_eq!(written_content, json_content);
53
54        // Cleanup
55        fs::remove_file(temp_path).await.unwrap();
56    }
57
58    #[tokio::test]
59    async fn test_write_to_file_invalid_path() {
60        // Use an invalid path
61        let invalid_path = PathBuf::from("/invalid_path/test_output.json");
62        let json_content = r#"{"key": "value"}"#;
63
64        // Attempt to write to the file
65        let result = write_to_file(&invalid_path, json_content).await;
66
67        // Verify the result is an error
68        assert!(result.is_err());
69    }
70}