1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use std::ffi::OsString;
13 use std::io::prelude::*;
15 use std::path::{Path, PathBuf};
16 use std::panic::{self, AssertUnwindSafe};
17 use std::process::Command;
19 use rustc_data_structures::sync::Lrc;
20 use std::sync::{Arc, Mutex};
25 use rustc::hir::intravisit;
26 use rustc::session::{self, CompileIncomplete, config};
27 use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
28 use rustc::session::search_paths::{SearchPaths, PathKind};
29 use rustc_metadata::dynamic_lib::DynamicLibrary;
30 use tempfile::Builder as TempFileBuilder;
31 use rustc_driver::{self, driver, target_features, Compilation};
32 use rustc_driver::driver::phase_2_configure_and_expand;
33 use rustc_metadata::cstore::CStore;
34 use rustc_resolve::MakeGlobMap;
36 use syntax::codemap::CodeMap;
37 use syntax::edition::Edition;
38 use syntax::feature_gate::UnstableFeatures;
39 use syntax::with_globals;
40 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName};
42 use errors::emitter::ColorConfig;
44 use clean::Attributes;
47 #[derive(Clone, Default)]
48 pub struct TestOptions {
49 /// Whether to disable the default `extern crate my_crate;` when creating doctests.
50 pub no_crate_inject: bool,
51 /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
52 /// the default `#![allow(unused)]`.
53 pub display_warnings: bool,
54 /// Additional crate-level attributes to add to doctests.
55 pub attrs: Vec<String>,
58 pub fn run(input_path: &Path,
62 mut test_args: Vec<String>,
63 crate_name: Option<String>,
64 maybe_sysroot: Option<PathBuf>,
65 display_warnings: bool,
66 linker: Option<PathBuf>,
70 let input = config::Input::File(input_path.to_owned());
72 let sessopts = config::Options {
73 maybe_sysroot: maybe_sysroot.clone().or_else(
74 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
75 search_paths: libs.clone(),
76 crate_types: vec![config::CrateTypeDylib],
78 externs: externs.clone(),
79 unstable_features: UnstableFeatures::from_environment(),
80 lint_cap: Some(::rustc::lint::Level::Allow),
81 actually_rustdoc: true,
82 debugging_opts: config::DebuggingOptions {
83 ..config::basic_debugging_options()
86 ..config::basic_options().clone()
88 driver::spawn_thread_pool(sessopts, |sessopts| {
89 let codemap = Lrc::new(CodeMap::new(sessopts.file_path_mapping()));
91 errors::Handler::with_tty_emitter(ColorConfig::Auto,
93 Some(codemap.clone()));
95 let mut sess = session::build_session_(
96 sessopts, Some(input_path.to_owned()), handler, codemap.clone(),
98 let codegen_backend = rustc_driver::get_codegen_backend(&sess);
99 let cstore = CStore::new(codegen_backend.metadata_loader());
100 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
102 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
103 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
104 sess.parse_sess.config = cfg;
106 let krate = panictry!(driver::phase_1_parse_input(&driver::CompileController::basic(),
109 let driver::ExpansionResult { defs, mut hir_forest, .. } = {
110 phase_2_configure_and_expand(
119 ).expect("phase_2_configure_and_expand aborted in rustdoc!")
122 let crate_name = crate_name.unwrap_or_else(|| {
123 ::rustc_codegen_utils::link::find_crate_name(None, &hir_forest.krate().attrs, &input)
125 let mut opts = scrape_test_config(hir_forest.krate());
126 opts.display_warnings |= display_warnings;
127 let mut collector = Collector::new(
143 let map = hir::map::map_crate(&sess, &cstore, &mut hir_forest, &defs);
144 let krate = map.krate();
145 let mut hir_collector = HirCollector {
147 collector: &mut collector,
150 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
151 intravisit::walk_crate(this, krate);
155 test_args.insert(0, "rustdoctest".to_string());
157 testing::test_main(&test_args,
158 collector.tests.into_iter().collect(),
159 testing::Options::new().display_output(display_warnings));
164 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
165 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
166 use syntax::print::pprust;
168 let mut opts = TestOptions {
169 no_crate_inject: false,
170 display_warnings: false,
174 let test_attrs: Vec<_> = krate.attrs.iter()
175 .filter(|a| a.check_name("doc"))
176 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
177 .filter(|a| a.check_name("test"))
179 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
182 if attr.check_name("no_crate_inject") {
183 opts.no_crate_inject = true;
185 if attr.check_name("attr") {
186 if let Some(l) = attr.meta_item_list() {
188 opts.attrs.push(pprust::meta_list_item_to_string(item));
197 fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
198 cfgs: Vec<String>, libs: SearchPaths,
199 cg: CodegenOptions, externs: Externs,
200 should_panic: bool, no_run: bool, as_test_harness: bool,
201 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
202 maybe_sysroot: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) {
203 // the test harness wants its own `main` & top level functions, so
204 // never wrap the test in `fn main() { ... }`
205 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
206 // FIXME(#44940): if doctests ever support path remapping, then this filename
207 // needs to be the result of CodeMap::span_to_unmapped_path
208 let input = config::Input::Str {
209 name: filename.to_owned(),
210 input: test.to_owned(),
212 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
214 let sessopts = config::Options {
215 maybe_sysroot: maybe_sysroot.or_else(
216 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
218 crate_types: vec![config::CrateTypeExecutable],
219 output_types: outputs,
221 cg: config::CodegenOptions {
222 prefer_dynamic: true,
226 test: as_test_harness,
227 unstable_features: UnstableFeatures::from_environment(),
228 debugging_opts: config::DebuggingOptions {
229 ..config::basic_debugging_options()
232 ..config::basic_options().clone()
235 let (libdir, outdir) = driver::spawn_thread_pool(sessopts, |sessopts| {
236 // Shuffle around a few input and output handles here. We're going to pass
237 // an explicit handle into rustc to collect output messages, but we also
238 // want to catch the error message that rustc prints when it fails.
240 // We take our thread-local stderr (likely set by the test runner) and replace
241 // it with a sink that is also passed to rustc itself. When this function
242 // returns the output of the sink is copied onto the output of our own thread.
244 // The basic idea is to not use a default Handler for rustc, and then also
245 // not print things by default to the actual stderr.
246 struct Sink(Arc<Mutex<Vec<u8>>>);
247 impl Write for Sink {
248 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
249 Write::write(&mut *self.0.lock().unwrap(), data)
251 fn flush(&mut self) -> io::Result<()> { Ok(()) }
253 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
256 let _ = self.1.write_all(&self.0.lock().unwrap());
259 let data = Arc::new(Mutex::new(Vec::new()));
260 let codemap = Lrc::new(CodeMap::new_doctest(
261 sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
263 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
264 Some(codemap.clone()),
267 let old = io::set_panic(Some(box Sink(data.clone())));
268 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
271 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
273 let mut sess = session::build_session_(
274 sessopts, None, diagnostic_handler, codemap,
276 let codegen_backend = rustc_driver::get_codegen_backend(&sess);
277 let cstore = CStore::new(codegen_backend.metadata_loader());
278 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
280 let outdir = Mutex::new(
281 TempFileBuilder::new().prefix("rustdoctest").tempdir().expect("rustdoc needs a tempdir")
283 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
284 let mut control = driver::CompileController::basic();
286 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
287 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
288 sess.parse_sess.config = cfg;
290 let out = Some(outdir.lock().unwrap().path().to_path_buf());
293 control.after_analysis.stop = Compilation::Stop;
296 let res = panic::catch_unwind(AssertUnwindSafe(|| {
297 driver::compile_input(
310 let compile_result = match res {
311 Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
312 Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
315 match (compile_result, compile_fail) {
317 panic!("test compiled while it wasn't supposed to")
319 (Ok(()), false) => {}
321 if error_codes.len() > 0 {
322 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
323 error_codes.retain(|err| !out.contains(err));
326 (Err(()), false) => {
327 panic!("couldn't compile the test")
331 if error_codes.len() > 0 {
332 panic!("Some expected error codes were not found: {:?}", error_codes);
342 // We're careful to prepend the *target* dylib search path to the child's
343 // environment to ensure that the target loads the right libraries at
344 // runtime. It would be a sad day if the *host* libraries were loaded as a
346 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
347 let var = DynamicLibrary::envvar();
349 let path = env::var_os(var).unwrap_or(OsString::new());
350 let mut path = env::split_paths(&path).collect::<Vec<_>>();
351 path.insert(0, libdir.clone());
352 env::join_paths(path).unwrap()
354 cmd.env(var, &newpath);
357 Err(e) => panic!("couldn't run the test: {}{}", e,
358 if e.kind() == io::ErrorKind::PermissionDenied {
359 " - maybe your tempdir is mounted with noexec?"
362 if should_panic && out.status.success() {
363 panic!("test executable succeeded when it should have failed");
364 } else if !should_panic && !out.status.success() {
365 panic!("test executable failed:\n{}\n{}\n",
366 str::from_utf8(&out.stdout).unwrap_or(""),
367 str::from_utf8(&out.stderr).unwrap_or(""));
373 /// Makes the test file. Also returns the number of lines before the code begins
374 pub fn make_test(s: &str,
375 cratename: Option<&str>,
376 dont_insert_main: bool,
379 let (crate_attrs, everything_else) = partition_source(s);
380 let everything_else = everything_else.trim();
381 let mut line_offset = 0;
382 let mut prog = String::new();
384 if opts.attrs.is_empty() && !opts.display_warnings {
385 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
386 // lints that are commonly triggered in doctests. The crate-level test attributes are
387 // commonly used to make tests fail in case they trigger warnings, so having this there in
388 // that case may cause some tests to pass when they shouldn't have.
389 prog.push_str("#![allow(unused)]\n");
393 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
394 for attr in &opts.attrs {
395 prog.push_str(&format!("#![{}]\n", attr));
399 // Now push any outer attributes from the example, assuming they
400 // are intended to be crate attributes.
401 prog.push_str(&crate_attrs);
403 // Don't inject `extern crate std` because it's already injected by the
405 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
406 if let Some(cratename) = cratename {
407 if s.contains(cratename) {
408 prog.push_str(&format!("extern crate {};\n", cratename));
414 // FIXME (#21299): prefer libsyntax or some other actual parser over this
415 // best-effort ad hoc approach
416 let already_has_main = s.lines()
418 let comment = line.find("//");
419 if let Some(comment_begins) = comment {
420 &line[0..comment_begins]
425 .any(|code| code.contains("fn main"));
427 if dont_insert_main || already_has_main {
428 prog.push_str(everything_else);
430 prog.push_str("fn main() {\n");
432 prog.push_str(everything_else);
433 prog.push_str("\n}");
436 info!("final test program: {}", prog);
441 // FIXME(aburka): use a real parser to deal with multiline attributes
442 fn partition_source(s: &str) -> (String, String) {
443 let mut after_header = false;
444 let mut before = String::new();
445 let mut after = String::new();
447 for line in s.lines() {
448 let trimline = line.trim();
449 let header = trimline.chars().all(|c| c.is_whitespace()) ||
450 trimline.starts_with("#![") ||
451 trimline.starts_with("#[macro_use] extern crate") ||
452 trimline.starts_with("extern crate");
453 if !header || after_header {
455 after.push_str(line);
456 after.push_str("\n");
458 before.push_str(line);
459 before.push_str("\n");
466 pub struct Collector {
467 pub tests: Vec<testing::TestDescAndFn>,
469 // The name of the test displayed to the user, separated by `::`.
471 // In tests from Rust source, this is the path to the item
472 // e.g. `["std", "vec", "Vec", "push"]`.
474 // In tests from a markdown file, this is the titles of all headers (h1~h6)
475 // of the sections that contain the code block, e.g. if the markdown file is
488 // the `names` vector of that test will be `["Title", "Subtitle"]`.
498 maybe_sysroot: Option<PathBuf>,
500 codemap: Option<Lrc<CodeMap>>,
501 filename: Option<PathBuf>,
502 linker: Option<PathBuf>,
507 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, cg: CodegenOptions,
508 externs: Externs, use_headers: bool, opts: TestOptions,
509 maybe_sysroot: Option<PathBuf>, codemap: Option<Lrc<CodeMap>>,
510 filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) -> Collector {
530 fn generate_name(&self, line: usize, filename: &FileName) -> String {
531 format!("{} - {} (line {})", filename, self.names.join("::"), line)
534 pub fn add_test(&mut self, test: String,
535 should_panic: bool, no_run: bool, should_ignore: bool,
536 as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
537 line: usize, filename: FileName, allow_fail: bool) {
538 let name = self.generate_name(line, &filename);
539 let cfgs = self.cfgs.clone();
540 let libs = self.libs.clone();
541 let cg = self.cg.clone();
542 let externs = self.externs.clone();
543 let cratename = self.cratename.to_string();
544 let opts = self.opts.clone();
545 let maybe_sysroot = self.maybe_sysroot.clone();
546 let linker = self.linker.clone();
547 let edition = self.edition;
548 debug!("Creating test {}: {}", name, test);
549 self.tests.push(testing::TestDescAndFn {
550 desc: testing::TestDesc {
551 name: testing::DynTestName(name),
552 ignore: should_ignore,
553 // compiler failures are test failures
554 should_panic: testing::ShouldPanic::No,
557 testfn: testing::DynTestFn(box move || {
558 let panic = io::set_panic(None);
559 let print = io::set_print(None);
561 rustc_driver::in_rustc_thread(move || with_globals(move || {
562 io::set_panic(panic);
563 io::set_print(print);
584 Err(err) => panic::resume_unwind(err),
590 pub fn get_line(&self) -> usize {
591 if let Some(ref codemap) = self.codemap {
592 let line = self.position.lo().to_usize();
593 let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
594 if line > 0 { line - 1 } else { line }
600 pub fn set_position(&mut self, position: Span) {
601 self.position = position;
604 pub fn get_filename(&self) -> FileName {
605 if let Some(ref codemap) = self.codemap {
606 let filename = codemap.span_to_filename(self.position);
607 if let FileName::Real(ref filename) = filename {
608 if let Ok(cur_dir) = env::current_dir() {
609 if let Ok(path) = filename.strip_prefix(&cur_dir) {
610 return path.to_owned().into();
615 } else if let Some(ref filename) = self.filename {
616 filename.clone().into()
618 FileName::Custom("input".to_owned())
622 pub fn register_header(&mut self, name: &str, level: u32) {
623 if self.use_headers {
624 // we use these headings as test names, so it's good if
625 // they're valid identifiers.
626 let name = name.chars().enumerate().map(|(i, c)| {
627 if (i == 0 && c.is_xid_start()) ||
628 (i != 0 && c.is_xid_continue()) {
633 }).collect::<String>();
635 // Here we try to efficiently assemble the header titles into the
636 // test name in the form of `h1::h2::h3::h4::h5::h6`.
638 // Suppose originally `self.names` contains `[h1, h2, h3]`...
639 let level = level as usize;
640 if level <= self.names.len() {
641 // ... Consider `level == 2`. All headers in the lower levels
642 // are irrelevant in this new level. So we should reset
643 // `self.names` to contain headers until <h2>, and replace that
644 // slot with the new name: `[h1, name]`.
645 self.names.truncate(level);
646 self.names[level - 1] = name;
648 // ... On the other hand, consider `level == 5`. This means we
649 // need to extend `self.names` to contain five headers. We fill
650 // in the missing level (<h4>) with `_`. Thus `self.names` will
651 // become `[h1, h2, h3, "_", name]`.
652 if level - 1 > self.names.len() {
653 self.names.resize(level - 1, "_".to_owned());
655 self.names.push(name);
661 struct HirCollector<'a, 'hir: 'a> {
662 sess: &'a session::Session,
663 collector: &'a mut Collector,
664 map: &'a hir::map::Map<'hir>
667 impl<'a, 'hir> HirCollector<'a, 'hir> {
668 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
670 attrs: &[ast::Attribute],
672 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
673 if let Some(ref cfg) = attrs.cfg {
674 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
679 let has_name = !name.is_empty();
681 self.collector.names.push(name);
684 attrs.collapse_doc_comments();
685 attrs.unindent_doc_comments();
686 // the collapse-docs pass won't combine sugared/raw doc attributes, or included files with
687 // anything else, this will combine them for us
688 if let Some(doc) = attrs.collapsed_doc_value() {
689 markdown::find_testable_code(&doc,
691 attrs.span.unwrap_or(DUMMY_SP),
698 self.collector.names.pop();
703 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
704 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
705 intravisit::NestedVisitorMap::All(&self.map)
708 fn visit_item(&mut self, item: &'hir hir::Item) {
709 let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
710 self.map.node_to_pretty_string(ty.id)
712 item.name.to_string()
715 self.visit_testable(name, &item.attrs, |this| {
716 intravisit::walk_item(this, item);
720 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
721 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
722 intravisit::walk_trait_item(this, item);
726 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
727 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
728 intravisit::walk_impl_item(this, item);
732 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
733 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
734 intravisit::walk_foreign_item(this, item);
738 fn visit_variant(&mut self,
739 v: &'hir hir::Variant,
740 g: &'hir hir::Generics,
741 item_id: ast::NodeId) {
742 self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
743 intravisit::walk_variant(this, v, g, item_id);
747 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
748 self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
749 intravisit::walk_struct_field(this, f);
753 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
754 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());
760 use super::{TestOptions, make_test};
763 fn make_test_basic() {
764 //basic use: wraps with `fn main`, adds `#![allow(unused)]`
765 let opts = TestOptions::default();
767 "assert_eq!(2+2, 4);";
773 let output = make_test(input, None, false, &opts);
774 assert_eq!(output, (expected.clone(), 2));
778 fn make_test_crate_name_no_use() {
779 //if you give a crate name but *don't* use it within the test, it won't bother inserting
780 //the `extern crate` statement
781 let opts = TestOptions::default();
783 "assert_eq!(2+2, 4);";
789 let output = make_test(input, Some("asdf"), false, &opts);
790 assert_eq!(output, (expected, 2));
794 fn make_test_crate_name() {
795 //if you give a crate name and use it within the test, it will insert an `extern crate`
796 //statement before `fn main`
797 let opts = TestOptions::default();
800 assert_eq!(2+2, 4);";
808 let output = make_test(input, Some("asdf"), false, &opts);
809 assert_eq!(output, (expected, 3));
813 fn make_test_no_crate_inject() {
814 //even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
816 let opts = TestOptions {
817 no_crate_inject: true,
818 display_warnings: false,
823 assert_eq!(2+2, 4);";
830 let output = make_test(input, Some("asdf"), false, &opts);
831 assert_eq!(output, (expected, 2));
835 fn make_test_ignore_std() {
836 //even if you include a crate name, and use it in the doctest, we still won't include an
837 //`extern crate` statement if the crate is "std" - that's included already by the compiler!
838 let opts = TestOptions::default();
841 assert_eq!(2+2, 4);";
848 let output = make_test(input, Some("std"), false, &opts);
849 assert_eq!(output, (expected, 2));
853 fn make_test_manual_extern_crate() {
854 //when you manually include an `extern crate` statement in your doctest, make_test assumes
855 //you've included one for your own crate too
856 let opts = TestOptions::default();
860 assert_eq!(2+2, 4);";
868 let output = make_test(input, Some("asdf"), false, &opts);
869 assert_eq!(output, (expected, 2));
873 fn make_test_manual_extern_crate_with_macro_use() {
874 let opts = TestOptions::default();
876 "#[macro_use] extern crate asdf;
878 assert_eq!(2+2, 4);";
881 #[macro_use] extern crate asdf;
886 let output = make_test(input, Some("asdf"), false, &opts);
887 assert_eq!(output, (expected, 2));
891 fn make_test_opts_attrs() {
892 //if you supplied some doctest attributes with #![doc(test(attr(...)))], it will use those
893 //instead of the stock #![allow(unused)]
894 let mut opts = TestOptions::default();
895 opts.attrs.push("feature(sick_rad)".to_string());
898 assert_eq!(2+2, 4);";
900 "#![feature(sick_rad)]
906 let output = make_test(input, Some("asdf"), false, &opts);
907 assert_eq!(output, (expected, 3));
909 //adding more will also bump the returned line offset
910 opts.attrs.push("feature(hella_dope)".to_string());
912 "#![feature(sick_rad)]
913 #![feature(hella_dope)]
919 let output = make_test(input, Some("asdf"), false, &opts);
920 assert_eq!(output, (expected, 4));
924 fn make_test_crate_attrs() {
925 //including inner attributes in your doctest will apply them to the whole "crate", pasting
926 //them outside the generated main function
927 let opts = TestOptions::default();
929 "#![feature(sick_rad)]
930 assert_eq!(2+2, 4);";
933 #![feature(sick_rad)]
937 let output = make_test(input, None, false, &opts);
938 assert_eq!(output, (expected, 2));
942 fn make_test_with_main() {
943 //including your own `fn main` wrapper lets the test use it verbatim
944 let opts = TestOptions::default();
954 let output = make_test(input, None, false, &opts);
955 assert_eq!(output, (expected, 1));
959 fn make_test_fake_main() {
960 //...but putting it in a comment will still provide a wrapper
961 let opts = TestOptions::default();
963 "//Ceci n'est pas une `fn main`
964 assert_eq!(2+2, 4);";
968 //Ceci n'est pas une `fn main`
971 let output = make_test(input, None, false, &opts);
972 assert_eq!(output, (expected.clone(), 2));
976 fn make_test_dont_insert_main() {
977 //even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper
978 let opts = TestOptions::default();
980 "//Ceci n'est pas une `fn main`
981 assert_eq!(2+2, 4);";
984 //Ceci n'est pas une `fn main`
985 assert_eq!(2+2, 4);".to_string();
986 let output = make_test(input, None, true, &opts);
987 assert_eq!(output, (expected.clone(), 1));
991 fn make_test_display_warnings() {
992 //if the user is asking to display doctest warnings, suppress the default allow(unused)
993 let mut opts = TestOptions::default();
994 opts.display_warnings = true;
996 "assert_eq!(2+2, 4);";
1001 let output = make_test(input, None, false, &opts);
1002 assert_eq!(output, (expected.clone(), 1));