1 use rustc_data_structures::sync::Lrc;
2 use rustc_interface::interface;
4 use rustc::hir::intravisit;
5 use rustc::hir::def_id::LOCAL_CRATE;
6 use rustc::session::{self, config, DiagnosticOutput};
7 use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
8 use rustc::session::search_paths::SearchPath;
9 use rustc::util::common::ErrorReported;
11 use syntax::with_globals;
12 use syntax::source_map::SourceMap;
13 use syntax::edition::Edition;
14 use syntax::feature_gate::UnstableFeatures;
16 use std::io::prelude::*;
18 use std::panic::{self, AssertUnwindSafe};
19 use std::path::PathBuf;
20 use std::process::Command;
22 use std::sync::{Arc, Mutex};
23 use syntax::symbol::sym;
24 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName};
25 use tempfile::Builder as TempFileBuilder;
28 use crate::clean::Attributes;
29 use crate::config::Options;
30 use crate::html::markdown::{self, ErrorCodes, LangString};
32 #[derive(Clone, Default)]
33 pub struct TestOptions {
34 /// Whether to disable the default `extern crate my_crate;` when creating doctests.
35 pub no_crate_inject: bool,
36 /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
37 /// the default `#![allow(unused)]`.
38 pub display_warnings: bool,
39 /// Additional crate-level attributes to add to doctests.
40 pub attrs: Vec<String>,
43 pub fn run(options: Options) -> i32 {
44 let input = config::Input::File(options.input.clone());
46 let sessopts = config::Options {
47 maybe_sysroot: options.maybe_sysroot.clone().or_else(
48 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
49 search_paths: options.libs.clone(),
50 crate_types: vec![config::CrateType::Dylib],
51 cg: options.codegen_options.clone(),
52 externs: options.externs.clone(),
53 unstable_features: UnstableFeatures::from_environment(),
54 lint_cap: Some(::rustc::lint::Level::Allow),
55 actually_rustdoc: true,
56 debugging_opts: config::DebuggingOptions {
57 ..config::basic_debugging_options()
59 edition: options.edition,
60 ..config::Options::default()
63 let config = interface::Config {
65 crate_cfg: config::parse_cfgspecs(options.cfgs.clone()),
71 diagnostic_output: DiagnosticOutput::Default,
73 crate_name: options.crate_name.clone(),
74 lint_caps: Default::default(),
77 let mut test_args = options.test_args.clone();
78 let display_warnings = options.display_warnings;
80 let tests = interface::run_compiler(config, |compiler| -> Result<_, ErrorReported> {
81 let lower_to_hir = compiler.lower_to_hir()?;
83 let mut opts = scrape_test_config(lower_to_hir.peek().0.borrow().krate());
84 opts.display_warnings |= options.display_warnings;
85 let mut collector = Collector::new(
86 compiler.crate_name()?.peek().to_string(),
89 options.codegen_options,
93 options.maybe_sysroot,
94 Some(compiler.source_map().clone()),
98 options.persist_doctests,
101 let mut global_ctxt = compiler.global_ctxt()?.take();
102 global_ctxt.enter(|tcx| {
103 let krate = tcx.hir().krate();
104 let mut hir_collector = HirCollector {
105 sess: compiler.session(),
106 collector: &mut collector,
108 codes: ErrorCodes::from(compiler.session().opts
109 .unstable_features.is_nightly_build()),
111 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
112 intravisit::walk_crate(this, krate);
117 }).expect("compiler aborted in rustdoc!");
119 test_args.insert(0, "rustdoctest".to_string());
124 testing::Options::new().display_output(display_warnings)
130 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
131 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
132 use syntax::print::pprust;
134 let mut opts = TestOptions {
135 no_crate_inject: false,
136 display_warnings: false,
140 let test_attrs: Vec<_> = krate.attrs.iter()
141 .filter(|a| a.check_name(sym::doc))
142 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
143 .filter(|a| a.check_name(sym::test))
145 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
148 if attr.check_name(sym::no_crate_inject) {
149 opts.no_crate_inject = true;
151 if attr.check_name(sym::attr) {
152 if let Some(l) = attr.meta_item_list() {
154 opts.attrs.push(pprust::meta_list_item_to_string(item));
163 fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
164 cfgs: Vec<String>, libs: Vec<SearchPath>,
165 cg: CodegenOptions, externs: Externs,
166 should_panic: bool, no_run: bool, as_test_harness: bool,
167 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
168 maybe_sysroot: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
169 persist_doctests: Option<PathBuf>) {
170 let (test, line_offset) = match panic::catch_unwind(|| {
171 make_test(test, Some(cratename), as_test_harness, opts, edition)
173 Ok((test, line_offset)) => (test, line_offset),
174 Err(cause) if cause.is::<errors::FatalErrorMarker>() => {
175 // If the parser used by `make_test` panicked due to a fatal error, pass the test code
176 // through unchanged. The error will be reported during compilation.
179 Err(cause) => panic::resume_unwind(cause),
182 // FIXME(#44940): if doctests ever support path remapping, then this filename
183 // needs to be the result of `SourceMap::span_to_unmapped_path`.
184 let path = match filename {
185 FileName::Real(path) => path.clone(),
186 _ => PathBuf::from(r"doctest.rs"),
189 let input = config::Input::Str {
190 name: FileName::DocTest(path, line as isize - line_offset as isize),
193 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
195 let sessopts = config::Options {
196 maybe_sysroot: maybe_sysroot.or_else(
197 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
199 crate_types: vec![config::CrateType::Executable],
200 output_types: outputs,
202 cg: config::CodegenOptions {
206 test: as_test_harness,
207 unstable_features: UnstableFeatures::from_environment(),
208 debugging_opts: config::DebuggingOptions {
209 ..config::basic_debugging_options()
212 ..config::Options::default()
215 // Shuffle around a few input and output handles here. We're going to pass
216 // an explicit handle into rustc to collect output messages, but we also
217 // want to catch the error message that rustc prints when it fails.
219 // We take our thread-local stderr (likely set by the test runner) and replace
220 // it with a sink that is also passed to rustc itself. When this function
221 // returns the output of the sink is copied onto the output of our own thread.
223 // The basic idea is to not use a default Handler for rustc, and then also
224 // not print things by default to the actual stderr.
225 struct Sink(Arc<Mutex<Vec<u8>>>);
226 impl Write for Sink {
227 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
228 Write::write(&mut *self.0.lock().unwrap(), data)
230 fn flush(&mut self) -> io::Result<()> { Ok(()) }
232 struct Bomb(Arc<Mutex<Vec<u8>>>, Option<Box<dyn Write+Send>>);
235 let mut old = self.1.take().unwrap();
236 let _ = old.write_all(&self.0.lock().unwrap());
237 io::set_panic(Some(old));
240 let data = Arc::new(Mutex::new(Vec::new()));
242 let old = io::set_panic(Some(box Sink(data.clone())));
243 let _bomb = Bomb(data.clone(), Some(old.unwrap_or(box io::stdout())));
246 Temp(tempfile::TempDir),
251 fn path(&self) -> &std::path::Path {
253 DirState::Temp(t) => t.path(),
254 DirState::Perm(p) => p.as_path(),
259 let outdir = if let Some(mut path) = persist_doctests {
260 path.push(format!("{}_{}",
269 std::fs::create_dir_all(&path)
270 .expect("Couldn't create directory for doctest executables");
274 DirState::Temp(TempFileBuilder::new()
275 .prefix("rustdoctest")
277 .expect("rustdoc needs a tempdir"))
279 let output_file = outdir.path().join("rust_out");
281 let config = interface::Config {
283 crate_cfg: config::parse_cfgspecs(cfgs),
286 output_file: Some(output_file.clone()),
289 diagnostic_output: DiagnosticOutput::Raw(box Sink(data.clone())),
290 stderr: Some(data.clone()),
292 lint_caps: Default::default(),
295 let compile_result = panic::catch_unwind(AssertUnwindSafe(|| {
296 interface::run_compiler(config, |compiler| {
298 compiler.global_ctxt().and_then(|global_ctxt| global_ctxt.take().enter(|tcx| {
299 tcx.analysis(LOCAL_CRATE)
302 compiler.compile().ok();
304 compiler.session().compile_status()
306 })).map_err(|_| ()).and_then(|s| s.map_err(|_| ()));
308 match (compile_result, compile_fail) {
310 panic!("test compiled while it wasn't supposed to")
312 (Ok(()), false) => {}
314 if error_codes.len() > 0 {
315 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
316 error_codes.retain(|err| !out.contains(err));
320 panic!("couldn't compile the test")
324 if error_codes.len() > 0 {
325 panic!("Some expected error codes were not found: {:?}", error_codes);
331 let mut cmd = Command::new(output_file);
334 Err(e) => panic!("couldn't run the test: {}{}", e,
335 if e.kind() == io::ErrorKind::PermissionDenied {
336 " - maybe your tempdir is mounted with noexec?"
339 if should_panic && out.status.success() {
340 panic!("test executable succeeded when it should have failed");
341 } else if !should_panic && !out.status.success() {
342 panic!("test executable failed:\n{}\n{}\n",
343 str::from_utf8(&out.stdout).unwrap_or(""),
344 str::from_utf8(&out.stderr).unwrap_or(""));
350 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
351 /// lines before the test code begins.
355 /// This function uses the compiler's parser internally. The parser will panic if it encounters a
356 /// fatal error while parsing the test.
357 pub fn make_test(s: &str,
358 cratename: Option<&str>,
359 dont_insert_main: bool,
363 let (crate_attrs, everything_else, crates) = partition_source(s);
364 let everything_else = everything_else.trim();
365 let mut line_offset = 0;
366 let mut prog = String::new();
368 if opts.attrs.is_empty() && !opts.display_warnings {
369 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
370 // lints that are commonly triggered in doctests. The crate-level test attributes are
371 // commonly used to make tests fail in case they trigger warnings, so having this there in
372 // that case may cause some tests to pass when they shouldn't have.
373 prog.push_str("#![allow(unused)]\n");
377 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
378 for attr in &opts.attrs {
379 prog.push_str(&format!("#![{}]\n", attr));
383 // Now push any outer attributes from the example, assuming they
384 // are intended to be crate attributes.
385 prog.push_str(&crate_attrs);
386 prog.push_str(&crates);
388 // Uses libsyntax to parse the doctest and find if there's a main fn and the extern
389 // crate already is included.
390 let (already_has_main, already_has_extern_crate, found_macro) = with_globals(edition, || {
391 use crate::syntax::{parse::{self, ParseSess}, source_map::FilePathMapping};
392 use errors::emitter::EmitterWriter;
395 let filename = FileName::anon_source_code(s);
396 let source = crates + &everything_else;
398 // Any errors in parsing should also appear when the doctest is compiled for real, so just
399 // send all the errors that libsyntax emits directly into a `Sink` instead of stderr.
400 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
401 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false);
402 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
403 let handler = Handler::with_emitter(false, None, box emitter);
404 let sess = ParseSess::with_span_handler(handler, cm);
406 let mut found_main = false;
407 let mut found_extern_crate = cratename.is_none();
408 let mut found_macro = false;
410 let mut parser = match parse::maybe_new_parser_from_source_str(&sess, filename, source) {
413 for mut err in errs {
417 return (found_main, found_extern_crate, found_macro);
422 match parser.parse_item() {
425 if let ast::ItemKind::Fn(..) = item.node {
426 if item.ident.as_str() == "main" {
432 if !found_extern_crate {
433 if let ast::ItemKind::ExternCrate(original) = item.node {
434 // This code will never be reached if `cratename` is none because
435 // `found_extern_crate` is initialized to `true` if it is none.
436 let cratename = cratename.unwrap();
439 Some(name) => found_extern_crate = name.as_str() == cratename,
440 None => found_extern_crate = item.ident.as_str() == cratename,
446 if let ast::ItemKind::Mac(..) = item.node {
451 if found_main && found_extern_crate {
463 (found_main, found_extern_crate, found_macro)
466 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
467 // see it. In that case, run the old text-based scan to see if they at least have a main
468 // function written inside a macro invocation. See
469 // https://github.com/rust-lang/rust/issues/56898
470 let already_has_main = if found_macro && !already_has_main {
473 let comment = line.find("//");
474 if let Some(comment_begins) = comment {
475 &line[0..comment_begins]
480 .any(|code| code.contains("fn main"))
485 // Don't inject `extern crate std` because it's already injected by the
487 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
488 if let Some(cratename) = cratename {
489 // Make sure its actually used if not included.
490 if s.contains(cratename) {
491 prog.push_str(&format!("extern crate {};\n", cratename));
497 // FIXME: This code cannot yet handle no_std test cases yet
498 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
499 prog.push_str(everything_else);
501 let returns_result = everything_else.trim_end().ends_with("(())");
502 let (main_pre, main_post) = if returns_result {
503 ("fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
504 "}\n_inner().unwrap() }")
506 ("fn main() {\n", "\n}")
508 prog.extend([main_pre, everything_else, main_post].iter().cloned());
512 debug!("final doctest:\n{}", prog);
517 // FIXME(aburka): use a real parser to deal with multiline attributes
518 fn partition_source(s: &str) -> (String, String, String) {
519 #[derive(Copy, Clone, PartialEq)]
520 enum PartitionState {
525 let mut state = PartitionState::Attrs;
526 let mut before = String::new();
527 let mut crates = String::new();
528 let mut after = String::new();
530 for line in s.lines() {
531 let trimline = line.trim();
533 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
534 // shunted into "everything else"
536 PartitionState::Attrs => {
537 state = if trimline.starts_with("#![") ||
538 trimline.chars().all(|c| c.is_whitespace()) ||
539 (trimline.starts_with("//") && !trimline.starts_with("///"))
541 PartitionState::Attrs
542 } else if trimline.starts_with("extern crate") ||
543 trimline.starts_with("#[macro_use] extern crate")
545 PartitionState::Crates
547 PartitionState::Other
550 PartitionState::Crates => {
551 state = if trimline.starts_with("extern crate") ||
552 trimline.starts_with("#[macro_use] extern crate") ||
553 trimline.chars().all(|c| c.is_whitespace()) ||
554 (trimline.starts_with("//") && !trimline.starts_with("///"))
556 PartitionState::Crates
558 PartitionState::Other
561 PartitionState::Other => {}
565 PartitionState::Attrs => {
566 before.push_str(line);
567 before.push_str("\n");
569 PartitionState::Crates => {
570 crates.push_str(line);
571 crates.push_str("\n");
573 PartitionState::Other => {
574 after.push_str(line);
575 after.push_str("\n");
580 debug!("before:\n{}", before);
581 debug!("crates:\n{}", crates);
582 debug!("after:\n{}", after);
584 (before, after, crates)
588 fn add_test(&mut self, test: String, config: LangString, line: usize);
589 fn get_line(&self) -> usize {
592 fn register_header(&mut self, _name: &str, _level: u32) {}
595 pub struct Collector {
596 pub tests: Vec<testing::TestDescAndFn>,
598 // The name of the test displayed to the user, separated by `::`.
600 // In tests from Rust source, this is the path to the item
601 // e.g., `["std", "vec", "Vec", "push"]`.
603 // In tests from a markdown file, this is the titles of all headers (h1~h6)
604 // of the sections that contain the code block, e.g., if the markdown file is
617 // the `names` vector of that test will be `["Title", "Subtitle"]`.
621 libs: Vec<SearchPath>,
627 maybe_sysroot: Option<PathBuf>,
629 source_map: Option<Lrc<SourceMap>>,
630 filename: Option<PathBuf>,
631 linker: Option<PathBuf>,
633 persist_doctests: Option<PathBuf>,
637 pub fn new(cratename: String, cfgs: Vec<String>, libs: Vec<SearchPath>, cg: CodegenOptions,
638 externs: Externs, use_headers: bool, opts: TestOptions,
639 maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>,
640 filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
641 persist_doctests: Option<PathBuf>) -> Collector {
662 fn generate_name(&self, line: usize, filename: &FileName) -> String {
663 format!("{} - {} (line {})", filename, self.names.join("::"), line)
666 pub fn set_position(&mut self, position: Span) {
667 self.position = position;
670 fn get_filename(&self) -> FileName {
671 if let Some(ref source_map) = self.source_map {
672 let filename = source_map.span_to_filename(self.position);
673 if let FileName::Real(ref filename) = filename {
674 if let Ok(cur_dir) = env::current_dir() {
675 if let Ok(path) = filename.strip_prefix(&cur_dir) {
676 return path.to_owned().into();
681 } else if let Some(ref filename) = self.filename {
682 filename.clone().into()
684 FileName::Custom("input".to_owned())
689 impl Tester for Collector {
690 fn add_test(&mut self, test: String, config: LangString, line: usize) {
691 let filename = self.get_filename();
692 let name = self.generate_name(line, &filename);
693 let cfgs = self.cfgs.clone();
694 let libs = self.libs.clone();
695 let cg = self.cg.clone();
696 let externs = self.externs.clone();
697 let cratename = self.cratename.to_string();
698 let opts = self.opts.clone();
699 let maybe_sysroot = self.maybe_sysroot.clone();
700 let linker = self.linker.clone();
701 let edition = config.edition.unwrap_or(self.edition);
702 let persist_doctests = self.persist_doctests.clone();
704 debug!("Creating test {}: {}", name, test);
705 self.tests.push(testing::TestDescAndFn {
706 desc: testing::TestDesc {
707 name: testing::DynTestName(name.clone()),
708 ignore: config.ignore,
709 // compiler failures are test failures
710 should_panic: testing::ShouldPanic::No,
711 allow_fail: config.allow_fail,
713 testfn: testing::DynTestFn(box move || {
738 fn get_line(&self) -> usize {
739 if let Some(ref source_map) = self.source_map {
740 let line = self.position.lo().to_usize();
741 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
742 if line > 0 { line - 1 } else { line }
748 fn register_header(&mut self, name: &str, level: u32) {
749 if self.use_headers {
750 // We use these headings as test names, so it's good if
751 // they're valid identifiers.
752 let name = name.chars().enumerate().map(|(i, c)| {
753 if (i == 0 && c.is_xid_start()) ||
754 (i != 0 && c.is_xid_continue()) {
759 }).collect::<String>();
761 // Here we try to efficiently assemble the header titles into the
762 // test name in the form of `h1::h2::h3::h4::h5::h6`.
764 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
765 let level = level as usize;
766 if level <= self.names.len() {
767 // ... Consider `level == 2`. All headers in the lower levels
768 // are irrelevant in this new level. So we should reset
769 // `self.names` to contain headers until <h2>, and replace that
770 // slot with the new name: `[h1, name]`.
771 self.names.truncate(level);
772 self.names[level - 1] = name;
774 // ... On the other hand, consider `level == 5`. This means we
775 // need to extend `self.names` to contain five headers. We fill
776 // in the missing level (<h4>) with `_`. Thus `self.names` will
777 // become `[h1, h2, h3, "_", name]`.
778 if level - 1 > self.names.len() {
779 self.names.resize(level - 1, "_".to_owned());
781 self.names.push(name);
787 struct HirCollector<'a, 'hir: 'a> {
788 sess: &'a session::Session,
789 collector: &'a mut Collector,
790 map: &'a hir::map::Map<'hir>,
794 impl<'a, 'hir> HirCollector<'a, 'hir> {
795 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
797 attrs: &[ast::Attribute],
799 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
800 if let Some(ref cfg) = attrs.cfg {
801 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
806 let has_name = !name.is_empty();
808 self.collector.names.push(name);
811 attrs.collapse_doc_comments();
812 attrs.unindent_doc_comments();
813 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
814 // anything else, this will combine them for us.
815 if let Some(doc) = attrs.collapsed_doc_value() {
816 self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
817 markdown::find_testable_code(&doc, self.collector, self.codes);
823 self.collector.names.pop();
828 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
829 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
830 intravisit::NestedVisitorMap::All(&self.map)
833 fn visit_item(&mut self, item: &'hir hir::Item) {
834 let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.node {
835 self.map.hir_to_pretty_string(ty.hir_id)
837 item.ident.to_string()
840 self.visit_testable(name, &item.attrs, |this| {
841 intravisit::walk_item(this, item);
845 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
846 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
847 intravisit::walk_trait_item(this, item);
851 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
852 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
853 intravisit::walk_impl_item(this, item);
857 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
858 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
859 intravisit::walk_foreign_item(this, item);
863 fn visit_variant(&mut self,
864 v: &'hir hir::Variant,
865 g: &'hir hir::Generics,
866 item_id: hir::HirId) {
867 self.visit_testable(v.node.ident.to_string(), &v.node.attrs, |this| {
868 intravisit::walk_variant(this, v, g, item_id);
872 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
873 self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
874 intravisit::walk_struct_field(this, f);
878 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
879 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());
885 use super::{TestOptions, make_test};
886 use syntax::edition::DEFAULT_EDITION;
889 fn make_test_basic() {
890 //basic use: wraps with `fn main`, adds `#![allow(unused)]`
891 let opts = TestOptions::default();
893 "assert_eq!(2+2, 4);";
899 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
900 assert_eq!(output, (expected, 2));
904 fn make_test_crate_name_no_use() {
905 // If you give a crate name but *don't* use it within the test, it won't bother inserting
906 // the `extern crate` statement.
907 let opts = TestOptions::default();
909 "assert_eq!(2+2, 4);";
915 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
916 assert_eq!(output, (expected, 2));
920 fn make_test_crate_name() {
921 // If you give a crate name and use it within the test, it will insert an `extern crate`
922 // statement before `fn main`.
923 let opts = TestOptions::default();
926 assert_eq!(2+2, 4);";
934 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
935 assert_eq!(output, (expected, 3));
939 fn make_test_no_crate_inject() {
940 // Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
942 let opts = TestOptions {
943 no_crate_inject: true,
944 display_warnings: false,
949 assert_eq!(2+2, 4);";
956 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
957 assert_eq!(output, (expected, 2));
961 fn make_test_ignore_std() {
962 // Even if you include a crate name, and use it in the doctest, we still won't include an
963 // `extern crate` statement if the crate is "std" -- that's included already by the
965 let opts = TestOptions::default();
968 assert_eq!(2+2, 4);";
975 let output = make_test(input, Some("std"), false, &opts, DEFAULT_EDITION);
976 assert_eq!(output, (expected, 2));
980 fn make_test_manual_extern_crate() {
981 // When you manually include an `extern crate` statement in your doctest, `make_test`
982 // assumes you've included one for your own crate too.
983 let opts = TestOptions::default();
987 assert_eq!(2+2, 4);";
995 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
996 assert_eq!(output, (expected, 2));
1000 fn make_test_manual_extern_crate_with_macro_use() {
1001 let opts = TestOptions::default();
1003 "#[macro_use] extern crate asdf;
1005 assert_eq!(2+2, 4);";
1008 #[macro_use] extern crate asdf;
1013 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1014 assert_eq!(output, (expected, 2));
1018 fn make_test_opts_attrs() {
1019 // If you supplied some doctest attributes with `#![doc(test(attr(...)))]`, it will use
1020 // those instead of the stock `#![allow(unused)]`.
1021 let mut opts = TestOptions::default();
1022 opts.attrs.push("feature(sick_rad)".to_string());
1025 assert_eq!(2+2, 4);";
1027 "#![feature(sick_rad)]
1033 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1034 assert_eq!(output, (expected, 3));
1036 // Adding more will also bump the returned line offset.
1037 opts.attrs.push("feature(hella_dope)".to_string());
1039 "#![feature(sick_rad)]
1040 #![feature(hella_dope)]
1046 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1047 assert_eq!(output, (expected, 4));
1051 fn make_test_crate_attrs() {
1052 // Including inner attributes in your doctest will apply them to the whole "crate", pasting
1053 // them outside the generated main function.
1054 let opts = TestOptions::default();
1056 "#![feature(sick_rad)]
1057 assert_eq!(2+2, 4);";
1060 #![feature(sick_rad)]
1064 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1065 assert_eq!(output, (expected, 2));
1069 fn make_test_with_main() {
1070 // Including your own `fn main` wrapper lets the test use it verbatim.
1071 let opts = TestOptions::default();
1081 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1082 assert_eq!(output, (expected, 1));
1086 fn make_test_fake_main() {
1087 // ... but putting it in a comment will still provide a wrapper.
1088 let opts = TestOptions::default();
1090 "//Ceci n'est pas une `fn main`
1091 assert_eq!(2+2, 4);";
1094 //Ceci n'est pas une `fn main`
1098 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1099 assert_eq!(output, (expected, 2));
1103 fn make_test_dont_insert_main() {
1104 // Even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper.
1105 let opts = TestOptions::default();
1107 "//Ceci n'est pas une `fn main`
1108 assert_eq!(2+2, 4);";
1111 //Ceci n'est pas une `fn main`
1112 assert_eq!(2+2, 4);".to_string();
1113 let output = make_test(input, None, true, &opts, DEFAULT_EDITION);
1114 assert_eq!(output, (expected, 1));
1118 fn make_test_display_warnings() {
1119 // If the user is asking to display doctest warnings, suppress the default `allow(unused)`.
1120 let mut opts = TestOptions::default();
1121 opts.display_warnings = true;
1123 "assert_eq!(2+2, 4);";
1128 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1129 assert_eq!(output, (expected, 1));
1133 fn make_test_issues_21299_33731() {
1134 let opts = TestOptions::default();
1138 assert_eq!(2+2, 4);";
1147 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1148 assert_eq!(output, (expected, 2));
1151 "extern crate hella_qwop;
1152 assert_eq!(asdf::foo, 4);";
1156 extern crate hella_qwop;
1159 assert_eq!(asdf::foo, 4);
1162 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1163 assert_eq!(output, (expected, 3));
1167 fn make_test_main_in_macro() {
1168 let opts = TestOptions::default();
1170 "#[macro_use] extern crate my_crate;
1176 #[macro_use] extern crate my_crate;
1181 let output = make_test(input, Some("my_crate"), false, &opts, DEFAULT_EDITION);
1182 assert_eq!(output, (expected, 1));