Added entry remove function.

This commit is contained in:
Jeff Baskin 2023-02-19 11:27:28 -05:00
parent 0ffb30d322
commit 691ab6a27e
1 changed files with 55 additions and 6 deletions

View File

@ -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<Self, DBError> {
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)]