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};
28 use errors::snippet::{SnippetData};
30 use entry::{self, EntryPointType};
31 use ext::base::{ExtCtxt, Resolver};
32 use ext::build::AstBuilder;
33 use ext::expand::ExpansionConfig;
34 use ext::hygiene::{Mark, SyntaxContext};
36 use util::move_map::MoveMap;
38 use parse::{token, ParseSess};
40 use ast::{self, Ident};
42 use symbol::{self, Symbol, keywords};
43 use util::small_vector::SmallVector;
55 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)
138 self.cx.testfns.push(test);
139 self.tests.push(i.ident);
144 let mut item = i.unwrap();
145 // We don't want to recurse into anything other than mods, since
146 // mods or tests inside of functions will break things
147 if let ast::ItemKind::Mod(module) = item.node {
148 let tests = mem::replace(&mut self.tests, Vec::new());
149 let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
150 let mut mod_folded = fold::noop_fold_mod(module, self);
151 let tests = mem::replace(&mut self.tests, tests);
152 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
154 if !tests.is_empty() || !tested_submods.is_empty() {
155 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
156 mod_folded.items.push(it);
158 if !self.cx.path.is_empty() {
159 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
161 debug!("pushing nothing, sym: {:?}", sym);
162 self.cx.toplevel_reexport = Some(sym);
165 item.node = ast::ItemKind::Mod(mod_folded);
167 if ident.name != keywords::Invalid.name() {
170 SmallVector::one(P(item))
173 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
176 struct EntryPointCleaner {
177 // Current depth in the ast
181 impl fold::Folder for EntryPointCleaner {
182 fn fold_item(&mut self, i: P<ast::Item>) -> SmallVector<P<ast::Item>> {
184 let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
187 // Remove any #[main] or #[start] from the AST so it doesn't
188 // clash with the one we're going to add, but mark it as
189 // #[allow(dead_code)] to avoid printing warnings.
190 let folded = match entry::entry_point_type(&folded, self.depth) {
191 EntryPointType::MainNamed |
192 EntryPointType::MainAttr |
193 EntryPointType::Start =>
194 folded.map(|ast::Item {id, ident, attrs, node, vis, span}| {
195 let allow_str = Symbol::intern("allow");
196 let dead_code_str = Symbol::intern("dead_code");
197 let word_vec = vec![attr::mk_list_word_item(dead_code_str)];
198 let allow_dead_code_item = attr::mk_list_item(allow_str, word_vec);
199 let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
201 allow_dead_code_item);
206 attrs: attrs.into_iter()
208 !attr.check_name("main") && !attr.check_name("start")
210 .chain(iter::once(allow_dead_code))
217 EntryPointType::None |
218 EntryPointType::OtherMain => folded,
221 SmallVector::one(folded)
224 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
227 fn mk_reexport_mod(cx: &mut TestCtxt,
230 tested_submods: Vec<(Ident, Ident)>)
231 -> (P<ast::Item>, Ident) {
232 let super_ = Ident::from_str("super");
234 // Generate imports with `#[allow(private_in_public)]` to work around issue #36768.
235 let allow_private_in_public = cx.ext_cx.attribute(DUMMY_SP, cx.ext_cx.meta_list(
237 Symbol::intern("allow"),
238 vec![cx.ext_cx.meta_list_item_word(DUMMY_SP, Symbol::intern("private_in_public"))],
240 let items = tests.into_iter().map(|r| {
241 cx.ext_cx.item_use_simple(DUMMY_SP, ast::Visibility::Public,
242 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
243 .map_attrs(|_| vec![allow_private_in_public.clone()])
244 }).chain(tested_submods.into_iter().map(|(r, sym)| {
245 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
246 cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Visibility::Public, r, path)
247 .map_attrs(|_| vec![allow_private_in_public.clone()])
250 let reexport_mod = ast::Mod {
255 let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
256 let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
257 cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
258 let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
261 id: ast::DUMMY_NODE_ID,
262 node: ast::ItemKind::Mod(reexport_mod),
263 vis: ast::Visibility::Public,
270 fn generate_test_harness(sess: &ParseSess,
271 resolver: &mut Resolver,
272 reexport_test_harness_main: Option<Symbol>,
274 sd: &errors::Handler) -> ast::Crate {
275 // Remove the entry points
276 let mut cleaner = EntryPointCleaner { depth: 0 };
277 let krate = cleaner.fold_crate(krate);
279 let mark = Mark::fresh();
280 let mut cx: TestCtxt = TestCtxt {
283 ext_cx: ExtCtxt::new(sess, ExpansionConfig::default("test".to_string()), resolver),
286 reexport_test_harness_main: reexport_test_harness_main,
287 is_test_crate: is_test_crate(&krate),
288 toplevel_reexport: None,
289 ctxt: SyntaxContext::empty().apply_mark(mark),
291 cx.ext_cx.crate_root = Some("std");
293 mark.set_expn_info(ExpnInfo {
295 callee: NameAndSpan {
296 format: MacroAttribute(Symbol::intern("test")),
298 allow_internal_unstable: true,
302 TestHarnessGenerator {
305 tested_submods: Vec::new(),
309 /// Craft a span that will be ignored by the stability lint's
310 /// call to codemap's `is_internal` check.
311 /// The expanded code calls some unstable functions in the test crate.
312 fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
313 Span { ctxt: cx.ctxt, ..sp }
317 enum HasTestSignature {
323 fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
324 let has_test_attr = attr::contains_name(&i.attrs, "test");
326 fn has_test_signature(i: &ast::Item) -> HasTestSignature {
328 ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
329 let no_output = match decl.output {
330 ast::FunctionRetTy::Default(..) => true,
331 ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
334 if decl.inputs.is_empty()
336 && !generics.is_parameterized() {
342 _ => NotEvenAFunction,
347 let diag = cx.span_diagnostic;
348 match has_test_signature(i) {
350 No => diag.span_err(i.span, "functions used as tests must have signature fn() -> ()"),
351 NotEvenAFunction => diag.span_err(i.span,
352 "only functions may be used as tests"),
356 has_test_attr && has_test_signature(i) == Yes
359 fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
360 let has_bench_attr = attr::contains_name(&i.attrs, "bench");
362 fn has_test_signature(i: &ast::Item) -> bool {
364 ast::ItemKind::Fn(ref decl, _, _, _, ref generics, _) => {
365 let input_cnt = decl.inputs.len();
366 let no_output = match decl.output {
367 ast::FunctionRetTy::Default(..) => true,
368 ast::FunctionRetTy::Ty(ref t) if t.node == ast::TyKind::Tup(vec![]) => true,
371 let tparm_cnt = generics.ty_params.len();
372 // NB: inadequate check, but we're running
373 // well before resolve, can't get too deep.
375 && no_output && tparm_cnt == 0
381 if has_bench_attr && !has_test_signature(i) {
382 let diag = cx.span_diagnostic;
383 diag.span_err(i.span, "functions used as benches must have signature \
384 `fn(&mut Bencher) -> ()`");
387 has_bench_attr && has_test_signature(i)
390 fn is_ignored(i: &ast::Item) -> bool {
391 i.attrs.iter().any(|attr| attr.check_name("ignore"))
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,
475 fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
476 // Writing this out by hand with 'ignored_span':
479 // use std::slice::AsSlice;
480 // test::test_main_static(::std::os::args().as_slice(), TESTS, test::Options::new());
483 let sp = ignored_span(cx, DUMMY_SP);
484 let ecx = &cx.ext_cx;
486 // test::test_main_static
488 ecx.path(sp, vec![Ident::from_str("test"), Ident::from_str("test_main_static")]);
490 // test::test_main_static(...)
491 let test_main_path_expr = ecx.expr_path(test_main_path);
492 let tests_ident_expr = ecx.expr_ident(sp, Ident::from_str("TESTS"));
493 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
494 vec![tests_ident_expr]);
495 let call_test_main = ecx.stmt_expr(call_test_main);
497 let main_meta = ecx.meta_word(sp, Symbol::intern("main"));
498 let main_attr = ecx.attribute(sp, main_meta);
499 // pub fn main() { ... }
500 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
501 let main_body = ecx.block(sp, vec![call_test_main]);
502 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], main_ret_ty),
503 ast::Unsafety::Normal,
504 dummy_spanned(ast::Constness::NotConst),
505 ::abi::Abi::Rust, ast::Generics::default(), main_body);
507 ident: Ident::from_str("main"),
508 attrs: vec![main_attr],
509 id: ast::DUMMY_NODE_ID,
511 vis: ast::Visibility::Public,
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::ItemKind::Mod(testmod);
532 let mod_ident = Ident::with_empty_ctxt(Symbol::gensym("__test"));
534 let mut expander = cx.ext_cx.monotonic_expander();
535 let item = expander.fold_item(P(ast::Item {
536 id: ast::DUMMY_NODE_ID,
540 vis: ast::Visibility::Public,
543 let reexport = cx.reexport_test_harness_main.map(|s| {
544 // building `use <ident> = __test::main`
545 let reexport_ident = Ident::with_empty_ctxt(s);
548 nospan(ast::ViewPathSimple(reexport_ident,
549 path_node(vec![mod_ident, Ident::from_str("main")])));
551 expander.fold_item(P(ast::Item {
552 id: ast::DUMMY_NODE_ID,
553 ident: keywords::Invalid.ident(),
555 node: ast::ItemKind::Use(P(use_path)),
556 vis: ast::Visibility::Inherited,
561 debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item));
566 fn nospan<T>(t: T) -> codemap::Spanned<T> {
567 codemap::Spanned { node: t, span: DUMMY_SP }
570 fn path_node(ids: Vec<Ident>) -> ast::Path {
573 segments: ids.into_iter().map(|id| ast::PathSegment::from_ident(id, DUMMY_SP)).collect(),
577 fn path_name_i(idents: &[Ident]) -> String {
578 // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
579 idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
582 fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
583 // The vector of test_descs for this crate
584 let test_descs = mk_test_descs(cx);
586 // FIXME #15962: should be using quote_item, but that stringifies
587 // __test_reexports, causing it to be reinterned, losing the
588 // gensym information.
589 let sp = ignored_span(cx, DUMMY_SP);
590 let ecx = &cx.ext_cx;
591 let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"),
592 ecx.ident_of("test"),
593 ecx.ident_of("TestDescAndFn")]));
594 let static_lt = ecx.lifetime(sp, keywords::StaticLifetime.name());
595 // &'static [self::test::TestDescAndFn]
596 let static_type = ecx.ty_rptr(sp,
597 ecx.ty(sp, ast::TyKind::Slice(struct_type)),
599 ast::Mutability::Immutable);
600 // static TESTS: $static_type = &[...];
602 ecx.ident_of("TESTS"),
607 fn is_test_crate(krate: &ast::Crate) -> bool {
608 match attr::find_crate_name(&krate.attrs) {
609 Some(s) if "test" == s.as_str() => true,
614 fn mk_test_descs(cx: &TestCtxt) -> P<ast::Expr> {
615 debug!("building test vector from {} tests", cx.testfns.len());
618 id: ast::DUMMY_NODE_ID,
619 node: ast::ExprKind::AddrOf(ast::Mutability::Immutable,
621 id: ast::DUMMY_NODE_ID,
622 node: ast::ExprKind::Array(cx.testfns.iter().map(|test| {
623 mk_test_desc_and_fn_rec(cx, test)
626 attrs: ast::ThinVec::new(),
629 attrs: ast::ThinVec::new(),
633 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
634 // FIXME #15962: should be using quote_expr, but that stringifies
635 // __test_reexports, causing it to be reinterned, losing the
636 // gensym information.
638 let span = ignored_span(cx, test.span);
639 let path = test.path.clone();
640 let ecx = &cx.ext_cx;
641 let self_id = ecx.ident_of("self");
642 let test_id = ecx.ident_of("test");
644 // creates self::test::$name
645 let test_path = |name| {
646 ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
648 // creates $name: $expr
649 let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
651 debug!("encoding {}", path_name_i(&path[..]));
653 // path to the #[test] function: "foo::bar::baz"
654 let path_string = path_name_i(&path[..]);
655 let name_expr = ecx.expr_str(span, Symbol::intern(&path_string));
657 // self::test::StaticTestName($name_expr)
658 let name_expr = ecx.expr_call(span,
659 ecx.expr_path(test_path("StaticTestName")),
662 let ignore_expr = ecx.expr_bool(span, test.ignore);
663 let should_panic_path = |name| {
664 ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldPanic"), ecx.ident_of(name)])
666 let fail_expr = match test.should_panic {
667 ShouldPanic::No => ecx.expr_path(should_panic_path("No")),
668 ShouldPanic::Yes(msg) => {
671 let msg = ecx.expr_str(span, msg);
672 let path = should_panic_path("YesWithMessage");
673 ecx.expr_call(span, ecx.expr_path(path), vec![msg])
675 None => ecx.expr_path(should_panic_path("Yes")),
680 // self::test::TestDesc { ... }
681 let desc_expr = ecx.expr_struct(
683 test_path("TestDesc"),
684 vec![field("name", name_expr),
685 field("ignore", ignore_expr),
686 field("should_panic", fail_expr)]);
689 let mut visible_path = match cx.toplevel_reexport {
690 Some(id) => vec![id],
692 let diag = cx.span_diagnostic;
693 diag.bug("expected to find top-level re-export name, but found None");
696 visible_path.extend(path);
698 let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path));
700 let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" };
701 // self::test::$variant_name($fn_expr)
702 let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]);
704 // self::test::TestDescAndFn { ... }
705 ecx.expr_struct(span,
706 test_path("TestDescAndFn"),
707 vec![field("desc", desc_expr),
708 field("testfn", testfn_expr)])