#[cfg(test)]
mod test;
use aldrin::error::RunError;
use aldrin::Handle;
use aldrin_broker::{BrokerHandle, ConnectionError, ConnectionHandle};
use aldrin_core::channel::Disconnected;
use std::ops::{Deref, DerefMut};
use tokio::task::JoinHandle;
#[derive(Debug)]
pub struct TestBroker {
inner: crate::TestBroker,
join: Option<JoinHandle<()>>,
}
impl TestBroker {
pub fn new() -> Self {
let mut inner = crate::TestBroker::new();
Self {
join: Some(tokio::spawn(inner.take_broker().run())),
inner,
}
}
pub fn handle(&self) -> &BrokerHandle {
&self.inner
}
pub async fn join(&mut self) {
self.inner.shutdown().await;
self.join.take().expect("already joined").await.unwrap();
}
pub async fn join_idle(&mut self) {
self.inner.shutdown_idle().await;
self.join.take().expect("already joined").await.unwrap();
}
pub async fn add_client(&mut self) -> TestClient {
let inner = self.inner.add_client().await;
TestClient::new(inner)
}
}
impl Default for TestBroker {
fn default() -> Self {
Self::new()
}
}
impl Deref for TestBroker {
type Target = BrokerHandle;
fn deref(&self) -> &BrokerHandle {
&self.inner
}
}
impl DerefMut for TestBroker {
fn deref_mut(&mut self) -> &mut BrokerHandle {
&mut self.inner
}
}
#[derive(Debug)]
pub struct TestClient {
inner: crate::TestClient,
client: Option<JoinHandle<Result<(), RunError<Disconnected>>>>,
conn: Option<JoinHandle<Result<(), ConnectionError<Disconnected>>>>,
}
impl TestClient {
fn new(mut inner: crate::TestClient) -> Self {
Self {
client: Some(tokio::spawn(inner.take_client().run())),
conn: Some(tokio::spawn(inner.take_connection().run())),
inner,
}
}
pub fn handle(&self) -> &Handle {
&self.inner
}
pub fn connection(&self) -> &ConnectionHandle {
self.inner.connection()
}
pub async fn join(&mut self) {
self.inner.shutdown();
self.join_client().await;
self.join_connection().await;
}
async fn join_client(&mut self) {
self.client
.take()
.expect("client already joined")
.await
.unwrap()
.unwrap();
}
async fn join_connection(&mut self) {
self.conn
.take()
.expect("connection already joined")
.await
.unwrap()
.unwrap();
}
}
impl Deref for TestClient {
type Target = Handle;
fn deref(&self) -> &Handle {
&self.inner
}
}