1 //! Module providing interface for running tests in the console.
5 use std::io::prelude::Write;
6 use std::time::Instant;
9 bench::fmt_bench_samples,
11 event::{CompletedTest, TestEvent},
13 formatters::{JsonFormatter, JunitFormatter, OutputFormatter, PrettyFormatter, TerseFormatter},
14 helpers::{concurrency::get_concurrency, metrics::MetricMap},
15 options::{Options, OutputFormat},
17 test_result::TestResult,
18 time::{TestExecTime, TestSuiteExecTime},
19 types::{NamePadding, TestDesc, TestDescAndFn},
22 /// Generic wrapper over stdout.
23 pub enum OutputLocation<T> {
24 Pretty(Box<term::StdoutTerminal>),
28 impl<T: Write> Write for OutputLocation<T> {
29 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
31 OutputLocation::Pretty(ref mut term) => term.write(buf),
32 OutputLocation::Raw(ref mut stdout) => stdout.write(buf),
36 fn flush(&mut self) -> io::Result<()> {
38 OutputLocation::Pretty(ref mut term) => term.flush(),
39 OutputLocation::Raw(ref mut stdout) => stdout.flush(),
44 pub struct ConsoleTestState {
45 pub log_out: Option<File>,
50 pub filtered_out: usize,
52 pub exec_time: Option<TestSuiteExecTime>,
53 pub metrics: MetricMap,
54 pub failures: Vec<(TestDesc, Vec<u8>)>,
55 pub not_failures: Vec<(TestDesc, Vec<u8>)>,
56 pub time_failures: Vec<(TestDesc, Vec<u8>)>,
60 impl ConsoleTestState {
61 pub fn new(opts: &TestOpts) -> io::Result<ConsoleTestState> {
62 let log_out = match opts.logfile {
63 Some(ref path) => Some(File::create(path)?),
76 metrics: MetricMap::new(),
78 not_failures: Vec::new(),
79 time_failures: Vec::new(),
80 options: opts.options,
84 pub fn write_log<F, S>(&mut self, msg: F) -> io::Result<()>
93 let msg = msg.as_ref();
94 o.write_all(msg.as_bytes())
99 pub fn write_log_result(
103 exec_time: Option<&TestExecTime>,
104 ) -> io::Result<()> {
109 TestResult::TrOk => "ok".to_owned(),
110 TestResult::TrFailed => "failed".to_owned(),
111 TestResult::TrFailedMsg(ref msg) => format!("failed: {}", msg),
112 TestResult::TrIgnored => "ignored".to_owned(),
113 TestResult::TrBench(ref bs) => fmt_bench_samples(bs),
114 TestResult::TrTimedFail => "failed (time limit exceeded)".to_owned(),
119 if let Some(exec_time) = exec_time {
120 self.write_log(|| format!(" <{}>", exec_time))?;
122 self.write_log(|| "\n")
125 fn current_test_count(&self) -> usize {
126 self.passed + self.failed + self.ignored + self.measured
130 // List the tests to console, and optionally to logfile. Filters are honored.
131 pub fn list_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Result<()> {
132 let mut output = match term::stdout() {
133 None => OutputLocation::Raw(io::stdout()),
134 Some(t) => OutputLocation::Pretty(t),
137 let quiet = opts.format == OutputFormat::Terse;
138 let mut st = ConsoleTestState::new(opts)?;
143 for test in filter_tests(&opts, tests) {
144 use crate::TestFn::*;
146 let TestDescAndFn { desc: TestDesc { name, .. }, testfn } = test;
148 let fntype = match testfn {
149 StaticTestFn(..) | DynTestFn(..) => {
153 StaticBenchFn(..) | DynBenchFn(..) => {
159 writeln!(output, "{}: {}", name, fntype)?;
160 st.write_log(|| format!("{} {}\n", fntype, name))?;
163 fn plural(count: u32, s: &str) -> String {
165 1 => format!("{} {}", 1, s),
166 n => format!("{} {}s", n, s),
171 if ntest != 0 || nbench != 0 {
175 writeln!(output, "{}, {}", plural(ntest, "test"), plural(nbench, "benchmark"))?;
181 // Updates `ConsoleTestState` depending on result of the test execution.
182 fn handle_test_result(st: &mut ConsoleTestState, completed_test: CompletedTest) {
183 let test = completed_test.desc;
184 let stdout = completed_test.stdout;
185 match completed_test.result {
186 TestResult::TrOk => {
188 st.not_failures.push((test, stdout));
190 TestResult::TrIgnored => st.ignored += 1,
191 TestResult::TrBench(bs) => {
192 st.metrics.insert_metric(
193 test.name.as_slice(),
194 bs.ns_iter_summ.median,
195 bs.ns_iter_summ.max - bs.ns_iter_summ.min,
199 TestResult::TrFailed => {
201 st.failures.push((test, stdout));
203 TestResult::TrFailedMsg(msg) => {
205 let mut stdout = stdout;
206 stdout.extend_from_slice(format!("note: {}", msg).as_bytes());
207 st.failures.push((test, stdout));
209 TestResult::TrTimedFail => {
211 st.time_failures.push((test, stdout));
216 // Handler for events that occur during test execution.
217 // It is provided as a callback to the `run_tests` function.
220 st: &mut ConsoleTestState,
221 out: &mut dyn OutputFormatter,
222 ) -> io::Result<()> {
223 match (*event).clone() {
224 TestEvent::TeFiltered(ref filtered_tests, shuffle_seed) => {
225 st.total = filtered_tests.len();
226 out.write_run_start(filtered_tests.len(), shuffle_seed)?;
228 TestEvent::TeFilteredOut(filtered_out) => {
229 st.filtered_out = filtered_out;
231 TestEvent::TeWait(ref test) => out.write_test_start(test)?,
232 TestEvent::TeTimeout(ref test) => out.write_timeout(test)?,
233 TestEvent::TeResult(completed_test) => {
234 let test = &completed_test.desc;
235 let result = &completed_test.result;
236 let exec_time = &completed_test.exec_time;
237 let stdout = &completed_test.stdout;
239 st.write_log_result(test, result, exec_time.as_ref())?;
240 out.write_result(test, result, exec_time.as_ref(), &*stdout, st)?;
241 handle_test_result(st, completed_test);
248 /// A simple console test runner.
249 /// Runs provided tests reporting process and results to the stdout.
250 pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Result<bool> {
251 let output = match term::stdout() {
252 None => OutputLocation::Raw(io::stdout()),
253 Some(t) => OutputLocation::Pretty(t),
256 let max_name_len = tests
258 .max_by_key(|t| len_if_padded(*t))
259 .map(|t| t.desc.name.as_slice().len())
262 let is_multithreaded = opts.test_threads.unwrap_or_else(get_concurrency) > 1;
264 let mut out: Box<dyn OutputFormatter> = match opts.format {
265 OutputFormat::Pretty => Box::new(PrettyFormatter::new(
272 OutputFormat::Terse => {
273 Box::new(TerseFormatter::new(output, opts.use_color(), max_name_len, is_multithreaded))
275 OutputFormat::Json => Box::new(JsonFormatter::new(output)),
276 OutputFormat::Junit => Box::new(JunitFormatter::new(output)),
278 let mut st = ConsoleTestState::new(opts)?;
280 // Prevent the usage of `Instant` in some cases:
281 // - It's currently not supported for wasm targets.
282 // - We disable it for miri because it's not available when isolation is enabled.
283 let is_instant_supported = !cfg!(target_family = "wasm") && !cfg!(miri);
285 let start_time = is_instant_supported.then(Instant::now);
286 run_tests(opts, tests, |x| on_test_event(&x, &mut st, &mut *out))?;
287 st.exec_time = start_time.map(|t| TestSuiteExecTime(t.elapsed()));
289 assert!(st.current_test_count() == st.total);
291 out.write_run_finish(&st)
294 // Calculates padding for given test description.
295 fn len_if_padded(t: &TestDescAndFn) -> usize {
296 match t.testfn.padding() {
297 NamePadding::PadNone => 0,
298 NamePadding::PadOnRight => t.desc.name.as_slice().len(),