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::*;
22 use attr::AttrMetaMethods;
24 use codemap::{DUMMY_SP, Span, ExpnInfo, NameAndSpan, MacroAttribute};
28 use entry::{self, EntryPointType};
29 use ext::base::ExtCtxt;
30 use ext::build::AstBuilder;
31 use ext::expand::ExpansionConfig;
33 use util::move_map::MoveMap;
35 use owned_slice::OwnedSlice;
36 use parse::token::{intern, InternedString};
37 use parse::{token, ParseSess};
41 use util::small_vector::SmallVector;
45 Yes(Option<InternedString>),
50 path: Vec<ast::Ident> ,
53 should_panic: ShouldPanic
58 span_diagnostic: &'a diagnostic::SpanHandler,
59 path: Vec<ast::Ident>,
62 reexport_test_harness_main: Option<InternedString>,
64 config: ast::CrateConfig,
66 // top-level re-export submodule, filled out after folding is finished
67 toplevel_reexport: Option<ast::Ident>,
70 // Traverse the crate, collecting all the test functions, eliding any
71 // existing main functions, and synthesizing a main test harness
72 pub fn modify_for_testing(sess: &ParseSess,
73 cfg: &ast::CrateConfig,
75 span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
76 // We generate the test harness when building in the 'test'
77 // configuration, either with the '--test' or '--cfg test'
78 // command line options.
79 let should_test = attr::contains_name(&krate.config, "test");
81 // Check for #[reexport_test_harness_main = "some_name"] which
82 // creates a `use some_name = __test::main;`. This needs to be
83 // unconditional, so that the attribute is still marked as used in
85 let reexport_test_harness_main =
86 attr::first_attr_value_str_by_name(&krate.attrs,
87 "reexport_test_harness_main");
90 generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic)
92 strip_test_functions(span_diagnostic, krate)
96 struct TestHarnessGenerator<'a> {
98 tests: Vec<ast::Ident>,
100 // submodule name, gensym'd identifier for re-exports
101 tested_submods: Vec<(ast::Ident, ast::Ident)>,
104 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
105 fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
106 let mut folded = fold::noop_fold_crate(c, self);
108 // Add a special __test module to the crate that will contain code
109 // generated for the test harness
110 let (mod_, reexport) = mk_test_module(&mut self.cx);
112 Some(re) => folded.module.items.push(re),
115 folded.module.items.push(mod_);
119 fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
121 if ident.name != token::special_idents::invalid.name {
122 self.cx.path.push(ident);
124 debug!("current path: {}",
125 ast_util::path_name_i(&self.cx.path));
127 let i = if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) {
129 ast::ItemFn(_, ast::Unsafety::Unsafe, _, _, _, _) => {
130 let diag = self.cx.span_diagnostic;
131 panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests"));
134 debug!("this is a test function");
137 path: self.cx.path.clone(),
138 bench: is_bench_fn(&self.cx, &*i),
139 ignore: is_ignored(&*i),
140 should_panic: should_panic(&*i)
142 self.cx.testfns.push(test);
143 self.tests.push(i.ident);
144 // debug!("have {} test/bench functions",
145 // cx.testfns.len());
147 // Make all tests public so we can call them from outside
148 // the module (note that the tests are re-exported and must
149 // be made public themselves to avoid privacy errors).
160 // We don't want to recurse into anything other than mods, since
161 // mods or tests inside of functions will break things
162 let res = match i.node {
163 ast::ItemMod(..) => fold::noop_fold_item(i, self),
164 _ => SmallVector::one(i),
166 if ident.name != token::special_idents::invalid.name {
172 fn fold_mod(&mut self, m: ast::Mod) -> ast::Mod {
173 let tests = mem::replace(&mut self.tests, Vec::new());
174 let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
175 let mut mod_folded = fold::noop_fold_mod(m, self);
176 let tests = mem::replace(&mut self.tests, tests);
177 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
179 if !tests.is_empty() || !tested_submods.is_empty() {
180 let (it, sym) = mk_reexport_mod(&mut self.cx, tests, tested_submods);
181 mod_folded.items.push(it);
183 if !self.cx.path.is_empty() {
184 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
186 debug!("pushing nothing, sym: {:?}", sym);
187 self.cx.toplevel_reexport = Some(sym);
195 struct EntryPointCleaner {
196 // Current depth in the ast
200 impl fold::Folder for EntryPointCleaner {
201 fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
203 let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
206 // Remove any #[main] or #[start] from the AST so it doesn't
207 // clash with the one we're going to add, but mark it as
208 // #[allow(dead_code)] to avoid printing warnings.
209 let folded = match entry::entry_point_type(&*folded, self.depth) {
210 EntryPointType::MainNamed |
211 EntryPointType::MainAttr |
212 EntryPointType::Start =>
213 folded.map(|ast::Item {id, ident, attrs, node, vis, span}| {
214 let allow_str = InternedString::new("allow");
215 let dead_code_str = InternedString::new("dead_code");
216 let allow_dead_code_item =
217 attr::mk_list_item(allow_str,
218 vec![attr::mk_word_item(dead_code_str)]);
219 let allow_dead_code = attr::mk_attr_outer(attr::mk_attr_id(),
220 allow_dead_code_item);
225 attrs: attrs.into_iter()
227 !attr.check_name("main") && !attr.check_name("start")
229 .chain(iter::once(allow_dead_code))
236 EntryPointType::None |
237 EntryPointType::OtherMain => folded,
240 SmallVector::one(folded)
244 fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>,
245 tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) {
246 let super_ = token::str_to_ident("super");
248 let items = tests.into_iter().map(|r| {
249 cx.ext_cx.item_use_simple(DUMMY_SP, ast::Public,
250 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
251 }).chain(tested_submods.into_iter().map(|(r, sym)| {
252 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
253 cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Public, r, path)
256 let reexport_mod = ast::Mod {
258 items: items.collect(),
261 let sym = token::gensym_ident("__test_reexports");
262 let it = P(ast::Item {
265 id: ast::DUMMY_NODE_ID,
266 node: ast::ItemMod(reexport_mod),
274 fn generate_test_harness(sess: &ParseSess,
275 reexport_test_harness_main: Option<InternedString>,
277 cfg: &ast::CrateConfig,
278 sd: &diagnostic::SpanHandler) -> ast::Crate {
279 // Remove the entry points
280 let mut cleaner = EntryPointCleaner { depth: 0 };
281 let krate = cleaner.fold_crate(krate);
283 let mut feature_gated_cfgs = vec![];
284 let mut cx: TestCtxt = TestCtxt {
287 ext_cx: ExtCtxt::new(sess, cfg.clone(),
288 ExpansionConfig::default("test".to_string()),
289 &mut feature_gated_cfgs),
292 reexport_test_harness_main: reexport_test_harness_main,
293 is_test_crate: is_test_crate(&krate),
294 config: krate.config.clone(),
295 toplevel_reexport: None,
297 cx.ext_cx.crate_root = Some("std");
299 cx.ext_cx.bt_push(ExpnInfo {
301 callee: NameAndSpan {
302 format: MacroAttribute(intern("test")),
304 allow_internal_unstable: false,
308 let mut fold = TestHarnessGenerator {
311 tested_submods: Vec::new(),
313 let res = fold.fold_crate(krate);
314 fold.cx.ext_cx.bt_pop();
318 fn strip_test_functions(diagnostic: &diagnostic::SpanHandler, krate: ast::Crate)
320 // When not compiling with --test we should not compile the
322 config::strip_items(diagnostic, krate, |attrs| {
323 !attr::contains_name(&attrs[..], "test") &&
324 !attr::contains_name(&attrs[..], "bench")
328 /// Craft a span that will be ignored by the stability lint's
329 /// call to codemap's is_internal check.
330 /// The expanded code calls some unstable functions in the test crate.
331 fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
332 let info = ExpnInfo {
334 callee: NameAndSpan {
335 format: MacroAttribute(intern("test")),
337 allow_internal_unstable: true,
340 let expn_id = cx.sess.codemap().record_expansion(info);
342 sp.expn_id = expn_id;
347 enum HasTestSignature {
354 fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
355 let has_test_attr = attr::contains_name(&i.attrs, "test");
357 fn has_test_signature(i: &ast::Item) -> HasTestSignature {
359 ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
360 let no_output = match decl.output {
361 ast::DefaultReturn(..) => true,
362 ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
365 if decl.inputs.is_empty()
367 && !generics.is_parameterized() {
373 _ => NotEvenAFunction,
378 let diag = cx.span_diagnostic;
379 match has_test_signature(i) {
381 No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
382 NotEvenAFunction => diag.span_err(i.span,
383 "only functions may be used as tests"),
387 return has_test_attr && has_test_signature(i) == Yes;
390 fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
391 let has_bench_attr = attr::contains_name(&i.attrs, "bench");
393 fn has_test_signature(i: &ast::Item) -> bool {
395 ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
396 let input_cnt = decl.inputs.len();
397 let no_output = match decl.output {
398 ast::DefaultReturn(..) => true,
399 ast::Return(ref t) if t.node == ast::TyTup(vec![]) => true,
402 let tparm_cnt = generics.ty_params.len();
403 // NB: inadequate check, but we're running
404 // well before resolve, can't get too deep.
406 && no_output && tparm_cnt == 0
412 if has_bench_attr && !has_test_signature(i) {
413 let diag = cx.span_diagnostic;
414 diag.span_err(i.span, "functions used as benches must have signature \
415 `fn(&mut Bencher) -> ()`");
418 return has_bench_attr && has_test_signature(i);
421 fn is_ignored(i: &ast::Item) -> bool {
422 i.attrs.iter().any(|attr| attr.check_name("ignore"))
425 fn should_panic(i: &ast::Item) -> ShouldPanic {
426 match i.attrs.iter().find(|attr| attr.check_name("should_panic")) {
428 let msg = attr.meta_item_list()
429 .and_then(|list| list.iter().find(|mi| mi.check_name("expected")))
430 .and_then(|mi| mi.value_str());
431 ShouldPanic::Yes(msg)
433 None => ShouldPanic::No,
439 We're going to be building a module that looks more or less like:
442 extern crate test (name = "test", vers = "...");
444 test::test_main_static(&::os::args()[], tests)
447 static tests : &'static [test::TestDescAndFn] = &[
448 ... the list of tests in the crate ...
454 fn mk_std(cx: &TestCtxt) -> P<ast::Item> {
455 let id_test = token::str_to_ident("test");
456 let (vi, vis, ident) = if cx.is_test_crate {
458 P(nospan(ast::ViewPathSimple(id_test,
459 path_node(vec!(id_test)))))),
460 ast::Public, token::special_idents::invalid)
462 (ast::ItemExternCrate(None), ast::Inherited, id_test)
465 id: ast::DUMMY_NODE_ID,
474 fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
475 // Writing this out by hand with 'ignored_span':
478 // use std::slice::AsSlice;
479 // test::test_main_static(::std::os::args().as_slice(), TESTS);
482 let sp = ignored_span(cx, DUMMY_SP);
483 let ecx = &cx.ext_cx;
485 // test::test_main_static
486 let test_main_path = ecx.path(sp, vec![token::str_to_ident("test"),
487 token::str_to_ident("test_main_static")]);
488 // test::test_main_static(...)
489 let test_main_path_expr = ecx.expr_path(test_main_path);
490 let tests_ident_expr = ecx.expr_ident(sp, token::str_to_ident("TESTS"));
491 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
492 vec![tests_ident_expr]);
493 let call_test_main = ecx.stmt_expr(call_test_main);
495 let main_meta = ecx.meta_word(sp, token::intern_and_get_ident("main"));
496 let main_attr = ecx.attribute(sp, main_meta);
497 // pub fn main() { ... }
498 let main_ret_ty = ecx.ty(sp, ast::TyTup(vec![]));
499 let main_body = ecx.block_all(sp, vec![call_test_main], None);
500 let main = ast::ItemFn(ecx.fn_decl(vec![], main_ret_ty),
501 ast::Unsafety::Normal,
502 ast::Constness::NotConst,
503 ::abi::Rust, ast::Generics::default(), main_body);
504 let main = P(ast::Item {
505 ident: token::str_to_ident("main"),
506 attrs: vec![main_attr],
507 id: ast::DUMMY_NODE_ID,
516 fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
517 // Link to test crate
518 let import = mk_std(cx);
520 // A constant vector of test descriptors.
521 let tests = mk_tests(cx);
523 // The synthesized main function which will call the console test runner
524 // with our list of tests
525 let mainfn = mk_main(cx);
527 let testmod = ast::Mod {
529 items: vec![import, mainfn, tests],
531 let item_ = ast::ItemMod(testmod);
533 let mod_ident = token::gensym_ident("__test");
534 let item = P(ast::Item {
535 id: ast::DUMMY_NODE_ID,
542 let reexport = cx.reexport_test_harness_main.as_ref().map(|s| {
543 // building `use <ident> = __test::main`
544 let reexport_ident = token::str_to_ident(&s);
547 nospan(ast::ViewPathSimple(reexport_ident,
548 path_node(vec![mod_ident, token::str_to_ident("main")])));
551 id: ast::DUMMY_NODE_ID,
552 ident: token::special_idents::invalid,
554 node: ast::ItemUse(P(use_path)),
560 debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&*item));
565 fn nospan<T>(t: T) -> codemap::Spanned<T> {
566 codemap::Spanned { node: t, span: DUMMY_SP }
569 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
573 segments: ids.into_iter().map(|identifier| ast::PathSegment {
574 identifier: identifier,
575 parameters: ast::PathParameters::none(),
580 fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
581 // The vector of test_descs for this crate
582 let test_descs = mk_test_descs(cx);
584 // FIXME #15962: should be using quote_item, but that stringifies
585 // __test_reexports, causing it to be reinterned, losing the
586 // gensym information.
588 let ecx = &cx.ext_cx;
589 let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"),
590 ecx.ident_of("test"),
591 ecx.ident_of("TestDescAndFn")]));
592 let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name);
593 // &'static [self::test::TestDescAndFn]
594 let static_type = ecx.ty_rptr(sp,
595 ecx.ty(sp, ast::TyVec(struct_type)),
598 // static TESTS: $static_type = &[...];
600 ecx.ident_of("TESTS"),
605 fn is_test_crate(krate: &ast::Crate) -> bool {
606 match attr::find_crate_name(&krate.attrs) {
607 Some(ref s) if "test" == &s[..] => true,
612 fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> {
613 debug!("building test vector from {} tests", cx.testfns.len());
616 id: ast::DUMMY_NODE_ID,
617 node: ast::ExprAddrOf(ast::MutImmutable,
619 id: ast::DUMMY_NODE_ID,
620 node: ast::ExprVec(cx.testfns.iter().map(|test| {
621 mk_test_desc_and_fn_rec(cx, test)
631 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
632 // FIXME #15962: should be using quote_expr, but that stringifies
633 // __test_reexports, causing it to be reinterned, losing the
634 // gensym information.
636 let span = ignored_span(cx, test.span);
637 let path = test.path.clone();
638 let ecx = &cx.ext_cx;
639 let self_id = ecx.ident_of("self");
640 let test_id = ecx.ident_of("test");
642 // creates self::test::$name
643 let test_path = |name| {
644 ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
646 // creates $name: $expr
647 let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
649 debug!("encoding {}", ast_util::path_name_i(&path[..]));
651 // path to the #[test] function: "foo::bar::baz"
652 let path_string = ast_util::path_name_i(&path[..]);
653 let name_expr = ecx.expr_str(span, token::intern_and_get_ident(&path_string[..]));
655 // self::test::StaticTestName($name_expr)
656 let name_expr = ecx.expr_call(span,
657 ecx.expr_path(test_path("StaticTestName")),
660 let ignore_expr = ecx.expr_bool(span, test.ignore);
661 let should_panic_path = |name| {
662 ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldPanic"), ecx.ident_of(name)])
664 let fail_expr = match test.should_panic {
665 ShouldPanic::No => ecx.expr_path(should_panic_path("No")),
666 ShouldPanic::Yes(ref msg) => {
669 let msg = ecx.expr_str(span, msg.clone());
670 let path = should_panic_path("YesWithMessage");
671 ecx.expr_call(span, ecx.expr_path(path), vec![msg])
673 None => ecx.expr_path(should_panic_path("Yes")),
678 // self::test::TestDesc { ... }
679 let desc_expr = ecx.expr_struct(
681 test_path("TestDesc"),
682 vec![field("name", name_expr),
683 field("ignore", ignore_expr),
684 field("should_panic", fail_expr)]);
687 let mut visible_path = match cx.toplevel_reexport {
688 Some(id) => vec![id],
690 let diag = cx.span_diagnostic;
691 diag.handler.bug("expected to find top-level re-export name, but found None");
694 visible_path.extend(path);
696 let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path));
698 let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" };
699 // self::test::$variant_name($fn_expr)
700 let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]);
702 // self::test::TestDescAndFn { ... }
703 ecx.expr_struct(span,
704 test_path("TestDescAndFn"),
705 vec![field("desc", desc_expr),
706 field("testfn", testfn_expr)])