1 // Code that generates a test runner to run all the tests in a crate
4 #![allow(unused_imports)]
6 use HasTestSignature::*;
14 use smallvec::{smallvec, SmallVec};
15 use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, BytePos};
17 use crate::attr::{self, HasAttrs};
18 use crate::source_map::{self, SourceMap, ExpnInfo, MacroAttribute, dummy_spanned, respan};
20 use crate::entry::{self, EntryPointType};
21 use crate::ext::base::{ExtCtxt, Resolver};
22 use crate::ext::build::AstBuilder;
23 use crate::ext::expand::ExpansionConfig;
24 use crate::ext::hygiene::{self, Mark, SyntaxContext};
25 use crate::mut_visit::{*, ExpectOne};
26 use crate::feature_gate::Features;
27 use crate::util::map_in_place::MapInPlace;
28 use crate::parse::{token, ParseSess};
29 use crate::print::pprust;
30 use crate::ast::{self, Ident};
32 use crate::symbol::{self, Symbol, keywords};
41 span_diagnostic: &'a errors::Handler,
44 test_cases: Vec<Test>,
45 reexport_test_harness_main: Option<Symbol>,
48 features: &'a Features,
49 test_runner: Option<ast::Path>,
51 // top-level re-export submodule, filled out after folding is finished
52 toplevel_reexport: Option<Ident>,
55 // Traverse the crate, collecting all the test functions, eliding any
56 // existing main functions, and synthesizing a main test harness
57 pub fn modify_for_testing(sess: &ParseSess,
58 resolver: &mut dyn Resolver,
60 krate: &mut ast::Crate,
61 span_diagnostic: &errors::Handler,
62 features: &Features) {
63 // Check for #[reexport_test_harness_main = "some_name"] which
64 // creates a `use __test::main as some_name;`. This needs to be
65 // unconditional, so that the attribute is still marked as used in
67 let reexport_test_harness_main =
68 attr::first_attr_value_str_by_name(&krate.attrs,
69 "reexport_test_harness_main");
71 // Do this here so that the test_runner crate attribute gets marked as used
72 // even in non-test builds
73 let test_runner = get_test_runner(span_diagnostic, &krate);
76 generate_test_harness(sess, resolver, reexport_test_harness_main,
77 krate, span_diagnostic, features, test_runner)
81 struct TestHarnessGenerator<'a> {
85 // submodule name, gensym'd identifier for re-exports
86 tested_submods: Vec<(Ident, Ident)>,
89 impl<'a> MutVisitor for TestHarnessGenerator<'a> {
90 fn visit_crate(&mut self, c: &mut ast::Crate) {
91 noop_visit_crate(c, self);
93 // Create a main function to run our tests
95 let unresolved = mk_main(&mut self.cx);
96 self.cx.ext_cx.monotonic_expander().flat_map_item(unresolved).pop().unwrap()
99 c.module.items.push(test_main);
102 fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
104 if ident.name != keywords::Invalid.name() {
105 self.cx.path.push(ident);
107 debug!("current path: {}", path_name_i(&self.cx.path));
109 let mut item = i.into_inner();
110 if is_test_case(&item) {
111 debug!("this is a test item");
115 path: self.cx.path.clone(),
117 self.cx.test_cases.push(test);
118 self.tests.push(item.ident);
121 // We don't want to recurse into anything other than mods, since
122 // mods or tests inside of functions will break things
123 if let ast::ItemKind::Mod(mut module) = item.node {
124 let tests = mem::replace(&mut self.tests, Vec::new());
125 let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
126 noop_visit_mod(&mut module, self);
127 let tests = mem::replace(&mut self.tests, tests);
128 let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
130 if !tests.is_empty() || !tested_submods.is_empty() {
131 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
132 module.items.push(it);
134 if !self.cx.path.is_empty() {
135 self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
137 debug!("pushing nothing, sym: {:?}", sym);
138 self.cx.toplevel_reexport = Some(sym);
141 item.node = ast::ItemKind::Mod(module);
143 if ident.name != keywords::Invalid.name() {
149 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
154 /// A folder used to remove any entry points (like fn main) because the harness
155 /// generator will provide its own
156 struct EntryPointCleaner {
157 // Current depth in the ast
161 impl MutVisitor for EntryPointCleaner {
162 fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
164 let item = noop_flat_map_item(i, self).expect_one("noop did something");
167 // Remove any #[main] or #[start] from the AST so it doesn't
168 // clash with the one we're going to add, but mark it as
169 // #[allow(dead_code)] to avoid printing warnings.
170 let item = match entry::entry_point_type(&item, self.depth) {
171 EntryPointType::MainNamed |
172 EntryPointType::MainAttr |
173 EntryPointType::Start =>
174 item.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
175 let allow_ident = Ident::from_str("allow");
176 let dc_nested = attr::mk_nested_word_item(Ident::from_str("dead_code"));
177 let allow_dead_code_item = attr::mk_list_item(DUMMY_SP, allow_ident,
179 let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
181 allow_dead_code_item);
186 attrs: attrs.into_iter()
188 !attr.check_name("main") && !attr.check_name("start")
190 .chain(iter::once(allow_dead_code))
198 EntryPointType::None |
199 EntryPointType::OtherMain => item,
205 fn visit_mac(&mut self, _mac: &mut ast::Mac) {
210 /// Creates an item (specifically a module) that "pub use"s the tests passed in.
211 /// Each tested submodule will contain a similar reexport module that we will export
212 /// under the name of the original module. That is, `submod::__test_reexports` is
213 /// reexported like so `pub use submod::__test_reexports as submod`.
214 fn mk_reexport_mod(cx: &mut TestCtxt<'_>,
217 tested_submods: Vec<(Ident, Ident)>)
218 -> (P<ast::Item>, Ident) {
219 let super_ = Ident::from_str("super");
221 let items = tests.into_iter().map(|r| {
222 cx.ext_cx.item_use_simple(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
223 cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
224 }).chain(tested_submods.into_iter().map(|(r, sym)| {
225 let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
226 cx.ext_cx.item_use_simple_(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
230 let reexport_mod = ast::Mod {
236 let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
237 let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
238 cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
239 let it = cx.ext_cx.monotonic_expander().flat_map_item(P(ast::Item {
242 id: ast::DUMMY_NODE_ID,
243 node: ast::ItemKind::Mod(reexport_mod),
244 vis: dummy_spanned(ast::VisibilityKind::Public),
252 /// Crawl over the crate, inserting test reexports and the test main function
253 fn generate_test_harness(sess: &ParseSess,
254 resolver: &mut dyn Resolver,
255 reexport_test_harness_main: Option<Symbol>,
256 krate: &mut ast::Crate,
257 sd: &errors::Handler,
259 test_runner: Option<ast::Path>) {
260 // Remove the entry points
261 let mut cleaner = EntryPointCleaner { depth: 0 };
262 cleaner.visit_crate(krate);
264 let mark = Mark::fresh(Mark::root());
266 let mut econfig = ExpansionConfig::default("test".to_string());
267 econfig.features = Some(features);
271 ext_cx: ExtCtxt::new(sess, econfig, resolver),
273 test_cases: Vec::new(),
274 reexport_test_harness_main,
275 // N.B., doesn't consider the value of `--crate-name` passed on the command line.
276 is_libtest: attr::find_crate_name(&krate.attrs).map(|s| s == "test").unwrap_or(false),
277 toplevel_reexport: None,
278 ctxt: SyntaxContext::empty().apply_mark(mark),
283 mark.set_expn_info(ExpnInfo {
286 format: MacroAttribute(Symbol::intern("test_case")),
287 allow_internal_unstable: Some(vec![
288 Symbol::intern("main"),
289 Symbol::intern("test"),
290 Symbol::intern("rustc_attrs"),
292 allow_internal_unsafe: false,
293 local_inner_macros: false,
294 edition: hygiene::default_edition(),
297 TestHarnessGenerator {
300 tested_submods: Vec::new(),
301 }.visit_crate(krate);
304 /// Craft a span that will be ignored by the stability lint's
305 /// call to source_map's `is_internal` check.
306 /// The expanded code calls some unstable functions in the test crate.
307 fn ignored_span(cx: &TestCtxt<'_>, sp: Span) -> Span {
308 sp.with_ctxt(cx.ctxt)
311 enum HasTestSignature {
313 No(BadTestSignature),
317 enum BadTestSignature {
321 ShouldPanicOnlyWithNoArgs,
324 /// Creates a function item for use as the main function of a test build.
325 /// This function will call the `test_runner` as specified by the crate attribute
326 fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
327 // Writing this out by hand with 'ignored_span':
330 // test::test_main_static(::std::os::args().as_slice(), &[..tests]);
332 let sp = ignored_span(cx, DUMMY_SP);
333 let ecx = &cx.ext_cx;
334 let test_id = ecx.ident_of("test").gensym();
336 // test::test_main_static(...)
337 let mut test_runner = cx.test_runner.clone().unwrap_or(
339 test_id, ecx.ident_of("test_main_static")
342 test_runner.span = sp;
344 let test_main_path_expr = ecx.expr_path(test_runner);
345 let call_test_main = ecx.expr_call(sp, test_main_path_expr,
346 vec![mk_tests_slice(cx)]);
347 let call_test_main = ecx.stmt_expr(call_test_main);
350 let main_meta = ecx.meta_word(sp, Symbol::intern("main"));
351 let main_attr = ecx.attribute(sp, main_meta);
353 // extern crate test as test_gensym
354 let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
357 ast::ItemKind::ExternCrate(Some(Symbol::intern("test")))
360 // pub fn main() { ... }
361 let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
363 // If no test runner is provided we need to import the test crate
364 let main_body = if cx.test_runner.is_none() {
365 ecx.block(sp, vec![test_extern_stmt, call_test_main])
367 ecx.block(sp, vec![call_test_main])
370 let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
371 ast::FnHeader::default(),
372 ast::Generics::default(),
375 // Honor the reexport_test_harness_main attribute
376 let main_id = Ident::new(
377 cx.reexport_test_harness_main.unwrap_or(Symbol::gensym("main")),
382 attrs: vec![main_attr],
383 id: ast::DUMMY_NODE_ID,
385 vis: dummy_spanned(ast::VisibilityKind::Public),
392 fn path_name_i(idents: &[Ident]) -> String {
393 let mut path_name = "".to_string();
394 let mut idents_iter = idents.iter().peekable();
395 while let Some(ident) = idents_iter.next() {
396 path_name.push_str(&ident.as_str());
397 if idents_iter.peek().is_some() {
398 path_name.push_str("::")
404 /// Creates a slice containing every test like so:
405 /// &[path::to::test1, path::to::test2]
406 fn mk_tests_slice(cx: &TestCtxt<'_>) -> P<ast::Expr> {
407 debug!("building test vector from {} tests", cx.test_cases.len());
408 let ref ecx = cx.ext_cx;
410 ecx.expr_vec_slice(DUMMY_SP,
411 cx.test_cases.iter().map(|test| {
412 ecx.expr_addr_of(test.span,
413 ecx.expr_path(ecx.path(test.span, visible_path(cx, &test.path))))
417 /// Creates a path from the top-level __test module to the test via __test_reexports
418 fn visible_path(cx: &TestCtxt<'_>, path: &[Ident]) -> Vec<Ident>{
419 let mut visible_path = vec![];
420 match cx.toplevel_reexport {
421 Some(id) => visible_path.push(id),
423 cx.span_diagnostic.bug("expected to find top-level re-export name, but found None");
426 visible_path.extend_from_slice(path);
430 fn is_test_case(i: &ast::Item) -> bool {
431 attr::contains_name(&i.attrs, "rustc_test_marker")
434 fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
435 let test_attr = attr::find_by_name(&krate.attrs, "test_runner")?;
436 test_attr.meta_item_list().map(|meta_list| {
437 if meta_list.len() != 1 {
438 sd.span_fatal(test_attr.span(),
439 "#![test_runner(..)] accepts exactly 1 argument").raise()
441 meta_list[0].word().as_ref().unwrap().ident.clone()