]> git.lizzy.rs Git - rust.git/blob - src/libtest/lib.rs
auto merge of #13704 : edwardw/rust/doc-hidden, r=alexcrichton
[rust.git] / src / libtest / lib.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Support code for rustc's built in unit-test and micro-benchmarking
12 //! framework.
13 //!
14 //! Almost all user code will only be interested in `Bencher` and
15 //! `black_box`. All other interactions (such as writing tests and
16 //! benchmarks themselves) should be done via the `#[test]` and
17 //! `#[bench]` attributes.
18 //!
19 //! See the [Testing Guide](../guide-testing.html) for more details.
20
21 // Currently, not much of this is meant for users. It is intended to
22 // support the simplest interface possible for representing and
23 // running tests while providing a base that other test frameworks may
24 // build off of.
25
26 #![crate_id = "test#0.11-pre"]
27 #![comment = "Rust internal test library only used by rustc"]
28 #![license = "MIT/ASL2"]
29 #![crate_type = "rlib"]
30 #![crate_type = "dylib"]
31 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
32        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
33        html_root_url = "http://static.rust-lang.org/doc/master")]
34
35 #![feature(asm, macro_rules)]
36 #![deny(deprecated_owned_vector)]
37
38 extern crate collections;
39 extern crate getopts;
40 extern crate serialize;
41 extern crate term;
42 extern crate time;
43
44 use collections::TreeMap;
45 use stats::Stats;
46 use time::precise_time_ns;
47 use getopts::{OptGroup, optflag, optopt};
48 use serialize::{json, Decodable};
49 use serialize::json::{Json, ToJson};
50 use term::Terminal;
51 use term::color::{Color, RED, YELLOW, GREEN, CYAN};
52
53 use std::cmp;
54 use std::f64;
55 use std::fmt;
56 use std::from_str::FromStr;
57 use std::io::stdio::StdWriter;
58 use std::io::{File, ChanReader, ChanWriter};
59 use std::io;
60 use std::os;
61 use std::str;
62 use std::strbuf::StrBuf;
63 use std::task::TaskBuilder;
64
65 // to be used by rustc to compile tests in libtest
66 pub mod test {
67     pub use {Bencher, TestName, TestResult, TestDesc,
68              TestDescAndFn, TestOpts, TrFailed, TrIgnored, TrOk,
69              Metric, MetricMap, MetricAdded, MetricRemoved,
70              MetricChange, Improvement, Regression, LikelyNoise,
71              StaticTestFn, StaticTestName, DynTestName, DynTestFn,
72              run_test, test_main, test_main_static, filter_tests,
73              parse_opts, StaticBenchFn};
74 }
75
76 pub mod stats;
77
78 // The name of a test. By convention this follows the rules for rust
79 // paths; i.e. it should be a series of identifiers separated by double
80 // colons. This way if some test runner wants to arrange the tests
81 // hierarchically it may.
82
83 #[deriving(Clone)]
84 pub enum TestName {
85     StaticTestName(&'static str),
86     DynTestName(~str)
87 }
88 impl fmt::Show for TestName {
89     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90         match *self {
91             StaticTestName(s) => f.buf.write_str(s),
92             DynTestName(ref s) => f.buf.write_str(s.as_slice()),
93         }
94     }
95 }
96
97 #[deriving(Clone)]
98 enum NamePadding { PadNone, PadOnLeft, PadOnRight }
99
100 impl TestDesc {
101     fn padded_name(&self, column_count: uint, align: NamePadding) -> ~str {
102         use std::num::Saturating;
103         let mut name = StrBuf::from_str(self.name.to_str());
104         let fill = column_count.saturating_sub(name.len());
105         let mut pad = StrBuf::from_owned_str(" ".repeat(fill));
106         match align {
107             PadNone => name.into_owned(),
108             PadOnLeft => {
109                 pad.push_str(name.as_slice());
110                 pad.into_owned()
111             }
112             PadOnRight => {
113                 name.push_str(pad.as_slice());
114                 name.into_owned()
115             }
116         }
117     }
118 }
119
120 /// Represents a benchmark function.
121 pub trait TDynBenchFn {
122     fn run(&self, harness: &mut Bencher);
123 }
124
125 // A function that runs a test. If the function returns successfully,
126 // the test succeeds; if the function fails then the test fails. We
127 // may need to come up with a more clever definition of test in order
128 // to support isolation of tests into tasks.
129 pub enum TestFn {
130     StaticTestFn(fn()),
131     StaticBenchFn(fn(&mut Bencher)),
132     StaticMetricFn(proc(&mut MetricMap)),
133     DynTestFn(proc():Send),
134     DynMetricFn(proc(&mut MetricMap)),
135     DynBenchFn(~TDynBenchFn)
136 }
137
138 impl TestFn {
139     fn padding(&self) -> NamePadding {
140         match self {
141             &StaticTestFn(..)   => PadNone,
142             &StaticBenchFn(..)  => PadOnRight,
143             &StaticMetricFn(..) => PadOnRight,
144             &DynTestFn(..)      => PadNone,
145             &DynMetricFn(..)    => PadOnRight,
146             &DynBenchFn(..)     => PadOnRight,
147         }
148     }
149 }
150
151 /// Manager of the benchmarking runs.
152 ///
153 /// This is feed into functions marked with `#[bench]` to allow for
154 /// set-up & tear-down before running a piece of code repeatedly via a
155 /// call to `iter`.
156 pub struct Bencher {
157     iterations: u64,
158     ns_start: u64,
159     ns_end: u64,
160     pub bytes: u64,
161 }
162
163 // The definition of a single test. A test runner will run a list of
164 // these.
165 #[deriving(Clone)]
166 pub struct TestDesc {
167     pub name: TestName,
168     pub ignore: bool,
169     pub should_fail: bool,
170 }
171
172 pub struct TestDescAndFn {
173     pub desc: TestDesc,
174     pub testfn: TestFn,
175 }
176
177 #[deriving(Clone, Encodable, Decodable, Eq, Show)]
178 pub struct Metric {
179     value: f64,
180     noise: f64
181 }
182
183 impl Metric {
184     pub fn new(value: f64, noise: f64) -> Metric {
185         Metric {value: value, noise: noise}
186     }
187 }
188
189 #[deriving(Eq)]
190 pub struct MetricMap(TreeMap<~str,Metric>);
191
192 impl Clone for MetricMap {
193     fn clone(&self) -> MetricMap {
194         let MetricMap(ref map) = *self;
195         MetricMap(map.clone())
196     }
197 }
198
199 /// Analysis of a single change in metric
200 #[deriving(Eq, Show)]
201 pub enum MetricChange {
202     LikelyNoise,
203     MetricAdded,
204     MetricRemoved,
205     Improvement(f64),
206     Regression(f64)
207 }
208
209 pub type MetricDiff = TreeMap<~str,MetricChange>;
210
211 // The default console test runner. It accepts the command line
212 // arguments and a vector of test_descs.
213 pub fn test_main(args: &[~str], tests: Vec<TestDescAndFn> ) {
214     let opts =
215         match parse_opts(args) {
216             Some(Ok(o)) => o,
217             Some(Err(msg)) => fail!("{}", msg),
218             None => return
219         };
220     match run_tests_console(&opts, tests) {
221         Ok(true) => {}
222         Ok(false) => fail!("Some tests failed"),
223         Err(e) => fail!("io error when running tests: {}", e),
224     }
225 }
226
227 // A variant optimized for invocation with a static test vector.
228 // This will fail (intentionally) when fed any dynamic tests, because
229 // it is copying the static values out into a dynamic vector and cannot
230 // copy dynamic values. It is doing this because from this point on
231 // a ~[TestDescAndFn] is used in order to effect ownership-transfer
232 // semantics into parallel test runners, which in turn requires a ~[]
233 // rather than a &[].
234 pub fn test_main_static(args: &[~str], tests: &[TestDescAndFn]) {
235     let owned_tests = tests.iter().map(|t| {
236         match t.testfn {
237             StaticTestFn(f) =>
238             TestDescAndFn { testfn: StaticTestFn(f), desc: t.desc.clone() },
239
240             StaticBenchFn(f) =>
241             TestDescAndFn { testfn: StaticBenchFn(f), desc: t.desc.clone() },
242
243             _ => {
244                 fail!("non-static tests passed to test::test_main_static");
245             }
246         }
247     }).collect();
248     test_main(args, owned_tests)
249 }
250
251 pub struct TestOpts {
252     pub filter: Option<~str>,
253     pub run_ignored: bool,
254     pub run_tests: bool,
255     pub run_benchmarks: bool,
256     pub ratchet_metrics: Option<Path>,
257     pub ratchet_noise_percent: Option<f64>,
258     pub save_metrics: Option<Path>,
259     pub test_shard: Option<(uint,uint)>,
260     pub logfile: Option<Path>
261 }
262
263 /// Result of parsing the options.
264 pub type OptRes = Result<TestOpts, ~str>;
265
266 fn optgroups() -> Vec<getopts::OptGroup> {
267     vec!(getopts::optflag("", "ignored", "Run ignored tests"),
268       getopts::optflag("", "test", "Run tests and not benchmarks"),
269       getopts::optflag("", "bench", "Run benchmarks instead of tests"),
270       getopts::optflag("h", "help", "Display this message (longer with --help)"),
271       getopts::optopt("", "save-metrics", "Location to save bench metrics",
272                      "PATH"),
273       getopts::optopt("", "ratchet-metrics",
274                      "Location to load and save metrics from. The metrics \
275                       loaded are cause benchmarks to fail if they run too \
276                       slowly", "PATH"),
277       getopts::optopt("", "ratchet-noise-percent",
278                      "Tests within N% of the recorded metrics will be \
279                       considered as passing", "PERCENTAGE"),
280       getopts::optopt("", "logfile", "Write logs to the specified file instead \
281                           of stdout", "PATH"),
282       getopts::optopt("", "test-shard", "run shard A, of B shards, worth of the testsuite",
283                      "A.B"))
284 }
285
286 fn usage(binary: &str, helpstr: &str) {
287     let message = format!("Usage: {} [OPTIONS] [FILTER]", binary);
288     println!("{}", getopts::usage(message, optgroups().as_slice()));
289     println!("");
290     if helpstr == "help" {
291         println!("{}", "\
292 The FILTER is matched against the name of all tests to run, and if any tests
293 have a substring match, only those tests are run.
294
295 By default, all tests are run in parallel. This can be altered with the
296 RUST_TEST_TASKS environment variable when running tests (set it to 1).
297
298 Test Attributes:
299
300     #[test]        - Indicates a function is a test to be run. This function
301                      takes no arguments.
302     #[bench]       - Indicates a function is a benchmark to be run. This
303                      function takes one argument (test::Bencher).
304     #[should_fail] - This function (also labeled with #[test]) will only pass if
305                      the code causes a failure (an assertion failure or fail!)
306     #[ignore]      - When applied to a function which is already attributed as a
307                      test, then the test runner will ignore these tests during
308                      normal test runs. Running with --ignored will run these
309                      tests. This may also be written as #[ignore(cfg(...))] to
310                      ignore the test on certain configurations.");
311     }
312 }
313
314 // Parses command line arguments into test options
315 pub fn parse_opts(args: &[~str]) -> Option<OptRes> {
316     let args_ = args.tail();
317     let matches =
318         match getopts::getopts(args_, optgroups().as_slice()) {
319           Ok(m) => m,
320           Err(f) => return Some(Err(f.to_err_msg()))
321         };
322
323     if matches.opt_present("h") { usage(args[0], "h"); return None; }
324     if matches.opt_present("help") { usage(args[0], "help"); return None; }
325
326     let filter =
327         if matches.free.len() > 0 {
328             Some((*matches.free.get(0)).clone())
329         } else {
330             None
331         };
332
333     let run_ignored = matches.opt_present("ignored");
334
335     let logfile = matches.opt_str("logfile");
336     let logfile = logfile.map(|s| Path::new(s));
337
338     let run_benchmarks = matches.opt_present("bench");
339     let run_tests = ! run_benchmarks ||
340         matches.opt_present("test");
341
342     let ratchet_metrics = matches.opt_str("ratchet-metrics");
343     let ratchet_metrics = ratchet_metrics.map(|s| Path::new(s));
344
345     let ratchet_noise_percent = matches.opt_str("ratchet-noise-percent");
346     let ratchet_noise_percent = ratchet_noise_percent.map(|s| from_str::<f64>(s).unwrap());
347
348     let save_metrics = matches.opt_str("save-metrics");
349     let save_metrics = save_metrics.map(|s| Path::new(s));
350
351     let test_shard = matches.opt_str("test-shard");
352     let test_shard = opt_shard(test_shard);
353
354     let test_opts = TestOpts {
355         filter: filter,
356         run_ignored: run_ignored,
357         run_tests: run_tests,
358         run_benchmarks: run_benchmarks,
359         ratchet_metrics: ratchet_metrics,
360         ratchet_noise_percent: ratchet_noise_percent,
361         save_metrics: save_metrics,
362         test_shard: test_shard,
363         logfile: logfile
364     };
365
366     Some(Ok(test_opts))
367 }
368
369 pub fn opt_shard(maybestr: Option<~str>) -> Option<(uint,uint)> {
370     match maybestr {
371         None => None,
372         Some(s) => {
373             let mut it = s.split('.');
374             match (it.next().and_then(from_str), it.next().and_then(from_str), it.next()) {
375                 (Some(a), Some(b), None) => Some((a, b)),
376                 _ => None,
377             }
378         }
379     }
380 }
381
382
383 #[deriving(Clone, Eq)]
384 pub struct BenchSamples {
385     ns_iter_summ: stats::Summary,
386     mb_s: uint,
387 }
388
389 #[deriving(Clone, Eq)]
390 pub enum TestResult {
391     TrOk,
392     TrFailed,
393     TrIgnored,
394     TrMetrics(MetricMap),
395     TrBench(BenchSamples),
396 }
397
398 enum OutputLocation<T> {
399     Pretty(term::Terminal<T>),
400     Raw(T),
401 }
402
403 struct ConsoleTestState<T> {
404     log_out: Option<File>,
405     out: OutputLocation<T>,
406     use_color: bool,
407     total: uint,
408     passed: uint,
409     failed: uint,
410     ignored: uint,
411     measured: uint,
412     metrics: MetricMap,
413     failures: Vec<(TestDesc, Vec<u8> )> ,
414     max_name_len: uint, // number of columns to fill when aligning names
415 }
416
417 impl<T: Writer> ConsoleTestState<T> {
418     pub fn new(opts: &TestOpts,
419                _: Option<T>) -> io::IoResult<ConsoleTestState<StdWriter>> {
420         let log_out = match opts.logfile {
421             Some(ref path) => Some(try!(File::create(path))),
422             None => None
423         };
424         let out = match term::Terminal::new(io::stdio::stdout_raw()) {
425             Err(_) => Raw(io::stdio::stdout_raw()),
426             Ok(t) => Pretty(t)
427         };
428         Ok(ConsoleTestState {
429             out: out,
430             log_out: log_out,
431             use_color: use_color(),
432             total: 0u,
433             passed: 0u,
434             failed: 0u,
435             ignored: 0u,
436             measured: 0u,
437             metrics: MetricMap::new(),
438             failures: Vec::new(),
439             max_name_len: 0u,
440         })
441     }
442
443     pub fn write_ok(&mut self) -> io::IoResult<()> {
444         self.write_pretty("ok", term::color::GREEN)
445     }
446
447     pub fn write_failed(&mut self) -> io::IoResult<()> {
448         self.write_pretty("FAILED", term::color::RED)
449     }
450
451     pub fn write_ignored(&mut self) -> io::IoResult<()> {
452         self.write_pretty("ignored", term::color::YELLOW)
453     }
454
455     pub fn write_metric(&mut self) -> io::IoResult<()> {
456         self.write_pretty("metric", term::color::CYAN)
457     }
458
459     pub fn write_bench(&mut self) -> io::IoResult<()> {
460         self.write_pretty("bench", term::color::CYAN)
461     }
462
463     pub fn write_added(&mut self) -> io::IoResult<()> {
464         self.write_pretty("added", term::color::GREEN)
465     }
466
467     pub fn write_improved(&mut self) -> io::IoResult<()> {
468         self.write_pretty("improved", term::color::GREEN)
469     }
470
471     pub fn write_removed(&mut self) -> io::IoResult<()> {
472         self.write_pretty("removed", term::color::YELLOW)
473     }
474
475     pub fn write_regressed(&mut self) -> io::IoResult<()> {
476         self.write_pretty("regressed", term::color::RED)
477     }
478
479     pub fn write_pretty(&mut self,
480                         word: &str,
481                         color: term::color::Color) -> io::IoResult<()> {
482         match self.out {
483             Pretty(ref mut term) => {
484                 if self.use_color {
485                     try!(term.fg(color));
486                 }
487                 try!(term.write(word.as_bytes()));
488                 if self.use_color {
489                     try!(term.reset());
490                 }
491                 Ok(())
492             }
493             Raw(ref mut stdout) => stdout.write(word.as_bytes())
494         }
495     }
496
497     pub fn write_plain(&mut self, s: &str) -> io::IoResult<()> {
498         match self.out {
499             Pretty(ref mut term) => term.write(s.as_bytes()),
500             Raw(ref mut stdout) => stdout.write(s.as_bytes())
501         }
502     }
503
504     pub fn write_run_start(&mut self, len: uint) -> io::IoResult<()> {
505         self.total = len;
506         let noun = if len != 1 { &"tests" } else { &"test" };
507         self.write_plain(format!("\nrunning {} {}\n", len, noun))
508     }
509
510     pub fn write_test_start(&mut self, test: &TestDesc,
511                             align: NamePadding) -> io::IoResult<()> {
512         let name = test.padded_name(self.max_name_len, align);
513         self.write_plain(format!("test {} ... ", name))
514     }
515
516     pub fn write_result(&mut self, result: &TestResult) -> io::IoResult<()> {
517         try!(match *result {
518             TrOk => self.write_ok(),
519             TrFailed => self.write_failed(),
520             TrIgnored => self.write_ignored(),
521             TrMetrics(ref mm) => {
522                 try!(self.write_metric());
523                 self.write_plain(format!(": {}", fmt_metrics(mm)))
524             }
525             TrBench(ref bs) => {
526                 try!(self.write_bench());
527                 self.write_plain(format!(": {}", fmt_bench_samples(bs)))
528             }
529         });
530         self.write_plain("\n")
531     }
532
533     pub fn write_log(&mut self, test: &TestDesc,
534                      result: &TestResult) -> io::IoResult<()> {
535         match self.log_out {
536             None => Ok(()),
537             Some(ref mut o) => {
538                 let s = format!("{} {}\n", match *result {
539                         TrOk => "ok".to_owned(),
540                         TrFailed => "failed".to_owned(),
541                         TrIgnored => "ignored".to_owned(),
542                         TrMetrics(ref mm) => fmt_metrics(mm),
543                         TrBench(ref bs) => fmt_bench_samples(bs)
544                     }, test.name.to_str());
545                 o.write(s.as_bytes())
546             }
547         }
548     }
549
550     pub fn write_failures(&mut self) -> io::IoResult<()> {
551         try!(self.write_plain("\nfailures:\n"));
552         let mut failures = Vec::new();
553         let mut fail_out = StrBuf::new();
554         for &(ref f, ref stdout) in self.failures.iter() {
555             failures.push(f.name.to_str());
556             if stdout.len() > 0 {
557                 fail_out.push_str(format!("---- {} stdout ----\n\t",
558                                   f.name.to_str()));
559                 let output = str::from_utf8_lossy(stdout.as_slice());
560                 fail_out.push_str(output.as_slice().replace("\n", "\n\t"));
561                 fail_out.push_str("\n");
562             }
563         }
564         if fail_out.len() > 0 {
565             try!(self.write_plain("\n"));
566             try!(self.write_plain(fail_out.as_slice()));
567         }
568
569         try!(self.write_plain("\nfailures:\n"));
570         failures.as_mut_slice().sort();
571         for name in failures.iter() {
572             try!(self.write_plain(format!("    {}\n", name.to_str())));
573         }
574         Ok(())
575     }
576
577     pub fn write_metric_diff(&mut self, diff: &MetricDiff) -> io::IoResult<()> {
578         let mut noise = 0;
579         let mut improved = 0;
580         let mut regressed = 0;
581         let mut added = 0;
582         let mut removed = 0;
583
584         for (k, v) in diff.iter() {
585             match *v {
586                 LikelyNoise => noise += 1,
587                 MetricAdded => {
588                     added += 1;
589                     try!(self.write_added());
590                     try!(self.write_plain(format!(": {}\n", *k)));
591                 }
592                 MetricRemoved => {
593                     removed += 1;
594                     try!(self.write_removed());
595                     try!(self.write_plain(format!(": {}\n", *k)));
596                 }
597                 Improvement(pct) => {
598                     improved += 1;
599                     try!(self.write_plain(format!(": {}", *k)));
600                     try!(self.write_improved());
601                     try!(self.write_plain(format!(" by {:.2f}%\n", pct as f64)));
602                 }
603                 Regression(pct) => {
604                     regressed += 1;
605                     try!(self.write_plain(format!(": {}", *k)));
606                     try!(self.write_regressed());
607                     try!(self.write_plain(format!(" by {:.2f}%\n", pct as f64)));
608                 }
609             }
610         }
611         try!(self.write_plain(format!("result of ratchet: {} metrics added, \
612                                         {} removed, {} improved, {} regressed, \
613                                         {} noise\n",
614                                        added, removed, improved, regressed,
615                                        noise)));
616         if regressed == 0 {
617             try!(self.write_plain("updated ratchet file\n"));
618         } else {
619             try!(self.write_plain("left ratchet file untouched\n"));
620         }
621         Ok(())
622     }
623
624     pub fn write_run_finish(&mut self,
625                             ratchet_metrics: &Option<Path>,
626                             ratchet_pct: Option<f64>) -> io::IoResult<bool> {
627         assert!(self.passed + self.failed + self.ignored + self.measured == self.total);
628
629         let ratchet_success = match *ratchet_metrics {
630             None => true,
631             Some(ref pth) => {
632                 try!(self.write_plain(format!("\nusing metrics ratchet: {}\n",
633                                         pth.display())));
634                 match ratchet_pct {
635                     None => (),
636                     Some(pct) =>
637                         try!(self.write_plain(format!("with noise-tolerance \
638                                                          forced to: {}%\n",
639                                                         pct)))
640                 }
641                 let (diff, ok) = self.metrics.ratchet(pth, ratchet_pct);
642                 try!(self.write_metric_diff(&diff));
643                 ok
644             }
645         };
646
647         let test_success = self.failed == 0u;
648         if !test_success {
649             try!(self.write_failures());
650         }
651
652         let success = ratchet_success && test_success;
653
654         try!(self.write_plain("\ntest result: "));
655         if success {
656             // There's no parallelism at this point so it's safe to use color
657             try!(self.write_ok());
658         } else {
659             try!(self.write_failed());
660         }
661         let s = format!(". {} passed; {} failed; {} ignored; {} measured\n\n",
662                         self.passed, self.failed, self.ignored, self.measured);
663         try!(self.write_plain(s));
664         return Ok(success);
665     }
666 }
667
668 pub fn fmt_metrics(mm: &MetricMap) -> ~str {
669     let MetricMap(ref mm) = *mm;
670     let v : Vec<~str> = mm.iter()
671         .map(|(k,v)| format!("{}: {} (+/- {})",
672                           *k,
673                           v.value as f64,
674                           v.noise as f64))
675         .collect();
676     v.connect(", ")
677 }
678
679 pub fn fmt_bench_samples(bs: &BenchSamples) -> ~str {
680     if bs.mb_s != 0 {
681         format!("{:>9} ns/iter (+/- {}) = {} MB/s",
682              bs.ns_iter_summ.median as uint,
683              (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as uint,
684              bs.mb_s)
685     } else {
686         format!("{:>9} ns/iter (+/- {})",
687              bs.ns_iter_summ.median as uint,
688              (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as uint)
689     }
690 }
691
692 // A simple console test runner
693 pub fn run_tests_console(opts: &TestOpts,
694                          tests: Vec<TestDescAndFn> ) -> io::IoResult<bool> {
695     fn callback<T: Writer>(event: &TestEvent,
696                            st: &mut ConsoleTestState<T>) -> io::IoResult<()> {
697         match (*event).clone() {
698             TeFiltered(ref filtered_tests) => st.write_run_start(filtered_tests.len()),
699             TeWait(ref test, padding) => st.write_test_start(test, padding),
700             TeResult(test, result, stdout) => {
701                 try!(st.write_log(&test, &result));
702                 try!(st.write_result(&result));
703                 match result {
704                     TrOk => st.passed += 1,
705                     TrIgnored => st.ignored += 1,
706                     TrMetrics(mm) => {
707                         let tname = test.name.to_str();
708                         let MetricMap(mm) = mm;
709                         for (k,v) in mm.iter() {
710                             st.metrics.insert_metric(tname + "." + *k,
711                                                      v.value, v.noise);
712                         }
713                         st.measured += 1
714                     }
715                     TrBench(bs) => {
716                         st.metrics.insert_metric(test.name.to_str(),
717                                                  bs.ns_iter_summ.median,
718                                                  bs.ns_iter_summ.max - bs.ns_iter_summ.min);
719                         st.measured += 1
720                     }
721                     TrFailed => {
722                         st.failed += 1;
723                         st.failures.push((test, stdout));
724                     }
725                 }
726                 Ok(())
727             }
728         }
729     }
730     let mut st = try!(ConsoleTestState::new(opts, None::<StdWriter>));
731     fn len_if_padded(t: &TestDescAndFn) -> uint {
732         match t.testfn.padding() {
733             PadNone => 0u,
734             PadOnLeft | PadOnRight => t.desc.name.to_str().len(),
735         }
736     }
737     match tests.iter().max_by(|t|len_if_padded(*t)) {
738         Some(t) => {
739             let n = t.desc.name.to_str();
740             st.max_name_len = n.len();
741         },
742         None => {}
743     }
744     try!(run_tests(opts, tests, |x| callback(&x, &mut st)));
745     match opts.save_metrics {
746         None => (),
747         Some(ref pth) => {
748             try!(st.metrics.save(pth));
749             try!(st.write_plain(format!("\nmetrics saved to: {}",
750                                           pth.display())));
751         }
752     }
753     return st.write_run_finish(&opts.ratchet_metrics, opts.ratchet_noise_percent);
754 }
755
756 #[test]
757 fn should_sort_failures_before_printing_them() {
758     use std::io::MemWriter;
759     use std::str;
760
761     let test_a = TestDesc {
762         name: StaticTestName("a"),
763         ignore: false,
764         should_fail: false
765     };
766
767     let test_b = TestDesc {
768         name: StaticTestName("b"),
769         ignore: false,
770         should_fail: false
771     };
772
773     let mut st = ConsoleTestState {
774         log_out: None,
775         out: Raw(MemWriter::new()),
776         use_color: false,
777         total: 0u,
778         passed: 0u,
779         failed: 0u,
780         ignored: 0u,
781         measured: 0u,
782         max_name_len: 10u,
783         metrics: MetricMap::new(),
784         failures: vec!((test_b, Vec::new()), (test_a, Vec::new()))
785     };
786
787     st.write_failures().unwrap();
788     let s = match st.out {
789         Raw(ref m) => str::from_utf8_lossy(m.get_ref()),
790         Pretty(_) => unreachable!()
791     };
792
793     let apos = s.as_slice().find_str("a").unwrap();
794     let bpos = s.as_slice().find_str("b").unwrap();
795     assert!(apos < bpos);
796 }
797
798 fn use_color() -> bool { return get_concurrency() == 1; }
799
800 #[deriving(Clone)]
801 enum TestEvent {
802     TeFiltered(Vec<TestDesc> ),
803     TeWait(TestDesc, NamePadding),
804     TeResult(TestDesc, TestResult, Vec<u8> ),
805 }
806
807 pub type MonitorMsg = (TestDesc, TestResult, Vec<u8> );
808
809 fn run_tests(opts: &TestOpts,
810              tests: Vec<TestDescAndFn> ,
811              callback: |e: TestEvent| -> io::IoResult<()>) -> io::IoResult<()> {
812     let filtered_tests = filter_tests(opts, tests);
813     let filtered_descs = filtered_tests.iter()
814                                        .map(|t| t.desc.clone())
815                                        .collect();
816
817     try!(callback(TeFiltered(filtered_descs)));
818
819     let (filtered_tests, filtered_benchs_and_metrics) =
820         filtered_tests.partition(|e| {
821             match e.testfn {
822                 StaticTestFn(_) | DynTestFn(_) => true,
823                 _ => false
824             }
825         });
826
827     // It's tempting to just spawn all the tests at once, but since we have
828     // many tests that run in other processes we would be making a big mess.
829     let concurrency = get_concurrency();
830
831     let mut remaining = filtered_tests;
832     remaining.reverse();
833     let mut pending = 0;
834
835     let (tx, rx) = channel::<MonitorMsg>();
836
837     while pending > 0 || !remaining.is_empty() {
838         while pending < concurrency && !remaining.is_empty() {
839             let test = remaining.pop().unwrap();
840             if concurrency == 1 {
841                 // We are doing one test at a time so we can print the name
842                 // of the test before we run it. Useful for debugging tests
843                 // that hang forever.
844                 try!(callback(TeWait(test.desc.clone(), test.testfn.padding())));
845             }
846             run_test(!opts.run_tests, test, tx.clone());
847             pending += 1;
848         }
849
850         let (desc, result, stdout) = rx.recv();
851         if concurrency != 1 {
852             try!(callback(TeWait(desc.clone(), PadNone)));
853         }
854         try!(callback(TeResult(desc, result, stdout)));
855         pending -= 1;
856     }
857
858     // All benchmarks run at the end, in serial.
859     // (this includes metric fns)
860     for b in filtered_benchs_and_metrics.move_iter() {
861         try!(callback(TeWait(b.desc.clone(), b.testfn.padding())));
862         run_test(!opts.run_benchmarks, b, tx.clone());
863         let (test, result, stdout) = rx.recv();
864         try!(callback(TeResult(test, result, stdout)));
865     }
866     Ok(())
867 }
868
869 fn get_concurrency() -> uint {
870     use std::rt;
871     match os::getenv("RUST_TEST_TASKS") {
872         Some(s) => {
873             let opt_n: Option<uint> = FromStr::from_str(s);
874             match opt_n {
875                 Some(n) if n > 0 => n,
876                 _ => fail!("RUST_TEST_TASKS is `{}`, should be a positive integer.", s)
877             }
878         }
879         None => {
880             rt::default_sched_threads()
881         }
882     }
883 }
884
885 pub fn filter_tests(
886     opts: &TestOpts,
887     tests: Vec<TestDescAndFn> ) -> Vec<TestDescAndFn> {
888     let mut filtered = tests;
889
890     // Remove tests that don't match the test filter
891     filtered = if opts.filter.is_none() {
892         filtered
893     } else {
894         let filter_str = match opts.filter {
895           Some(ref f) => (*f).clone(),
896           None => "".to_owned()
897         };
898
899         fn filter_fn(test: TestDescAndFn, filter_str: &str) ->
900             Option<TestDescAndFn> {
901             if test.desc.name.to_str().contains(filter_str) {
902                 return Some(test);
903             } else {
904                 return None;
905             }
906         }
907
908         filtered.move_iter().filter_map(|x| filter_fn(x, filter_str)).collect()
909     };
910
911     // Maybe pull out the ignored test and unignore them
912     filtered = if !opts.run_ignored {
913         filtered
914     } else {
915         fn filter(test: TestDescAndFn) -> Option<TestDescAndFn> {
916             if test.desc.ignore {
917                 let TestDescAndFn {desc, testfn} = test;
918                 Some(TestDescAndFn {
919                     desc: TestDesc {ignore: false, ..desc},
920                     testfn: testfn
921                 })
922             } else {
923                 None
924             }
925         };
926         filtered.move_iter().filter_map(|x| filter(x)).collect()
927     };
928
929     // Sort the tests alphabetically
930     filtered.sort_by(|t1, t2| t1.desc.name.to_str().cmp(&t2.desc.name.to_str()));
931
932     // Shard the remaining tests, if sharding requested.
933     match opts.test_shard {
934         None => filtered,
935         Some((a,b)) => {
936             filtered.move_iter().enumerate()
937             .filter(|&(i,_)| i % b == a)
938             .map(|(_,t)| t)
939             .collect()
940         }
941     }
942 }
943
944 pub fn run_test(force_ignore: bool,
945                 test: TestDescAndFn,
946                 monitor_ch: Sender<MonitorMsg>) {
947
948     let TestDescAndFn {desc, testfn} = test;
949
950     if force_ignore || desc.ignore {
951         monitor_ch.send((desc, TrIgnored, Vec::new()));
952         return;
953     }
954
955     #[allow(deprecated_owned_vector)]
956     fn run_test_inner(desc: TestDesc,
957                       monitor_ch: Sender<MonitorMsg>,
958                       testfn: proc():Send) {
959         spawn(proc() {
960             let (tx, rx) = channel();
961             let mut reader = ChanReader::new(rx);
962             let stdout = ChanWriter::new(tx.clone());
963             let stderr = ChanWriter::new(tx);
964             let mut task = TaskBuilder::new().named(match desc.name {
965                 DynTestName(ref name) => name.clone().into_maybe_owned(),
966                 StaticTestName(name) => name.into_maybe_owned(),
967             });
968             task.opts.stdout = Some(~stdout as ~Writer:Send);
969             task.opts.stderr = Some(~stderr as ~Writer:Send);
970             let result_future = task.future_result();
971             task.spawn(testfn);
972
973             let stdout = reader.read_to_end().unwrap().move_iter().collect();
974             let task_result = result_future.recv();
975             let test_result = calc_result(&desc, task_result.is_ok());
976             monitor_ch.send((desc.clone(), test_result, stdout));
977         })
978     }
979
980     match testfn {
981         DynBenchFn(bencher) => {
982             let bs = ::bench::benchmark(|harness| bencher.run(harness));
983             monitor_ch.send((desc, TrBench(bs), Vec::new()));
984             return;
985         }
986         StaticBenchFn(benchfn) => {
987             let bs = ::bench::benchmark(|harness| benchfn(harness));
988             monitor_ch.send((desc, TrBench(bs), Vec::new()));
989             return;
990         }
991         DynMetricFn(f) => {
992             let mut mm = MetricMap::new();
993             f(&mut mm);
994             monitor_ch.send((desc, TrMetrics(mm), Vec::new()));
995             return;
996         }
997         StaticMetricFn(f) => {
998             let mut mm = MetricMap::new();
999             f(&mut mm);
1000             monitor_ch.send((desc, TrMetrics(mm), Vec::new()));
1001             return;
1002         }
1003         DynTestFn(f) => run_test_inner(desc, monitor_ch, f),
1004         StaticTestFn(f) => run_test_inner(desc, monitor_ch, proc() f())
1005     }
1006 }
1007
1008 fn calc_result(desc: &TestDesc, task_succeeded: bool) -> TestResult {
1009     if task_succeeded {
1010         if desc.should_fail { TrFailed }
1011         else { TrOk }
1012     } else {
1013         if desc.should_fail { TrOk }
1014         else { TrFailed }
1015     }
1016 }
1017
1018
1019 impl ToJson for Metric {
1020     fn to_json(&self) -> json::Json {
1021         let mut map = ~TreeMap::new();
1022         map.insert("value".to_owned(), json::Number(self.value));
1023         map.insert("noise".to_owned(), json::Number(self.noise));
1024         json::Object(map)
1025     }
1026 }
1027
1028
1029 impl MetricMap {
1030
1031     pub fn new() -> MetricMap {
1032         MetricMap(TreeMap::new())
1033     }
1034
1035     /// Load MetricDiff from a file.
1036     ///
1037     /// # Failure
1038     ///
1039     /// This function will fail if the path does not exist or the path does not
1040     /// contain a valid metric map.
1041     pub fn load(p: &Path) -> MetricMap {
1042         assert!(p.exists());
1043         let mut f = File::open(p).unwrap();
1044         let value = json::from_reader(&mut f as &mut io::Reader).unwrap();
1045         let mut decoder = json::Decoder::new(value);
1046         MetricMap(match Decodable::decode(&mut decoder) {
1047             Ok(t) => t,
1048             Err(e) => fail!("failure decoding JSON: {}", e)
1049         })
1050     }
1051
1052     /// Write MetricDiff to a file.
1053     pub fn save(&self, p: &Path) -> io::IoResult<()> {
1054         let mut file = try!(File::create(p));
1055         let MetricMap(ref map) = *self;
1056         map.to_json().to_pretty_writer(&mut file)
1057     }
1058
1059     /// Compare against another MetricMap. Optionally compare all
1060     /// measurements in the maps using the provided `noise_pct` as a
1061     /// percentage of each value to consider noise. If `None`, each
1062     /// measurement's noise threshold is independently chosen as the
1063     /// maximum of that measurement's recorded noise quantity in either
1064     /// map.
1065     pub fn compare_to_old(&self, old: &MetricMap,
1066                           noise_pct: Option<f64>) -> MetricDiff {
1067         let mut diff : MetricDiff = TreeMap::new();
1068         let MetricMap(ref selfmap) = *self;
1069         let MetricMap(ref old) = *old;
1070         for (k, vold) in old.iter() {
1071             let r = match selfmap.find(k) {
1072                 None => MetricRemoved,
1073                 Some(v) => {
1074                     let delta = v.value - vold.value;
1075                     let noise = match noise_pct {
1076                         None => vold.noise.abs().max(v.noise.abs()),
1077                         Some(pct) => vold.value * pct / 100.0
1078                     };
1079                     if delta.abs() <= noise {
1080                         LikelyNoise
1081                     } else {
1082                         let pct = delta.abs() / vold.value.max(f64::EPSILON) * 100.0;
1083                         if vold.noise < 0.0 {
1084                             // When 'noise' is negative, it means we want
1085                             // to see deltas that go up over time, and can
1086                             // only tolerate slight negative movement.
1087                             if delta < 0.0 {
1088                                 Regression(pct)
1089                             } else {
1090                                 Improvement(pct)
1091                             }
1092                         } else {
1093                             // When 'noise' is positive, it means we want
1094                             // to see deltas that go down over time, and
1095                             // can only tolerate slight positive movements.
1096                             if delta < 0.0 {
1097                                 Improvement(pct)
1098                             } else {
1099                                 Regression(pct)
1100                             }
1101                         }
1102                     }
1103                 }
1104             };
1105             diff.insert((*k).clone(), r);
1106         }
1107         let MetricMap(ref map) = *self;
1108         for (k, _) in map.iter() {
1109             if !diff.contains_key(k) {
1110                 diff.insert((*k).clone(), MetricAdded);
1111             }
1112         }
1113         diff
1114     }
1115
1116     /// Insert a named `value` (+/- `noise`) metric into the map. The value
1117     /// must be non-negative. The `noise` indicates the uncertainty of the
1118     /// metric, which doubles as the "noise range" of acceptable
1119     /// pairwise-regressions on this named value, when comparing from one
1120     /// metric to the next using `compare_to_old`.
1121     ///
1122     /// If `noise` is positive, then it means this metric is of a value
1123     /// you want to see grow smaller, so a change larger than `noise` in the
1124     /// positive direction represents a regression.
1125     ///
1126     /// If `noise` is negative, then it means this metric is of a value
1127     /// you want to see grow larger, so a change larger than `noise` in the
1128     /// negative direction represents a regression.
1129     pub fn insert_metric(&mut self, name: &str, value: f64, noise: f64) {
1130         let m = Metric {
1131             value: value,
1132             noise: noise
1133         };
1134         let MetricMap(ref mut map) = *self;
1135         map.insert(name.to_owned(), m);
1136     }
1137
1138     /// Attempt to "ratchet" an external metric file. This involves loading
1139     /// metrics from a metric file (if it exists), comparing against
1140     /// the metrics in `self` using `compare_to_old`, and rewriting the
1141     /// file to contain the metrics in `self` if none of the
1142     /// `MetricChange`s are `Regression`. Returns the diff as well
1143     /// as a boolean indicating whether the ratchet succeeded.
1144     pub fn ratchet(&self, p: &Path, pct: Option<f64>) -> (MetricDiff, bool) {
1145         let old = if p.exists() {
1146             MetricMap::load(p)
1147         } else {
1148             MetricMap::new()
1149         };
1150
1151         let diff : MetricDiff = self.compare_to_old(&old, pct);
1152         let ok = diff.iter().all(|(_, v)| {
1153             match *v {
1154                 Regression(_) => false,
1155                 _ => true
1156             }
1157         });
1158
1159         if ok {
1160             self.save(p).unwrap();
1161         }
1162         return (diff, ok)
1163     }
1164 }
1165
1166
1167 // Benchmarking
1168
1169 /// A function that is opaque to the optimizer, to allow benchmarks to
1170 /// pretend to use outputs to assist in avoiding dead-code
1171 /// elimination.
1172 ///
1173 /// This function is a no-op, and does not even read from `dummy`.
1174 pub fn black_box<T>(dummy: T) {
1175     // we need to "use" the argument in some way LLVM can't
1176     // introspect.
1177     unsafe {asm!("" : : "r"(&dummy))}
1178 }
1179
1180
1181 impl Bencher {
1182     /// Callback for benchmark functions to run in their body.
1183     pub fn iter<T>(&mut self, inner: || -> T) {
1184         self.ns_start = precise_time_ns();
1185         let k = self.iterations;
1186         for _ in range(0u64, k) {
1187             black_box(inner());
1188         }
1189         self.ns_end = precise_time_ns();
1190     }
1191
1192     pub fn ns_elapsed(&mut self) -> u64 {
1193         if self.ns_start == 0 || self.ns_end == 0 {
1194             0
1195         } else {
1196             self.ns_end - self.ns_start
1197         }
1198     }
1199
1200     pub fn ns_per_iter(&mut self) -> u64 {
1201         if self.iterations == 0 {
1202             0
1203         } else {
1204             self.ns_elapsed() / cmp::max(self.iterations, 1)
1205         }
1206     }
1207
1208     pub fn bench_n(&mut self, n: u64, f: |&mut Bencher|) {
1209         self.iterations = n;
1210         f(self);
1211     }
1212
1213     // This is a more statistics-driven benchmark algorithm
1214     pub fn auto_bench(&mut self, f: |&mut Bencher|) -> stats::Summary {
1215
1216         // Initial bench run to get ballpark figure.
1217         let mut n = 1_u64;
1218         self.bench_n(n, |x| f(x));
1219
1220         // Try to estimate iter count for 1ms falling back to 1m
1221         // iterations if first run took < 1ns.
1222         if self.ns_per_iter() == 0 {
1223             n = 1_000_000;
1224         } else {
1225             n = 1_000_000 / cmp::max(self.ns_per_iter(), 1);
1226         }
1227         // if the first run took more than 1ms we don't want to just
1228         // be left doing 0 iterations on every loop. The unfortunate
1229         // side effect of not being able to do as many runs is
1230         // automatically handled by the statistical analysis below
1231         // (i.e. larger error bars).
1232         if n == 0 { n = 1; }
1233
1234         let mut total_run = 0;
1235         let samples : &mut [f64] = [0.0_f64, ..50];
1236         loop {
1237             let loop_start = precise_time_ns();
1238
1239             for p in samples.mut_iter() {
1240                 self.bench_n(n, |x| f(x));
1241                 *p = self.ns_per_iter() as f64;
1242             };
1243
1244             stats::winsorize(samples, 5.0);
1245             let summ = stats::Summary::new(samples);
1246
1247             for p in samples.mut_iter() {
1248                 self.bench_n(5 * n, |x| f(x));
1249                 *p = self.ns_per_iter() as f64;
1250             };
1251
1252             stats::winsorize(samples, 5.0);
1253             let summ5 = stats::Summary::new(samples);
1254
1255             let now = precise_time_ns();
1256             let loop_run = now - loop_start;
1257
1258             // If we've run for 100ms and seem to have converged to a
1259             // stable median.
1260             if loop_run > 100_000_000 &&
1261                 summ.median_abs_dev_pct < 1.0 &&
1262                 summ.median - summ5.median < summ5.median_abs_dev {
1263                 return summ5;
1264             }
1265
1266             total_run += loop_run;
1267             // Longest we ever run for is 3s.
1268             if total_run > 3_000_000_000 {
1269                 return summ5;
1270             }
1271
1272             n *= 2;
1273         }
1274     }
1275 }
1276
1277 pub mod bench {
1278     use std::cmp;
1279     use super::{Bencher, BenchSamples};
1280
1281     pub fn benchmark(f: |&mut Bencher|) -> BenchSamples {
1282         let mut bs = Bencher {
1283             iterations: 0,
1284             ns_start: 0,
1285             ns_end: 0,
1286             bytes: 0
1287         };
1288
1289         let ns_iter_summ = bs.auto_bench(f);
1290
1291         let ns_iter = cmp::max(ns_iter_summ.median as u64, 1);
1292         let iter_s = 1_000_000_000 / ns_iter;
1293         let mb_s = (bs.bytes * iter_s) / 1_000_000;
1294
1295         BenchSamples {
1296             ns_iter_summ: ns_iter_summ,
1297             mb_s: mb_s as uint
1298         }
1299     }
1300 }
1301
1302 #[cfg(test)]
1303 mod tests {
1304     use test::{TrFailed, TrIgnored, TrOk, filter_tests, parse_opts,
1305                TestDesc, TestDescAndFn, TestOpts, run_test,
1306                Metric, MetricMap, MetricAdded, MetricRemoved,
1307                Improvement, Regression, LikelyNoise,
1308                StaticTestName, DynTestName, DynTestFn};
1309     use std::io::TempDir;
1310
1311     #[test]
1312     pub fn do_not_run_ignored_tests() {
1313         fn f() { fail!(); }
1314         let desc = TestDescAndFn {
1315             desc: TestDesc {
1316                 name: StaticTestName("whatever"),
1317                 ignore: true,
1318                 should_fail: false
1319             },
1320             testfn: DynTestFn(proc() f()),
1321         };
1322         let (tx, rx) = channel();
1323         run_test(false, desc, tx);
1324         let (_, res, _) = rx.recv();
1325         assert!(res != TrOk);
1326     }
1327
1328     #[test]
1329     pub fn ignored_tests_result_in_ignored() {
1330         fn f() { }
1331         let desc = TestDescAndFn {
1332             desc: TestDesc {
1333                 name: StaticTestName("whatever"),
1334                 ignore: true,
1335                 should_fail: false
1336             },
1337             testfn: DynTestFn(proc() f()),
1338         };
1339         let (tx, rx) = channel();
1340         run_test(false, desc, tx);
1341         let (_, res, _) = rx.recv();
1342         assert!(res == TrIgnored);
1343     }
1344
1345     #[test]
1346     fn test_should_fail() {
1347         fn f() { fail!(); }
1348         let desc = TestDescAndFn {
1349             desc: TestDesc {
1350                 name: StaticTestName("whatever"),
1351                 ignore: false,
1352                 should_fail: true
1353             },
1354             testfn: DynTestFn(proc() f()),
1355         };
1356         let (tx, rx) = channel();
1357         run_test(false, desc, tx);
1358         let (_, res, _) = rx.recv();
1359         assert!(res == TrOk);
1360     }
1361
1362     #[test]
1363     fn test_should_fail_but_succeeds() {
1364         fn f() { }
1365         let desc = TestDescAndFn {
1366             desc: TestDesc {
1367                 name: StaticTestName("whatever"),
1368                 ignore: false,
1369                 should_fail: true
1370             },
1371             testfn: DynTestFn(proc() f()),
1372         };
1373         let (tx, rx) = channel();
1374         run_test(false, desc, tx);
1375         let (_, res, _) = rx.recv();
1376         assert!(res == TrFailed);
1377     }
1378
1379     #[test]
1380     fn first_free_arg_should_be_a_filter() {
1381         let args = vec!("progname".to_owned(), "filter".to_owned());
1382         let opts = match parse_opts(args.as_slice()) {
1383             Some(Ok(o)) => o,
1384             _ => fail!("Malformed arg in first_free_arg_should_be_a_filter")
1385         };
1386         assert!("filter" == opts.filter.clone().unwrap());
1387     }
1388
1389     #[test]
1390     fn parse_ignored_flag() {
1391         let args = vec!("progname".to_owned(), "filter".to_owned(), "--ignored".to_owned());
1392         let opts = match parse_opts(args.as_slice()) {
1393             Some(Ok(o)) => o,
1394             _ => fail!("Malformed arg in parse_ignored_flag")
1395         };
1396         assert!((opts.run_ignored));
1397     }
1398
1399     #[test]
1400     pub fn filter_for_ignored_option() {
1401         // When we run ignored tests the test filter should filter out all the
1402         // unignored tests and flip the ignore flag on the rest to false
1403
1404         let opts = TestOpts {
1405             filter: None,
1406             run_ignored: true,
1407             logfile: None,
1408             run_tests: true,
1409             run_benchmarks: false,
1410             ratchet_noise_percent: None,
1411             ratchet_metrics: None,
1412             save_metrics: None,
1413             test_shard: None
1414         };
1415
1416         let tests = vec!(
1417             TestDescAndFn {
1418                 desc: TestDesc {
1419                     name: StaticTestName("1"),
1420                     ignore: true,
1421                     should_fail: false,
1422                 },
1423                 testfn: DynTestFn(proc() {}),
1424             },
1425             TestDescAndFn {
1426                 desc: TestDesc {
1427                     name: StaticTestName("2"),
1428                     ignore: false,
1429                     should_fail: false
1430                 },
1431                 testfn: DynTestFn(proc() {}),
1432             });
1433         let filtered = filter_tests(&opts, tests);
1434
1435         assert_eq!(filtered.len(), 1);
1436         assert_eq!(filtered.get(0).desc.name.to_str(), "1".to_owned());
1437         assert!(filtered.get(0).desc.ignore == false);
1438     }
1439
1440     #[test]
1441     pub fn sort_tests() {
1442         let opts = TestOpts {
1443             filter: None,
1444             run_ignored: false,
1445             logfile: None,
1446             run_tests: true,
1447             run_benchmarks: false,
1448             ratchet_noise_percent: None,
1449             ratchet_metrics: None,
1450             save_metrics: None,
1451             test_shard: None
1452         };
1453
1454         let names =
1455             vec!("sha1::test".to_owned(), "int::test_to_str".to_owned(), "int::test_pow".to_owned(),
1456              "test::do_not_run_ignored_tests".to_owned(),
1457              "test::ignored_tests_result_in_ignored".to_owned(),
1458              "test::first_free_arg_should_be_a_filter".to_owned(),
1459              "test::parse_ignored_flag".to_owned(), "test::filter_for_ignored_option".to_owned(),
1460              "test::sort_tests".to_owned());
1461         let tests =
1462         {
1463             fn testfn() { }
1464             let mut tests = Vec::new();
1465             for name in names.iter() {
1466                 let test = TestDescAndFn {
1467                     desc: TestDesc {
1468                         name: DynTestName((*name).clone()),
1469                         ignore: false,
1470                         should_fail: false
1471                     },
1472                     testfn: DynTestFn(testfn),
1473                 };
1474                 tests.push(test);
1475             }
1476             tests
1477         };
1478         let filtered = filter_tests(&opts, tests);
1479
1480         let expected =
1481             vec!("int::test_pow".to_owned(), "int::test_to_str".to_owned(), "sha1::test".to_owned(),
1482               "test::do_not_run_ignored_tests".to_owned(),
1483               "test::filter_for_ignored_option".to_owned(),
1484               "test::first_free_arg_should_be_a_filter".to_owned(),
1485               "test::ignored_tests_result_in_ignored".to_owned(),
1486               "test::parse_ignored_flag".to_owned(),
1487               "test::sort_tests".to_owned());
1488
1489         for (a, b) in expected.iter().zip(filtered.iter()) {
1490             assert!(*a == b.desc.name.to_str());
1491         }
1492     }
1493
1494     #[test]
1495     pub fn test_metricmap_compare() {
1496         let mut m1 = MetricMap::new();
1497         let mut m2 = MetricMap::new();
1498         m1.insert_metric("in-both-noise", 1000.0, 200.0);
1499         m2.insert_metric("in-both-noise", 1100.0, 200.0);
1500
1501         m1.insert_metric("in-first-noise", 1000.0, 2.0);
1502         m2.insert_metric("in-second-noise", 1000.0, 2.0);
1503
1504         m1.insert_metric("in-both-want-downwards-but-regressed", 1000.0, 10.0);
1505         m2.insert_metric("in-both-want-downwards-but-regressed", 2000.0, 10.0);
1506
1507         m1.insert_metric("in-both-want-downwards-and-improved", 2000.0, 10.0);
1508         m2.insert_metric("in-both-want-downwards-and-improved", 1000.0, 10.0);
1509
1510         m1.insert_metric("in-both-want-upwards-but-regressed", 2000.0, -10.0);
1511         m2.insert_metric("in-both-want-upwards-but-regressed", 1000.0, -10.0);
1512
1513         m1.insert_metric("in-both-want-upwards-and-improved", 1000.0, -10.0);
1514         m2.insert_metric("in-both-want-upwards-and-improved", 2000.0, -10.0);
1515
1516         let diff1 = m2.compare_to_old(&m1, None);
1517
1518         assert_eq!(*(diff1.find(&"in-both-noise".to_owned()).unwrap()), LikelyNoise);
1519         assert_eq!(*(diff1.find(&"in-first-noise".to_owned()).unwrap()), MetricRemoved);
1520         assert_eq!(*(diff1.find(&"in-second-noise".to_owned()).unwrap()), MetricAdded);
1521         assert_eq!(*(diff1.find(&"in-both-want-downwards-but-regressed".to_owned()).unwrap()),
1522                    Regression(100.0));
1523         assert_eq!(*(diff1.find(&"in-both-want-downwards-and-improved".to_owned()).unwrap()),
1524                    Improvement(50.0));
1525         assert_eq!(*(diff1.find(&"in-both-want-upwards-but-regressed".to_owned()).unwrap()),
1526                    Regression(50.0));
1527         assert_eq!(*(diff1.find(&"in-both-want-upwards-and-improved".to_owned()).unwrap()),
1528                    Improvement(100.0));
1529         assert_eq!(diff1.len(), 7);
1530
1531         let diff2 = m2.compare_to_old(&m1, Some(200.0));
1532
1533         assert_eq!(*(diff2.find(&"in-both-noise".to_owned()).unwrap()), LikelyNoise);
1534         assert_eq!(*(diff2.find(&"in-first-noise".to_owned()).unwrap()), MetricRemoved);
1535         assert_eq!(*(diff2.find(&"in-second-noise".to_owned()).unwrap()), MetricAdded);
1536         assert_eq!(*(diff2.find(&"in-both-want-downwards-but-regressed".to_owned()).unwrap()),
1537                    LikelyNoise);
1538         assert_eq!(*(diff2.find(&"in-both-want-downwards-and-improved".to_owned()).unwrap()),
1539                    LikelyNoise);
1540         assert_eq!(*(diff2.find(&"in-both-want-upwards-but-regressed".to_owned()).unwrap()),
1541                    LikelyNoise);
1542         assert_eq!(*(diff2.find(&"in-both-want-upwards-and-improved".to_owned()).unwrap()),
1543                    LikelyNoise);
1544         assert_eq!(diff2.len(), 7);
1545     }
1546
1547     #[test]
1548     pub fn ratchet_test() {
1549
1550         let dpth = TempDir::new("test-ratchet").expect("missing test for ratchet");
1551         let pth = dpth.path().join("ratchet.json");
1552
1553         let mut m1 = MetricMap::new();
1554         m1.insert_metric("runtime", 1000.0, 2.0);
1555         m1.insert_metric("throughput", 50.0, 2.0);
1556
1557         let mut m2 = MetricMap::new();
1558         m2.insert_metric("runtime", 1100.0, 2.0);
1559         m2.insert_metric("throughput", 50.0, 2.0);
1560
1561         m1.save(&pth).unwrap();
1562
1563         // Ask for a ratchet that should fail to advance.
1564         let (diff1, ok1) = m2.ratchet(&pth, None);
1565         assert_eq!(ok1, false);
1566         assert_eq!(diff1.len(), 2);
1567         assert_eq!(*(diff1.find(&"runtime".to_owned()).unwrap()), Regression(10.0));
1568         assert_eq!(*(diff1.find(&"throughput".to_owned()).unwrap()), LikelyNoise);
1569
1570         // Check that it was not rewritten.
1571         let m3 = MetricMap::load(&pth);
1572         let MetricMap(m3) = m3;
1573         assert_eq!(m3.len(), 2);
1574         assert_eq!(*(m3.find(&"runtime".to_owned()).unwrap()), Metric::new(1000.0, 2.0));
1575         assert_eq!(*(m3.find(&"throughput".to_owned()).unwrap()), Metric::new(50.0, 2.0));
1576
1577         // Ask for a ratchet with an explicit noise-percentage override,
1578         // that should advance.
1579         let (diff2, ok2) = m2.ratchet(&pth, Some(10.0));
1580         assert_eq!(ok2, true);
1581         assert_eq!(diff2.len(), 2);
1582         assert_eq!(*(diff2.find(&"runtime".to_owned()).unwrap()), LikelyNoise);
1583         assert_eq!(*(diff2.find(&"throughput".to_owned()).unwrap()), LikelyNoise);
1584
1585         // Check that it was rewritten.
1586         let m4 = MetricMap::load(&pth);
1587         let MetricMap(m4) = m4;
1588         assert_eq!(m4.len(), 2);
1589         assert_eq!(*(m4.find(&"runtime".to_owned()).unwrap()), Metric::new(1100.0, 2.0));
1590         assert_eq!(*(m4.find(&"throughput".to_owned()).unwrap()), Metric::new(50.0, 2.0));
1591     }
1592 }