1 // Copyright 2012 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
22 use syntax::ast_util::*;
24 use syntax::codemap::{dummy_sp, span, ExpandedFrom};
27 use syntax::print::pprust;
28 use syntax::{ast, ast_util};
29 use syntax::attr::attrs_contains_name;
31 use syntax::ext::base::{mk_ctxt, ext_ctxt};
33 type node_id_gen = fn@() -> ast::node_id;
44 sess: session::Session,
51 // Traverse the crate, collecting all the test functions, eliding any
52 // existing main functions, and synthesizing a main test harness
53 pub fn modify_for_testing(sess: session::Session,
56 // We generate the test harness when building in the 'test'
57 // configuration, either with the '--test' or '--cfg test'
58 // command line options.
59 let should_test = attr::contains(crate.node.config,
60 attr::mk_word_item(~"test"));
63 generate_test_harness(sess, crate)
65 strip_test_functions(crate)
69 fn generate_test_harness(sess: session::Session,
72 let cx: @mut TestCtxt = @mut TestCtxt {
75 ext_cx: mk_ctxt(sess.parse_sess, copy sess.opts.cfg),
80 cx.ext_cx.bt_push(ExpandedFrom({call_site: dummy_sp(),
81 callie: {name: ~"test",
84 let precursor = @fold::AstFoldFns {
85 fold_crate: fold::wrap(|a,b| fold_crate(cx, a, b) ),
86 fold_item: |a,b| fold_item(cx, a, b),
87 fold_mod: |a,b| fold_mod(cx, a, b),.. *fold::default_ast_fold()};
89 let fold = fold::make_fold(precursor);
90 let res = @fold.fold_crate(*crate);
95 fn strip_test_functions(crate: @ast::crate) -> @ast::crate {
96 // When not compiling with --test we should not compile the
98 do config::strip_items(crate) |attrs| {
99 !attr::contains_name(attr::attr_metas(attrs), ~"test") &&
100 !attr::contains_name(attr::attr_metas(attrs), ~"bench")
104 fn fold_mod(cx: @mut TestCtxt,
108 // Remove any #[main] from the AST so it doesn't clash with
109 // the one we're going to add. Only if compiling an executable.
111 fn nomain(cx: @mut TestCtxt, item: @ast::item) -> @ast::item {
112 if !*cx.sess.building_library {
113 @ast::item{attrs: item.attrs.filtered(|attr| {
114 attr::get_attr_name(*attr) != ~"main"
119 let mod_nomain = ast::_mod {
120 view_items: /*bad*/copy m.view_items,
121 items: vec::map(m.items, |i| nomain(cx, *i)),
124 fold::noop_fold_mod(mod_nomain, fld)
127 fn fold_crate(cx: @mut TestCtxt,
131 let folded = fold::noop_fold_crate(c, fld);
133 // Add a special __test module to the crate that will contain code
134 // generated for the test harness
135 ast::crate_ { module: add_test_module(cx, /*bad*/copy folded.module),
140 fn fold_item(cx: @mut TestCtxt, &&i: @ast::item, fld: fold::ast_fold)
141 -> Option<@ast::item> {
142 cx.path.push(i.ident);
143 debug!("current path: %s",
144 ast_util::path_name_i(cx.path, cx.sess.parse_sess.interner));
146 if is_test_fn(i) || is_bench_fn(i) {
148 ast::item_fn(_, purity, _, _) if purity == ast::unsafe_fn => {
152 ~"unsafe functions cannot be used for tests");
155 debug!("this is a test function");
156 let test = {span: i.span,
157 path: /*bad*/copy cx.path,
158 bench: is_bench_fn(i),
159 ignore: is_ignored(cx, i),
160 should_fail: should_fail(i)};
161 cx.testfns.push(test);
162 debug!("have %u test/bench functions", cx.testfns.len());
167 let res = fold::noop_fold_item(i, fld);
172 fn is_test_fn(i: @ast::item) -> bool {
173 let has_test_attr = !attr::find_attrs_by_name(i.attrs,
176 fn has_test_signature(i: @ast::item) -> bool {
178 &ast::item_fn(ref decl, _, ref tps, _) => {
179 let no_output = match decl.output.node {
183 decl.inputs.is_empty() && no_output && tps.is_empty()
189 return has_test_attr && has_test_signature(i);
192 fn is_bench_fn(i: @ast::item) -> bool {
194 vec::len(attr::find_attrs_by_name(i.attrs, ~"bench")) > 0u;
196 fn has_test_signature(i: @ast::item) -> bool {
197 match /*bad*/copy i.node {
198 ast::item_fn(decl, _, tps, _) => {
199 let input_cnt = vec::len(decl.inputs);
200 let no_output = match decl.output.node {
204 let tparm_cnt = vec::len(tps);
205 // NB: inadequate check, but we're running
206 // well before resolve, can't get too deep.
208 && no_output && tparm_cnt == 0u
214 return has_bench_attr && has_test_signature(i);
217 fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool {
218 let ignoreattrs = attr::find_attrs_by_name(i.attrs, "ignore");
219 let ignoreitems = attr::attr_metas(ignoreattrs);
220 return if !ignoreitems.is_empty() {
223 vec::filter_map(ignoreitems,
224 |i| attr::get_meta_item_list(i)));
225 config::metas_in_cfg(/*bad*/copy cx.crate.node.config, cfg_metas)
231 fn should_fail(i: @ast::item) -> bool {
232 vec::len(attr::find_attrs_by_name(i.attrs, ~"should_fail")) > 0u
235 fn add_test_module(cx: &TestCtxt, +m: ast::_mod) -> ast::_mod {
236 let testmod = mk_test_module(cx);
238 items: vec::append_one(/*bad*/copy m.items, testmod),
245 We're going to be building a module that looks more or less like:
248 #[!resolve_unexported]
249 extern mod std (name = "std", vers = "...");
252 std::test::test_main_static(::os::args(), tests)
255 const tests : &static/[std::test::TestDescAndFn] = &[
256 ... the list of tests in the crate ...
262 fn mk_std(cx: &TestCtxt) -> @ast::view_item {
263 let vers = ast::lit_str(@~"0.6");
264 let vers = nospan(vers);
265 let mi = ast::meta_name_value(~"vers", vers);
267 let id_std = cx.sess.ident_of(~"std");
268 let vi = if is_std(cx) {
270 ~[@nospan(ast::view_path_simple(id_std,
271 path_node(~[id_std]),
273 cx.sess.next_node_id()))])
275 ast::view_item_extern_mod(id_std, ~[@mi],
276 cx.sess.next_node_id())
278 let vi = ast::view_item {
287 fn mk_test_module(cx: &TestCtxt) -> @ast::item {
290 let view_items = ~[mk_std(cx)];
292 // A constant vector of test descriptors.
293 let tests = mk_tests(cx);
295 // The synthesized main function which will call the console test runner
296 // with our list of tests
297 let ext_cx = cx.ext_cx;
298 let mainfn = (quote_item!(
301 std::test::test_main_static(::os::args(), tests);
305 let testmod = ast::_mod {
306 view_items: view_items,
307 items: ~[mainfn, tests],
309 let item_ = ast::item_mod(testmod);
311 // This attribute tells resolve to let us call unexported functions
312 let resolve_unexported_attr =
313 attr::mk_attr(attr::mk_word_item(~"!resolve_unexported"));
315 let item = ast::item {
316 ident: cx.sess.ident_of(~"__test"),
317 attrs: ~[resolve_unexported_attr],
318 id: cx.sess.next_node_id(),
324 debug!("Synthetic test module:\n%s\n",
325 pprust::item_to_str(@copy item, cx.sess.intr()));
330 fn nospan<T: Copy>(t: T) -> codemap::spanned<T> {
331 codemap::spanned { node: t, span: dummy_sp() }
334 fn path_node(+ids: ~[ast::ident]) -> @ast::path {
335 @ast::path { span: dummy_sp(),
342 fn path_node_global(+ids: ~[ast::ident]) -> @ast::path {
343 @ast::path { span: dummy_sp(),
351 fn mk_tests(cx: &TestCtxt) -> @ast::item {
353 let ext_cx = cx.ext_cx;
355 // The vector of test_descs for this crate
356 let test_descs = mk_test_descs(cx);
359 pub const tests : &static/[self::std::test::TestDescAndFn] =
365 fn is_std(cx: &TestCtxt) -> bool {
367 let items = attr::find_linkage_metas(cx.crate.node.attrs);
368 match attr::last_meta_item_value_str_by_name(items, ~"name") {
369 Some(~"std") => true,
376 fn mk_test_descs(cx: &TestCtxt) -> @ast::expr {
377 debug!("building test vector from %u tests", cx.testfns.len());
379 for cx.testfns.each |test| {
380 descs.push(mk_test_desc_and_fn_rec(cx, *test));
384 let inner_expr = @ast::expr {
385 id: sess.next_node_id(),
386 callee_id: sess.next_node_id(),
387 node: ast::expr_vec(descs, ast::m_imm),
392 id: sess.next_node_id(),
393 callee_id: sess.next_node_id(),
394 node: ast::expr_vstore(inner_expr, ast::expr_vstore_slice),
399 fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: test) -> @ast::expr {
400 let span = test.span;
401 let path = /*bad*/copy test.path;
403 let ext_cx = cx.ext_cx;
405 debug!("encoding %s", ast_util::path_name_i(path,
406 cx.sess.parse_sess.interner));
408 let name_lit: ast::lit =
409 nospan(ast::lit_str(@ast_util::path_name_i(
411 cx.sess.parse_sess.interner)));
413 let name_expr = @ast::expr {
414 id: cx.sess.next_node_id(),
415 callee_id: cx.sess.next_node_id(),
416 node: ast::expr_lit(@name_lit),
420 let fn_path = path_node_global(path);
422 let fn_expr = @ast::expr {
423 id: cx.sess.next_node_id(),
424 callee_id: cx.sess.next_node_id(),
425 node: ast::expr_path(fn_path),
429 let t_expr = if test.bench {
430 quote_expr!( self::std::test::StaticBenchFn($fn_expr) )
432 quote_expr!( self::std::test::StaticTestFn($fn_expr) )
435 let ignore_expr = if test.ignore {
441 let fail_expr = if test.should_fail {
448 self::std::test::TestDescAndFn {
449 desc: self::std::test::TestDesc {
450 name: self::std::test::StaticTestName($name_expr),
451 ignore: $ignore_expr,
452 should_fail: $fail_expr
463 // indent-tabs-mode: nil
465 // buffer-file-coding-system: utf-8-unix