test: add tests to sqlite_init_db function

This commit is contained in:
2025-10-16 15:28:19 +02:00
parent 7509bd2bdf
commit 6f39925fe3

View File

@@ -32,19 +32,53 @@ pub fn run(path: &path::Path) -> result::Result<(), FailedTo> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::fs;
use std::path::Path;
#[test] #[test]
fn init_db_should_create_tables_and_indexes_on_new_db() { 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. // 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<String> = 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<String> = 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] #[test]
fn init_db_should_be_idempotent_and_not_fail_on_existing_db() { 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. // 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] #[test]
fn init_db_should_fail_gracefully_on_invalid_path() { 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. // 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());
} }
} }