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.get().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.get(),
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(cx: &TestCtxt, item: @ast::Item) -> @ast::Item {
129 if !cx.sess.building_library.get() {
131 attrs: item.attrs.iter().filter_map(|attr| {
132 if !attr.name().equiv(&("main")) {
145 let mod_nomain = ast::Mod {
146 view_items: m.view_items.clone(),
147 items: m.items.iter().map(|i| nomain(&self.cx, *i)).collect(),
150 fold::noop_fold_mod(&mod_nomain, self)
154 fn generate_test_harness(sess: &Session, krate: ast::Crate)
156 let loader = &mut Loader::new(sess);
157 let mut cx: TestCtxt = TestCtxt {
159 ext_cx: ExtCtxt::new(&sess.parse_sess, sess.opts.cfg.clone(),
162 deriving_hash_type_parameter: false,
163 crate_id: from_str("test").unwrap(),
165 path: RefCell::new(Vec::new()),
166 testfns: RefCell::new(Vec::new()),
167 is_test_crate: is_test_crate(&krate),
168 config: krate.config.clone(),
171 cx.ext_cx.bt_push(ExpnInfo {
173 callee: NameAndSpan {
175 format: MacroAttribute,
180 let mut fold = TestHarnessGenerator {
183 let res = fold.fold_crate(krate);
184 fold.cx.ext_cx.bt_pop();
188 fn strip_test_functions(krate: ast::Crate) -> ast::Crate {
189 // When not compiling with --test we should not compile the
191 config::strip_items(krate, |attrs| {
192 !attr::contains_name(attrs.as_slice(), "test") &&
193 !attr::contains_name(attrs.as_slice(), "bench")
197 fn is_test_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
198 let has_test_attr = attr::contains_name(i.attrs.as_slice(), "test");
200 fn has_test_signature(i: @ast::Item) -> bool {
202 &ast::ItemFn(ref decl, _, _, ref generics, _) => {
203 let no_output = match decl.output.node {
207 decl.inputs.is_empty()
209 && !generics.is_parameterized()
215 if has_test_attr && !has_test_signature(i) {
219 "functions used as tests must have signature fn() -> ()."
223 return has_test_attr && has_test_signature(i);
226 fn is_bench_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
227 let has_bench_attr = attr::contains_name(i.attrs.as_slice(), "bench");
229 fn has_test_signature(i: @ast::Item) -> bool {
231 ast::ItemFn(ref decl, _, _, ref generics, _) => {
232 let input_cnt = decl.inputs.len();
233 let no_output = match decl.output.node {
237 let tparm_cnt = generics.ty_params.len();
238 // NB: inadequate check, but we're running
239 // well before resolve, can't get too deep.
241 && no_output && tparm_cnt == 0u
247 if has_bench_attr && !has_test_signature(i) {
249 sess.span_err(i.span, "functions used as benches must have signature \
250 `fn(&mut BenchHarness) -> ()`");
253 return has_bench_attr && has_test_signature(i);
256 fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> bool {
257 i.attrs.iter().any(|attr| {
258 // check ignore(cfg(foo, bar))
259 attr.name().equiv(&("ignore")) && match attr.meta_item_list() {
261 attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
268 fn should_fail(i: @ast::Item) -> bool {
269 attr::contains_name(i.attrs.as_slice(), "should_fail")
272 fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
273 let testmod = mk_test_module(cx);
275 items: vec::append_one(m.items.clone(), testmod),
282 We're going to be building a module that looks more or less like:
285 #[!resolve_unexported]
286 extern crate test (name = "test", vers = "...");
288 test::test_main_static(::os::args(), tests)
291 static tests : &'static [test::TestDescAndFn] = &[
292 ... the list of tests in the crate ...
298 fn mk_std(cx: &TestCtxt) -> ast::ViewItem {
299 let id_test = token::str_to_ident("test");
300 let vi = if cx.is_test_crate {
302 vec!(@nospan(ast::ViewPathSimple(id_test,
303 path_node(vec!(id_test)),
304 ast::DUMMY_NODE_ID))))
306 ast::ViewItemExternCrate(id_test,
307 with_version("test"),
318 fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
319 // Link to test crate
320 let view_items = vec!(mk_std(cx));
322 // A constant vector of test descriptors.
323 let tests = mk_tests(cx);
325 // The synthesized main function which will call the console test runner
326 // with our list of tests
327 let mainfn = (quote_item!(&cx.ext_cx,
329 #[allow(deprecated_owned_vector)];
331 test::test_main_static(::std::os::args(), TESTS);
335 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(attr::mk_word_item(resolve_unexported_str));
346 let item = ast::Item {
347 ident: token::str_to_ident("__test"),
348 attrs: vec!(resolve_unexported_attr),
349 id: ast::DUMMY_NODE_ID,
355 debug!("Synthetic test module:\n{}\n", pprust::item_to_str(&item));
360 fn nospan<T>(t: T) -> codemap::Spanned<T> {
361 codemap::Spanned { node: t, span: DUMMY_SP }
364 fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
368 segments: ids.move_iter().map(|identifier| ast::PathSegment {
369 identifier: identifier,
370 lifetimes: Vec::new(),
371 types: OwnedSlice::empty(),
376 fn path_node_global(ids: Vec<ast::Ident> ) -> ast::Path {
380 segments: ids.move_iter().map(|identifier| ast::PathSegment {
381 identifier: identifier,
382 lifetimes: Vec::new(),
383 types: OwnedSlice::empty(),
388 fn mk_tests(cx: &TestCtxt) -> @ast::Item {
389 // The vector of test_descs for this crate
390 let test_descs = mk_test_descs(cx);
392 (quote_item!(&cx.ext_cx,
393 pub static TESTS : &'static [self::test::TestDescAndFn] =
399 fn is_test_crate(krate: &ast::Crate) -> bool {
400 match attr::find_crateid(krate.attrs.as_slice()) {
401 Some(ref s) if "test" == s.name => true,
406 fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
407 let mut descs = Vec::new();
408 debug!("building test vector from {} tests", cx.testfns.borrow().len());
409 for test in cx.testfns.borrow().iter() {
410 descs.push(mk_test_desc_and_fn_rec(cx, test));
413 let inner_expr = @ast::Expr {
414 id: ast::DUMMY_NODE_ID,
415 node: ast::ExprVec(descs, ast::MutImmutable),
420 id: ast::DUMMY_NODE_ID,
421 node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
426 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
427 let span = test.span;
428 let path = test.path.clone();
430 debug!("encoding {}", ast_util::path_name_i(path.as_slice()));
432 let name_lit: ast::Lit =
433 nospan(ast::LitStr(token::intern_and_get_ident(
434 ast_util::path_name_i(path.as_slice())),
437 let name_expr = @ast::Expr {
438 id: ast::DUMMY_NODE_ID,
439 node: ast::ExprLit(@name_lit),
443 let fn_path = path_node_global(path);
445 let fn_expr = @ast::Expr {
446 id: ast::DUMMY_NODE_ID,
447 node: ast::ExprPath(fn_path),
451 let t_expr = if test.bench {
452 quote_expr!(&cx.ext_cx, self::test::StaticBenchFn($fn_expr) )
454 quote_expr!(&cx.ext_cx, self::test::StaticTestFn($fn_expr) )
457 let ignore_expr = if test.ignore {
458 quote_expr!(&cx.ext_cx, true )
460 quote_expr!(&cx.ext_cx, false )
463 let fail_expr = if test.should_fail {
464 quote_expr!(&cx.ext_cx, true )
466 quote_expr!(&cx.ext_cx, false )
469 let e = quote_expr!(&cx.ext_cx,
470 self::test::TestDescAndFn {
471 desc: self::test::TestDesc {
472 name: self::test::StaticTestName($name_expr),
473 ignore: $ignore_expr,
474 should_fail: $fail_expr