#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use crate::actor::util::throttler::{Throttle, ThrottleCallback, Valve};
#[tokio::test]
async fn test_throttler() {
let callback_called = Arc::new(Mutex::new(false));
let callback_called_clone = Arc::clone(&callback_called);
let throttle = Throttle::new(
10,
Duration::from_millis(100),
ThrottleCallback::new(move |_| {
let callback_called = callback_called_clone.clone();
async move {
let mut called = callback_called.lock().await;
*called = true;
}
}),
)
.await;
assert_eq!(throttle.should_throttle(), Valve::Open);
assert_eq!(throttle.should_throttle(), Valve::Open);
for _ in 0..7 {
throttle.should_throttle();
}
assert_eq!(throttle.should_throttle(), Valve::Closing);
assert_eq!(throttle.should_throttle(), Valve::Closed);
tokio::time::sleep(Duration::from_millis(150)).await;
assert!(*callback_called.lock().await);
assert_eq!(throttle.should_throttle(), Valve::Open);
}
}