From 6f6df06be2adc1841f4ff47184e68e6cc150b4c3 Mon Sep 17 00:00:00 2001 From: davidemazzocchi Date: Wed, 29 Oct 2025 12:04:01 +0100 Subject: [PATCH] wip: add test for thread safety --- 01.workspace/heave/src/str/catalog.rs | 1 + .../heave/src/tst/catalog_thread_safety.rs | 57 +++++++++++++++++++ 01.workspace/heave/src/tst/mod.rs | 1 + 3 files changed, 59 insertions(+) create mode 100644 01.workspace/heave/src/tst/catalog_thread_safety.rs diff --git a/01.workspace/heave/src/str/catalog.rs b/01.workspace/heave/src/str/catalog.rs index 85e7d38..b114f13 100644 --- a/01.workspace/heave/src/str/catalog.rs +++ b/01.workspace/heave/src/str/catalog.rs @@ -1,5 +1,6 @@ use crate::*; use std::collections::HashMap; +use std::ops::*; use std::sync::*; /// Represents a catalog of entities that can be persisted to a SQLite database. diff --git a/01.workspace/heave/src/tst/catalog_thread_safety.rs b/01.workspace/heave/src/tst/catalog_thread_safety.rs new file mode 100644 index 0000000..b08bf21 --- /dev/null +++ b/01.workspace/heave/src/tst/catalog_thread_safety.rs @@ -0,0 +1,57 @@ +#[cfg(test)] +mod tests { + use crate::*; + use std::sync::*; + use std::thread; + + #[test] + fn thread_safety_test() { + let db_path = "target/test_dbs/thread_safety_test.db"; + let path = std::path::Path::new(db_path); + if path.exists() { + std::fs::remove_file(path).unwrap(); + } + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + + let catalog = Arc::new(Catalog::new(db_path)); + catalog.init().unwrap(); + + let mut handles = vec![]; + for i in 0..10 { + let catalog = Arc::clone(&catalog); + let handle = thread::spawn(move || { + for j in 0..100 { + let item_id = format!("item-{}-{}", i, j); + let item = Item { + id: item_id.clone(), + subclass: Some("subclass".to_string()), + name: format!("Item {} {}", i, j), + price: (i * 100 + j), + sell_trend: 0, + in_stock: true, + ..Item::default() + }; + catalog.upsert(item).unwrap(); + } + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + let total_items = catalog.with_items(|items| Ok(items.len())).unwrap(); + assert_eq!(total_items, 1000); + + catalog.persist().unwrap(); + + let mut new_catalog = Catalog::new(db_path); + new_catalog.load_by_class::().unwrap(); + + let total_items_after_load = new_catalog.with_items(|items| Ok(items.len())).unwrap(); + assert_eq!(total_items_after_load, 1000); + + std::fs::remove_file(path).unwrap(); + } +} diff --git a/01.workspace/heave/src/tst/mod.rs b/01.workspace/heave/src/tst/mod.rs index 2ff9e1c..bbb7e32 100644 --- a/01.workspace/heave/src/tst/mod.rs +++ b/01.workspace/heave/src/tst/mod.rs @@ -10,6 +10,7 @@ pub mod catalog_load_by_filter; pub mod catalog_load_by_id; pub mod catalog_new; pub mod catalog_persist; +pub mod catalog_thread_safety; pub mod catalog_upsert; pub mod sqlite_init_db; pub mod sqlite_load_attributes;