aboutsummaryrefslogtreecommitdiff
path: root/helix-event/src/test.rs
diff options
context:
space:
mode:
authorPascal Kuthe2023-11-30 23:03:26 +0000
committerBlaž Hrastnik2024-01-23 02:20:19 +0000
commit13ed4f6c4748019787d24c2b686d417b71604242 (patch)
tree8263b77ee05a22dfc85410345069efb3668b1877 /helix-event/src/test.rs
parent7d7ace551cd58f0b6d65af7a6dfa8f896d94724a (diff)
Add hook/event system
Diffstat (limited to 'helix-event/src/test.rs')
-rw-r--r--helix-event/src/test.rs90
1 files changed, 90 insertions, 0 deletions
diff --git a/helix-event/src/test.rs b/helix-event/src/test.rs
new file mode 100644
index 00000000..a1283ada
--- /dev/null
+++ b/helix-event/src/test.rs
@@ -0,0 +1,90 @@
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use parking_lot::Mutex;
+
+use crate::{dispatch, events, register_dynamic_hook, register_event, register_hook};
+#[test]
+fn smoke_test() {
+ events! {
+ Event1 { content: String }
+ Event2 { content: usize }
+ }
+ register_event::<Event1>();
+ register_event::<Event2>();
+
+ // setup hooks
+ let res1: Arc<Mutex<String>> = Arc::default();
+ let acc = Arc::clone(&res1);
+ register_hook!(move |event: &mut Event1| {
+ acc.lock().push_str(&event.content);
+ Ok(())
+ });
+ let res2: Arc<AtomicUsize> = Arc::default();
+ let acc = Arc::clone(&res2);
+ register_hook!(move |event: &mut Event2| {
+ acc.fetch_add(event.content, Ordering::Relaxed);
+ Ok(())
+ });
+
+ // triggers events
+ let thread = std::thread::spawn(|| {
+ for i in 0..1000 {
+ dispatch(Event2 { content: i });
+ }
+ });
+ std::thread::sleep(Duration::from_millis(1));
+ dispatch(Event1 {
+ content: "foo".to_owned(),
+ });
+ dispatch(Event2 { content: 42 });
+ dispatch(Event1 {
+ content: "bar".to_owned(),
+ });
+ dispatch(Event1 {
+ content: "hello world".to_owned(),
+ });
+ thread.join().unwrap();
+
+ // check output
+ assert_eq!(&**res1.lock(), "foobarhello world");
+ assert_eq!(
+ res2.load(Ordering::Relaxed),
+ 42 + (0..1000usize).sum::<usize>()
+ );
+}
+
+#[test]
+fn dynamic() {
+ events! {
+ Event3 {}
+ Event4 { count: usize }
+ };
+ register_event::<Event3>();
+ register_event::<Event4>();
+
+ let count = Arc::new(AtomicUsize::new(0));
+ let count1 = count.clone();
+ let count2 = count.clone();
+ register_dynamic_hook(
+ move || {
+ count1.fetch_add(2, Ordering::Relaxed);
+ Ok(())
+ },
+ "Event3",
+ )
+ .unwrap();
+ register_dynamic_hook(
+ move || {
+ count2.fetch_add(3, Ordering::Relaxed);
+ Ok(())
+ },
+ "Event4",
+ )
+ .unwrap();
+ dispatch(Event3 {});
+ dispatch(Event4 { count: 0 });
+ dispatch(Event3 {});
+ assert_eq!(count.load(Ordering::Relaxed), 7)
+}