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::ext::expand::ExpansionConfig;
32 use syntax::fold::Folder;
35 use syntax::parse::token::InternedString;
36 use syntax::parse::token;
37 use syntax::print::pprust;
38 use syntax::{ast, ast_util};
39 use syntax::util::small_vector::SmallVector;
43 path: Vec<ast::Ident> ,
50 sess: session::Session,
51 path: RefCell<Vec<ast::Ident> >,
53 testfns: RefCell<Vec<Test> >,
55 config: ast::CrateConfig,
58 // Traverse the crate, collecting all the test functions, eliding any
59 // existing main functions, and synthesizing a main test harness
60 pub fn modify_for_testing(sess: session::Session,
61 krate: ast::Crate) -> ast::Crate {
62 // We generate the test harness when building in the 'test'
63 // configuration, either with the '--test' or '--cfg test'
64 // command line options.
65 let should_test = attr::contains_name(krate.config.as_slice(), "test");
68 generate_test_harness(sess, krate)
70 strip_test_functions(krate)
74 struct TestHarnessGenerator<'a> {
78 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
79 fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
80 let folded = fold::noop_fold_crate(c, self);
82 // Add a special __test module to the crate that will contain code
83 // generated for the test harness
85 module: add_test_module(&self.cx, &folded.module),
90 fn fold_item(&mut self, i: @ast::Item) -> SmallVector<@ast::Item> {
92 let mut path = self.cx.path.borrow_mut();
93 path.get().push(i.ident);
95 debug!("current path: {}",
96 ast_util::path_name_i(self.cx.path.get()));
98 if is_test_fn(&self.cx, i) || is_bench_fn(i) {
100 ast::ItemFn(_, purity, _, _, _)
101 if purity == ast::UnsafeFn => {
102 let sess = self.cx.sess;
103 sess.span_fatal(i.span,
104 "unsafe functions cannot be used for \
108 debug!("this is a test function");
111 path: self.cx.path.get(),
112 bench: is_bench_fn(i),
113 ignore: is_ignored(&self.cx, i),
114 should_fail: should_fail(i)
117 let mut testfns = self.cx.testfns.borrow_mut();
118 testfns.get().push(test);
120 // debug!("have {} test/bench functions",
121 // cx.testfns.len());
126 let res = fold::noop_fold_item(i, self);
128 let mut path = self.cx.path.borrow_mut();
134 fn fold_mod(&mut self, m: &ast::Mod) -> ast::Mod {
135 // Remove any #[main] from the AST so it doesn't clash with
136 // the one we're going to add. Only if compiling an executable.
138 fn nomain(cx: &TestCtxt, item: @ast::Item) -> @ast::Item {
139 if !cx.sess.building_library.get() {
141 attrs: item.attrs.iter().filter_map(|attr| {
142 if !attr.name().equiv(&("main")) {
155 let mod_nomain = ast::Mod {
156 view_items: m.view_items.clone(),
157 items: m.items.iter().map(|i| nomain(&self.cx, *i)).collect(),
160 fold::noop_fold_mod(&mod_nomain, self)
164 fn generate_test_harness(sess: session::Session, krate: ast::Crate)
166 let loader = &mut Loader::new(sess);
167 let mut cx: TestCtxt = TestCtxt {
169 ext_cx: ExtCtxt::new(sess.parse_sess, sess.opts.cfg.clone(),
172 deriving_hash_type_parameter: false,
174 path: RefCell::new(Vec::new()),
175 testfns: RefCell::new(Vec::new()),
176 is_test_crate: is_test_crate(&krate),
177 config: krate.config.clone(),
180 cx.ext_cx.bt_push(ExpnInfo {
182 callee: NameAndSpan {
184 format: MacroAttribute,
189 let mut fold = TestHarnessGenerator {
192 let res = fold.fold_crate(krate);
193 fold.cx.ext_cx.bt_pop();
197 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
198 // When not compiling with --test we should not compile the
200 config::strip_items(krate, |attrs| {
201 !attr::contains_name(attrs.as_slice(), "test") &&
202 !attr::contains_name(attrs.as_slice(), "bench")
206 fn is_test_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
207 let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test");
209 fn has_test_signature(i: @ast::Item) -> bool {
211 &ast::ItemFn(ref decl, _, _, ref generics, _) => {
212 let no_output = match decl.output.node {
216 decl.inputs.is_empty()
218 && !generics.is_parameterized()
224 if has_test_attr && !has_test_signature(i) {
228 "functions used as tests must have signature fn() -> ()."
232 return has_test_attr && has_test_signature(i);
235 fn is_bench_fn(i: @ast::Item) -> bool {
236 let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
238 fn has_test_signature(i: @ast::Item) -> bool {
240 ast::ItemFn(ref decl, _, _, ref generics, _) => {
241 let input_cnt = decl.inputs.len();
242 let no_output = match decl.output.node {
246 let tparm_cnt = generics.ty_params.len();
247 // NB: inadequate check, but we're running
248 // well before resolve, can't get too deep.
250 && no_output && tparm_cnt == 0u
256 return has_bench_attr && has_test_signature(i);
259 fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> bool {
260 i.attrs.iter().any(|attr| {
261 // check ignore(cfg(foo, bar))
262 attr.name().equiv(&("ignore")) && match attr.meta_item_list() {
264 attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
271 fn should_fail(i: @ast::Item) -> bool {
272 attr::contains_name(i.attrs.as_slice(), "should_fail")
275 fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
276 let testmod = mk_test_module(cx);
278 items: vec_ng::append_one(m.items.clone(), testmod),
285 We're going to be building a module that looks more or less like:
288 #[!resolve_unexported]
289 extern crate test (name = "test", vers = "...");
291 test::test_main_static(::os::args(), tests)
294 static tests : &'static [test::TestDescAndFn] = &[
295 ... the list of tests in the crate ...
301 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
302 let id_test = token::str_to_ident("test");
303 let vi = if cx.is_test_crate {
305 vec!(@nospan(ast::ViewPathSimple(id_test,
306 path_node(vec!(id_test)),
307 ast::DUMMY_NODE_ID))))
309 ast::ViewItemExternCrate(id_test,
310 with_version("test"),
321 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
322 // Link to test crate
323 let view_items = vec!(mk_std(cx));
325 // A constant vector of test descriptors.
326 let tests = mk_tests(cx);
328 // The synthesized main function which will call the console test runner
329 // with our list of tests
330 let mainfn = (quote_item!(&cx.ext_cx,
333 test::test_main_static(::std::os::args(), TESTS);
337 let testmod = ast::Mod {
338 view_items: view_items,
339 items: vec!(mainfn, tests),
341 let item_ = ast::ItemMod(testmod);
343 // This attribute tells resolve to let us call unexported functions
344 let resolve_unexported_str = InternedString::new("!resolve_unexported");
345 let resolve_unexported_attr =
346 attr::mk_attr(attr::mk_word_item(resolve_unexported_str));
348 let item = ast::Item {
349 ident: token::str_to_ident("__test"),
350 attrs: vec!(resolve_unexported_attr),
351 id: ast::DUMMY_NODE_ID,
357 debug!("Synthetic test module:\n{}\n", pprust::item_to_str(&item));
362 fn nospan<T>(t: T) -> codemap::Spanned<T> {
363 codemap::Spanned { node: t, span: DUMMY_SP }
366 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
370 segments: ids.move_iter().map(|identifier| ast::PathSegment {
371 identifier: identifier,
372 lifetimes: opt_vec::Empty,
373 types: opt_vec::Empty,
378 fn path_node_global(ids: Vec<ast::Ident> ) -> ast::Path {
382 segments: ids.move_iter().map(|identifier| ast::PathSegment {
383 identifier: identifier,
384 lifetimes: opt_vec::Empty,
385 types: opt_vec::Empty,
390 fn mk_tests(cx: &TestCtxt) -> @ast::Item {
391 // The vector of test_descs for this crate
392 let test_descs = mk_test_descs(cx);
394 (quote_item!(&cx.ext_cx,
395 pub static TESTS : &'static [self::test::TestDescAndFn] =
401 fn is_test_crate(krate: &ast::Crate) -> bool {
402 match attr::find_crateid(krate.attrs.as_slice()) {
403 Some(ref s) if "test" == s.name => true,
408 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
409 let mut descs = Vec::new();
411 let testfns = cx.testfns.borrow();
412 debug!("building test vector from {} tests", testfns.get().len());
413 for test in testfns.get().iter() {
414 descs.push(mk_test_desc_and_fn_rec(cx, test));
418 let inner_expr = @ast::Expr {
419 id: ast::DUMMY_NODE_ID,
420 node: ast::ExprVec(descs, ast::MutImmutable),
425 id: ast::DUMMY_NODE_ID,
426 node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
431 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
432 let span = test.span;
433 let path = test.path.clone();
435 debug!("encoding {}", ast_util::path_name_i(path));
437 let name_lit: ast::Lit =
438 nospan(ast::LitStr(token::intern_and_get_ident(
439 ast_util::path_name_i(path)), ast::CookedStr));
441 let name_expr = @ast::Expr {
442 id: ast::DUMMY_NODE_ID,
443 node: ast::ExprLit(@name_lit),
447 let fn_path = path_node_global(path);
449 let fn_expr = @ast::Expr {
450 id: ast::DUMMY_NODE_ID,
451 node: ast::ExprPath(fn_path),
455 let t_expr = if test.bench {
456 quote_expr!(&cx.ext_cx, self::test::StaticBenchFn($fn_expr) )
458 quote_expr!(&cx.ext_cx, self::test::StaticTestFn($fn_expr) )
461 let ignore_expr = if test.ignore {
462 quote_expr!(&cx.ext_cx, true )
464 quote_expr!(&cx.ext_cx, false )
467 let fail_expr = if test.should_fail {
468 quote_expr!(&cx.ext_cx, true )
470 quote_expr!(&cx.ext_cx, false )
473 let e = quote_expr!(&cx.ext_cx,
474 self::test::TestDescAndFn {
475 desc: self::test::TestDesc {
476 name: self::test::StaticTestName($name_expr),
477 ignore: $ignore_expr,
478 should_fail: $fail_expr