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