diff options
| author | bors <bors@rust-lang.org> | 2019-12-23 02:47:52 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2019-12-23 02:47:52 +0000 |
| commit | a916ac22b9f7f1f0f7aba0a41a789b3ecd765018 (patch) | |
| tree | 139cba4184f0f290fdbdff1aa0aa68352b16ccbb /src/libtest | |
| parent | 9b98af84c4aa66392236fff59c86da2130d46d46 (diff) | |
| parent | 0f24ccd21d9f734a21daaf3566900127167556d1 (diff) | |
Auto merge of #67540 - Mark-Simulacrum:fmt-the-world, r=Centril
Format the world This PR modifies the formatting infrastructure a bit in the first commit (to enable the forgotten 2018 edition), as well as removes most directories from the ignore list in rustfmt.toml. It then follows that up with the second commit which runs `x.py fmt` and formats the entire repository. We continue to not format the test directory (`src/test`) because of interactions with pretty printing and, in part, because re-blessing all of those files is somewhat harder to review, so is best suited for a follow up PR in my opinion.
Diffstat (limited to 'src/libtest')
| -rw-r--r-- | src/libtest/bench.rs | 36 | ||||
| -rw-r--r-- | src/libtest/cli.rs | 46 | ||||
| -rw-r--r-- | src/libtest/console.rs | 75 | ||||
| -rw-r--r-- | src/libtest/event.rs | 11 | ||||
| -rw-r--r-- | src/libtest/formatters/json.rs | 29 | ||||
| -rw-r--r-- | src/libtest/formatters/mod.rs | 15 | ||||
| -rw-r--r-- | src/libtest/formatters/pretty.rs | 32 | ||||
| -rw-r--r-- | src/libtest/formatters/terse.rs | 26 | ||||
| -rw-r--r-- | src/libtest/helpers/exit_code.rs | 2 | ||||
| -rw-r--r-- | src/libtest/helpers/isatty.rs | 3 | ||||
| -rw-r--r-- | src/libtest/helpers/mod.rs | 2 | ||||
| -rw-r--r-- | src/libtest/lib.rs | 135 | ||||
| -rw-r--r-- | src/libtest/options.rs | 5 | ||||
| -rw-r--r-- | src/libtest/stats/tests.rs | 11 | ||||
| -rw-r--r-- | src/libtest/test_result.rs | 4 | ||||
| -rw-r--r-- | src/libtest/tests.rs | 120 | ||||
| -rw-r--r-- | src/libtest/time.rs | 51 | ||||
| -rw-r--r-- | src/libtest/types.rs | 6 |
18 files changed, 219 insertions, 390 deletions
diff --git a/src/libtest/bench.rs b/src/libtest/bench.rs index c86bfd16c21..e92e5b9829e 100644 --- a/src/libtest/bench.rs +++ b/src/libtest/bench.rs @@ -2,20 +2,16 @@ pub use std::hint::black_box; use super::{ - event::CompletedTest, - helpers::sink::Sink, - options::BenchMode, - types::TestDesc, - test_result::TestResult, - Sender, + event::CompletedTest, helpers::sink::Sink, options::BenchMode, test_result::TestResult, + types::TestDesc, Sender, }; use crate::stats; -use std::time::{Duration, Instant}; use std::cmp; use std::io; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; /// Manager of the benchmarking runs. /// @@ -73,9 +69,7 @@ pub fn fmt_bench_samples(bs: &BenchSamples) -> String { )) .unwrap(); if bs.mb_s != 0 { - output - .write_fmt(format_args!(" = {} MB/s", bs.mb_s)) - .unwrap(); + output.write_fmt(format_args!(" = {} MB/s", bs.mb_s)).unwrap(); } output } @@ -192,11 +186,7 @@ pub fn benchmark<F>(desc: TestDesc, monitor_ch: Sender<CompletedTest>, nocapture where F: FnMut(&mut Bencher), { - let mut bs = Bencher { - mode: BenchMode::Auto, - summary: None, - bytes: 0, - }; + let mut bs = Bencher { mode: BenchMode::Auto, summary: None, bytes: 0 }; let data = Arc::new(Mutex::new(Vec::new())); let oldio = if !nocapture { @@ -221,20 +211,14 @@ where let ns_iter = cmp::max(ns_iter_summ.median as u64, 1); let mb_s = bs.bytes * 1000 / ns_iter; - let bs = BenchSamples { - ns_iter_summ, - mb_s: mb_s as usize, - }; + let bs = BenchSamples { ns_iter_summ, mb_s: mb_s as usize }; TestResult::TrBench(bs) } Ok(None) => { // iter not called, so no data. // FIXME: error in this case? let samples: &mut [f64] = &mut [0.0_f64; 1]; - let bs = BenchSamples { - ns_iter_summ: stats::Summary::new(samples), - mb_s: 0, - }; + let bs = BenchSamples { ns_iter_summ: stats::Summary::new(samples), mb_s: 0 }; TestResult::TrBench(bs) } Err(_) => TestResult::TrFailed, @@ -249,10 +233,6 @@ pub fn run_once<F>(f: F) where F: FnMut(&mut Bencher), { - let mut bs = Bencher { - mode: BenchMode::Single, - summary: None, - bytes: 0, - }; + let mut bs = Bencher { mode: BenchMode::Single, summary: None, bytes: 0 }; bs.bench(f); } diff --git a/src/libtest/cli.rs b/src/libtest/cli.rs index c97cb0e0605..ea6d632f48a 100644 --- a/src/libtest/cli.rs +++ b/src/libtest/cli.rs @@ -1,12 +1,12 @@ //! Module converting command-line arguments into test configuration. +use getopts; use std::env; use std::path::PathBuf; -use getopts; -use super::options::{RunIgnored, ColorConfig, OutputFormat, Options}; -use super::time::TestTimeOptions; use super::helpers::isatty; +use super::options::{ColorConfig, Options, OutputFormat, RunIgnored}; +use super::time::TestTimeOptions; #[derive(Debug)] pub struct TestOpts { @@ -86,11 +86,7 @@ fn optgroups() -> getopts::Options { "Display one character per test instead of one line. \ Alias to --format=terse", ) - .optflag( - "", - "exact", - "Exactly match filters rather than by substring", - ) + .optflag("", "exact", "Exactly match filters rather than by substring") .optopt( "", "color", @@ -109,11 +105,7 @@ fn optgroups() -> getopts::Options { json = Output a json document", "pretty|terse|json", ) - .optflag( - "", - "show-output", - "Show captured stdout of successful tests" - ) + .optflag("", "show-output", "Show captured stdout of successful tests") .optopt( "Z", "", @@ -135,7 +127,7 @@ fn optgroups() -> getopts::Options { Expected format of environment variable is `VARIABLE=WARN_TIME,CRITICAL_TIME`. Not available for --format=terse", - "plain|colored" + "plain|colored", ) .optflag( "", @@ -149,7 +141,7 @@ fn optgroups() -> getopts::Options { Expected format of environment variable is `VARIABLE=WARN_TIME,CRITICAL_TIME`. `CRITICAL_TIME` here means the limit that should not be exceeded by test. - " + ", ); opts } @@ -293,8 +285,8 @@ fn is_nightly() -> bool { // Gets the CLI options assotiated with `report-time` feature. fn get_time_options( matches: &getopts::Matches, - allow_unstable: bool) --> OptPartRes<Option<TestTimeOptions>> { + allow_unstable: bool, +) -> OptPartRes<Option<TestTimeOptions>> { let report_time = unstable_optflag!(matches, allow_unstable, "report-time"); let colored_opt_str = matches.opt_str("report-time"); let mut report_time_colored = report_time && colored_opt_str == Some("colored".into()); @@ -336,7 +328,7 @@ fn get_test_threads(matches: &getopts::Matches) -> OptPartRes<Option<usize>> { fn get_format( matches: &getopts::Matches, quiet: bool, - allow_unstable: bool + allow_unstable: bool, ) -> OptPartRes<OutputFormat> { let format = match matches.opt_str("format").as_ref().map(|s| &**s) { None if quiet => OutputFormat::Terse, @@ -344,9 +336,7 @@ fn get_format( Some("terse") => OutputFormat::Terse, Some("json") => { if !allow_unstable { - return Err( - "The \"json\" format is only accepted on the nightly compiler".into(), - ); + return Err("The \"json\" format is only accepted on the nightly compiler".into()); } OutputFormat::Json } @@ -396,9 +386,7 @@ fn get_nocapture(matches: &getopts::Matches) -> OptPartRes<bool> { fn get_run_ignored(matches: &getopts::Matches, include_ignored: bool) -> OptPartRes<RunIgnored> { let run_ignored = match (include_ignored, matches.opt_present("ignored")) { (true, true) => { - return Err( - "the options --include-ignored and --ignored are mutually exclusive".into(), - ); + return Err("the options --include-ignored and --ignored are mutually exclusive".into()); } (true, false) => RunIgnored::Yes, (false, true) => RunIgnored::Only, @@ -409,11 +397,7 @@ fn get_run_ignored(matches: &getopts::Matches, include_ignored: bool) -> OptPart } fn get_filter(matches: &getopts::Matches) -> OptPartRes<Option<String>> { - let filter = if !matches.free.is_empty() { - Some(matches.free[0].clone()) - } else { - None - }; + let filter = if !matches.free.is_empty() { Some(matches.free[0].clone()) } else { None }; Ok(filter) } @@ -423,9 +407,7 @@ fn get_allow_unstable(matches: &getopts::Matches) -> OptPartRes<bool> { if let Some(opt) = matches.opt_str("Z") { if !is_nightly() { - return Err( - "the option `Z` is only accepted on the nightly compiler".into(), - ); + return Err("the option `Z` is only accepted on the nightly compiler".into()); } match &*opt { diff --git a/src/libtest/console.rs b/src/libtest/console.rs index 244cbd2cf5f..ebdfb162947 100644 --- a/src/libtest/console.rs +++ b/src/libtest/console.rs @@ -1,26 +1,23 @@ //! Module providing interface for running tests in the console. use std::fs::File; -use std::io::prelude::Write; use std::io; +use std::io::prelude::Write; use term; use super::{ bench::fmt_bench_samples, cli::TestOpts, - event::{TestEvent, CompletedTest}, + event::{CompletedTest, TestEvent}, + filter_tests, formatters::{JsonFormatter, OutputFormatter, PrettyFormatter, TerseFormatter}, - helpers::{ - concurrency::get_concurrency, - metrics::MetricMap, - }, - types::{TestDesc, TestDescAndFn, NamePadding}, + helpers::{concurrency::get_concurrency, metrics::MetricMap}, options::{Options, OutputFormat}, + run_tests, test_result::TestResult, time::TestExecTime, - run_tests, - filter_tests, + types::{NamePadding, TestDesc, TestDescAndFn}, }; /// Generic wrapper over stdout. @@ -85,10 +82,7 @@ impl ConsoleTestState { }) } - pub fn write_log<F, S>( - &mut self, - msg: F, - ) -> io::Result<()> + pub fn write_log<F, S>(&mut self, msg: F) -> io::Result<()> where S: AsRef<str>, F: FnOnce() -> S, @@ -99,27 +93,31 @@ impl ConsoleTestState { let msg = msg(); let msg = msg.as_ref(); o.write_all(msg.as_bytes()) - }, + } } } - pub fn write_log_result(&mut self,test: &TestDesc, + pub fn write_log_result( + &mut self, + test: &TestDesc, result: &TestResult, exec_time: Option<&TestExecTime>, ) -> io::Result<()> { - self.write_log(|| format!( - "{} {}", - match *result { - TestResult::TrOk => "ok".to_owned(), - TestResult::TrFailed => "failed".to_owned(), - TestResult::TrFailedMsg(ref msg) => format!("failed: {}", msg), - TestResult::TrIgnored => "ignored".to_owned(), - TestResult::TrAllowedFail => "failed (allowed)".to_owned(), - TestResult::TrBench(ref bs) => fmt_bench_samples(bs), - TestResult::TrTimedFail => "failed (time limit exceeded)".to_owned(), - }, - test.name, - ))?; + self.write_log(|| { + format!( + "{} {}", + match *result { + TestResult::TrOk => "ok".to_owned(), + TestResult::TrFailed => "failed".to_owned(), + TestResult::TrFailedMsg(ref msg) => format!("failed: {}", msg), + TestResult::TrIgnored => "ignored".to_owned(), + TestResult::TrAllowedFail => "failed (allowed)".to_owned(), + TestResult::TrBench(ref bs) => fmt_bench_samples(bs), + TestResult::TrTimedFail => "failed (time limit exceeded)".to_owned(), + }, + test.name, + ) + })?; if let Some(exec_time) = exec_time { self.write_log(|| format!(" <{}>", exec_time))?; } @@ -147,10 +145,7 @@ pub fn list_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Res for test in filter_tests(&opts, tests) { use crate::TestFn::*; - let TestDescAndFn { - desc: TestDesc { name, .. }, - testfn, - } = test; + let TestDescAndFn { desc: TestDesc { name, .. }, testfn } = test; let fntype = match testfn { StaticTestFn(..) | DynTestFn(..) => { @@ -179,12 +174,7 @@ pub fn list_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Res writeln!(output, "")?; } - writeln!( - output, - "{}, {}", - plural(ntest, "test"), - plural(nbench, "benchmark") - )?; + writeln!(output, "{}, {}", plural(ntest, "test"), plural(nbench, "benchmark"))?; } Ok(()) @@ -282,12 +272,9 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Resu is_multithreaded, opts.time_options, )), - OutputFormat::Terse => Box::new(TerseFormatter::new( - output, - opts.use_color(), - max_name_len, - is_multithreaded, - )), + OutputFormat::Terse => { + Box::new(TerseFormatter::new(output, opts.use_color(), max_name_len, is_multithreaded)) + } OutputFormat::Json => Box::new(JsonFormatter::new(output)), }; let mut st = ConsoleTestState::new(opts)?; diff --git a/src/libtest/event.rs b/src/libtest/event.rs index eefbd2d6a81..297bb72aecb 100644 --- a/src/libtest/event.rs +++ b/src/libtest/event.rs @@ -1,9 +1,9 @@ //! Module containing different events that can occur //! during tests execution process. -use super::types::TestDesc; use super::test_result::TestResult; use super::time::TestExecTime; +use super::types::TestDesc; #[derive(Debug, Clone)] pub struct CompletedTest { @@ -18,14 +18,9 @@ impl CompletedTest { desc: TestDesc, result: TestResult, exec_time: Option<TestExecTime>, - stdout: Vec<u8> + stdout: Vec<u8>, ) -> Self { - Self { - desc, - result, - exec_time, - stdout, - } + Self { desc, result, exec_time, stdout } } } diff --git a/src/libtest/formatters/json.rs b/src/libtest/formatters/json.rs index b73d7349678..863cad9f9d7 100644 --- a/src/libtest/formatters/json.rs +++ b/src/libtest/formatters/json.rs @@ -1,16 +1,12 @@ -use std::{ - io, - io::prelude::Write, - borrow::Cow, -}; +use std::{borrow::Cow, io, io::prelude::Write}; +use super::OutputFormatter; use crate::{ - types::TestDesc, - time, - test_result::TestResult, console::{ConsoleTestState, OutputLocation}, + test_result::TestResult, + time, + types::TestDesc, }; -use super::OutputFormatter; pub(crate) struct JsonFormatter<T> { out: OutputLocation<T>, @@ -48,22 +44,13 @@ impl<T: Write> JsonFormatter<T> { ty, name, evt ))?; if let Some(exec_time) = exec_time { - self.write_message(&*format!( - r#", "exec_time": "{}""#, - exec_time - ))?; + self.write_message(&*format!(r#", "exec_time": "{}""#, exec_time))?; } if let Some(stdout) = stdout { - self.write_message(&*format!( - r#", "stdout": "{}""#, - EscapedString(stdout) - ))?; + self.write_message(&*format!(r#", "stdout": "{}""#, EscapedString(stdout)))?; } if let Some(extra) = extra { - self.write_message(&*format!( - r#", {}"#, - extra - ))?; + self.write_message(&*format!(r#", {}"#, extra))?; } self.writeln_message(" }") } diff --git a/src/libtest/formatters/mod.rs b/src/libtest/formatters/mod.rs index b6649a3effc..a64c0fc263d 100644 --- a/src/libtest/formatters/mod.rs +++ b/src/libtest/formatters/mod.rs @@ -1,21 +1,18 @@ -use std::{ - io, - io::prelude::Write, -}; +use std::{io, io::prelude::Write}; use crate::{ - types::{TestDesc, TestName}, - time, + console::ConsoleTestState, test_result::TestResult, - console::{ConsoleTestState}, + time, + types::{TestDesc, TestName}, }; -mod pretty; mod json; +mod pretty; mod terse; -pub(crate) use self::pretty::PrettyFormatter; pub(crate) use self::json::JsonFormatter; +pub(crate) use self::pretty::PrettyFormatter; pub(crate) use self::terse::TerseFormatter; pub(crate) trait OutputFormatter { diff --git a/src/libtest/formatters/pretty.rs b/src/libtest/formatters/pretty.rs index 2fdbc63d513..4a93e084df1 100644 --- a/src/libtest/formatters/pretty.rs +++ b/src/libtest/formatters/pretty.rs @@ -1,16 +1,13 @@ -use std::{ - io, - io::prelude::Write, -}; +use std::{io, io::prelude::Write}; +use super::OutputFormatter; use crate::{ - types::TestDesc, - time, - test_result::TestResult, - console::{ConsoleTestState, OutputLocation}, bench::fmt_bench_samples, + console::{ConsoleTestState, OutputLocation}, + test_result::TestResult, + time, + types::TestDesc, }; -use super::OutputFormatter; pub(crate) struct PrettyFormatter<T> { out: OutputLocation<T>, @@ -31,13 +28,7 @@ impl<T: Write> PrettyFormatter<T> { is_multithreaded: bool, time_options: Option<time::TestTimeOptions>, ) -> Self { - PrettyFormatter { - out, - use_color, - max_name_len, - is_multithreaded, - time_options - } + PrettyFormatter { out, use_color, max_name_len, is_multithreaded, time_options } } #[cfg(test)] @@ -105,7 +96,7 @@ impl<T: Write> PrettyFormatter<T> { fn write_time( &mut self, desc: &TestDesc, - exec_time: Option<&time::TestExecTime> + exec_time: Option<&time::TestExecTime>, ) -> io::Result<()> { if let (Some(opts), Some(time)) = (self.time_options, exec_time) { let time_str = format!(" <{}>", time); @@ -124,7 +115,7 @@ impl<T: Write> PrettyFormatter<T> { match color { Some(color) => self.write_pretty(&time_str, color)?, - None => self.write_plain(&time_str)? + None => self.write_plain(&time_str)?, } } @@ -134,7 +125,7 @@ impl<T: Write> PrettyFormatter<T> { fn write_results( &mut self, inputs: &Vec<(TestDesc, Vec<u8>)>, - results_type: &str + results_type: &str, ) -> io::Result<()> { let results_out_str = format!("\n{}:\n", results_type); @@ -237,7 +228,8 @@ impl<T: Write> OutputFormatter for PrettyFormatter<T> { self.write_plain(&format!( "test {} has been running for over {} seconds\n", - desc.name, time::TEST_WARN_TIMEOUT_S + desc.name, + time::TEST_WARN_TIMEOUT_S )) } diff --git a/src/libtest/formatters/terse.rs b/src/libtest/formatters/terse.rs index fe56157d9c1..5a264d20057 100644 --- a/src/libtest/formatters/terse.rs +++ b/src/libtest/formatters/terse.rs @@ -1,17 +1,14 @@ -use std::{ - io, - io::prelude::Write, -}; +use std::{io, io::prelude::Write}; +use super::OutputFormatter; use crate::{ - types::TestDesc, - time, + bench::fmt_bench_samples, + console::{ConsoleTestState, OutputLocation}, test_result::TestResult, + time, types::NamePadding, - console::{ConsoleTestState, OutputLocation}, - bench::fmt_bench_samples, + types::TestDesc, }; -use super::OutputFormatter; // insert a '\n' after 100 tests in quiet mode const QUIET_MODE_MAX_COLUMN: usize = 100; @@ -74,7 +71,7 @@ impl<T: Write> TerseFormatter<T> { // we insert a new line every 100 dots in order to flush the // screen when dealing with line-buffered output (e.g., piping to // `stamp` in the rust CI). - let out = format!(" {}/{}\n", self.test_count+1, self.total_test_count); + let out = format!(" {}/{}\n", self.test_count + 1, self.total_test_count); self.write_plain(&out)?; } @@ -196,9 +193,9 @@ impl<T: Write> OutputFormatter for TerseFormatter<T> { ) -> io::Result<()> { match *result { TestResult::TrOk => self.write_ok(), - TestResult::TrFailed - | TestResult::TrFailedMsg(_) - | TestResult::TrTimedFail => self.write_failed(), + TestResult::TrFailed | TestResult::TrFailedMsg(_) | TestResult::TrTimedFail => { + self.write_failed() + } TestResult::TrIgnored => self.write_ignored(), TestResult::TrAllowedFail => self.write_allowed_fail(), TestResult::TrBench(ref bs) => { @@ -214,7 +211,8 @@ impl<T: Write> OutputFormatter for TerseFormatter<T> { fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> { self.write_plain(&format!( "test {} has been running for over {} seconds\n", - desc.name, time::TEST_WARN_TIMEOUT_S + desc.name, + time::TEST_WARN_TIMEOUT_S )) } diff --git a/src/libtest/helpers/exit_code.rs b/src/libtest/helpers/exit_code.rs index 831bef3b118..31e234d9818 100644 --- a/src/libtest/helpers/exit_code.rs +++ b/src/libtest/helpers/exit_code.rs @@ -15,6 +15,6 @@ pub fn get_exit_code(status: ExitStatus) -> Result<i32, String> { None => match status.signal() { Some(signal) => Err(format!("child process exited with signal {}", signal)), None => Err("child process exited with unknown signal".into()), - } + }, } } diff --git a/src/libtest/helpers/isatty.rs b/src/libtest/helpers/isatty.rs index 4955e1fc888..831094f7545 100644 --- a/src/libtest/helpers/isatty.rs +++ b/src/libtest/helpers/isatty.rs @@ -2,7 +2,8 @@ //! if stdout is a tty. #[cfg(any( - target_os = "cloudabi", target_os = "hermit", + target_os = "cloudabi", + target_os = "hermit", all(target_arch = "wasm32", not(target_os = "emscripten")), all(target_vendor = "fortanix", target_env = "sgx") ))] diff --git a/src/libtest/helpers/mod.rs b/src/libtest/helpers/mod.rs index 6a2ef6086cb..eb416b10150 100644 --- a/src/libtest/helpers/mod.rs +++ b/src/libtest/helpers/mod.rs @@ -2,7 +2,7 @@ //! but used in `libtest`. pub mod concurrency; +pub mod exit_code; pub mod isatty; pub mod metrics; pub mod sink; -pub mod exit_code; diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 0097558eae6..884db85efe0 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -32,34 +32,35 @@ #![feature(test)] // Public reexports -pub use self::ColorConfig::*; -pub use self::types::*; -pub use self::types::TestName::*; -pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic}; -pub use self::bench::{Bencher, black_box}; +pub use self::bench::{black_box, Bencher}; pub use self::console::run_tests_console; +pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic}; +pub use self::types::TestName::*; +pub use self::types::*; +pub use self::ColorConfig::*; pub use cli::TestOpts; // Module to be used by rustc to compile tests in libtest pub mod test { pub use crate::{ + assert_test_result, bench::Bencher, cli::{parse_opts, TestOpts}, + filter_tests, helpers::metrics::{Metric, MetricMap}, - options::{ShouldPanic, Options, RunIgnored, RunStrategy}, + options::{Options, RunIgnored, RunStrategy, ShouldPanic}, + run_test, test_main, test_main_static, test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk}, - time::{TestTimeOptions, TestExecTime}, + time::{TestExecTime, TestTimeOptions}, types::{ - DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, - TestDesc, TestDescAndFn, TestName, TestType, + DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc, + TestDescAndFn, TestName, TestType, }, - assert_test_result, filter_tests, run_test, test_main, test_main_static, }; } use std::{ - env, - io, + env, io, io::prelude::Write, panic::{self, catch_unwind, AssertUnwindSafe, PanicInfo}, process, @@ -70,28 +71,28 @@ use std::{ time::{Duration, Instant}, }; -pub mod stats; pub mod bench; -mod formatters; mod cli; mod console; mod event; +mod formatters; mod helpers; -mod time; -mod types; mod options; +pub mod stats; mod test_result; +mod time; +mod types; #[cfg(test)] mod tests; -use test_result::*; -use time::TestExecTime; -use options::{RunStrategy, Concurrent}; use event::{CompletedTest, TestEvent}; -use helpers::sink::Sink; use helpers::concurrency::get_concurrency; use helpers::exit_code::get_exit_code; +use helpers::sink::Sink; +use options::{Concurrent, RunStrategy}; +use test_result::*; +use time::TestExecTime; // Process exit code to be used to indicate test failures. const ERROR_EXIT_CODE: i32 = 101; @@ -177,14 +178,8 @@ pub fn test_main_static_abort(tests: &[&TestDescAndFn]) { /// This will panic when fed any dynamic tests, because they cannot be cloned. fn make_owned_test(test: &&TestDescAndFn) -> TestDescAndFn { match test.testfn { - StaticTestFn(f) => TestDescAndFn { - testfn: StaticTestFn(f), - desc: test.desc.clone(), - }, - StaticBenchFn(f) => TestDescAndFn { - testfn: StaticBenchFn(f), - desc: test.desc.clone(), - }, + StaticTestFn(f) => TestDescAndFn { testfn: StaticTestFn(f), desc: test.desc.clone() }, + StaticBenchFn(f) => TestDescAndFn { testfn: StaticBenchFn(f), desc: test.desc.clone() }, _ => panic!("non-static tests passed to test::test_main_static"), } } @@ -205,7 +200,7 @@ pub fn assert_test_result<T: Termination>(result: T) { pub fn run_tests<F>( opts: &TestOpts, tests: Vec<TestDescAndFn>, - mut notify_about_test_event: F + mut notify_about_test_event: F, ) -> io::Result<()> where F: FnMut(TestEvent) -> io::Result<()>, @@ -267,13 +262,7 @@ where let now = Instant::now(); let timed_out = running_tests .iter() - .filter_map(|(desc, timeout)| { - if &now >= timeout { - Some(desc.clone()) - } else { - None - } - }) + .filter_map(|(desc, timeout)| if &now >= timeout { Some(desc.clone()) } else { None }) .collect(); for test in &timed_out { running_tests.remove(test); @@ -284,11 +273,7 @@ where fn calc_timeout(running_tests: &TestMap) -> Option<Duration> { running_tests.values().min().map(|next_timeout| { let now = Instant::now(); - if *next_timeout >= now { - *next_timeout - now - } else { - Duration::new(0, 0) - } + if *next_timeout >= now { *next_timeout - now } else { Duration::new(0, 0) } }) }; @@ -391,15 +376,11 @@ pub fn filter_tests(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> Vec<TestDescA // maybe unignore tests match opts.run_ignored { RunIgnored::Yes => { - filtered - .iter_mut() - .for_each(|test| test.desc.ignore = false); + filtered.iter_mut().for_each(|test| test.desc.ignore = false); } RunIgnored::Only => { filtered.retain(|test| test.desc.ignore); - filtered - .iter_mut() - .for_each(|test| test.desc.ignore = false); + filtered.iter_mut().for_each(|test| test.desc.ignore = false); } RunIgnored::No => {} } @@ -424,10 +405,7 @@ pub fn convert_benchmarks_to_tests(tests: Vec<TestDescAndFn>) -> Vec<TestDescAnd })), f => f, }; - TestDescAndFn { - desc: x.desc, - testfn, - } + TestDescAndFn { desc: x.desc, testfn } }) .collect() } @@ -444,7 +422,8 @@ pub fn run_test( // Emscripten can catch panics but other wasm targets cannot let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No - && cfg!(target_arch = "wasm32") && !cfg!(target_os = "emscripten"); + && cfg!(target_arch = "wasm32") + && !cfg!(target_os = "emscripten"); if force_ignore || desc.ignore || ignore_because_no_process_support { let message = CompletedTest::new(desc, TrIgnored, None, Vec::new()); @@ -468,19 +447,17 @@ pub fn run_test( let concurrency = opts.concurrency; let name = desc.name.clone(); - let runtest = move || { - match opts.strategy { - RunStrategy::InProcess => - run_test_in_process( - desc, - opts.nocapture, - opts.time.is_some(), - testfn, - monitor_ch, - opts.time - ), - RunStrategy::SpawnPrimary => - spawn_test_subprocess(desc, opts.time.is_some(), monitor_ch, opts.time), + let runtest = move || match opts.strategy { + RunStrategy::InProcess => run_test_in_process( + desc, + opts.nocapture, + opts.time.is_some(), + testfn, + monitor_ch, + opts.time, + ), + RunStrategy::SpawnPrimary => { + spawn_test_subprocess(desc, opts.time.is_some(), monitor_ch, opts.time) } }; @@ -496,12 +473,8 @@ pub fn run_test( } } - let test_run_opts = TestRunOpts { - strategy, - nocapture: opts.nocapture, - concurrency, - time: opts.time_options - }; + let test_run_opts = + TestRunOpts { strategy, nocapture: opts.nocapture, concurrency, time: opts.time_options }; match testfn { DynBenchFn(bencher) => { @@ -597,13 +570,14 @@ fn spawn_test_subprocess( let start = report_time.then(Instant::now); let output = match Command::new(current_exe) .env(SECONDARY_TEST_INVOKER_VAR, desc.name.as_slice()) - .output() { - Ok(out) => out, - Err(e) => { - let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e); - return (TrFailed, err.into_bytes(), None); - } - }; + .output() + { + Ok(out) => out, + Err(e) => { + let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e); + return (TrFailed, err.into_bytes(), None); + } + }; let exec_time = start.map(|start| { let duration = start.elapsed(); TestExecTime(duration) @@ -632,10 +606,7 @@ fn spawn_test_subprocess( monitor_ch.send(message).unwrap(); } -fn run_test_in_spawned_subprocess( - desc: TestDesc, - testfn: Box<dyn FnOnce() + Send>, -) -> ! { +fn run_test_in_spawned_subprocess(desc: TestDesc, testfn: Box<dyn FnOnce() + Send>) -> ! { let builtin_panic_hook = panic::take_hook(); let record_result = Arc::new(move |panic_info: Option<&'_ PanicInfo<'_>>| { let test_result = match panic_info { diff --git a/src/libtest/options.rs b/src/libtest/options.rs index ec87b0fcd46..7db164c269a 100644 --- a/src/libtest/options.rs +++ b/src/libtest/options.rs @@ -72,10 +72,7 @@ pub struct Options { impl Options { pub fn new() -> Options { - Options { - display_output: false, - panic_abort: false, - } + Options { display_output: false, panic_abort: false } } pub fn display_output(mut self, display_output: bool) -> Options { diff --git a/src/libtest/stats/tests.rs b/src/libtest/stats/tests.rs index eaf41bc9e22..5bfd1d3885f 100644 --- a/src/libtest/stats/tests.rs +++ b/src/libtest/stats/tests.rs @@ -1,22 +1,17 @@ use super::*; extern crate test; +use self::test::test::Bencher; use std::f64; -use std::io::prelude::*; use std::io; -use self::test::test::Bencher; +use std::io::prelude::*; // Test vectors generated from R, using the script src/etc/stat-test-vectors.r. macro_rules! assert_approx_eq { ($a: expr, $b: expr) => {{ let (a, b) = (&$a, &$b); - assert!( - (*a - *b).abs() < 1.0e-6, - "{} is not approximately equal to {}", - *a, - *b - ); + assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b); }}; } diff --git a/src/libtest/test_result.rs b/src/libtest/test_result.rs index bfabe1722db..bfa572c887a 100644 --- a/src/libtest/test_result.rs +++ b/src/libtest/test_result.rs @@ -1,9 +1,9 @@ use std::any::Any; use super::bench::BenchSamples; +use super::options::ShouldPanic; use super::time; use super::types::TestDesc; -use super::options::ShouldPanic; pub use self::TestResult::*; @@ -32,7 +32,7 @@ pub fn calc_result<'a>( desc: &TestDesc, task_result: Result<(), &'a (dyn Any + 'static + Send)>, time_opts: &Option<time::TestTimeOptions>, - exec_time: &Option<time::TestExecTime> + exec_time: &Option<time::TestExecTime>, ) -> TestResult { let result = match (&desc.should_panic, task_result) { (&ShouldPanic::No, Ok(())) | (&ShouldPanic::Yes, Err(_)) => TestResult::TrOk, diff --git a/src/libtest/tests.rs b/src/libtest/tests.rs index 0bea2b80ecf..85a0705f69c 100644 --- a/src/libtest/tests.rs +++ b/src/libtest/tests.rs @@ -3,17 +3,29 @@ use super::*; use crate::{ bench::Bencher, console::OutputLocation, - options::OutputFormat, - time::{TimeThreshold, TestTimeOptions}, formatters::PrettyFormatter, + options::OutputFormat, test::{ - filter_tests, parse_opts, run_test, DynTestFn, DynTestName, MetricMap, - RunIgnored, RunStrategy, ShouldPanic, StaticTestName, TestDesc, - TestDescAndFn, TestOpts, TrIgnored, TrOk, + filter_tests, + parse_opts, + run_test, + DynTestFn, + DynTestName, + MetricMap, + RunIgnored, + RunStrategy, + ShouldPanic, + StaticTestName, + TestDesc, + TestDescAndFn, + TestOpts, + TrIgnored, + TrOk, // FIXME (introduced by #65251) // ShouldPanic, StaticTestName, TestDesc, TestDescAndFn, TestOpts, TestTimeOptions, // TestType, TrFailedMsg, TrIgnored, TrOk, }, + time::{TestTimeOptions, TimeThreshold}, }; use std::any::TypeId; use std::sync::mpsc::channel; @@ -190,9 +202,12 @@ fn test_should_panic_non_string_message_type() { panic!(1i32); } let expected = "foobar"; - let failed_msg = format!(r#"expected panic with string value, + let failed_msg = format!( + r#"expected panic with string value, found non-string value: `{:?}` - expected substring: `"foobar"`"#, TypeId::of::<i32>()); + expected substring: `"foobar"`"#, + TypeId::of::<i32>() + ); let desc = TestDescAndFn { desc: TestDesc { name: StaticTestName("whatever"), @@ -242,16 +257,9 @@ fn report_time_test_template(report_time: bool) -> Option<TestExecTime> { }, testfn: DynTestFn(Box::new(f)), }; - let time_options = if report_time { - Some(TestTimeOptions::default()) - } else { - None - }; + let time_options = if report_time { Some(TestTimeOptions::default()) } else { None }; - let test_opts = TestOpts { - time_options, - ..TestOpts::new() - }; + let test_opts = TestOpts { time_options, ..TestOpts::new() }; let (tx, rx) = channel(); run_test(&test_opts, false, desc, RunStrategy::InProcess, tx, Concurrent::No); let exec_time = rx.recv().unwrap().exec_time; @@ -278,7 +286,7 @@ fn time_test_failure_template(test_type: TestType) -> TestResult { ignore: false, should_panic: ShouldPanic::No, allow_fail: false, - test_type + test_type, }, testfn: DynTestFn(Box::new(f)), }; @@ -286,10 +294,7 @@ fn time_test_failure_template(test_type: TestType) -> TestResult { let mut time_options = TestTimeOptions::default(); time_options.error_on_excess = true; - let test_opts = TestOpts { - time_options: Some(time_options), - ..TestOpts::new() - }; + let test_opts = TestOpts { time_options: Some(time_options), ..TestOpts::new() }; let (tx, rx) = channel(); run_test(&test_opts, false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; @@ -318,7 +323,7 @@ fn typed_test_desc(test_type: TestType) -> TestDesc { ignore: false, should_panic: ShouldPanic::No, allow_fail: false, - test_type + test_type, } } @@ -363,22 +368,14 @@ fn test_time_options_threshold() { #[test] fn parse_ignored_flag() { - let args = vec![ - "progname".to_string(), - "filter".to_string(), - "--ignored".to_string(), - ]; + let args = vec!["progname".to_string(), "filter".to_string(), "--ignored".to_string()]; let opts = parse_opts(&args).unwrap().unwrap(); assert_eq!(opts.run_ignored, RunIgnored::Only); } #[test] fn parse_show_output_flag() { - let args = vec![ - "progname".to_string(), - "filter".to_string(), - "--show-output".to_string(), - ]; + let args = vec!["progname".to_string(), "filter".to_string(), "--show-output".to_string()]; let opts = parse_opts(&args).unwrap().unwrap(); assert!(opts.options.display_output); } @@ -471,78 +468,41 @@ pub fn exact_filter_match() { .collect() } - let substr = filter_tests( - &TestOpts { - filter: Some("base".into()), - ..TestOpts::new() - }, - tests(), - ); + let substr = + filter_tests(&TestOpts { filter: Some("base".into()), ..TestOpts::new() }, tests()); assert_eq!(substr.len(), 4); - let substr = filter_tests( - &TestOpts { - filter: Some("bas".into()), - ..TestOpts::new() - }, - tests(), - ); + let substr = filter_tests(&TestOpts { filter: Some("bas".into()), ..TestOpts::new() }, tests()); assert_eq!(substr.len(), 4); - let substr = filter_tests( - &TestOpts { - filter: Some("::test".into()), - ..TestOpts::new() - }, - tests(), - ); + let substr = + filter_tests(&TestOpts { filter: Some("::test".into()), ..TestOpts::new() }, tests()); assert_eq!(substr.len(), 3); - let substr = filter_tests( - &TestOpts { - filter: Some("base::test".into()), - ..TestOpts::new() - }, - tests(), - ); + let substr = + filter_tests(&TestOpts { filter: Some("base::test".into()), ..TestOpts::new() }, tests()); assert_eq!(substr.len(), 3); let exact = filter_tests( - &TestOpts { - filter: Some("base".into()), - filter_exact: true, - ..TestOpts::new() - }, + &TestOpts { filter: Some("base".into()), filter_exact: true, ..TestOpts::new() }, tests(), ); assert_eq!(exact.len(), 1); let exact = filter_tests( - &TestOpts { - filter: Some("bas".into()), - filter_exact: true, - ..TestOpts::new() - }, + &TestOpts { filter: Some("bas".into()), filter_exact: true, ..TestOpts::new() }, tests(), ); assert_eq!(exact.len(), 0); let exact = filter_tests( - &TestOpts { - filter: Some("::test".into()), - filter_exact: true, - ..TestOpts::new() - }, + &TestOpts { filter: Some("::test".into()), filter_exact: true, ..TestOpts::new() }, tests(), ); assert_eq!(exact.len(), 0); let exact = filter_tests( - &TestOpts { - filter: Some("base::test".into()), - filter_exact: true, - ..TestOpts::new() - }, + &TestOpts { filter: Some("base::test".into()), filter_exact: true, ..TestOpts::new() }, tests(), ); assert_eq!(exact.len(), 1); diff --git a/src/libtest/time.rs b/src/libtest/time.rs index f4d4b17b620..96c090f9b01 100644 --- a/src/libtest/time.rs +++ b/src/libtest/time.rs @@ -4,10 +4,10 @@ //! - Check whether test is timed out. //! - Provide helpers for `report-time` and `measure-time` options. -use std::time::{Duration, Instant}; -use std::str::FromStr; -use std::fmt; use std::env; +use std::fmt; +use std::str::FromStr; +use std::time::{Duration, Instant}; use super::types::{TestDesc, TestType}; @@ -23,8 +23,8 @@ pub const TEST_WARN_TIMEOUT_S: u64 = 60; /// Example of the expected format is `RUST_TEST_TIME_xxx=100,200`, where 100 means /// warn time, and 200 means critical time. pub mod time_constants { - use std::time::Duration; use super::TEST_WARN_TIMEOUT_S; + use std::time::Duration; /// Environment variable for overriding default threshold for unit-tests. pub const UNIT_ENV_NAME: &str = "RUST_TEST_TIME_UNIT"; @@ -80,10 +80,7 @@ pub struct TimeThreshold { impl TimeThreshold { /// Creates a new `TimeThreshold` instance with provided durations. pub fn new(warn: Duration, critical: Duration) -> Self { - Self { - warn, - critical, - } + Self { warn, critical } } /// Attempts to create a `TimeThreshold` instance with values obtained @@ -99,16 +96,14 @@ impl TimeThreshold { let durations_str = env::var(env_var_name).ok()?; // Split string into 2 substrings by comma and try to parse numbers. - let mut durations = durations_str - .splitn(2, ',') - .map(|v| { - u64::from_str(v).unwrap_or_else(|_| { - panic!( - "Duration value in variable {} is expected to be a number, but got {}", - env_var_name, v - ) - }) - }); + let mut durations = durations_str.splitn(2, ',').map(|v| { + u64::from_str(v).unwrap_or_else(|_| { + panic!( + "Duration value in variable {} is expected to be a number, but got {}", + env_var_name, v + ) + }) + }); // Callback to be called if the environment variable has unexpected structure. let panic_on_incorrect_value = || { @@ -120,7 +115,7 @@ impl TimeThreshold { let (warn, critical) = ( durations.next().unwrap_or_else(panic_on_incorrect_value), - durations.next().unwrap_or_else(panic_on_incorrect_value) + durations.next().unwrap_or_else(panic_on_incorrect_value), ); if warn > critical { @@ -145,25 +140,17 @@ pub struct TestTimeOptions { impl TestTimeOptions { pub fn new_from_env(error_on_excess: bool, colored: bool) -> Self { - let unit_threshold = - TimeThreshold::from_env_var(time_constants::UNIT_ENV_NAME) - .unwrap_or_else(Self::default_unit); + let unit_threshold = TimeThreshold::from_env_var(time_constants::UNIT_ENV_NAME) + .unwrap_or_else(Self::default_unit); let integration_threshold = TimeThreshold::from_env_var(time_constants::INTEGRATION_ENV_NAME) .unwrap_or_else(Self::default_integration); - let doctest_threshold = - TimeThreshold::from_env_var(time_constants::DOCTEST_ENV_NAME) - .unwrap_or_else(Self::default_doctest); + let doctest_threshold = TimeThreshold::from_env_var(time_constants::DOCTEST_ENV_NAME) + .unwrap_or_else(Self::default_doctest); - Self { - error_on_excess, - colored, - unit_threshold, - integration_threshold, - doctest_threshold, - } + Self { error_on_excess, colored, unit_threshold, integration_threshold, doctest_threshold } } pub fn is_warn(&self, test: &TestDesc, exec_time: &TestExecTime) -> bool { diff --git a/src/libtest/types.rs b/src/libtest/types.rs index 89bcf2cf285..2619f99592a 100644 --- a/src/libtest/types.rs +++ b/src/libtest/types.rs @@ -1,14 +1,14 @@ //! Common types used by `libtest`. -use std::fmt; use std::borrow::Cow; +use std::fmt; -use super::options; use super::bench::Bencher; +use super::options; pub use NamePadding::*; -pub use TestName::*; pub use TestFn::*; +pub use TestName::*; /// Type of the test according to the [rust book](https://doc.rust-lang.org/cargo/guide/tests.html) /// conventions. |
