From 6f39925fe3b915c24facad5fb63d630e8f3df4ec Mon Sep 17 00:00:00 2001 From: davidemazzocchi Date: Thu, 16 Oct 2025 15:28:19 +0200 Subject: [PATCH] test: add tests to sqlite_init_db function --- 01.workspace/heave/src/fun/sqlite_init_db.rs | 40 ++++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/01.workspace/heave/src/fun/sqlite_init_db.rs b/01.workspace/heave/src/fun/sqlite_init_db.rs index 54a0165..a04c62a 100644 --- a/01.workspace/heave/src/fun/sqlite_init_db.rs +++ b/01.workspace/heave/src/fun/sqlite_init_db.rs @@ -32,19 +32,53 @@ pub fn run(path: &path::Path) -> result::Result<(), FailedTo> { #[cfg(test)] mod tests { use super::*; + use std::fs; + use std::path::Path; #[test] fn init_db_should_create_tables_and_indexes_on_new_db() { // This test verifies that a new database is correctly initialized with the necessary tables ('entity', 'attribute') and indexes. - todo!(); + let db_path = Path::new("test_new.db"); + let _ = fs::remove_file(db_path); // Ensure the file doesn't exist + assert!(run(db_path).is_ok()); + let conn = Connection::open(db_path).unwrap(); + let mut stmt = conn + .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name IN ('entity', 'attribute')") + .unwrap(); + let tables: Vec = stmt + .query_map([], |row| row.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + assert_eq!(tables.len(), 2); + assert!(tables.contains(&"entity".to_string())); + assert!(tables.contains(&"attribute".to_string())); + let mut stmt = conn + .prepare("SELECT name FROM sqlite_master WHERE type='index' AND name IN ('entity_class', 'attribute_id')") + .unwrap(); + let indexes: Vec = stmt + .query_map([], |row| row.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + assert_eq!(indexes.len(), 2); + assert!(indexes.contains(&"entity_class".to_string())); + assert!(indexes.contains(&"attribute_id".to_string())); + let _ = fs::remove_file(db_path); } #[test] fn init_db_should_be_idempotent_and_not_fail_on_existing_db() { // This test ensures that initializing an already existing and initialized database does not cause errors. - todo!(); + let db_path = Path::new("test_idempotent.db"); + let _ = fs::remove_file(db_path); + assert!(run(db_path).is_ok()); + assert!(run(db_path).is_ok()); + let _ = fs::remove_file(db_path); } #[test] fn init_db_should_fail_gracefully_on_invalid_path() { // This test checks that the function returns an error when provided with an invalid or inaccessible file path. - todo!(); + // An invalid path, like a directory, should cause an error + let invalid_path = Path::new("/"); + assert!(run(invalid_path).is_err()); } }