1 //! Module providing interface for running tests in the console.
5 use std::io::prelude::Write;
8 bench::fmt_bench_samples,
10 event::{CompletedTest, TestEvent},
12 formatters::{JsonFormatter, OutputFormatter, PrettyFormatter, TerseFormatter},
13 helpers::{concurrency::get_concurrency, metrics::MetricMap},
14 options::{Options, OutputFormat},
16 test_result::TestResult,
18 types::{NamePadding, TestDesc, TestDescAndFn},
21 /// Generic wrapper over stdout.
22 pub enum OutputLocation<T> {
23 Pretty(Box<term::StdoutTerminal>),
27 impl<T: Write> Write for OutputLocation<T> {
28 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
30 OutputLocation::Pretty(ref mut term) => term.write(buf),
31 OutputLocation::Raw(ref mut stdout) => stdout.write(buf),
35 fn flush(&mut self) -> io::Result<()> {
37 OutputLocation::Pretty(ref mut term) => term.flush(),
38 OutputLocation::Raw(ref mut stdout) => stdout.flush(),
43 pub struct ConsoleTestState {
44 pub log_out: Option<File>,
49 pub allowed_fail: usize,
50 pub filtered_out: usize,
52 pub metrics: MetricMap,
53 pub failures: Vec<(TestDesc, Vec<u8>)>,
54 pub not_failures: Vec<(TestDesc, Vec<u8>)>,
55 pub time_failures: Vec<(TestDesc, Vec<u8>)>,
59 impl ConsoleTestState {
60 pub fn new(opts: &TestOpts) -> io::Result<ConsoleTestState> {
61 let log_out = match opts.logfile {
62 Some(ref path) => Some(File::create(path)?),
75 metrics: MetricMap::new(),
77 not_failures: Vec::new(),
78 time_failures: Vec::new(),
79 options: opts.options,
83 pub fn write_log<F, S>(&mut self, msg: F) -> io::Result<()>
92 let msg = msg.as_ref();
93 o.write_all(msg.as_bytes())
98 pub fn write_log_result(
102 exec_time: Option<&TestExecTime>,
103 ) -> io::Result<()> {
108 TestResult::TrOk => "ok".to_owned(),
109 TestResult::TrFailed => "failed".to_owned(),
110 TestResult::TrFailedMsg(ref msg) => format!("failed: {}", msg),
111 TestResult::TrIgnored => "ignored".to_owned(),
112 TestResult::TrAllowedFail => "failed (allowed)".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 + self.allowed_fail
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::TrAllowedFail => st.allowed_fail += 1,
192 TestResult::TrBench(bs) => {
193 st.metrics.insert_metric(
194 test.name.as_slice(),
195 bs.ns_iter_summ.median,
196 bs.ns_iter_summ.max - bs.ns_iter_summ.min,
200 TestResult::TrFailed => {
202 st.failures.push((test, stdout));
204 TestResult::TrFailedMsg(msg) => {
206 let mut stdout = stdout;
207 stdout.extend_from_slice(format!("note: {}", msg).as_bytes());
208 st.failures.push((test, stdout));
210 TestResult::TrTimedFail => {
212 st.time_failures.push((test, stdout));
217 // Handler for events that occur during test execution.
218 // It is provided as a callback to the `run_tests` function.
221 st: &mut ConsoleTestState,
222 out: &mut dyn OutputFormatter,
223 ) -> io::Result<()> {
224 match (*event).clone() {
225 TestEvent::TeFiltered(ref filtered_tests) => {
226 st.total = filtered_tests.len();
227 out.write_run_start(filtered_tests.len())?;
229 TestEvent::TeFilteredOut(filtered_out) => {
230 st.filtered_out = filtered_out;
232 TestEvent::TeWait(ref test) => out.write_test_start(test)?,
233 TestEvent::TeTimeout(ref test) => out.write_timeout(test)?,
234 TestEvent::TeResult(completed_test) => {
235 let test = &completed_test.desc;
236 let result = &completed_test.result;
237 let exec_time = &completed_test.exec_time;
238 let stdout = &completed_test.stdout;
240 st.write_log_result(test, result, exec_time.as_ref())?;
241 out.write_result(test, result, exec_time.as_ref(), &*stdout, st)?;
242 handle_test_result(st, completed_test);
249 /// A simple console test runner.
250 /// Runs provided tests reporting process and results to the stdout.
251 pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Result<bool> {
252 let output = match term::stdout() {
253 None => OutputLocation::Raw(io::stdout()),
254 Some(t) => OutputLocation::Pretty(t),
257 let max_name_len = tests
259 .max_by_key(|t| len_if_padded(*t))
260 .map(|t| t.desc.name.as_slice().len())
263 let is_multithreaded = opts.test_threads.unwrap_or_else(get_concurrency) > 1;
265 let mut out: Box<dyn OutputFormatter> = match opts.format {
266 OutputFormat::Pretty => Box::new(PrettyFormatter::new(
273 OutputFormat::Terse => {
274 Box::new(TerseFormatter::new(output, opts.use_color(), max_name_len, is_multithreaded))
276 OutputFormat::Json => Box::new(JsonFormatter::new(output)),
278 let mut st = ConsoleTestState::new(opts)?;
280 run_tests(opts, tests, |x| on_test_event(&x, &mut st, &mut *out))?;
282 assert!(st.current_test_count() == st.total);
284 out.write_run_finish(&st)
287 // Calculates padding for given test description.
288 fn len_if_padded(t: &TestDescAndFn) -> usize {
289 match t.testfn.padding() {
290 NamePadding::PadNone => 0,
291 NamePadding::PadOnRight => t.desc.name.as_slice().len(),