use schematics::async_utils::run; use schematics::symbols::file::File as FileSymbol; use schematics::symbols::Symbol; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}; fn get_dir(content: Option<&str>) -> TempDir { let tmp_dir = tempdir().expect("create temp dir"); if content.is_none() { return tmp_dir; } let file_path = tmp_dir.path().join("filename"); let mut tmp_file = File::create(file_path).expect("create temp file"); tmp_file .write_all(content.unwrap().as_bytes()) .expect("write temp file"); tmp_dir } fn get_symbol(path: &Path) -> FileSymbol { FileSymbol::new(path.join("filename"), "target content") } // Normal cases // Good #[test] fn already_reached() { let dir = get_dir(Some("target content")); let symbol = get_symbol(dir.path()); run(async { assert_eq!(symbol.target_reached().await.unwrap(), true); }) } // Bad #[test] fn wrong_prefix() { let dir = get_dir(Some("not target content")); let symbol = get_symbol(dir.path()); run(async { assert_eq!(symbol.target_reached().await.unwrap(), false); symbol.execute().await.unwrap(); assert_eq!(symbol.target_reached().await.unwrap(), true); }) } #[test] fn wrong_postfix() { let dir = get_dir(Some("target content not")); let symbol = get_symbol(dir.path()); run(async { assert_eq!(symbol.target_reached().await.unwrap(), false); symbol.execute().await.unwrap(); assert_eq!(symbol.target_reached().await.unwrap(), true); }) } #[test] fn empty_file() { let dir = get_dir(Some("")); let symbol = get_symbol(dir.path()); run(async { assert_eq!(symbol.target_reached().await.unwrap(), false); symbol.execute().await.unwrap(); assert_eq!(symbol.target_reached().await.unwrap(), true); }) } #[test] fn no_file() { let dir = get_dir(None); let symbol = get_symbol(dir.path()); run(async { assert_eq!(symbol.target_reached().await.unwrap(), false); symbol.execute().await.unwrap(); assert_eq!(symbol.target_reached().await.unwrap(), true); }) } // Exceptional cases #[test] fn may_not_read_file() { let symbol = FileSymbol::new(Path::new("/etc/shadow"), ""); run(async { assert_eq!(symbol.target_reached().await.is_err(), true); }) } #[test] fn may_not_create_file() { let symbol = get_symbol(Path::new("/proc/somefile")); run(async { // Could also return an error assert_eq!(symbol.target_reached().await.unwrap(), false); assert!(symbol.execute().await.is_err()); }) } #[test] fn directory_missing() { let symbol = get_symbol(Path::new("/nonexisting")); run(async { // Could also return an error assert_eq!(symbol.target_reached().await.unwrap(), false); assert!(symbol.execute().await.is_err()); }) }