1 /// The expansion from a test function to the appropriate test struct for libtest
2 /// Ideally, this code would be in libtest but for efficiency and error messages it lives here.
3 use crate::util::check_builtin_macro_attribute;
5 use rustc_expand::base::*;
6 use rustc_span::source_map::respan;
7 use rustc_span::symbol::{sym, Symbol};
11 use syntax::print::pprust;
15 // #[test_case] is used by custom test authors to mark tests
16 // When building for test, it needs to make the item public and gensym the name
17 // Otherwise, we'll omit the item. This behavior means that any item annotated
18 // with #[test_case] is never addressable.
20 // We mark item with an inert attribute "rustc_test_marker" which the test generation
21 // logic will pick up on.
22 pub fn expand_test_case(
23 ecx: &mut ExtCtxt<'_>,
25 meta_item: &ast::MetaItem,
26 anno_item: Annotatable,
27 ) -> Vec<Annotatable> {
28 check_builtin_macro_attribute(ecx, meta_item, sym::test_case);
30 if !ecx.ecfg.should_test {
34 let sp = ecx.with_def_site_ctxt(attr_sp);
35 let mut item = anno_item.expect_item();
36 item = item.map(|mut item| {
37 item.vis = respan(item.vis.span, ast::VisibilityKind::Public);
38 item.ident.span = item.ident.span.with_ctxt(sp.ctxt());
39 item.attrs.push(ecx.attribute(ecx.meta_word(sp, sym::rustc_test_marker)));
43 return vec![Annotatable::Item(item)];
49 meta_item: &ast::MetaItem,
51 ) -> Vec<Annotatable> {
52 check_builtin_macro_attribute(cx, meta_item, sym::test);
53 expand_test_or_bench(cx, attr_sp, item, false)
59 meta_item: &ast::MetaItem,
61 ) -> Vec<Annotatable> {
62 check_builtin_macro_attribute(cx, meta_item, sym::bench);
63 expand_test_or_bench(cx, attr_sp, item, true)
66 pub fn expand_test_or_bench(
71 ) -> Vec<Annotatable> {
72 // If we're not in test configuration, remove the annotated item
73 if !cx.ecfg.should_test {
77 let item = if let Annotatable::Item(i) = item {
84 "`#[test]` attribute is only allowed on non associated functions",
89 if let ast::ItemKind::Mac(_) = item.kind {
90 cx.parse_sess.span_diagnostic.span_warn(
92 "`#[test]` attribute should not be used on macros. Use `#[cfg(test)]` instead.",
94 return vec![Annotatable::Item(item)];
97 // has_*_signature will report any errors in the type so compilation
98 // will fail. We shouldn't try to expand in this case because the errors
100 if (!is_bench && !has_test_signature(cx, &item))
101 || (is_bench && !has_bench_signature(cx, &item))
103 return vec![Annotatable::Item(item)];
106 let (sp, attr_sp) = (cx.with_def_site_ctxt(item.span), cx.with_def_site_ctxt(attr_sp));
108 let test_id = ast::Ident::new(sym::test, attr_sp);
110 // creates test::$name
111 let test_path = |name| cx.path(sp, vec![test_id, cx.ident_of(name, sp)]);
113 // creates test::ShouldPanic::$name
114 let should_panic_path =
115 |name| cx.path(sp, vec![test_id, cx.ident_of("ShouldPanic", sp), cx.ident_of(name, sp)]);
117 // creates test::TestType::$name
119 |name| cx.path(sp, vec![test_id, cx.ident_of("TestType", sp), cx.ident_of(name, sp)]);
121 // creates $name: $expr
122 let field = |name, expr| cx.field_imm(sp, cx.ident_of(name, sp), expr);
124 let test_fn = if is_bench {
125 // A simple ident for a lambda
126 let b = cx.ident_of("b", attr_sp);
130 cx.expr_path(test_path("StaticBenchFn")),
132 // |b| self::test::assert_test_result(
137 cx.expr_path(test_path("assert_test_result")),
139 // super::$test_fn(b)
142 cx.expr_path(cx.path(sp, vec![item.ident])),
143 vec![cx.expr_ident(sp, b)],
154 cx.expr_path(test_path("StaticTestFn")),
159 // test::assert_test_result(
162 cx.expr_path(test_path("assert_test_result")),
165 cx.expr_call(sp, cx.expr_path(cx.path(sp, vec![item.ident])), vec![]), // )
173 let mut test_const = cx.item(
175 ast::Ident::new(item.ident.name, sp),
178 cx.attribute(attr::mk_list_item(
179 ast::Ident::new(sym::cfg, attr_sp),
180 vec![attr::mk_nested_word_item(ast::Ident::new(sym::test, attr_sp))],
182 // #[rustc_test_marker]
183 cx.attribute(cx.meta_word(attr_sp, sym::rustc_test_marker)),
185 // const $ident: test::TestDescAndFn =
186 ast::ItemKind::Const(
187 cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))),
188 // test::TestDescAndFn {
191 test_path("TestDescAndFn"),
193 // desc: test::TestDesc {
198 test_path("TestDesc"),
200 // name: "path::to::test"
205 cx.expr_path(test_path("StaticTestName")),
208 Symbol::intern(&item_path(
209 // skip the name of the root module
210 &cx.current_expansion.module.mod_path[1..],
216 // ignore: true | false
217 field("ignore", cx.expr_bool(sp, should_ignore(&item))),
218 // allow_fail: true | false
219 field("allow_fail", cx.expr_bool(sp, should_fail(&item))),
223 match should_panic(cx, &item) {
224 // test::ShouldPanic::No
225 ShouldPanic::No => cx.expr_path(should_panic_path("No")),
226 // test::ShouldPanic::Yes
227 ShouldPanic::Yes(None) => {
228 cx.expr_path(should_panic_path("Yes"))
230 // test::ShouldPanic::YesWithMessage("...")
231 ShouldPanic::Yes(Some(sym)) => cx.expr_call(
233 cx.expr_path(should_panic_path("YesWithMessage")),
234 vec![cx.expr_str(sp, sym)],
241 match test_type(cx) {
242 // test::TestType::UnitTest
243 TestType::UnitTest => {
244 cx.expr_path(test_type_path("UnitTest"))
246 // test::TestType::IntegrationTest
247 TestType::IntegrationTest => {
248 cx.expr_path(test_type_path("IntegrationTest"))
250 // test::TestPath::Unknown
251 TestType::Unknown => {
252 cx.expr_path(test_type_path("Unknown"))
260 // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...)
261 field("testfn", test_fn), // }
266 test_const = test_const.map(|mut tc| {
267 tc.vis.node = ast::VisibilityKind::Public;
272 let test_extern = cx.item(sp, test_id, vec![], ast::ItemKind::ExternCrate(None));
274 log::debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const));
277 // Access to libtest under a hygienic name
278 Annotatable::Item(test_extern),
279 // The generated test case
280 Annotatable::Item(test_const),
282 Annotatable::Item(item),
286 fn item_path(mod_path: &[ast::Ident], item_ident: &ast::Ident) -> String {
289 .chain(iter::once(item_ident))
290 .map(|x| x.to_string())
291 .collect::<Vec<String>>()
300 fn should_ignore(i: &ast::Item) -> bool {
301 attr::contains_name(&i.attrs, sym::ignore)
304 fn should_fail(i: &ast::Item) -> bool {
305 attr::contains_name(&i.attrs, sym::allow_fail)
308 fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
309 match attr::find_by_name(&i.attrs, sym::should_panic) {
311 let ref sd = cx.parse_sess.span_diagnostic;
313 match attr.meta_item_list() {
314 // Handle #[should_panic(expected = "foo")]
318 .find(|mi| mi.check_name(sym::expected))
319 .and_then(|mi| mi.meta_item())
320 .and_then(|mi| mi.value_str());
321 if list.len() != 1 || msg.is_none() {
324 "argument must be of the form: \
325 `expected = \"error message\"`",
328 "Errors in this attribute were erroneously \
329 allowed and will become a hard error in a \
333 ShouldPanic::Yes(None)
335 ShouldPanic::Yes(msg)
338 // Handle #[should_panic] and #[should_panic = "expected"]
339 None => ShouldPanic::Yes(attr.value_str()),
342 None => ShouldPanic::No,
352 /// Attempts to determine the type of test.
353 /// Since doctests are created without macro expanding, only possible variants here
354 /// are `UnitTest`, `IntegrationTest` or `Unknown`.
355 fn test_type(cx: &ExtCtxt<'_>) -> TestType {
356 // Root path from context contains the topmost sources directory of the crate.
357 // I.e., for `project` with sources in `src` and tests in `tests` folders
358 // (no matter how many nested folders lie inside),
359 // there will be two different root paths: `/project/src` and `/project/tests`.
360 let crate_path = cx.root_path.as_path();
362 if crate_path.ends_with("src") {
363 // `/src` folder contains unit-tests.
365 } else if crate_path.ends_with("tests") {
366 // `/tests` folder contains integration tests.
367 TestType::IntegrationTest
369 // Crate layout doesn't match expected one, test type is unknown.
374 fn has_test_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
375 let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
376 let ref sd = cx.parse_sess.span_diagnostic;
377 if let ast::ItemKind::Fn(ref sig, ref generics, _) = i.kind {
378 if sig.header.unsafety == ast::Unsafety::Unsafe {
379 sd.span_err(i.span, "unsafe functions cannot be used for tests");
382 if sig.header.asyncness.node.is_async() {
383 sd.span_err(i.span, "async functions cannot be used for tests");
387 // If the termination trait is active, the compiler will check that the output
388 // type implements the `Termination` trait as `libtest` enforces that.
389 let has_output = match sig.decl.output {
390 ast::FunctionRetTy::Default(..) => false,
391 ast::FunctionRetTy::Ty(ref t) if t.kind.is_unit() => false,
395 if !sig.decl.inputs.is_empty() {
396 sd.span_err(i.span, "functions used as tests can not have any arguments");
400 match (has_output, has_should_panic_attr) {
402 sd.span_err(i.span, "functions using `#[should_panic]` must return `()`");
406 if !generics.params.is_empty() {
407 sd.span_err(i.span, "functions used as tests must have signature fn() -> ()");
416 sd.span_err(i.span, "only functions may be used as tests");
421 fn has_bench_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
422 let has_sig = if let ast::ItemKind::Fn(ref sig, _, _) = i.kind {
423 // N.B., inadequate check, but we're running
424 // well before resolve, can't get too deep.
425 sig.decl.inputs.len() == 1
431 cx.parse_sess.span_diagnostic.span_err(
433 "functions used as benches must have \
434 signature `fn(&mut Bencher) -> impl Termination`",