Skip to content

Commit

Permalink
update both async functions to use database error, update test temp d…
Browse files Browse the repository at this point in the history
…b unit test
  • Loading branch information
giuseppe-g-gelardi committed Dec 1, 2024
1 parent 2ea6719 commit d9ce3e9
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 26 deletions.
33 changes: 19 additions & 14 deletions src/cargobase/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ impl Database {
}

#[cfg(feature = "async")]
pub(crate) async fn save_to_file_async(&self) -> Result<(), std::io::Error> {
// pub(crate) async fn save_to_file_async(&self) -> Result<(), std::io::Error> {
pub(crate) async fn save_to_file_async(&self) -> Result<(), DatabaseError> {
let json_data = serde_json::to_string_pretty(&self)?;
tokio::fs::write(&self.file_name, json_data).await?;
tracing::info!("Database saved to file: {}", self.file_name);
Expand All @@ -114,7 +115,8 @@ impl Database {
}

#[cfg(feature = "async")]
pub(crate) async fn load_from_file_async(file_name: &str) -> Result<(), std::io::Error> {
// pub(crate) async fn load_from_file_async(file_name: &str) -> Result<(), std::io::Error> {
pub(crate) async fn load_from_file_async(file_name: &str) -> Result<(), DatabaseError> {
let json_data = tokio::fs::read_to_string(file_name).await?;
let db: Database = serde_json::from_str(&json_data)?;
tracing::info!("Database loaded from file: {}", file_name); // needed?
Expand Down Expand Up @@ -291,43 +293,46 @@ mod tests {
#[cfg(feature = "async")]
#[tokio::test]
async fn test_save_to_file_async() {
use tempfile::NamedTempFile;

let temp_file = NamedTempFile::new().expect("Failed to create a temporary file");
let db_path = temp_file.path().to_str().unwrap().to_string();

let db = Database {
name: "test_db".to_string(),
file_name: "test_db.json".to_string(),
file_name: db_path.to_clone(),
tables: vec![],
};

// Ensure the async save works
db.save_to_file_async()
.await
.expect("Failed to save database");
assert!(std::path::Path::new("test_db.json").exists());

// Cleanup
std::fs::remove_file("test_db.json").ok();
let loaded_db = Database::load_from_file(&file_path).expect("Failed to load database");
assert_eq!(db, loaded_db);
}

#[cfg(feature = "async")]
#[tokio::test]
async fn test_load_from_file_async() {
use tempfile::NamedTempFile;

let temp_file = NamedTempFile::new().expect("Failed to create a temporary file");
let db_path = temp_file.path().to_str().unwrap().to_string();

let db = Database {
name: "test_db".to_string(),
file_name: "test_db.json".to_string(),
file_name: db_path.to_string(),
tables: vec![],
};

// Save and then load
db.save_to_file_async()
.await
.expect("Failed to save database");

let loaded_db = Database::load_from_file_async("test_db.json")
.await
.expect("Failed to load database");

// Assert that the loaded database matches the original
assert_eq!(db, loaded_db);

// Cleanup
std::fs::remove_file("test_db.json").ok();
}
}
7 changes: 7 additions & 0 deletions src/cargobase/errors/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,11 @@ pub enum DatabaseError {

#[error("")] // could expand to specify serialization/deserialization error
JSONError(#[from] serde_json::Error),

#[error("IO error: `{0}`")]
Io(#[from] std::io::Error),

#[cfg(feature = "async")]
#[error("Tokio IO error: `{0}`")]
TokioIo(#[from] tokio::io::Error),
}
42 changes: 30 additions & 12 deletions src/cargobase/util.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
// use tracing_subscriber::fmt::Subscriber;

use super::{Columns, Database, Table};

Expand All @@ -25,14 +24,33 @@ pub fn setup_temp_db() -> Database {
db
}

// pub fn init_tracing() {
// // let subscriber = fmt::Subscriber::builder()
// let subscriber = Subscriber::builder()
// .with_max_level(tracing::Level::WARN)
// .finish();
// /*
// example implementation:
// info!(target: "cargobase", "Database `{name}` already exists, loading...");
// */
// tracing::subscriber::set_global_default(subscriber).expect("Failed to set subscriber");
// }
#[cfg(test)]
mod tests {
use super::*;
use std::fs;

#[test]
fn test_setup_temp_db() {
let db = setup_temp_db();
assert_eq!(db.tables.len(), 1);
assert_eq!(db.tables[0].name, "TestTable");
}

#[test]
fn test_temp_file_cleanup() {
// Create a temporary database
let temp_file = NamedTempFile::new().expect("Failed to create a temporary file");
let db_path = temp_file.path().to_str().unwrap().to_string();

// Drop the file explicitly by dropping the `NamedTempFile` instance
drop(temp_file);

// Verify that the temporary file is removed
let file_exists = fs::metadata(&db_path).is_ok();
assert!(
!file_exists,
"Temporary file `{}` should have been removed after being dropped",
db_path
);
}
}

0 comments on commit d9ce3e9

Please sign in to comment.