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)]
16 use self::HasTestSignature::*;
22 use attr::{self, HasAttrs};
23 use syntax_pos::{self, DUMMY_SP, NO_EXPANSION, Span, FileMap, BytePos};
26 use codemap::{self, CodeMap, ExpnInfo, NameAndSpan, MacroAttribute, dummy_spanned};
29 use entry::{self, EntryPointType};
30 use ext::base::{ExtCtxt, Resolver};
31 use ext::build::AstBuilder;
32 use ext::expand::ExpansionConfig;
33 use ext::hygiene::{Mark, SyntaxContext};
35 use util::move_map::MoveMap;
37 use parse::{token, ParseSess};
39 use ast::{self, Ident};
41 use symbol::{self, Symbol, keywords};
42 use util::small_vector::SmallVector;
54 should_panic: ShouldPanic,
60 span_diagnostic: &'a errors::Handler,
64 reexport_test_harness_main: Option<Symbol>,
68 // top-level re-export submodule, filled out after folding is finished
69 toplevel_reexport: Option<Ident>,
72 // Traverse the crate, collecting all the test functions, eliding any
73 // existing main functions, and synthesizing a main test harness
74 pub fn modify_for_testing(sess: &ParseSess,
75 resolver: &mut Resolver,
78 span_diagnostic: &errors::Handler) -> ast::Crate {
79 // Check for #[reexport_test_harness_main = "some_name"] which
80 // creates a `use some_name = __test::main;`. This needs to be
81 // unconditional, so that the attribute is still marked as used in
83 let reexport_test_harness_main =
84 attr::first_attr_value_str_by_name(&krate.attrs,
85 "reexport_test_harness_main");
88 generate_test_harness(sess, resolver, reexport_test_harness_main, krate, span_diagnostic)
94 struct TestHarnessGenerator<'a> {
98 // submodule name, gensym'd identifier for re-exports
99 tested_submods: Vec<(Ident, Ident)>,
102 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
103 fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
104 let mut folded = fold::noop_fold_crate(c, self);
106 // Add a special __test module to the crate that will contain code
107 // generated for the test harness
108 let (mod_, reexport) = mk_test_module(&mut self.cx);
109 if let Some(re) = reexport {
110 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 != keywords::Invalid.name() {
119 self.cx.path.push(ident);
121 debug!("current path: {}", path_name_i(&self.cx.path));
123 if is_test_fn(&self.cx, &i) || is_bench_fn(&self.cx, &i) {
125 ast::ItemKind::Fn(_, ast::Unsafety::Unsafe, _, _, _, _) => {
126 let diag = self.cx.span_diagnostic;
127 panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests"));
130 debug!("this is a test function");
133 path: self.cx.path.clone(),
134 bench: is_bench_fn(&self.cx, &i),
135 ignore: is_ignored(&i),
136 should_panic: should_panic(&i, &self.cx),
137 allow_fail: is_allowed_fail(&i),
139 self.cx.testfns.push(test);
140 self.tests.push(i.ident);
145 let mut item = i.unwrap();
146 // We don't want to recurse into anything other than mods, since
147 // mods or tests inside of functions will break things
148 if let ast::ItemKind::Mod(module) = item.node {
149 let tests = mem::replace(&mut self.tests, Vec::new());
150 let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
151 let mut mod_folded = fold::noop_fold_mod(module, self);
152 let tests = mem::replace(&mut self.tests, tests);
153 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
155 if !tests.is_empty() || !tested_submods.is_empty() {
156 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
157 mod_folded.items.push(it);
159 if !self.cx.path.is_empty() {
160 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
162 debug!("pushing nothing, sym: {:?}", sym);
163 self.cx.toplevel_reexport = Some(sym);
166 item.node = ast::ItemKind::Mod(mod_folded);
168 if ident.name != keywords::Invalid.name() {
171 SmallVector::one(P(item))
174 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
177 struct EntryPointCleaner {
178 // Current depth in the ast
182 impl fold::Folder for EntryPointCleaner {
183 fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
185 let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
188 // Remove any #[main] or #[start] from the AST so it doesn't
189 // clash with the one we're going to add, but mark it as
190 // #[allow(dead_code)] to avoid printing warnings.
191 let folded = match entry::entry_point_type(&folded, self.depth) {
192 EntryPointType::MainNamed |
193 EntryPointType::MainAttr |
194 EntryPointType::Start =>
195 folded.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
196 let allow_str = Symbol::intern("allow");
197 let dead_code_str = Symbol::intern("dead_code");
198 let word_vec = vec![attr::mk_list_word_item(dead_code_str)];
199 let allow_dead_code_item = attr::mk_list_item(allow_str, word_vec);
200 let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
202 allow_dead_code_item);
207 attrs: attrs.into_iter()
209 !attr.check_name("main") && !attr.check_name("start")
211 .chain(iter::once(allow_dead_code))
219 EntryPointType::None |
220 EntryPointType::OtherMain => folded,
223 SmallVector::one(folded)
226 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
229 fn mk_reexport_mod(cx: &mut TestCtxt,
232 tested_submods: Vec<(Ident, Ident)>)
233 -> (P<ast::Item>, Ident) {
234 let super_ = Ident::from_str("super");
236 let items = tests.into_iter().map(|r| {
237 cx.ext_cx.item_use_simple(DUMMY_SP, ast::Visibility::Public,
238 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
239 }).chain(tested_submods.into_iter().map(|(r, sym)| {
240 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
241 cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Visibility::Public, r, path)
244 let reexport_mod = ast::Mod {
249 let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
250 let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
251 cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
252 let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
255 id: ast::DUMMY_NODE_ID,
256 node: ast::ItemKind::Mod(reexport_mod),
257 vis: ast::Visibility::Public,
265 fn generate_test_harness(sess: &ParseSess,
266 resolver: &mut Resolver,
267 reexport_test_harness_main: Option<Symbol>,
269 sd: &errors::Handler) -> ast::Crate {
270 // Remove the entry points
271 let mut cleaner = EntryPointCleaner { depth: 0 };
272 let krate = cleaner.fold_crate(krate);
274 let mark = Mark::fresh(Mark::root());
275 let mut cx: TestCtxt = TestCtxt {
278 ext_cx: ExtCtxt::new(sess, ExpansionConfig::default("test".to_string()), resolver),
281 reexport_test_harness_main,
282 is_test_crate: is_test_crate(&krate),
283 toplevel_reexport: None,
284 ctxt: SyntaxContext::empty().apply_mark(mark),
286 cx.ext_cx.crate_root = Some("std");
288 mark.set_expn_info(ExpnInfo {
290 callee: NameAndSpan {
291 format: MacroAttribute(Symbol::intern("test")),
293 allow_internal_unstable: true,
294 allow_internal_unsafe: false,
298 TestHarnessGenerator {
301 tested_submods: Vec::new(),
305 /// Craft a span that will be ignored by the stability lint's
306 /// call to codemap's `is_internal` check.
307 /// The expanded code calls some unstable functions in the test crate.
308 fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
309 Span { ctxt: cx.ctxt, ..sp }
313 enum HasTestSignature {
319 fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
320 let has_test_attr = attr::contains_name(&i.attrs, "test");
322 fn has_test_signature(i: &ast::Item) -> HasTestSignature {
324 ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
325 let no_output = match decl.output {
326 ast::FunctionRetTy::Default(..) => true,
327 ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
330 if decl.inputs.is_empty()
332 && !generics.is_parameterized() {
338 _ => NotEvenAFunction,
343 let diag = cx.span_diagnostic;
344 match has_test_signature(i) {
346 No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
347 NotEvenAFunction => diag.span_err(i.span,
348 "only functions may be used as tests"),
352 has_test_attr && has_test_signature(i) == Yes
355 fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
356 let has_bench_attr = attr::contains_name(&i.attrs, "bench");
358 fn has_test_signature(i: &ast::Item) -> bool {
360 ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
361 let input_cnt = decl.inputs.len();
362 let no_output = match decl.output {
363 ast::FunctionRetTy::Default(..) => true,
364 ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
367 let tparm_cnt = generics.ty_params.len();
368 // NB: inadequate check, but we're running
369 // well before resolve, can't get too deep.
371 && no_output && tparm_cnt == 0
377 if has_bench_attr && !has_test_signature(i) {
378 let diag = cx.span_diagnostic;
379 diag.span_err(i.span, "functions used as benches must have signature \
380 `fn(&mut Bencher) -> ()`");
383 has_bench_attr && has_test_signature(i)
386 fn is_ignored(i: &ast::Item) -> bool {
387 i.attrs.iter().any(|attr| attr.check_name("ignore"))
390 fn is_allowed_fail(i: &ast::Item) -> bool {
391 i.attrs.iter().any(|attr| attr.check_name("allow_fail"))
394 fn should_panic(i: &ast::Item, cx: &TestCtxt) -> ShouldPanic {
395 match i.attrs.iter().find(|attr| attr.check_name("should_panic")) {
397 let sd = cx.span_diagnostic;
398 if attr.is_value_str() {
401 "attribute must be of the form: \
402 `#[should_panic]` or \
403 `#[should_panic(expected = \"error message\")]`"
404 ).note("Errors in this attribute were erroneously allowed \
405 and will become a hard error in a future release.")
407 return ShouldPanic::Yes(None);
409 match attr.meta_item_list() {
410 // Handle #[should_panic]
411 None => ShouldPanic::Yes(None),
412 // Handle #[should_panic(expected = "foo")]
414 let msg = list.iter()
415 .find(|mi| mi.check_name("expected"))
416 .and_then(|mi| mi.meta_item())
417 .and_then(|mi| mi.value_str());
418 if list.len() != 1 || msg.is_none() {
421 "argument must be of the form: \
422 `expected = \"error message\"`"
423 ).note("Errors in this attribute were erroneously \
424 allowed and will become a hard error in a \
425 future release.").emit();
426 ShouldPanic::Yes(None)
428 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, test::Options::new())
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 = Ident::from_str("test");
456 let sp = ignored_span(cx, DUMMY_SP);
457 let (vi, vis, ident) = if cx.is_test_crate {
459 P(nospan(ast::ViewPathSimple(id_test,
460 path_node(vec![id_test]))))),
461 ast::Visibility::Public, keywords::Invalid.ident())
463 (ast::ItemKind::ExternCrate(None), ast::Visibility::Inherited, id_test)
466 id: ast::DUMMY_NODE_ID,
476 fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
477 // Writing this out by hand with 'ignored_span':
480 // use std::slice::AsSlice;
481 // test::test_main_static(::std::os::args().as_slice(), TESTS, test::Options::new());
484 let sp = ignored_span(cx, DUMMY_SP);
485 let ecx = &cx.ext_cx;
487 // test::test_main_static
489 ecx.path(sp, vec![Ident::from_str("test"), Ident::from_str("test_main_static")]);
491 // test::test_main_static(...)
492 let test_main_path_expr = ecx.expr_path(test_main_path);
493 let tests_ident_expr = ecx.expr_ident(sp, Ident::from_str("TESTS"));
494 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
495 vec![tests_ident_expr]);
496 let call_test_main = ecx.stmt_expr(call_test_main);
498 let main_meta = ecx.meta_word(sp, Symbol::intern("main"));
499 let main_attr = ecx.attribute(sp, main_meta);
500 // pub fn main() { ... }
501 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
502 let main_body = ecx.block(sp, vec![call_test_main]);
503 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], main_ret_ty),
504 ast::Unsafety::Normal,
505 dummy_spanned(ast::Constness::NotConst),
506 ::abi::Abi::Rust, ast::Generics::default(), main_body);
508 ident: Ident::from_str("main"),
509 attrs: vec![main_attr],
510 id: ast::DUMMY_NODE_ID,
512 vis: ast::Visibility::Public,
518 fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
519 // Link to test crate
520 let import = mk_std(cx);
522 // A constant vector of test descriptors.
523 let tests = mk_tests(cx);
525 // The synthesized main function which will call the console test runner
526 // with our list of tests
527 let mainfn = mk_main(cx);
529 let testmod = ast::Mod {
531 items: vec![import, mainfn, tests],
533 let item_ = ast::ItemKind::Mod(testmod);
534 let mod_ident = Ident::with_empty_ctxt(Symbol::gensym("__test"));
536 let mut expander = cx.ext_cx.monotonic_expander();
537 let item = expander.fold_item(P(ast::Item {
538 id: ast::DUMMY_NODE_ID,
542 vis: ast::Visibility::Public,
546 let reexport = cx.reexport_test_harness_main.map(|s| {
547 // building `use <ident> = __test::main`
548 let reexport_ident = Ident::with_empty_ctxt(s);
551 nospan(ast::ViewPathSimple(reexport_ident,
552 path_node(vec![mod_ident, Ident::from_str("main")])));
554 expander.fold_item(P(ast::Item {
555 id: ast::DUMMY_NODE_ID,
556 ident: keywords::Invalid.ident(),
558 node: ast::ItemKind::Use(P(use_path)),
559 vis: ast::Visibility::Inherited,
565 debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item));
570 fn nospan<T>(t: T) -> codemap::Spanned<T> {
571 codemap::Spanned { node: t, span: DUMMY_SP }
574 fn path_node(ids: Vec<Ident>) -> ast::Path {
577 segments: ids.into_iter().map(|id| ast::PathSegment::from_ident(id, DUMMY_SP)).collect(),
581 fn path_name_i(idents: &[Ident]) -> String {
582 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
583 idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
586 fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
587 // The vector of test_descs for this crate
588 let test_descs = mk_test_descs(cx);
590 // FIXME #15962: should be using quote_item, but that stringifies
591 // __test_reexports, causing it to be reinterned, losing the
592 // gensym information.
593 let sp = ignored_span(cx, DUMMY_SP);
594 let ecx = &cx.ext_cx;
595 let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"),
596 ecx.ident_of("test"),
597 ecx.ident_of("TestDescAndFn")]));
598 let static_lt = ecx.lifetime(sp, keywords::StaticLifetime.ident());
599 // &'static [self::test::TestDescAndFn]
600 let static_type = ecx.ty_rptr(sp,
601 ecx.ty(sp, ast::TyKind::Slice(struct_type)),
603 ast::Mutability::Immutable);
604 // static TESTS: $static_type = &[...];
606 ecx.ident_of("TESTS"),
611 fn is_test_crate(krate: &ast::Crate) -> bool {
612 match attr::find_crate_name(&krate.attrs) {
613 Some(s) if "test" == s.as_str() => true,
618 fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> {
619 debug!("building test vector from {} tests", cx.testfns.len());
622 id: ast::DUMMY_NODE_ID,
623 node: ast::ExprKind::AddrOf(ast::Mutability::Immutable,
625 id: ast::DUMMY_NODE_ID,
626 node: ast::ExprKind::Array(cx.testfns.iter().map(|test| {
627 mk_test_desc_and_fn_rec(cx, test)
630 attrs: ast::ThinVec::new(),
633 attrs: ast::ThinVec::new(),
637 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
638 // FIXME #15962: should be using quote_expr, but that stringifies
639 // __test_reexports, causing it to be reinterned, losing the
640 // gensym information.
642 let span = ignored_span(cx, test.span);
643 let path = test.path.clone();
644 let ecx = &cx.ext_cx;
645 let self_id = ecx.ident_of("self");
646 let test_id = ecx.ident_of("test");
648 // creates self::test::$name
649 let test_path = |name| {
650 ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
652 // creates $name: $expr
653 let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
655 debug!("encoding {}", path_name_i(&path[..]));
657 // path to the #[test] function: "foo::bar::baz"
658 let path_string = path_name_i(&path[..]);
659 let name_expr = ecx.expr_str(span, Symbol::intern(&path_string));
661 // self::test::StaticTestName($name_expr)
662 let name_expr = ecx.expr_call(span,
663 ecx.expr_path(test_path("StaticTestName")),
666 let ignore_expr = ecx.expr_bool(span, test.ignore);
667 let should_panic_path = |name| {
668 ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldPanic"), ecx.ident_of(name)])
670 let fail_expr = match test.should_panic {
671 ShouldPanic::No => ecx.expr_path(should_panic_path("No")),
672 ShouldPanic::Yes(msg) => {
675 let msg = ecx.expr_str(span, msg);
676 let path = should_panic_path("YesWithMessage");
677 ecx.expr_call(span, ecx.expr_path(path), vec![msg])
679 None => ecx.expr_path(should_panic_path("Yes")),
683 let allow_fail_expr = ecx.expr_bool(span, test.allow_fail);
685 // self::test::TestDesc { ... }
686 let desc_expr = ecx.expr_struct(
688 test_path("TestDesc"),
689 vec![field("name", name_expr),
690 field("ignore", ignore_expr),
691 field("should_panic", fail_expr),
692 field("allow_fail", allow_fail_expr)]);
695 let mut visible_path = match cx.toplevel_reexport {
696 Some(id) => vec![id],
698 let diag = cx.span_diagnostic;
699 diag.bug("expected to find top-level re-export name, but found None");
702 visible_path.extend(path);
704 let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path));
706 let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" };
707 // self::test::$variant_name($fn_expr)
708 let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]);
710 // self::test::TestDescAndFn { ... }
711 ecx.expr_struct(span,
712 test_path("TestDescAndFn"),
713 vec![field("desc", desc_expr),
714 field("testfn", testfn_expr)])