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)];
18 use front::std_inject::with_version;
19 use metadata::creader::Loader;
21 use std::cell::RefCell;
25 use syntax::ast_util::*;
26 use syntax::attr::AttrMetaMethods;
28 use syntax::codemap::{DUMMY_SP, Span, ExpnInfo, NameAndSpan, MacroAttribute};
30 use syntax::ext::base::ExtCtxt;
31 use syntax::fold::Folder;
34 use syntax::parse::token::InternedString;
35 use syntax::parse::token;
36 use syntax::print::pprust;
37 use syntax::{ast, ast_util};
38 use syntax::util::small_vector::SmallVector;
49 sess: session::Session,
50 path: RefCell<~[ast::Ident]>,
52 testfns: RefCell<~[Test]>,
54 config: ast::CrateConfig,
57 // Traverse the crate, collecting all the test functions, eliding any
58 // existing main functions, and synthesizing a main test harness
59 pub fn modify_for_testing(sess: session::Session,
60 krate: ast::Crate) -> ast::Crate {
61 // We generate the test harness when building in the 'test'
62 // configuration, either with the '--test' or '--cfg test'
63 // command line options.
64 let should_test = attr::contains_name(krate.config.as_slice(), "test");
67 generate_test_harness(sess, krate)
69 strip_test_functions(krate)
73 struct TestHarnessGenerator<'a> {
77 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
78 fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
79 let folded = fold::noop_fold_crate(c, self);
81 // Add a special __test module to the crate that will contain code
82 // generated for the test harness
84 module: add_test_module(&self.cx, &folded.module),
89 fn fold_item(&mut self, i: @ast::Item) -> SmallVector<@ast::Item> {
91 let mut path = self.cx.path.borrow_mut();
92 path.get().push(i.ident);
94 debug!("current path: {}",
95 ast_util::path_name_i(self.cx.path.get()));
97 if is_test_fn(&self.cx, i) || is_bench_fn(i) {
99 ast::ItemFn(_, purity, _, _, _)
100 if purity == ast::UnsafeFn => {
101 let sess = self.cx.sess;
102 sess.span_fatal(i.span,
103 "unsafe functions cannot be used for \
107 debug!("this is a test function");
110 path: self.cx.path.get(),
111 bench: is_bench_fn(i),
112 ignore: is_ignored(&self.cx, i),
113 should_fail: should_fail(i)
116 let mut testfns = self.cx.testfns.borrow_mut();
117 testfns.get().push(test);
119 // debug!("have {} test/bench functions",
120 // cx.testfns.len());
125 let res = fold::noop_fold_item(i, self);
127 let mut path = self.cx.path.borrow_mut();
133 fn fold_mod(&mut self, m: &ast::Mod) -> ast::Mod {
134 // Remove any #[main] from the AST so it doesn't clash with
135 // the one we're going to add. Only if compiling an executable.
137 fn nomain(cx: &TestCtxt, item: @ast::Item) -> @ast::Item {
138 if !cx.sess.building_library.get() {
140 attrs: item.attrs.iter().filter_map(|attr| {
141 if !attr.name().equiv(&("main")) {
154 let mod_nomain = ast::Mod {
155 view_items: m.view_items.clone(),
156 items: m.items.iter().map(|i| nomain(&self.cx, *i)).collect(),
159 fold::noop_fold_mod(&mod_nomain, self)
163 fn generate_test_harness(sess: session::Session, krate: ast::Crate)
165 let loader = &mut Loader::new(sess);
166 let mut cx: TestCtxt = TestCtxt {
168 ext_cx: ExtCtxt::new(sess.parse_sess, sess.opts.cfg.clone(), loader),
169 path: RefCell::new(~[]),
170 testfns: RefCell::new(~[]),
171 is_test_crate: is_test_crate(&krate),
172 config: krate.config.clone(),
175 cx.ext_cx.bt_push(ExpnInfo {
177 callee: NameAndSpan {
179 format: MacroAttribute,
184 let mut fold = TestHarnessGenerator {
187 let res = fold.fold_crate(krate);
188 fold.cx.ext_cx.bt_pop();
192 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
193 // When not compiling with --test we should not compile the
195 config::strip_items(krate, |attrs| {
196 !attr::contains_name(attrs.as_slice(), "test") &&
197 !attr::contains_name(attrs.as_slice(), "bench")
201 fn is_test_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
202 let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test");
204 fn has_test_signature(i: @ast::Item) -> bool {
206 &ast::ItemFn(ref decl, _, _, ref generics, _) => {
207 let no_output = match decl.output.node {
211 decl.inputs.is_empty()
213 && !generics.is_parameterized()
219 if has_test_attr && !has_test_signature(i) {
223 "functions used as tests must have signature fn() -> ()."
227 return has_test_attr && has_test_signature(i);
230 fn is_bench_fn(i: @ast::Item) -> bool {
231 let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
233 fn has_test_signature(i: @ast::Item) -> bool {
235 ast::ItemFn(ref decl, _, _, ref generics, _) => {
236 let input_cnt = decl.inputs.len();
237 let no_output = match decl.output.node {
241 let tparm_cnt = generics.ty_params.len();
242 // NB: inadequate check, but we're running
243 // well before resolve, can't get too deep.
245 && no_output && tparm_cnt == 0u
251 return has_bench_attr && has_test_signature(i);
254 fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> bool {
255 i.attrs.iter().any(|attr| {
256 // check ignore(cfg(foo, bar))
257 attr.name().equiv(&("ignore")) && match attr.meta_item_list() {
259 attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
266 fn should_fail(i: @ast::Item) -> bool {
267 attr::contains_name(i.attrs.as_slice(), "should_fail")
270 fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
271 let testmod = mk_test_module(cx);
273 items: vec_ng::append_one(m.items.clone(), testmod),
280 We're going to be building a module that looks more or less like:
283 #[!resolve_unexported]
284 extern crate test (name = "test", vers = "...");
286 test::test_main_static(::os::args(), tests)
289 static tests : &'static [test::TestDescAndFn] = &[
290 ... the list of tests in the crate ...
296 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
297 let id_test = token::str_to_ident("test");
298 let vi = if cx.is_test_crate {
300 vec!(@nospan(ast::ViewPathSimple(id_test,
301 path_node(~[id_test]),
302 ast::DUMMY_NODE_ID))))
304 ast::ViewItemExternMod(id_test,
305 with_version("test"),
317 fn mk_test_module(_: &TestCtxt) -> @ast::Item {
318 fail!("test disabled in this stage due to quasiquoter")
322 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
323 // Link to test crate
324 let view_items = vec!(mk_std(cx));
326 // A constant vector of test descriptors.
327 let tests = mk_tests(cx);
329 // The synthesized main function which will call the console test runner
330 // with our list of tests
331 let mainfn = (quote_item!(&cx.ext_cx,
334 test::test_main_static(::std::os::args(), TESTS);
338 let testmod = ast::Mod {
339 view_items: view_items,
340 items: vec!(mainfn, tests),
342 let item_ = ast::ItemMod(testmod);
344 // This attribute tells resolve to let us call unexported functions
345 let resolve_unexported_str = InternedString::new("!resolve_unexported");
346 let resolve_unexported_attr =
347 attr::mk_attr(attr::mk_word_item(resolve_unexported_str));
349 let item = ast::Item {
350 ident: token::str_to_ident("__test"),
351 attrs: vec!(resolve_unexported_attr),
352 id: ast::DUMMY_NODE_ID,
358 debug!("Synthetic test module:\n{}\n", pprust::item_to_str(&item));
363 fn nospan<T>(t: T) -> codemap::Spanned<T> {
364 codemap::Spanned { node: t, span: DUMMY_SP }
367 fn path_node(ids: ~[ast::Ident]) -> ast::Path {
371 segments: ids.move_iter().map(|identifier| ast::PathSegment {
372 identifier: identifier,
373 lifetimes: opt_vec::Empty,
374 types: opt_vec::Empty,
379 fn path_node_global(ids: ~[ast::Ident]) -> ast::Path {
383 segments: ids.move_iter().map(|identifier| ast::PathSegment {
384 identifier: identifier,
385 lifetimes: opt_vec::Empty,
386 types: opt_vec::Empty,
392 fn mk_tests(_: &TestCtxt) -> @ast::Item {
393 fail!("tests disabled in this stage due to quasiquoter")
397 fn mk_tests(cx: &TestCtxt) -> @ast::Item {
398 // The vector of test_descs for this crate
399 let test_descs = mk_test_descs(cx);
401 (quote_item!(&cx.ext_cx,
402 pub static TESTS : &'static [self::test::TestDescAndFn] =
408 fn is_test_crate(krate: &ast::Crate) -> bool {
409 match attr::find_crateid(krate.attrs.as_slice()) {
410 Some(ref s) if "test" == s.name => true,
415 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
416 let mut descs = Vec::new();
418 let testfns = cx.testfns.borrow();
419 debug!("building test vector from {} tests", testfns.get().len());
420 for test in testfns.get().iter() {
421 descs.push(mk_test_desc_and_fn_rec(cx, test));
425 let inner_expr = @ast::Expr {
426 id: ast::DUMMY_NODE_ID,
427 node: ast::ExprVec(descs, ast::MutImmutable),
432 id: ast::DUMMY_NODE_ID,
433 node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
439 fn mk_test_desc_and_fn_rec(_: &TestCtxt, _: &Test) -> @ast::Expr {
440 fail!("tests disabled in this stage due to quasiquoter")
444 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
445 let span = test.span;
446 let path = test.path.clone();
448 debug!("encoding {}", ast_util::path_name_i(path));
450 let name_lit: ast::Lit =
451 nospan(ast::LitStr(token::intern_and_get_ident(
452 ast_util::path_name_i(path)), ast::CookedStr));
454 let name_expr = @ast::Expr {
455 id: ast::DUMMY_NODE_ID,
456 node: ast::ExprLit(@name_lit),
460 let fn_path = path_node_global(path);
462 let fn_expr = @ast::Expr {
463 id: ast::DUMMY_NODE_ID,
464 node: ast::ExprPath(fn_path),
468 let t_expr = if test.bench {
469 quote_expr!(&cx.ext_cx, self::test::StaticBenchFn($fn_expr) )
471 quote_expr!(&cx.ext_cx, self::test::StaticTestFn($fn_expr) )
474 let ignore_expr = if test.ignore {
475 quote_expr!(&cx.ext_cx, true )
477 quote_expr!(&cx.ext_cx, false )
480 let fail_expr = if test.should_fail {
481 quote_expr!(&cx.ext_cx, true )
483 quote_expr!(&cx.ext_cx, false )
486 let e = quote_expr!(&cx.ext_cx,
487 self::test::TestDescAndFn {
488 desc: self::test::TestDesc {
489 name: self::test::StaticTestName($name_expr),
490 ignore: $ignore_expr,
491 should_fail: $fail_expr