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.
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.
11 // Code that generates a test runner to run all the tests in a crate
14 #![allow(unused_imports)]
15 use self::HasTestSignature::*;
21 use attr::AttrMetaMethods;
23 use codemap::{DUMMY_SP, Span, ExpnInfo, NameAndSpan, MacroAttribute};
27 use ext::base::ExtCtxt;
28 use ext::build::AstBuilder;
29 use ext::expand::ExpansionConfig;
30 use fold::{Folder, MoveMap};
32 use owned_slice::OwnedSlice;
33 use parse::token::InternedString;
34 use parse::{token, ParseSess};
38 use util::small_vector::SmallVector;
42 Yes(Option<InternedString>),
47 path: Vec<ast::Ident> ,
50 should_fail: ShouldFail
55 span_diagnostic: &'a diagnostic::SpanHandler,
56 path: Vec<ast::Ident>,
59 reexport_test_harness_main: Option<InternedString>,
61 config: ast::CrateConfig,
63 // top-level re-export submodule, filled out after folding is finished
64 toplevel_reexport: Option<ast::Ident>,
67 // Traverse the crate, collecting all the test functions, eliding any
68 // existing main functions, and synthesizing a main test harness
69 pub fn modify_for_testing(sess: &ParseSess,
70 cfg: &ast::CrateConfig,
72 span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
73 // We generate the test harness when building in the 'test'
74 // configuration, either with the '--test' or '--cfg test'
75 // command line options.
76 let should_test = attr::contains_name(&krate.config[], "test");
78 // Check for #[reexport_test_harness_main = "some_name"] which
79 // creates a `use some_name = __test::main;`. This needs to be
80 // unconditional, so that the attribute is still marked as used in
82 let reexport_test_harness_main =
83 attr::first_attr_value_str_by_name(&krate.attrs[],
84 "reexport_test_harness_main");
87 generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic)
89 strip_test_functions(krate)
93 struct TestHarnessGenerator<'a> {
95 tests: Vec<ast::Ident>,
97 // submodule name, gensym'd identifier for re-exports
98 tested_submods: Vec<(ast::Ident, ast::Ident)>,
101 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
102 fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
103 let mut folded = fold::noop_fold_crate(c, self);
105 // Add a special __test module to the crate that will contain code
106 // generated for the test harness
107 let (mod_, reexport) = mk_test_module(&mut self.cx);
109 Some(re) => folded.module.items.push(re),
112 folded.module.items.push(mod_);
116 fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
118 if ident.name != token::special_idents::invalid.name {
119 self.cx.path.push(ident);
121 debug!("current path: {}",
122 ast_util::path_name_i(&self.cx.path[]));
124 if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) {
126 ast::ItemFn(_, ast::Unsafety::Unsafe, _, _, _) => {
127 let diag = self.cx.span_diagnostic;
128 diag.span_fatal(i.span,
129 "unsafe functions cannot be used for \
133 debug!("this is a test function");
136 path: self.cx.path.clone(),
137 bench: is_bench_fn(&self.cx, &*i),
138 ignore: is_ignored(&*i),
139 should_fail: should_fail(&*i)
141 self.cx.testfns.push(test);
142 self.tests.push(i.ident);
143 // debug!("have {} test/bench functions",
144 // cx.testfns.len());
149 // We don't want to recurse into anything other than mods, since
150 // mods or tests inside of functions will break things
151 let res = match i.node {
152 ast::ItemMod(..) => fold::noop_fold_item(i, self),
153 _ => SmallVector::one(i),
155 if ident.name != token::special_idents::invalid.name {
161 fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod {
162 let tests = mem::replace(&mut self.tests, Vec::new());
163 let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
164 let mut mod_folded = fold::noop_fold_mod(m, self);
165 let tests = mem::replace(&mut self.tests, tests);
166 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
168 // Remove any #[main] from the AST so it doesn't clash with
169 // the one we're going to add. Only if compiling an executable.
171 mod_folded.items = mem::replace(&mut mod_folded.items, vec![]).move_map(|item| {
172 item.map(|ast::Item {id, ident, attrs, node, vis, span}| {
176 attrs: attrs.into_iter().filter_map(|attr| {
177 if !attr.check_name("main") {
190 if !tests.is_empty() || !tested_submods.is_empty() {
191 let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods);
192 mod_folded.items.push(it);
194 if !self.cx.path.is_empty() {
195 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
197 debug!("pushing nothing, sym: {:?}", sym);
198 self.cx.toplevel_reexport = Some(sym);
206 fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>,
207 tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) {
208 let super_ = token::str_to_ident("super");
210 let items = tests.into_iter().map(|r| {
211 cx.ext_cx.item_use_simple(DUMMY_SP, ast::Public,
212 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
213 }).chain(tested_submods.into_iter().map(|(r, sym)| {
214 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
215 cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Public, r, path)
218 let reexport_mod = ast::Mod {
220 items: items.collect(),
223 let sym = token::gensym_ident("__test_reexports");
224 let it = P(ast::Item {
227 id: ast::DUMMY_NODE_ID,
228 node: ast::ItemMod(reexport_mod),
236 fn generate_test_harness(sess: &ParseSess,
237 reexport_test_harness_main: Option<InternedString>,
239 cfg: &ast::CrateConfig,
240 sd: &diagnostic::SpanHandler) -> ast::Crate {
241 let mut cx: TestCtxt = TestCtxt {
244 ext_cx: ExtCtxt::new(sess, cfg.clone(),
245 ExpansionConfig::default("test".to_string())),
248 reexport_test_harness_main: reexport_test_harness_main,
249 is_test_crate: is_test_crate(&krate),
250 config: krate.config.clone(),
251 toplevel_reexport: None,
254 cx.ext_cx.bt_push(ExpnInfo {
256 callee: NameAndSpan {
257 name: "test".to_string(),
258 format: MacroAttribute,
263 let mut fold = TestHarnessGenerator {
266 tested_submods: Vec::new(),
268 let res = fold.fold_crate(krate);
269 fold.cx.ext_cx.bt_pop();
273 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
274 // When not compiling with --test we should not compile the
276 config::strip_items(krate, |attrs| {
277 !attr::contains_name(&attrs[], "test") &&
278 !attr::contains_name(&attrs[], "bench")
283 enum HasTestSignature {
290 fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
291 let has_test_attr = attr::contains_name(&i.attrs[], "test");
293 fn has_test_signature(i: &ast::Item) -> HasTestSignature {
295 &ast::ItemFn(ref decl, _, _, ref generics, _) => {
296 let no_output = match decl.output {
297 ast::DefaultReturn(..) => true,
300 if decl.inputs.is_empty()
302 && !generics.is_parameterized() {
308 _ => NotEvenAFunction,
313 let diag = cx.span_diagnostic;
314 match has_test_signature(i) {
316 No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
317 NotEvenAFunction => diag.span_err(i.span,
318 "only functions may be used as tests"),
322 return has_test_attr && has_test_signature(i) == Yes;
325 fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
326 let has_bench_attr = attr::contains_name(&i.attrs[], "bench");
328 fn has_test_signature(i: &ast::Item) -> bool {
330 ast::ItemFn(ref decl, _, _, ref generics, _) => {
331 let input_cnt = decl.inputs.len();
332 let no_output = match decl.output {
333 ast::DefaultReturn(..) => true,
336 let tparm_cnt = generics.ty_params.len();
337 // NB: inadequate check, but we're running
338 // well before resolve, can't get too deep.
340 && no_output && tparm_cnt == 0us
346 if has_bench_attr && !has_test_signature(i) {
347 let diag = cx.span_diagnostic;
348 diag.span_err(i.span, "functions used as benches must have signature \
349 `fn(&mut Bencher) -> ()`");
352 return has_bench_attr && has_test_signature(i);
355 fn is_ignored(i: &ast::Item) -> bool {
356 i.attrs.iter().any(|attr| attr.check_name("ignore"))
359 fn should_fail(i: &ast::Item) -> ShouldFail {
360 match i.attrs.iter().find(|attr| attr.check_name("should_fail")) {
362 let msg = attr.meta_item_list()
363 .and_then(|list| list.iter().find(|mi| mi.check_name("expected")))
364 .and_then(|mi| mi.value_str());
367 None => ShouldFail::No,
373 We're going to be building a module that looks more or less like:
376 extern crate test (name = "test", vers = "...");
378 test::test_main_static(&::os::args()[], tests)
381 static tests : &'static [test::TestDescAndFn] = &[
382 ... the list of tests in the crate ...
388 fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
389 let id_test = token::str_to_ident("test");
390 let (vi, vis, ident) = if cx.is_test_crate {
392 P(nospan(ast::ViewPathSimple(id_test,
393 path_node(vec!(id_test)))))),
394 ast::Public, token::special_idents::invalid)
396 (ast::ItemExternCrate(None), ast::Inherited, id_test)
399 id: ast::DUMMY_NODE_ID,
408 fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
409 // Link to test crate
410 let import = mk_std(cx);
412 // A constant vector of test descriptors.
413 let tests = mk_tests(cx);
415 // The synthesized main function which will call the console test runner
416 // with our list of tests
417 let mainfn = (quote_item!(&mut cx.ext_cx,
420 use std::slice::AsSlice;
421 test::test_main_static(::std::os::args().as_slice(), TESTS);
425 let testmod = ast::Mod {
427 items: vec![import, mainfn, tests],
429 let item_ = ast::ItemMod(testmod);
431 let mod_ident = token::gensym_ident("__test");
432 let allow_unstable = {
433 let unstable = P(nospan(ast::MetaWord(InternedString::new("unstable"))));
434 let allow = P(nospan(ast::MetaList(InternedString::new("allow"),
436 attr::mk_attr_inner(attr::mk_attr_id(), allow)
438 let item = P(ast::Item {
439 id: ast::DUMMY_NODE_ID,
441 attrs: vec![allow_unstable],
446 let reexport = cx.reexport_test_harness_main.as_ref().map(|s| {
447 // building `use <ident> = __test::main`
448 let reexport_ident = token::str_to_ident(s.get());
451 nospan(ast::ViewPathSimple(reexport_ident,
452 path_node(vec![mod_ident, token::str_to_ident("main")])));
455 id: ast::DUMMY_NODE_ID,
456 ident: token::special_idents::invalid,
458 node: ast::ItemUse(P(use_path)),
464 debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&*item));
469 fn nospan<T>(t: T) -> codemap::Spanned<T> {
470 codemap::Spanned { node: t, span: DUMMY_SP }
473 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
477 segments: ids.into_iter().map(|identifier| ast::PathSegment {
478 identifier: identifier,
479 parameters: ast::PathParameters::none(),
484 fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
485 // The vector of test_descs for this crate
486 let test_descs = mk_test_descs(cx);
488 // FIXME #15962: should be using quote_item, but that stringifies
489 // __test_reexports, causing it to be reinterned, losing the
490 // gensym information.
492 let ecx = &cx.ext_cx;
493 let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"),
494 ecx.ident_of("test"),
495 ecx.ident_of("TestDescAndFn")]));
496 let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name);
497 // &'static [self::test::TestDescAndFn]
498 let static_type = ecx.ty_rptr(sp,
499 ecx.ty(sp, ast::TyVec(struct_type)),
502 // static TESTS: $static_type = &[...];
504 ecx.ident_of("TESTS"),
509 fn is_test_crate(krate: &ast::Crate) -> bool {
510 match attr::find_crate_name(&krate.attrs[]) {
511 Some(ref s) if "test" == &s.get()[] => true,
516 fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> {
517 debug!("building test vector from {} tests", cx.testfns.len());
520 id: ast::DUMMY_NODE_ID,
521 node: ast::ExprAddrOf(ast::MutImmutable,
523 id: ast::DUMMY_NODE_ID,
524 node: ast::ExprVec(cx.testfns.iter().map(|test| {
525 mk_test_desc_and_fn_rec(cx, test)
533 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
534 // FIXME #15962: should be using quote_expr, but that stringifies
535 // __test_reexports, causing it to be reinterned, losing the
536 // gensym information.
538 let span = test.span;
539 let path = test.path.clone();
540 let ecx = &cx.ext_cx;
541 let self_id = ecx.ident_of("self");
542 let test_id = ecx.ident_of("test");
544 // creates self::test::$name
545 let test_path = |&: name| {
546 ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
548 // creates $name: $expr
549 let field = |&: name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
551 debug!("encoding {}", ast_util::path_name_i(&path[]));
553 // path to the #[test] function: "foo::bar::baz"
554 let path_string = ast_util::path_name_i(&path[]);
555 let name_expr = ecx.expr_str(span, token::intern_and_get_ident(&path_string[]));
557 // self::test::StaticTestName($name_expr)
558 let name_expr = ecx.expr_call(span,
559 ecx.expr_path(test_path("StaticTestName")),
562 let ignore_expr = ecx.expr_bool(span, test.ignore);
563 let should_fail_path = |&: name| {
564 ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldFail"), ecx.ident_of(name)])
566 let fail_expr = match test.should_fail {
567 ShouldFail::No => ecx.expr_path(should_fail_path("No")),
568 ShouldFail::Yes(ref msg) => {
569 let path = should_fail_path("Yes");
570 let arg = match *msg {
571 Some(ref msg) => ecx.expr_some(span, ecx.expr_str(span, msg.clone())),
572 None => ecx.expr_none(span),
574 ecx.expr_call(span, ecx.expr_path(path), vec![arg])
578 // self::test::TestDesc { ... }
579 let desc_expr = ecx.expr_struct(
581 test_path("TestDesc"),
582 vec![field("name", name_expr),
583 field("ignore", ignore_expr),
584 field("should_fail", fail_expr)]);
587 let mut visible_path = match cx.toplevel_reexport {
588 Some(id) => vec![id],
590 let diag = cx.span_diagnostic;
591 diag.handler.bug("expected to find top-level re-export name, but found None");
594 visible_path.extend(path.into_iter());
596 let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path));
598 let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" };
599 // self::test::$variant_name($fn_expr)
600 let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]);
602 // self::test::TestDescAndFn { ... }
603 ecx.expr_struct(span,
604 test_path("TestDescAndFn"),
605 vec![field("desc", desc_expr),
606 field("testfn", testfn_expr)])