1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
//! A tool for testing that ensures code parts are called as expected.
//!
//! By creating an instance of [`CallRecorder`],
//! it starts recording the calls to [`call`], and then [`CallRecorder::verify`] verifies that the calls to [`call`] are as expected.
//!
//! The pattern of expected calls specified in [`CallRecorder::verify`] uses [`Call`].
//!
//! ## Examples
//!
//! ```should_panic
//! use assert_call::{call, CallRecorder};
//!
//! let mut c = CallRecorder::new();
//!
//! call!("1");
//! call!("2");
//!
//! c.verify(["1", "3"]);
//! ```
//!
//! The above code panics and outputs the following message
//! because the call to [`call`] macro is different from what is specified in [`CallRecorder::verify`].
//!
//! ```txt
//! actual calls :
//! 1
//! * 2
//! (end)
//!
//! mismatch call
//! src\lib.rs:10
//! actual : 2
//! expect : 3
//! ```
use std::{cmp::min, collections::VecDeque, error::Error, fmt::Display};
use records::{Global, Local, Thread};
use yansi::{Condition, Paint};
pub mod records;
#[cfg(test)]
mod tests;
/// Record the call.
///
/// The argument is the call ID with the same format as [`std::format`].
///
/// # Examples
///
/// ```
/// use assert_call::call;
/// let c = assert_call::CallRecorder::new_local();
///
/// call!("1");
/// call!("{}-{}", 1, 2);
/// ```
#[macro_export]
macro_rules! call {
($($id:tt)*) => {
$crate::records::Records::push(::std::format!($($id)*), ::std::file!(), ::std::line!());
};
}
/// Records and verifies calls to [`call`].
pub struct CallRecorder<T: Thread = Global> {
thread: T,
}
impl CallRecorder {
/// Start recording [`call`] macro calls in all threads.
///
/// If there are other instances of `CallRecorder` created by this function,
/// wait until the other instances are dropped.
pub fn new() -> Self {
Self::new_raw()
}
}
impl CallRecorder<Local> {
/// Start recording [`call`] macro calls in current thread.
///
/// # Panics
///
/// Panics if an instance of `CallRecorder` created by `new_local` already exists in this thread.
pub fn new_local() -> Self {
Self::new_raw()
}
}
impl<T: Thread> CallRecorder<T> {
fn new_raw() -> Self {
Self { thread: T::init() }
}
/// Panic if [`call`] call does not match the expected pattern.
///
/// Calling this method clears the recorded [`call`] calls.
#[track_caller]
pub fn verify(&mut self, expect: impl ToCall) {
self.verify_with_msg(expect, "mismatch call");
}
/// Panic with specified message if [`call`] call does not match the expected pattern.
///
/// Calling this method clears the recorded [`call`] calls.
#[track_caller]
pub fn verify_with_msg(&mut self, expect: impl ToCall, msg: &str) {
match self.result_with_msg(expect, msg) {
Ok(_) => {}
Err(e) => {
if Condition::tty_and_color() {
panic!("{e:#}");
} else {
panic!("{e}")
}
}
}
}
/// Return `Err` with specified message if [`call`] call does not match the expected pattern.
///
/// Calling this method clears the recorded [`call`] calls.
fn result_with_msg(&mut self, expect: impl ToCall, msg: &str) -> Result<(), CallMismatchError> {
let expect: Call = expect.to_call();
let actual = self.thread.take_actual().0;
expect.verify(actual, msg)
}
}
impl<T: Thread> Default for CallRecorder<T> {
fn default() -> Self {
Self::new_raw()
}
}
impl<T: Thread> Drop for CallRecorder<T> {
fn drop(&mut self) {}
}
/// Pattern of expected [`call`] calls.
///
/// To create a value of this type, call a method of this type or use [`ToCall`].
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum Call {
Id(String),
Seq(VecDeque<Call>),
Par(Vec<Call>),
Any(Vec<Call>),
}
impl Call {
/// Create `Call` to represent a single [`call`] call.
///
/// # Examples
///
/// ```
/// use assert_call::{call, Call, CallRecorder};
///
/// let mut c = CallRecorder::new();
/// call!("1");
/// c.verify(Call::id("1"));
/// ```
pub fn id(id: impl Display) -> Self {
Self::Id(id.to_string())
}
/// Create `Call` to represent no [`call`] call.
///
/// # Examples
///
/// ```
/// use assert_call::{Call, CallRecorder};
///
/// let mut c = CallRecorder::new();
/// c.verify(Call::empty());
/// ```
pub fn empty() -> Self {
Self::Seq(VecDeque::new())
}
/// Create `Call` to represent all specified `Call`s will be called in sequence.
///
/// # Examples
///
/// ```
/// use assert_call::{call, Call, CallRecorder};
///
/// let mut c = CallRecorder::new();
/// call!("1");
/// call!("2");
/// c.verify(Call::seq(["1", "2"]));
/// ```
pub fn seq(p: impl IntoIterator<Item = impl ToCall>) -> Self {
Self::Seq(p.into_iter().map(|x| x.to_call()).collect())
}
/// Create `Call` to represent all specified `Call`s will be called in parallel.
///
/// # Examples
///
/// ```
/// use assert_call::{call, Call, CallRecorder};
///
/// let mut c = CallRecorder::new();
/// call!("a-1");
/// call!("b-1");
/// call!("b-2");
/// call!("a-2");
/// c.verify(Call::par([["a-1", "a-2"], ["b-1", "b-2"]]));
/// ```
pub fn par(p: impl IntoIterator<Item = impl ToCall>) -> Self {
Self::Par(p.into_iter().map(|x| x.to_call()).collect())
}
/// Create `Call` to represent one of the specified `Call`s will be called.
///
/// # Examples
///
/// ```
/// use assert_call::{call, Call, CallRecorder};
///
/// let mut c = CallRecorder::new();
/// call!("1");
/// c.verify(Call::any(["1", "2"]));
/// call!("4");
/// c.verify(Call::any(["3", "4"]));
/// ```
pub fn any(p: impl IntoIterator<Item = impl ToCall>) -> Self {
Self::Any(p.into_iter().map(|x| x.to_call()).collect())
}
fn verify(mut self, actual: Vec<Record>, msg: &str) -> Result<(), CallMismatchError> {
match self.verify_nexts(&actual) {
Ok(_) => Ok(()),
Err(mut e) => {
e.actual = actual;
e.expect.sort();
e.expect.dedup();
e.msg = msg.to_string();
Err(e)
}
}
}
fn verify_nexts(&mut self, actual: &[Record]) -> Result<(), CallMismatchError> {
for index in 0..=actual.len() {
self.verify_next(index, actual.get(index))?;
}
Ok(())
}
fn verify_next(&mut self, index: usize, a: Option<&Record>) -> Result<(), CallMismatchError> {
if let Err(e) = self.next(a) {
if a.is_none() && e.is_empty() {
return Ok(());
}
Err(CallMismatchError::new(e, index))
} else {
Ok(())
}
}
fn next(&mut self, p: Option<&Record>) -> Result<(), Vec<String>> {
match self {
Call::Id(id) => {
if Some(id.as_str()) == p.as_ref().map(|x| x.id.as_str()) {
*self = Call::Seq(VecDeque::new());
Ok(())
} else {
Err(vec![id.to_string()])
}
}
Call::Seq(list) => {
while !list.is_empty() {
match list[0].next(p) {
Err(e) if e.is_empty() => list.pop_front(),
ret => return ret,
};
}
Err(Vec::new())
}
Call::Par(s) => {
let mut es = Vec::new();
for i in s.iter_mut() {
match i.next(p) {
Ok(_) => return Ok(()),
Err(mut e) => es.append(&mut e),
}
}
Err(es)
}
Call::Any(s) => {
let mut is_end = false;
let mut is_ok = false;
let mut es = Vec::new();
s.retain_mut(|s| match s.next(p) {
Ok(_) => {
is_ok = true;
true
}
Err(e) => {
is_end |= e.is_empty();
es.extend(e);
false
}
});
if is_ok {
Ok(())
} else if is_end {
Err(Vec::new())
} else {
Err(es)
}
}
}
}
}
/// Types convertible to [`Call`].
pub trait ToCall {
fn to_call(&self) -> Call;
}
impl<T: ?Sized + ToCall> ToCall for &T {
fn to_call(&self) -> Call {
T::to_call(self)
}
}
impl ToCall for Call {
fn to_call(&self) -> Call {
self.clone()
}
}
/// Equivalent to [`Call::id`].
impl ToCall for str {
fn to_call(&self) -> Call {
Call::id(self)
}
}
/// Equivalent to [`Call::id`].
impl ToCall for String {
fn to_call(&self) -> Call {
Call::id(self)
}
}
/// Equivalent to [`Call::id`].
impl ToCall for usize {
fn to_call(&self) -> Call {
Call::id(self)
}
}
/// Equivalent to [`Call::seq`].
impl<T: ToCall> ToCall for [T] {
fn to_call(&self) -> Call {
Call::seq(self)
}
}
/// Equivalent to [`Call::seq`].
impl<T: ToCall, const N: usize> ToCall for [T; N] {
fn to_call(&self) -> Call {
Call::seq(self)
}
}
/// Equivalent to [`Call::seq`].
impl<T: ToCall> ToCall for Vec<T> {
fn to_call(&self) -> Call {
Call::seq(self)
}
}
/// Equivalent to [`Call::empty`].
impl ToCall for () {
fn to_call(&self) -> Call {
Call::empty()
}
}
/// The error type representing that the call to [`call`] is different from what was expected.
#[derive(Debug)]
struct CallMismatchError {
msg: String,
actual: Vec<Record>,
expect: Vec<String>,
mismatch_index: usize,
}
impl CallMismatchError {
fn new(expect: Vec<String>, mismatch_index: usize) -> Self {
Self {
msg: String::new(),
actual: Vec::new(),
expect,
mismatch_index,
}
}
fn actual_id(&self, index: usize) -> &str {
if let Some(a) = self.actual.get(index) {
&a.id
} else {
"(end)"
}
}
#[cfg(test)]
fn set_dummy_file_line(&mut self) {
for a in &mut self.actual {
a.set_dummy_file_line();
}
}
}
impl Display for CallMismatchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "actual calls :")?;
let around = 5;
let mut start = 0;
let end = self.actual.len();
if self.mismatch_index > around {
start = self.mismatch_index - around;
}
if start > 0 {
writeln!(f, " ...(previous {start} calls omitted)")?;
}
let end = min(self.mismatch_index + around + 1, end);
let write_actual = |f: &mut std::fmt::Formatter<'_>, index: usize, id: &str| {
let is_mismatch = index == self.mismatch_index;
let head = if is_mismatch { "*" } else { " " };
let cond = if is_mismatch && f.alternate() {
Condition::ALWAYS
} else {
Condition::NEVER
};
writeln!(f, "{}", format_args!("{head} {id}").red().whenever(cond))
};
for index in start..end {
write_actual(f, index, self.actual_id(index))?;
}
if end == self.actual.len() {
write_actual(f, end, "(end)")?;
} else {
writeln!(
f,
" ...(following {} calls omitted)",
self.actual.len() - end
)?;
}
writeln!(f)?;
writeln!(f, "{}", self.msg)?;
if let Some(a) = self.actual.get(self.mismatch_index) {
writeln!(f, "{}:{}", a.file, a.line)?;
}
writeln!(f, "actual : {}", self.actual_id(self.mismatch_index))?;
writeln!(f, "expect : {}", self.expect.join(", "))?;
Ok(())
}
}
impl Error for CallMismatchError {}
/// Record of one [`call`] call.
#[derive(Debug)]
struct Record {
id: String,
file: &'static str,
line: u32,
}
impl Record {
#[cfg(test)]
fn set_dummy_file_line(&mut self) {
self.file = r"tests\test.rs";
self.line = 10;
}
}