From cd886522eceda135e1282fcc5b9462f746971fff Mon Sep 17 00:00:00 2001 From: Gregory Ballantine Date: Thu, 1 Sep 2022 23:44:37 -0400 Subject: [PATCH] Added unit tests for the file locking function --- src/util/io.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/util/io.rs b/src/util/io.rs index ee6bd66..14c622c 100644 --- a/src/util/io.rs +++ b/src/util/io.rs @@ -8,9 +8,54 @@ pub fn is_file_locked(filepath: &str) -> bool { .expect("Failed to execute command"); let results = &String::from_utf8_lossy(&cmd.stdout); + println!("{}", results); if results.contains(filepath) { return true; } return false; } + +#[cfg(test)] +mod tests { + use std::fs; + use std::mem::drop; + use std::path::Path; + + use super::*; + + #[test] + fn file_should_not_be_locked() { + setup("test-not-locked.txt"); + assert!(!is_file_locked("test-not-locked.txt")); + teardown("test-not-locked.txt"); + } + + #[test] + fn file_should_be_locked() { + setup("test-locked.txt"); + let path = Path::new("test-locked.txt"); + match fs::File::open(&path) { + Err(e) => panic!("couldn't open {}: {}", "test-locked.txt", e), + Ok(_) => assert!(is_file_locked("test-locked.txt")), + }; + teardown("test-locked.txt"); + } + + // get things ready for our tests + fn setup(test_file: &str) { + let f = match fs::File::create(test_file) { + Ok(file) => file, + Err(e) => panic!("{:?}", e), + }; + drop(f); + } + + // clean up after running tests + fn teardown(test_file: &str) { + match fs::remove_file(test_file) { + Ok(_) => {}, + Err(e) => panic!("{:?}", e), + }; + } +}