haddock_restraints/core/
utils.rs

1use std::fs::File;
2use std::io::Write;
3use std::path::Path;
4
5pub fn write_string_to_file(content: &str, file_path: &str) -> std::io::Result<()> {
6    let path = Path::new(file_path);
7
8    let mut file =
9        File::create(path).unwrap_or_else(|e| panic!("Could not create {}: {}", file_path, e));
10
11    file.write_all(content.as_bytes())
12        .unwrap_or_else(|e| panic!("Could not write file {}: {}", file_path, e));
13
14    Ok(())
15}
16
17#[cfg(test)]
18mod tests {
19    use super::*;
20    use std::fs;
21    use std::path::Path;
22
23    #[test]
24    fn test_write_string_to_file() {
25        let temp_file = "test_file.txt";
26        let test_content = "test";
27
28        // Clean up any existing test file
29        if Path::new(temp_file).exists() {
30            fs::remove_file(temp_file).expect("Failed to remove existing test file");
31        }
32
33        // Test the function
34        let result = write_string_to_file(test_content, temp_file);
35        assert!(result.is_ok());
36
37        // Verify content was written correctly
38        let read_content = fs::read_to_string(temp_file).expect("Failed to read test file");
39        assert_eq!(read_content, test_content);
40
41        // Clean up
42        fs::remove_file(temp_file).expect("Failed to clean up test file");
43    }
44
45    #[test]
46    fn test_write_string_to_nonexistent_directory() {
47        let invalid_path = "nonexistent_dir/test_file.txt";
48        let test_content = "Hello, world!";
49
50        // This should panic with our custom error message
51        let result = std::panic::catch_unwind(|| write_string_to_file(test_content, invalid_path));
52
53        assert!(result.is_err());
54    }
55}