#![forbid(unsafe_code)]
use std::{process, sync::mpsc, fmt, time::Instant, borrow::Cow};
mod args;
mod printer;
use printer::Printer;
use threadpool::ThreadPool;
pub use crate::args::{Arguments, ColorSetting, FormatSetting};
pub struct Trial {
runner: Box<dyn FnOnce(bool) -> Outcome + Send>,
info: TestInfo,
}
impl Trial {
pub fn test<R>(name: impl Into<String>, runner: R) -> Self
where
R: FnOnce() -> Result<(), Failed> + Send + 'static,
{
Self {
runner: Box::new(move |_test_mode| match runner() {
Ok(()) => Outcome::Passed,
Err(failed) => Outcome::Failed(failed),
}),
info: TestInfo {
name: name.into(),
kind: String::new(),
is_ignored: false,
is_bench: false,
},
}
}
pub fn bench<R>(name: impl Into<String>, runner: R) -> Self
where
R: FnOnce(bool) -> Result<Option<Measurement>, Failed> + Send + 'static,
{
Self {
runner: Box::new(move |test_mode| match runner(test_mode) {
Err(failed) => Outcome::Failed(failed),
Ok(_) if test_mode => Outcome::Passed,
Ok(Some(measurement)) => Outcome::Measured(measurement),
Ok(None)
=> Outcome::Failed("bench runner returned `Ok(None)` in bench mode".into()),
}),
info: TestInfo {
name: name.into(),
kind: String::new(),
is_ignored: false,
is_bench: true,
},
}
}
pub fn with_kind(self, kind: impl Into<String>) -> Self {
Self {
info: TestInfo {
kind: kind.into(),
..self.info
},
..self
}
}
pub fn with_ignored_flag(self, is_ignored: bool) -> Self {
Self {
info: TestInfo {
is_ignored,
..self.info
},
..self
}
}
pub fn name(&self) -> &str {
&self.info.name
}
pub fn kind(&self) -> &str {
&self.info.kind
}
pub fn has_ignored_flag(&self) -> bool {
self.info.is_ignored
}
pub fn is_test(&self) -> bool {
!self.info.is_bench
}
pub fn is_bench(&self) -> bool {
self.info.is_bench
}
}
impl fmt::Debug for Trial {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct OpaqueRunner;
impl fmt::Debug for OpaqueRunner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<runner>")
}
}
f.debug_struct("Test")
.field("runner", &OpaqueRunner)
.field("name", &self.info.name)
.field("kind", &self.info.kind)
.field("is_ignored", &self.info.is_ignored)
.field("is_bench", &self.info.is_bench)
.finish()
}
}
#[derive(Debug)]
struct TestInfo {
name: String,
kind: String,
is_ignored: bool,
is_bench: bool,
}
impl TestInfo {
fn test_name_with_kind(&self) -> Cow<'_, str> {
if self.kind.is_empty() {
Cow::Borrowed(&self.name)
} else {
Cow::Owned(format!("[{}] {}", self.kind, self.name))
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Measurement {
pub avg: u64,
pub variance: u64,
}
#[derive(Debug, Clone)]
pub struct Failed {
msg: Option<String>,
}
impl Failed {
pub fn without_message() -> Self {
Self { msg: None }
}
pub fn message(&self) -> Option<&str> {
self.msg.as_deref()
}
}
impl<M: std::fmt::Display> From<M> for Failed {
fn from(msg: M) -> Self {
Self {
msg: Some(msg.to_string())
}
}
}
#[derive(Debug, Clone)]
enum Outcome {
Passed,
Failed(Failed),
Ignored,
Measured(Measurement),
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use = "Call `exit()` or `exit_if_failed()` to set the correct return code"]
pub struct Conclusion {
pub num_filtered_out: u64,
pub num_passed: u64,
pub num_failed: u64,
pub num_ignored: u64,
pub num_measured: u64,
}
impl Conclusion {
pub fn exit(&self) -> ! {
self.exit_if_failed();
process::exit(0);
}
pub fn exit_if_failed(&self) {
if self.has_failed() {
process::exit(101)
}
}
pub fn has_failed(&self) -> bool {
self.num_failed > 0
}
fn empty() -> Self {
Self {
num_filtered_out: 0,
num_passed: 0,
num_failed: 0,
num_ignored: 0,
num_measured: 0,
}
}
}
impl Arguments {
fn is_ignored(&self, test: &Trial) -> bool {
(test.info.is_ignored && !self.ignored && !self.include_ignored)
|| (test.info.is_bench && self.test)
|| (!test.info.is_bench && self.bench)
}
fn is_filtered_out(&self, test: &Trial) -> bool {
let test_name = test.name();
let test_name_with_kind = test.info.test_name_with_kind();
if let Some(filter) = &self.filter {
match self.exact {
true if test_name != filter && &test_name_with_kind != filter => return true,
false if !test_name_with_kind.contains(filter) => return true,
_ => {}
};
}
for skip_filter in &self.skip {
match self.exact {
true if test_name == skip_filter || &test_name_with_kind == skip_filter => {
return true
}
false if test_name_with_kind.contains(skip_filter) => return true,
_ => {}
}
}
if self.ignored && !test.info.is_ignored {
return true;
}
false
}
}
pub fn run(args: &Arguments, mut tests: Vec<Trial>) -> Conclusion {
let start_instant = Instant::now();
let mut conclusion = Conclusion::empty();
if args.filter.is_some() || !args.skip.is_empty() || args.ignored {
let len_before = tests.len() as u64;
tests.retain(|test| !args.is_filtered_out(test));
conclusion.num_filtered_out = len_before - tests.len() as u64;
}
let tests = tests;
let mut printer = printer::Printer::new(args, &tests);
if args.list {
printer.print_list(&tests, args.ignored);
return Conclusion::empty();
}
printer.print_title(tests.len() as u64);
let mut failed_tests = Vec::new();
let mut handle_outcome = |outcome: Outcome, test: TestInfo, printer: &mut Printer| {
printer.print_single_outcome(&test, &outcome);
match outcome {
Outcome::Passed => conclusion.num_passed += 1,
Outcome::Failed(failed) => {
failed_tests.push((test, failed.msg));
conclusion.num_failed += 1;
},
Outcome::Ignored => conclusion.num_ignored += 1,
Outcome::Measured(_) => conclusion.num_measured += 1,
}
};
let test_mode = !args.bench;
if args.test_threads == Some(1) {
for test in tests {
printer.print_test(&test.info);
let outcome = if args.is_ignored(&test) {
Outcome::Ignored
} else {
run_single(test.runner, test_mode)
};
handle_outcome(outcome, test.info, &mut printer);
}
} else {
let pool = match args.test_threads {
Some(num_threads) => ThreadPool::new(num_threads),
None => ThreadPool::default()
};
let (sender, receiver) = mpsc::channel();
let num_tests = tests.len();
for test in tests {
if args.is_ignored(&test) {
sender.send((Outcome::Ignored, test.info)).unwrap();
} else {
let sender = sender.clone();
pool.execute(move || {
let outcome = run_single(test.runner, test_mode);
let _ = sender.send((outcome, test.info));
});
}
}
for (outcome, test_info) in receiver.iter().take(num_tests) {
printer.print_test(&test_info);
handle_outcome(outcome, test_info, &mut printer);
}
}
if !failed_tests.is_empty() {
printer.print_failures(&failed_tests);
}
printer.print_summary(&conclusion, start_instant.elapsed());
conclusion
}
fn run_single(runner: Box<dyn FnOnce(bool) -> Outcome + Send>, test_mode: bool) -> Outcome {
use std::panic::{catch_unwind, AssertUnwindSafe};
catch_unwind(AssertUnwindSafe(move || runner(test_mode))).unwrap_or_else(|e| {
let payload = e.downcast_ref::<String>()
.map(|s| s.as_str())
.or(e.downcast_ref::<&str>().map(|s| *s));
let msg = match payload {
Some(payload) => format!("test panicked: {payload}"),
None => format!("test panicked"),
};
Outcome::Failed(msg.into())
})
}