Skip to content

Commit

Permalink
Add tests for SharedCore methods and events
Browse files Browse the repository at this point in the history
  • Loading branch information
cowlicks committed Oct 22, 2024
1 parent 26d1fba commit f2c6c3f
Showing 1 changed file with 112 additions and 0 deletions.
112 changes: 112 additions & 0 deletions src/replication/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
}

0 comments on commit f2c6c3f

Please sign in to comment.