use std::time::Duration;
#[cfg(feature = "stream")]
use futures_util::StreamExt;
use see::{error::RecvError, sync::channel};
#[compio::test]
async fn basic_send_recv() {
let (tx, mut rx) = channel(0);
let _keep_alive = tx.clone();
assert_eq!(*rx.borrow(), 0);
let sender_handle = compio::runtime::spawn(async move {
compio::time::sleep(Duration::from_millis(20)).await;
assert!(tx.send(42).is_ok());
});
assert!(rx.changed().await.is_ok());
let guard = rx.borrow_and_update();
assert!(guard.has_changed());
assert_eq!(*guard, 42);
sender_handle.await.unwrap();
}
#[compio::test]
async fn sender_dropped() {
let (tx, rx) = channel("live");
drop(tx);
let result = rx.changed().await;
assert!(matches!(result, Err(RecvError::ChannelClosed)));
}
#[compio::test]
async fn all_receivers_dropped() {
let (tx, rx) = channel(100);
assert!(!tx.is_closed());
let tx_clone = tx.clone();
let closed_handle = compio::runtime::spawn(async move {
tx_clone.closed().await;
});
drop(rx);
closed_handle.await.unwrap();
assert!(tx.is_closed());
assert!(tx.send(200).is_err());
}
#[compio::test]
#[cfg(feature = "stream")]
async fn sync_stream_basic() {
let (tx, rx) = channel(10);
let mut stream = rx.into_stream();
let value = stream.next().await;
assert_eq!(value, Some(10));
tx.send(20).unwrap();
let value = stream.next().await;
assert_eq!(value, Some(20));
drop(tx);
let value = stream.next().await;
assert_eq!(value, None);
}
#[compio::test]
#[cfg(feature = "stream")]
async fn sync_stream_from_changes() {
let (tx, rx) = channel("initial");
let mut stream = rx.into_stream();
tx.send("updated").unwrap();
let value = stream.next().await;
assert_eq!(value, Some("updated"));
drop(tx);
let value = stream.next().await;
assert_eq!(value, None);
}