#![allow(dead_code)]
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tiny_pubsub::Token;
pub fn unique_string() -> String {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed) + 1;
format!("my unique String number {n}")
}
#[derive(Clone, Default)]
pub struct Spy {
calls: Rc<RefCell<Vec<(String, String)>>>,
}
impl Spy {
pub fn new() -> Self {
Spy::default()
}
pub fn subscriber(&self) -> impl Fn(&str, &String) + 'static {
let calls = self.calls.clone();
move |message: &str, data: &String| {
calls.borrow_mut().push((message.to_string(), data.clone()));
}
}
pub fn call_count(&self) -> usize {
self.calls.borrow().len()
}
pub fn called(&self) -> bool {
self.call_count() > 0
}
pub fn called_once(&self) -> bool {
self.call_count() == 1
}
pub fn called_with_message(&self, message: &str) -> bool {
self.calls.borrow().iter().any(|(m, _)| m == message)
}
pub fn called_with(&self, message: &str, data: &str) -> bool {
self.calls
.borrow()
.iter()
.any(|(m, d)| m == message && d == data)
}
pub fn calls(&self) -> Vec<(String, String)> {
self.calls.borrow().clone()
}
}
pub fn assert_all_tokens_different(tokens: &[Token]) {
assert!(!tokens.is_empty(), "token list must be non-empty");
for (j, a) in tokens.iter().enumerate() {
for b in &tokens[j + 1..] {
assert!(a != b, "tokens must all differ: {a} == {b}");
}
}
}