From 691ab6a27e75d351223c7db60b41458cc166296d Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Sun, 19 Feb 2023 11:27:28 -0500 Subject: [PATCH] Added entry remove function. --- src/morethantext/cache.rs | 61 +++++++++++++++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/src/morethantext/cache.rs b/src/morethantext/cache.rs index f90ab6a..460c1e5 100644 --- a/src/morethantext/cache.rs +++ b/src/morethantext/cache.rs @@ -95,8 +95,7 @@ impl Entry { if Path::new(&filename).exists().await { return Err(DBError::new("entry already exists")); } else { - let filepath = Path::new(&filename); - match write(filepath, data.to_bytes()).await { + match write(&filename, data.to_bytes()).await { Ok(_) => (), Err(err) => { let mut error = DBError::new("failed to write"); @@ -113,8 +112,7 @@ impl Entry { } async fn get(filename: &str) -> Result { - let filepath = Path::new(filename); - let content = match read(filepath).await { + let content = match read(filename).await { Ok(text) => text, Err(err) => { let mut error = DBError::new("read error"); @@ -148,8 +146,7 @@ impl Entry { async fn update(&mut self, data: DataType) -> Result<(), DBError> { self.last_used.set(Instant::now()); - let filepath = Path::new(&self.filename); - match write(filepath, data.to_bytes()).await { + match write(&self.filename, data.to_bytes()).await { Ok(_) => (), Err(err) => { let mut error = DBError::new("write error"); @@ -160,6 +157,17 @@ impl Entry { self.data = data; Ok(()) } + + async fn remove(&self) -> Result<(), DBError> { + match remove_file(&self.filename).await { + Ok(_) => Ok(()), + Err(err) => { + let mut error = DBError::new("cannot remove"); + error.add_source(err); + Err(error) + } + } + } } struct Cache; @@ -508,6 +516,47 @@ mod entry { } } } + + #[async_std::test] + async fn delete() { + let dir = tempdir().unwrap(); + let filepath = dir.path().join("byebye"); + let filename = filepath.to_str().unwrap(); + let data = DataType::new("store").unwrap(); + let item = Entry::new(filename.to_string(), data.clone()) + .await + .unwrap(); + item.remove().await.unwrap(); + assert!(!filepath.exists(), "Entry file should be removed."); + } + + #[async_std::test] + async fn delete_bad_file() -> Result<(), DBError> { + let dir = tempdir().unwrap(); + let filepath = dir.path().join("itsnotthere"); + let filename = filepath.to_str().unwrap(); + let data = DataType::new("store").unwrap(); + let item = Entry::new(filename.to_string(), data.clone()) + .await + .unwrap(); + remove_file(filename).await.unwrap(); + match item.remove().await { + Ok(_) => Err(DBError::new("should have produced an error")), + Err(err) => { + assert_eq!(err.to_string(), "cannot remove"); + assert!(err.source().is_some(), "Error should have a source."); + assert!( + err.source() + .unwrap() + .to_string() + .contains("could not remove file"), + "Source Error Message: {}", + err.source().unwrap().to_string() + ); + Ok(()) + } + } + } } #[cfg(test)]