From 49b0eaf2ec402fc0da09bce990e90783e79eb1dd Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Tue, 18 Jul 2023 11:44:49 -0400 Subject: [PATCH] Made sure that cache did not over write itself. --- src/morethantext/cache.rs | 45 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/src/morethantext/cache.rs b/src/morethantext/cache.rs index de536bb..33c189c 100644 --- a/src/morethantext/cache.rs +++ b/src/morethantext/cache.rs @@ -99,6 +99,18 @@ impl Cache { output } + fn next_id(&mut self) -> String { + let mut id: String; + loop { + id = self.ids.next().unwrap(); + match self.get(&id) { + FromCache::Error(_) => break, + _ => (), + } + } + id + } + pub async fn listen(&mut self, listener: Receiver) { loop { match listener.recv().await.unwrap() { @@ -132,7 +144,7 @@ impl Cache { } }; for name in data.list() { - let id = self.ids.next().unwrap(); + let id = self.next_id(); match store.add_by_id(name, &id) { Ok(_) => { self.data.insert(id, FromCache::DB(Database::new())); @@ -244,6 +256,37 @@ mod engine { ), } } + + #[async_std::test] + async fn ids_are_not_overwritten() { + let ids = ["first", "first", "second"]; + let names = ["barney", "fred"]; + let dir = tempdir().unwrap(); + let mut cache = Cache::with_ids(dir.path(), ids).await; + let mut store1 = Store::new(); + store1.add(names[0]).unwrap(); + let mut store2 = Store::new(); + store2.add(names[1]).unwrap(); + cache.commit(store1); + cache.commit(store2); + assert_eq!( + cache.data.len(), + 3, + "cache.data had the following entries {:?}", + cache.data.keys() + ); + } + + #[async_std::test] + async fn no_duplicate_ids() { + let ids = ["one", "two"]; + let dir = tempdir().unwrap(); + let mut cache = Cache::with_ids(dir.path(), ids).await; + cache + .data + .insert(ids[0].to_string(), FromCache::DB(Database::new())); + assert_eq!(cache.next_id(), ids[1]); + } } #[cfg(test)]