From f2c6c3fe8d3aa5848c05f603b0d64b5e2b3bd99f Mon Sep 17 00:00:00 2001 From: Blake Griffith Date: Tue, 22 Oct 2024 17:55:05 -0400 Subject: [PATCH] Add tests for SharedCore methods and events --- src/replication/mod.rs | 112 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/src/replication/mod.rs b/src/replication/mod.rs index 8c29ea0..a32e3c3 100644 --- a/src/replication/mod.rs +++ b/src/replication/mod.rs @@ -194,3 +194,115 @@ impl CoreMethods for SharedCore { } } } + +#[cfg(test)] +mod tests { + use events::{Get, Have}; + + use super::*; + + #[async_std::test] + async fn shared_core_methods() -> Result<(), CoreMethodsError> { + let core = crate::core::tests::create_hypercore_with_data(0).await?; + let core = SharedCore::from(core); + + let info = core.info().await; + assert_eq!( + info, + crate::core::Info { + length: 0, + byte_length: 0, + contiguous_length: 0, + fork: 0, + writeable: true, + } + ); + + // key_pair is random, nothing to test here + let _kp = core.key_pair().await; + + assert_eq!(core.has(0).await, false); + assert_eq!(core.get(0).await?, None); + let res = core.append(b"foo").await?; + assert_eq!( + res, + AppendOutcome { + length: 1, + byte_length: 3 + } + ); + assert_eq!(core.has(0).await, true); + assert_eq!(core.get(0).await?, Some(b"foo".into())); + let res = core.append_batch([b"hello", b"world"]).await?; + assert_eq!( + res, + AppendOutcome { + length: 3, + byte_length: 13 + } + ); + assert_eq!(core.has(2).await, true); + assert_eq!(core.get(2).await?, Some(b"world".into())); + Ok(()) + } + + #[async_std::test] + async fn test_events() -> Result<(), CoreMethodsError> { + let core = crate::core::tests::create_hypercore_with_data(0).await?; + let core = SharedCore::from(core); + + // Check that appending data emits a DataUpgrade and Have event + + let mut rx = core.event_subscribe().await; + let handle = async_std::task::spawn(async move { + let mut out = vec![]; + loop { + if out.len() == 2 { + return (out, rx); + } + if let Ok(evt) = rx.recv().await { + out.push(evt); + } + } + }); + core.append(b"foo").await?; + let (res, mut rx) = handle.await; + assert!(matches!(res[0], Event::DataUpgrade(_))); + assert!(matches!( + res[1], + Event::Have(Have { + start: 0, + length: 1, + drop: false + }) + )); + // no messages in queue + assert!(rx.is_empty()); + + // Check that Hypercore::get for missing data emits a Get event + + let handle = async_std::task::spawn(async move { + let mut out = vec![]; + loop { + if out.len() == 1 { + return (out, rx); + } + if let Ok(evt) = rx.recv().await { + out.push(evt); + } + } + }); + assert_eq!(core.get(1).await?, None); + let (res, rx) = handle.await; + assert!(matches!( + res[0], + Event::Get(Get { + index: 1, + get_result: _ + }) + )); + // no messages in queue + assert!(rx.is_empty()); + Ok(()) + } +}