use std::{
io::{self, Write},
sync::{mpsc, Arc, Mutex},
time::Duration,
};
use pretty_assertions::assert_eq;
use super::{access_with_notice, NoticeState};
#[derive(Clone)]
struct Output {
bytes: Arc<Mutex<Vec<u8>>>,
flushed: mpsc::Sender<()>,
}
impl Write for Output {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.bytes.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
let _ = self.flushed.send(());
Ok(())
}
}
fn leaked_notice(state: NoticeState) -> &'static Mutex<NoticeState> {
Box::leak(Box::new(Mutex::new(state)))
}
#[test]
fn notice_prints_once_only_for_slow_startup_keyring_access() {
let notice = leaked_notice(NoticeState::Pending);
let (flushed, flushes) = mpsc::channel();
let output = Output {
bytes: Arc::default(),
flushed,
};
let never = Duration::from_secs(3600);
assert_eq!(access_with_notice(notice, never, output.clone(), || 1), 1);
assert_eq!(output.bytes.lock().unwrap().len(), 0);
let slow = || flushes.recv().unwrap();
access_with_notice(notice, Duration::ZERO, output.clone(), slow);
let first_notice = output.bytes.lock().unwrap().clone();
assert!(!first_notice.is_empty());
access_with_notice(notice, Duration::ZERO, output.clone(), || ());
*notice.lock().unwrap() = NoticeState::Disabled;
access_with_notice(notice, Duration::ZERO, output.clone(), || ());
assert_eq!(*output.bytes.lock().unwrap(), first_notice);
assert!(flushes.try_recv().is_err());
}