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(allow_ident, vec![dc_nested]);
161 let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item);
166 attrs: attrs.into_iter()
168 !attr.check_name(sym::main) && !attr.check_name(sym::start)
170 .chain(iter::once(allow_dead_code))
178 EntryPointType::None |
179 EntryPointType::OtherMain => item,
185 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
190 /// Creates an item (specifically a module) that "pub use"s the tests passed in.
191 /// Each tested submodule will contain a similar reexport module that we will export
192 /// under the name of the original module. That is, `submod::__test_reexports` is
193 /// reexported like so `pub use submod::__test_reexports as submod`.
194 fn mk_reexport_mod(cx: &mut TestCtxt<'_>,
197 tested_submods: Vec<(Ident, Ident)>)
198 -> (P<ast::Item>, Ident) {
199 let super_ = Ident::with_empty_ctxt(kw::Super);
201 let items = tests.into_iter().map(|r| {
202 cx.ext_cx.item_use_simple(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
203 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
204 }).chain(tested_submods.into_iter().map(|(r, sym)| {
205 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
206 cx.ext_cx.item_use_simple_(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
210 let reexport_mod = ast::Mod {
216 let name = Ident::from_str("__test_reexports").gensym();
217 let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
218 cx.ext_cx.current_expansion.id = cx.ext_cx.resolver.get_module_scope(parent);
219 let it = cx.ext_cx.monotonic_expander().flat_map_item(P(ast::Item {
222 id: ast::DUMMY_NODE_ID,
223 node: ast::ItemKind::Mod(reexport_mod),
224 vis: dummy_spanned(ast::VisibilityKind::Public),
232 /// Crawl over the crate, inserting test reexports and the test main function
233 fn generate_test_harness(sess: &ParseSess,
234 resolver: &mut dyn Resolver,
235 reexport_test_harness_main: Option<Symbol>,
236 krate: &mut ast::Crate,
237 sd: &errors::Handler,
239 test_runner: Option<ast::Path>) {
240 // Remove the entry points
241 let mut cleaner = EntryPointCleaner { depth: 0 };
242 cleaner.visit_crate(krate);
244 let mut econfig = ExpansionConfig::default("test".to_string());
245 econfig.features = Some(features);
249 ext_cx: ExtCtxt::new(sess, econfig, resolver),
251 test_cases: Vec::new(),
252 reexport_test_harness_main,
253 toplevel_reexport: None,
257 TestHarnessGenerator {
260 tested_submods: Vec::new(),
261 }.visit_crate(krate);
264 /// Creates a function item for use as the main function of a test build.
265 /// This function will call the `test_runner` as specified by the crate attribute
266 fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
267 // Writing this out by hand:
270 // test::test_main_static(&[..tests]);
272 let sp = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
273 ExpnKind::Macro(MacroKind::Attr, sym::test_case), DUMMY_SP, cx.ext_cx.parse_sess.edition,
274 [sym::main, sym::test, sym::rustc_attrs][..].into(),
276 let ecx = &cx.ext_cx;
277 let test_id = Ident::with_empty_ctxt(sym::test);
279 // test::test_main_static(...)
280 let mut test_runner = cx.test_runner.clone().unwrap_or(
282 test_id, ecx.ident_of("test_main_static")
285 test_runner.span = sp;
287 let test_main_path_expr = ecx.expr_path(test_runner);
288 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
289 vec![mk_tests_slice(cx)]);
290 let call_test_main = ecx.stmt_expr(call_test_main);
293 let main_meta = ecx.meta_word(sp, sym::main);
294 let main_attr = ecx.attribute(main_meta);
296 // extern crate test as test_gensym
297 let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
300 ast::ItemKind::ExternCrate(None)
303 // pub fn main() { ... }
304 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
306 // If no test runner is provided we need to import the test crate
307 let main_body = if cx.test_runner.is_none() {
308 ecx.block(sp, vec![test_extern_stmt, call_test_main])
310 ecx.block(sp, vec![call_test_main])
313 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
314 ast::FnHeader::default(),
315 ast::Generics::default(),
318 // Honor the reexport_test_harness_main attribute
319 let main_id = match cx.reexport_test_harness_main {
320 Some(sym) => Ident::new(sym, sp),
321 None => Ident::from_str_and_span("main", sp).gensym(),
326 attrs: vec![main_attr],
327 id: ast::DUMMY_NODE_ID,
329 vis: dummy_spanned(ast::VisibilityKind::Public),
336 fn path_name_i(idents: &[Ident]) -> String {
337 let mut path_name = "".to_string();
338 let mut idents_iter = idents.iter().peekable();
339 while let Some(ident) = idents_iter.next() {
340 path_name.push_str(&ident.as_str());
341 if idents_iter.peek().is_some() {
342 path_name.push_str("::")
348 /// Creates a slice containing every test like so:
349 /// &[path::to::test1, path::to::test2]
350 fn mk_tests_slice(cx: &TestCtxt<'_>) -> P<ast::Expr> {
351 debug!("building test vector from {} tests", cx.test_cases.len());
352 let ref ecx = cx.ext_cx;
354 ecx.expr_vec_slice(DUMMY_SP,
355 cx.test_cases.iter().map(|test| {
356 ecx.expr_addr_of(test.span,
357 ecx.expr_path(ecx.path(test.span, visible_path(cx, &test.path))))
361 /// Creates a path from the top-level __test module to the test via __test_reexports
362 fn visible_path(cx: &TestCtxt<'_>, path: &[Ident]) -> Vec<Ident>{
363 let mut visible_path = vec![];
364 match cx.toplevel_reexport {
365 Some(id) => visible_path.push(id),
367 cx.span_diagnostic.bug("expected to find top-level re-export name, but found None");
370 visible_path.extend_from_slice(path);
374 fn is_test_case(i: &ast::Item) -> bool {
375 attr::contains_name(&i.attrs, sym::rustc_test_marker)
378 fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
379 let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?;
380 test_attr.meta_item_list().map(|meta_list| {
381 if meta_list.len() != 1 {
382 sd.span_fatal(test_attr.span,
383 "`#![test_runner(..)]` accepts exactly 1 argument").raise()
385 match meta_list[0].meta_item() {
386 Some(meta_item) if meta_item.is_word() => meta_item.path.clone(),
387 _ => sd.span_fatal(test_attr.span, "`test_runner` argument must be a path").raise()