messagebus/tests/test_shared.rs

93 lines
2.1 KiB
Rust
Raw Normal View History

2021-07-30 16:58:30 +04:00
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
2021-07-23 17:29:47 +04:00
use async_trait::async_trait;
2021-07-20 16:04:10 +04:00
use messagebus::{
derive::{Error as MbError, Message},
error, AsyncHandler, Bus, Message, MessageBounds,
2021-07-20 16:04:10 +04:00
};
use thiserror::Error;
2021-07-20 16:04:10 +04:00
#[derive(Debug, Error, MbError)]
enum Error {
#[error("Error({0})")]
Error(anyhow::Error),
}
impl<M: Message> From<error::Error<M>> for Error {
fn from(err: error::Error<M>) -> Self {
Self::Error(err.into())
}
}
2021-07-20 16:04:10 +04:00
#[derive(Debug, Clone, Message)]
struct Msg;
2021-07-20 16:04:10 +04:00
#[derive(Debug, Clone, serde_derive::Serialize, serde_derive::Deserialize, Message)]
#[message(clone, shared)]
struct SharedMsg<T: serde::Serialize + MessageBounds + Clone>(
2021-07-20 16:04:10 +04:00
#[serde(bound(deserialize = "T: serde::Deserialize<'de>"))] T,
);
2021-07-23 17:29:47 +04:00
struct TmpReceiverContext {
sync1: AtomicBool,
sync2: AtomicBool,
}
struct TmpReceiver {
ctx: Arc<TmpReceiverContext>,
}
#[async_trait]
2021-07-23 17:29:47 +04:00
impl AsyncHandler<SharedMsg<f32>> for TmpReceiver {
type Error = Error;
type Response = ();
2021-07-30 16:58:30 +04:00
async fn handle(
&self,
_msg: SharedMsg<f32>,
_bus: &Bus,
) -> Result<Self::Response, Self::Error> {
2021-07-23 17:29:47 +04:00
self.ctx.sync1.store(true, Ordering::Relaxed);
2021-07-20 16:04:10 +04:00
Ok(())
}
}
#[async_trait]
2021-07-23 17:29:47 +04:00
impl AsyncHandler<Msg> for TmpReceiver {
2021-07-20 16:04:10 +04:00
type Error = Error;
type Response = ();
2021-07-23 17:29:47 +04:00
async fn handle(&self, _msg: Msg, _bus: &Bus) -> Result<Self::Response, Self::Error> {
self.ctx.sync2.store(false, Ordering::Relaxed);
Ok(())
}
}
2021-07-23 17:29:47 +04:00
#[tokio::test]
async fn test_shared() {
let ctx = Arc::new(TmpReceiverContext {
2021-07-30 16:58:30 +04:00
sync1: AtomicBool::new(false),
2021-07-23 17:29:47 +04:00
sync2: AtomicBool::new(false),
});
let (b, poller) = Bus::build()
2021-07-23 17:29:47 +04:00
.register(TmpReceiver { ctx: ctx.clone() })
2021-07-20 16:04:10 +04:00
.subscribe_async::<Msg>(8, Default::default())
.subscribe_async::<SharedMsg<f32>>(8, Default::default())
.done()
.build();
2021-07-20 16:04:10 +04:00
b.send_one(Msg).await.unwrap();
b.send_one(SharedMsg(0.0f32)).await.unwrap();
b.flush().await;
b.close().await;
poller.await;
2021-07-23 17:29:47 +04:00
assert_eq!(ctx.sync1.load(Ordering::Relaxed), true);
assert_eq!(ctx.sync2.load(Ordering::Relaxed), false);
}