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 driver::session::Session;
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;
34 use syntax::owned_slice::OwnedSlice;
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> ,
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,
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> {
91 self.cx.path.borrow_mut().push(i.ident);
92 debug!("current path: {}",
93 ast_util::path_name_i(self.cx.path.borrow().as_slice()));
95 if is_test_fn(&self.cx, i) || is_bench_fn(&self.cx, i) {
97 ast::ItemFn(_, ast::UnsafeFn, _, _, _) => {
98 let sess = self.cx.sess;
99 sess.span_fatal(i.span,
100 "unsafe functions cannot be used for \
104 debug!("this is a test function");
107 path: self.cx.path.borrow().clone(),
108 bench: is_bench_fn(&self.cx, i),
109 ignore: is_ignored(&self.cx, i),
110 should_fail: should_fail(i)
112 self.cx.testfns.borrow_mut().push(test);
113 // debug!("have {} test/bench functions",
114 // cx.testfns.len());
119 let res = fold::noop_fold_item(i, self);
120 self.cx.path.borrow_mut().pop();
124 fn fold_mod(&mut self, m: &ast::Mod) -> ast::Mod {
125 // Remove any #[main] from the AST so it doesn't clash with
126 // the one we're going to add. Only if compiling an executable.
128 fn nomain(item: @ast::Item) -> @ast::Item {
130 attrs: item.attrs.iter().filter_map(|attr| {
131 if !attr.name().equiv(&("main")) {
141 let mod_nomain = ast::Mod {
143 view_items: m.view_items.clone(),
144 items: m.items.iter().map(|i| nomain(*i)).collect(),
147 fold::noop_fold_mod(&mod_nomain, self)
151 fn generate_test_harness(sess: &Session, krate: ast::Crate)
153 let loader = &mut Loader::new(sess);
154 let mut cx: TestCtxt = TestCtxt {
156 ext_cx: ExtCtxt::new(&sess.parse_sess, sess.opts.cfg.clone(),
159 deriving_hash_type_parameter: false,
160 crate_id: from_str("test").unwrap(),
162 path: RefCell::new(Vec::new()),
163 testfns: RefCell::new(Vec::new()),
164 is_test_crate: is_test_crate(&krate),
165 config: krate.config.clone(),
168 cx.ext_cx.bt_push(ExpnInfo {
170 callee: NameAndSpan {
171 name: "test".to_strbuf(),
172 format: MacroAttribute,
177 let mut fold = TestHarnessGenerator {
180 let res = fold.fold_crate(krate);
181 fold.cx.ext_cx.bt_pop();
185 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
186 // When not compiling with --test we should not compile the
188 config::strip_items(krate, |attrs| {
189 !attr::contains_name(attrs.as_slice(), "test") &&
190 !attr::contains_name(attrs.as_slice(), "bench")
194 fn is_test_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
195 let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test");
197 fn has_test_signature(i: @ast::Item) -> bool {
199 &ast::ItemFn(ref decl, _, _, ref generics, _) => {
200 let no_output = match decl.output.node {
204 decl.inputs.is_empty()
206 && !generics.is_parameterized()
212 if has_test_attr && !has_test_signature(i) {
216 "functions used as tests must have signature fn() -> ()."
220 return has_test_attr && has_test_signature(i);
223 fn is_bench_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
224 let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
226 fn has_test_signature(i: @ast::Item) -> bool {
228 ast::ItemFn(ref decl, _, _, ref generics, _) => {
229 let input_cnt = decl.inputs.len();
230 let no_output = match decl.output.node {
234 let tparm_cnt = generics.ty_params.len();
235 // NB: inadequate check, but we're running
236 // well before resolve, can't get too deep.
238 && no_output && tparm_cnt == 0u
244 if has_bench_attr && !has_test_signature(i) {
246 sess.span_err(i.span, "functions used as benches must have signature \
247 `fn(&mut Bencher) -> ()`");
250 return has_bench_attr && has_test_signature(i);
253 fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> bool {
254 i.attrs.iter().any(|attr| {
255 // check ignore(cfg(foo, bar))
256 attr.check_name("ignore") && match attr.meta_item_list() {
258 attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
265 fn should_fail(i: @ast::Item) -> bool {
266 attr::contains_name(i.attrs.as_slice(), "should_fail")
269 fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
270 let testmod = mk_test_module(cx);
272 items: m.items.clone().append_one(testmod),
279 We're going to be building a module that looks more or less like:
282 #![!resolve_unexported]
283 extern crate test (name = "test", vers = "...");
285 test::test_main_static(::os::args().as_slice(), tests)
288 static tests : &'static [test::TestDescAndFn] = &[
289 ... the list of tests in the crate ...
295 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
296 let id_test = token::str_to_ident("test");
297 let (vi, vis) = if cx.is_test_crate {
299 @nospan(ast::ViewPathSimple(id_test,
300 path_node(vec!(id_test)),
301 ast::DUMMY_NODE_ID))),
304 (ast::ViewItemExternCrate(id_test,
305 with_version("test"),
317 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
318 // Link to test crate
319 let view_items = vec!(mk_std(cx));
321 // A constant vector of test descriptors.
322 let tests = mk_tests(cx);
324 // The synthesized main function which will call the console test runner
325 // with our list of tests
326 let mainfn = (quote_item!(&cx.ext_cx,
329 use std::slice::Vector;
330 test::test_main_static(::std::os::args().as_slice(), TESTS);
334 let testmod = ast::Mod {
336 view_items: view_items,
337 items: vec!(mainfn, tests),
339 let item_ = ast::ItemMod(testmod);
341 // This attribute tells resolve to let us call unexported functions
342 let resolve_unexported_str = InternedString::new("!resolve_unexported");
343 let resolve_unexported_attr =
344 attr::mk_attr_inner(attr::mk_attr_id(),
345 attr::mk_word_item(resolve_unexported_str));
347 let item = ast::Item {
348 ident: token::str_to_ident("__test"),
349 attrs: vec!(resolve_unexported_attr),
350 id: ast::DUMMY_NODE_ID,
356 debug!("Synthetic test module:\n{}\n", pprust::item_to_str(&item));
361 fn nospan<T>(t: T) -> codemap::Spanned<T> {
362 codemap::Spanned { node: t, span: DUMMY_SP }
365 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
369 segments: ids.move_iter().map(|identifier| ast::PathSegment {
370 identifier: identifier,
371 lifetimes: Vec::new(),
372 types: OwnedSlice::empty(),
377 fn path_node_global(ids: Vec<ast::Ident> ) -> ast::Path {
381 segments: ids.move_iter().map(|identifier| ast::PathSegment {
382 identifier: identifier,
383 lifetimes: Vec::new(),
384 types: OwnedSlice::empty(),
389 fn mk_tests(cx: &TestCtxt) -> @ast::Item {
390 // The vector of test_descs for this crate
391 let test_descs = mk_test_descs(cx);
393 (quote_item!(&cx.ext_cx,
394 pub static TESTS : &'static [self::test::TestDescAndFn] =
400 fn is_test_crate(krate: &ast::Crate) -> bool {
401 match attr::find_crateid(krate.attrs.as_slice()) {
402 Some(ref s) if "test" == s.name.as_slice() => true,
407 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
408 debug!("building test vector from {} tests", cx.testfns.borrow().len());
411 id: ast::DUMMY_NODE_ID,
412 node: ast::ExprVstore(@ast::Expr {
413 id: ast::DUMMY_NODE_ID,
414 node: ast::ExprVec(cx.testfns.borrow().iter().map(|test| {
415 mk_test_desc_and_fn_rec(cx, test)
418 }, ast::ExprVstoreSlice),
423 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
424 let span = test.span;
425 let path = test.path.clone();
427 debug!("encoding {}", ast_util::path_name_i(path.as_slice()));
429 let name_lit: ast::Lit =
430 nospan(ast::LitStr(token::intern_and_get_ident(
431 ast_util::path_name_i(path.as_slice()).as_slice()),
434 let name_expr = @ast::Expr {
435 id: ast::DUMMY_NODE_ID,
436 node: ast::ExprLit(@name_lit),
440 let fn_path = path_node_global(path);
442 let fn_expr = @ast::Expr {
443 id: ast::DUMMY_NODE_ID,
444 node: ast::ExprPath(fn_path),
448 let t_expr = if test.bench {
449 quote_expr!(&cx.ext_cx, self::test::StaticBenchFn($fn_expr) )
451 quote_expr!(&cx.ext_cx, self::test::StaticTestFn($fn_expr) )
454 let ignore_expr = if test.ignore {
455 quote_expr!(&cx.ext_cx, true )
457 quote_expr!(&cx.ext_cx, false )
460 let fail_expr = if test.should_fail {
461 quote_expr!(&cx.ext_cx, true )
463 quote_expr!(&cx.ext_cx, false )
466 let e = quote_expr!(&cx.ext_cx,
467 self::test::TestDescAndFn {
468 desc: self::test::TestDesc {
469 name: self::test::StaticTestName($name_expr),
470 ignore: $ignore_expr,
471 should_fail: $fail_expr