1 // Code that generates a test runner to run all the tests in a crate
4 use smallvec::{smallvec, SmallVec};
5 use syntax::ast::{self, Ident};
7 use syntax::entry::{self, EntryPointType};
8 use syntax::ext::base::{ExtCtxt, Resolver};
9 use syntax::ext::expand::ExpansionConfig;
10 use syntax::ext::hygiene::{ExpnId, MacroKind};
11 use syntax::feature_gate::Features;
12 use syntax::mut_visit::{*, ExpectOne};
13 use syntax::parse::ParseSess;
15 use syntax::source_map::{ExpnInfo, ExpnKind, dummy_spanned};
16 use syntax::symbol::{kw, sym, Symbol};
17 use syntax_pos::{Span, DUMMY_SP};
27 span_diagnostic: &'a errors::Handler,
30 test_cases: Vec<Test>,
31 reexport_test_harness_main: Option<Symbol>,
32 test_runner: Option<ast::Path>,
33 // top-level re-export submodule, filled out after folding is finished
34 toplevel_reexport: Option<Ident>,
37 // Traverse the crate, collecting all the test functions, eliding any
38 // existing main functions, and synthesizing a main test harness
41 resolver: &mut dyn Resolver,
43 krate: &mut ast::Crate,
44 span_diagnostic: &errors::Handler,
47 // Check for #[reexport_test_harness_main = "some_name"] which
48 // creates a `use __test::main as some_name;`. This needs to be
49 // unconditional, so that the attribute is still marked as used in
51 let reexport_test_harness_main =
52 attr::first_attr_value_str_by_name(&krate.attrs, sym::reexport_test_harness_main);
54 // Do this here so that the test_runner crate attribute gets marked as used
55 // even in non-test builds
56 let test_runner = get_test_runner(span_diagnostic, &krate);
59 generate_test_harness(sess, resolver, reexport_test_harness_main,
60 krate, span_diagnostic, features, test_runner)
64 struct TestHarnessGenerator<'a> {
68 // submodule name, gensym'd identifier for re-exports
69 tested_submods: Vec<(Ident, Ident)>,
72 impl<'a> MutVisitor for TestHarnessGenerator<'a> {
73 fn visit_crate(&mut self, c: &mut ast::Crate) {
74 noop_visit_crate(c, self);
76 // Create a main function to run our tests
78 let unresolved = mk_main(&mut self.cx);
79 self.cx.ext_cx.monotonic_expander().flat_map_item(unresolved).pop().unwrap()
82 c.module.items.push(test_main);
85 fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
87 if ident.name != kw::Invalid {
88 self.cx.path.push(ident);
90 debug!("current path: {}", path_name_i(&self.cx.path));
92 let mut item = i.into_inner();
93 if is_test_case(&item) {
94 debug!("this is a test item");
98 path: self.cx.path.clone(),
100 self.cx.test_cases.push(test);
101 self.tests.push(item.ident);
104 // We don't want to recurse into anything other than mods, since
105 // mods or tests inside of functions will break things
106 if let ast::ItemKind::Mod(mut module) = item.node {
107 let tests = mem::take(&mut self.tests);
108 let tested_submods = mem::take(&mut self.tested_submods);
109 noop_visit_mod(&mut module, self);
110 let tests = mem::replace(&mut self.tests, tests);
111 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
113 if !tests.is_empty() || !tested_submods.is_empty() {
114 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
115 module.items.push(it);
117 if !self.cx.path.is_empty() {
118 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
120 debug!("pushing nothing, sym: {:?}", sym);
121 self.cx.toplevel_reexport = Some(sym);
124 item.node = ast::ItemKind::Mod(module);
126 if ident.name != kw::Invalid {
132 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
137 /// A folder used to remove any entry points (like fn main) because the harness
138 /// generator will provide its own
139 struct EntryPointCleaner {
140 // Current depth in the ast
144 impl MutVisitor for EntryPointCleaner {
145 fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
147 let item = noop_flat_map_item(i, self).expect_one("noop did something");
150 // Remove any #[main] or #[start] from the AST so it doesn't
151 // clash with the one we're going to add, but mark it as
152 // #[allow(dead_code)] to avoid printing warnings.
153 let item = match entry::entry_point_type(&item, self.depth) {
154 EntryPointType::MainNamed |
155 EntryPointType::MainAttr |
156 EntryPointType::Start =>
157 item.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
158 let allow_ident = Ident::with_empty_ctxt(sym::allow);
159 let dc_nested = attr::mk_nested_word_item(Ident::from_str("dead_code"));
160 let allow_dead_code_item = attr::mk_list_item(DUMMY_SP, allow_ident,
162 let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item);
167 attrs: attrs.into_iter()
169 !attr.check_name(sym::main) && !attr.check_name(sym::start)
171 .chain(iter::once(allow_dead_code))
179 EntryPointType::None |
180 EntryPointType::OtherMain => item,
186 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
191 /// Creates an item (specifically a module) that "pub use"s the tests passed in.
192 /// Each tested submodule will contain a similar reexport module that we will export
193 /// under the name of the original module. That is, `submod::__test_reexports` is
194 /// reexported like so `pub use submod::__test_reexports as submod`.
195 fn mk_reexport_mod(cx: &mut TestCtxt<'_>,
198 tested_submods: Vec<(Ident, Ident)>)
199 -> (P<ast::Item>, Ident) {
200 let super_ = Ident::with_empty_ctxt(kw::Super);
202 let items = tests.into_iter().map(|r| {
203 cx.ext_cx.item_use_simple(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
204 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
205 }).chain(tested_submods.into_iter().map(|(r, sym)| {
206 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
207 cx.ext_cx.item_use_simple_(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
211 let reexport_mod = ast::Mod {
217 let name = Ident::from_str("__test_reexports").gensym();
218 let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
219 cx.ext_cx.current_expansion.id = cx.ext_cx.resolver.get_module_scope(parent);
220 let it = cx.ext_cx.monotonic_expander().flat_map_item(P(ast::Item {
223 id: ast::DUMMY_NODE_ID,
224 node: ast::ItemKind::Mod(reexport_mod),
225 vis: dummy_spanned(ast::VisibilityKind::Public),
233 /// Crawl over the crate, inserting test reexports and the test main function
234 fn generate_test_harness(sess: &ParseSess,
235 resolver: &mut dyn Resolver,
236 reexport_test_harness_main: Option<Symbol>,
237 krate: &mut ast::Crate,
238 sd: &errors::Handler,
240 test_runner: Option<ast::Path>) {
241 // Remove the entry points
242 let mut cleaner = EntryPointCleaner { depth: 0 };
243 cleaner.visit_crate(krate);
245 let mut econfig = ExpansionConfig::default("test".to_string());
246 econfig.features = Some(features);
250 ext_cx: ExtCtxt::new(sess, econfig, resolver),
252 test_cases: Vec::new(),
253 reexport_test_harness_main,
254 toplevel_reexport: None,
258 TestHarnessGenerator {
261 tested_submods: Vec::new(),
262 }.visit_crate(krate);
265 /// Creates a function item for use as the main function of a test build.
266 /// This function will call the `test_runner` as specified by the crate attribute
267 fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
268 // Writing this out by hand:
271 // test::test_main_static(&[..tests]);
273 let sp = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
274 ExpnKind::Macro(MacroKind::Attr, sym::test_case), DUMMY_SP, cx.ext_cx.parse_sess.edition,
275 [sym::main, sym::test, sym::rustc_attrs][..].into(),
277 let ecx = &cx.ext_cx;
278 let test_id = Ident::with_empty_ctxt(sym::test);
280 // test::test_main_static(...)
281 let mut test_runner = cx.test_runner.clone().unwrap_or(
283 test_id, ecx.ident_of("test_main_static")
286 test_runner.span = sp;
288 let test_main_path_expr = ecx.expr_path(test_runner);
289 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
290 vec![mk_tests_slice(cx)]);
291 let call_test_main = ecx.stmt_expr(call_test_main);
294 let main_meta = ecx.meta_word(sp, sym::main);
295 let main_attr = ecx.attribute(main_meta);
297 // extern crate test as test_gensym
298 let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
301 ast::ItemKind::ExternCrate(None)
304 // pub fn main() { ... }
305 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
307 // If no test runner is provided we need to import the test crate
308 let main_body = if cx.test_runner.is_none() {
309 ecx.block(sp, vec![test_extern_stmt, call_test_main])
311 ecx.block(sp, vec![call_test_main])
314 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
315 ast::FnHeader::default(),
316 ast::Generics::default(),
319 // Honor the reexport_test_harness_main attribute
320 let main_id = match cx.reexport_test_harness_main {
321 Some(sym) => Ident::new(sym, sp),
322 None => Ident::from_str_and_span("main", sp).gensym(),
327 attrs: vec![main_attr],
328 id: ast::DUMMY_NODE_ID,
330 vis: dummy_spanned(ast::VisibilityKind::Public),
337 fn path_name_i(idents: &[Ident]) -> String {
338 let mut path_name = "".to_string();
339 let mut idents_iter = idents.iter().peekable();
340 while let Some(ident) = idents_iter.next() {
341 path_name.push_str(&ident.as_str());
342 if idents_iter.peek().is_some() {
343 path_name.push_str("::")
349 /// Creates a slice containing every test like so:
350 /// &[path::to::test1, path::to::test2]
351 fn mk_tests_slice(cx: &TestCtxt<'_>) -> P<ast::Expr> {
352 debug!("building test vector from {} tests", cx.test_cases.len());
353 let ref ecx = cx.ext_cx;
355 ecx.expr_vec_slice(DUMMY_SP,
356 cx.test_cases.iter().map(|test| {
357 ecx.expr_addr_of(test.span,
358 ecx.expr_path(ecx.path(test.span, visible_path(cx, &test.path))))
362 /// Creates a path from the top-level __test module to the test via __test_reexports
363 fn visible_path(cx: &TestCtxt<'_>, path: &[Ident]) -> Vec<Ident>{
364 let mut visible_path = vec![];
365 match cx.toplevel_reexport {
366 Some(id) => visible_path.push(id),
368 cx.span_diagnostic.bug("expected to find top-level re-export name, but found None");
371 visible_path.extend_from_slice(path);
375 fn is_test_case(i: &ast::Item) -> bool {
376 attr::contains_name(&i.attrs, sym::rustc_test_marker)
379 fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
380 let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?;
381 test_attr.meta_item_list().map(|meta_list| {
382 if meta_list.len() != 1 {
383 sd.span_fatal(test_attr.span,
384 "`#![test_runner(..)]` accepts exactly 1 argument").raise()
386 match meta_list[0].meta_item() {
387 Some(meta_item) if meta_item.is_word() => meta_item.path.clone(),
388 _ => sd.span_fatal(test_attr.span, "`test_runner` argument must be a path").raise()