workspacer_toml/
check_existence.rs1crate::ix!();
3
4impl CheckExistence for CargoToml {
5 type Error = CargoTomlError;
6
7 fn check_existence(&self) -> Result<(), Self::Error> {
8 let p = self.path();
9
10 if !p.exists() {
11 return Err(CargoTomlError::FileNotFound {
12 missing_file: p.to_path_buf(),
13 });
14 }
15
16 let meta = std::fs::metadata(&p)
18 .map_err(|e| CargoTomlError::ReadError { path: p.to_path_buf(), io: e.into() })?;
19 if !meta.is_file() {
20 return Err(CargoTomlError::FileIsNotAFile {
21 invalid_path: p.to_path_buf(),
22 });
23 }
24
25 Ok(())
26 }
27}
28
29#[cfg(test)]
30mod test_check_existence_trait {
31 use super::*; use std::path::PathBuf;
33 use tempfile::tempdir;
34 use std::fs::{File, create_dir};
35
36 #[tokio::test]
40 async fn check_existence_returns_ok_when_file_exists() {
41 let temp = tempdir().expect("Failed to create temp dir");
43
44 let file_path = temp.path().join("Cargo.toml");
46
47 File::create(&file_path).expect("Failed to create a test file");
49
50 let cargo_toml = CargoToml::new(file_path).await.expect("expected to build the Cargo.toml instance");
52
53 let result = cargo_toml.check_existence();
55 assert!(result.is_ok(), "Expected Ok when the file exists");
56 }
57
58 #[test]
59 fn check_existence_returns_error_when_file_missing() {
60 let missing_path = PathBuf::from("this_file_should_not_exist.toml");
61
62 let cargo_toml = CargoTomlBuilder::default()
63 .path(missing_path.clone())
64 .content(toml::Value::Table(toml::map::Map::new()))
65 .build()
66 .unwrap();
67
68 let result = cargo_toml.check_existence();
69 match result {
70 Err(CargoTomlError::FileNotFound { missing_file }) => {
71 assert_eq!(missing_file, missing_path);
72 }
73 other => {
74 panic!("Expected FileNotFound error; got {:?}", other);
75 }
76 }
77 }
78
79 #[test]
80 fn check_existence_returns_error_when_path_is_a_directory() {
81 let temp = tempdir().expect("Failed to create temp dir");
82
83 let dir_path = temp.path().join("some_dir");
85 create_dir(&dir_path).expect("Failed to create directory for test");
86
87 let cargo_toml = CargoTomlBuilder::default()
88 .path(dir_path.clone())
89 .content(toml::Value::Table(toml::map::Map::new()))
90 .build()
91 .unwrap();
92
93 let result = cargo_toml.check_existence();
94 match result {
95 Err(CargoTomlError::FileIsNotAFile { invalid_path }) => {
96 assert_eq!(invalid_path, dir_path);
97 }
98 other => {
99 panic!("Expected FileIsNotAFile error; got {:?}", other);
100 }
101 }
102 }
103}