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;
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 {
84 ..config::basic_debugging_options()
86 ..config::basic_options().clone()
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 trans = rustc_driver::get_trans(&sess);
99 let cstore = CStore::new(trans.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, &*trans);
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_trans_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(crate_name,
141 let map = hir::map::map_crate(&sess, &cstore, &mut hir_forest, &defs);
142 let krate = map.krate();
143 let mut hir_collector = HirCollector {
145 collector: &mut collector,
148 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
149 intravisit::walk_crate(this, krate);
153 test_args.insert(0, "rustdoctest".to_string());
155 testing::test_main(&test_args,
156 collector.tests.into_iter().collect(),
157 testing::Options::new().display_output(display_warnings));
161 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
162 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
163 use syntax::print::pprust;
165 let mut opts = TestOptions {
166 no_crate_inject: false,
167 display_warnings: false,
171 let test_attrs: Vec<_> = krate.attrs.iter()
172 .filter(|a| a.check_name("doc"))
173 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
174 .filter(|a| a.check_name("test"))
176 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
179 if attr.check_name("no_crate_inject") {
180 opts.no_crate_inject = true;
182 if attr.check_name("attr") {
183 if let Some(l) = attr.meta_item_list() {
185 opts.attrs.push(pprust::meta_list_item_to_string(item));
194 fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
195 cfgs: Vec<String>, libs: SearchPaths,
196 cg: CodegenOptions, externs: Externs,
197 should_panic: bool, no_run: bool, as_test_harness: bool,
198 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
199 maybe_sysroot: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) {
200 // the test harness wants its own `main` & top level functions, so
201 // never wrap the test in `fn main() { ... }`
202 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
203 // FIXME(#44940): if doctests ever support path remapping, then this filename
204 // needs to be the result of CodeMap::span_to_unmapped_path
205 let input = config::Input::Str {
206 name: filename.to_owned(),
207 input: test.to_owned(),
209 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
211 let sessopts = config::Options {
212 maybe_sysroot: maybe_sysroot.or_else(
213 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
215 crate_types: vec![config::CrateTypeExecutable],
216 output_types: outputs,
218 cg: config::CodegenOptions {
219 prefer_dynamic: true,
223 test: as_test_harness,
224 unstable_features: UnstableFeatures::from_environment(),
225 debugging_opts: config::DebuggingOptions {
227 ..config::basic_debugging_options()
229 ..config::basic_options().clone()
232 // Shuffle around a few input and output handles here. We're going to pass
233 // an explicit handle into rustc to collect output messages, but we also
234 // want to catch the error message that rustc prints when it fails.
236 // We take our thread-local stderr (likely set by the test runner) and replace
237 // it with a sink that is also passed to rustc itself. When this function
238 // returns the output of the sink is copied onto the output of our own thread.
240 // The basic idea is to not use a default Handler for rustc, and then also
241 // not print things by default to the actual stderr.
242 struct Sink(Arc<Mutex<Vec<u8>>>);
243 impl Write for Sink {
244 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
245 Write::write(&mut *self.0.lock().unwrap(), data)
247 fn flush(&mut self) -> io::Result<()> { Ok(()) }
249 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
252 let _ = self.1.write_all(&self.0.lock().unwrap());
255 let data = Arc::new(Mutex::new(Vec::new()));
256 let codemap = Lrc::new(CodeMap::new_doctest(
257 sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
259 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
260 Some(codemap.clone()),
263 let old = io::set_panic(Some(box Sink(data.clone())));
264 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
267 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
269 let mut sess = session::build_session_(
270 sessopts, None, diagnostic_handler, codemap,
272 let trans = rustc_driver::get_trans(&sess);
273 let cstore = CStore::new(trans.metadata_loader());
274 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
276 let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
277 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
278 let mut control = driver::CompileController::basic();
280 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
281 target_features::add_configuration(&mut cfg, &sess, &*trans);
282 sess.parse_sess.config = cfg;
284 let out = Some(outdir.lock().unwrap().path().to_path_buf());
287 control.after_analysis.stop = Compilation::Stop;
290 let res = panic::catch_unwind(AssertUnwindSafe(|| {
291 driver::compile_input(
304 let compile_result = match res {
305 Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
306 Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
309 match (compile_result, compile_fail) {
311 panic!("test compiled while it wasn't supposed to")
313 (Ok(()), false) => {}
315 if error_codes.len() > 0 {
316 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
317 error_codes.retain(|err| !out.contains(err));
320 (Err(()), false) => {
321 panic!("couldn't compile the test")
325 if error_codes.len() > 0 {
326 panic!("Some expected error codes were not found: {:?}", error_codes);
333 // We're careful to prepend the *target* dylib search path to the child's
334 // environment to ensure that the target loads the right libraries at
335 // runtime. It would be a sad day if the *host* libraries were loaded as a
337 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
338 let var = DynamicLibrary::envvar();
340 let path = env::var_os(var).unwrap_or(OsString::new());
341 let mut path = env::split_paths(&path).collect::<Vec<_>>();
342 path.insert(0, libdir.clone());
343 env::join_paths(path).unwrap()
345 cmd.env(var, &newpath);
348 Err(e) => panic!("couldn't run the test: {}{}", e,
349 if e.kind() == io::ErrorKind::PermissionDenied {
350 " - maybe your tempdir is mounted with noexec?"
353 if should_panic && out.status.success() {
354 panic!("test executable succeeded when it should have failed");
355 } else if !should_panic && !out.status.success() {
356 panic!("test executable failed:\n{}\n{}\n",
357 str::from_utf8(&out.stdout).unwrap_or(""),
358 str::from_utf8(&out.stderr).unwrap_or(""));
364 /// Makes the test file. Also returns the number of lines before the code begins
365 pub fn make_test(s: &str,
366 cratename: Option<&str>,
367 dont_insert_main: bool,
370 let (crate_attrs, everything_else) = partition_source(s);
371 let everything_else = everything_else.trim();
372 let mut line_offset = 0;
373 let mut prog = String::new();
375 if opts.attrs.is_empty() && !opts.display_warnings {
376 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
377 // lints that are commonly triggered in doctests. The crate-level test attributes are
378 // commonly used to make tests fail in case they trigger warnings, so having this there in
379 // that case may cause some tests to pass when they shouldn't have.
380 prog.push_str("#![allow(unused)]\n");
384 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
385 for attr in &opts.attrs {
386 prog.push_str(&format!("#![{}]\n", attr));
390 // Now push any outer attributes from the example, assuming they
391 // are intended to be crate attributes.
392 prog.push_str(&crate_attrs);
394 // Don't inject `extern crate std` because it's already injected by the
396 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
397 if let Some(cratename) = cratename {
398 if s.contains(cratename) {
399 prog.push_str(&format!("extern crate {};\n", cratename));
405 // FIXME (#21299): prefer libsyntax or some other actual parser over this
406 // best-effort ad hoc approach
407 let already_has_main = s.lines()
409 let comment = line.find("//");
410 if let Some(comment_begins) = comment {
411 &line[0..comment_begins]
416 .any(|code| code.contains("fn main"));
418 if dont_insert_main || already_has_main {
419 prog.push_str(everything_else);
421 prog.push_str("fn main() {\n");
423 prog.push_str(everything_else);
424 prog.push_str("\n}");
427 info!("final test program: {}", prog);
432 // FIXME(aburka): use a real parser to deal with multiline attributes
433 fn partition_source(s: &str) -> (String, String) {
434 let mut after_header = false;
435 let mut before = String::new();
436 let mut after = String::new();
438 for line in s.lines() {
439 let trimline = line.trim();
440 let header = trimline.is_whitespace() ||
441 trimline.starts_with("#![") ||
442 trimline.starts_with("#[macro_use] extern crate") ||
443 trimline.starts_with("extern crate");
444 if !header || after_header {
446 after.push_str(line);
447 after.push_str("\n");
449 before.push_str(line);
450 before.push_str("\n");
457 pub struct Collector {
458 pub tests: Vec<testing::TestDescAndFn>,
460 // The name of the test displayed to the user, separated by `::`.
462 // In tests from Rust source, this is the path to the item
463 // e.g. `["std", "vec", "Vec", "push"]`.
465 // In tests from a markdown file, this is the titles of all headers (h1~h6)
466 // of the sections that contain the code block, e.g. if the markdown file is
479 // the `names` vector of that test will be `["Title", "Subtitle"]`.
489 maybe_sysroot: Option<PathBuf>,
491 codemap: Option<Lrc<CodeMap>>,
492 filename: Option<PathBuf>,
493 linker: Option<PathBuf>,
498 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, cg: CodegenOptions,
499 externs: Externs, use_headers: bool, opts: TestOptions,
500 maybe_sysroot: Option<PathBuf>, codemap: Option<Lrc<CodeMap>>,
501 filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) -> Collector {
521 fn generate_name(&self, line: usize, filename: &FileName) -> String {
522 format!("{} - {} (line {})", filename, self.names.join("::"), line)
525 pub fn add_test(&mut self, test: String,
526 should_panic: bool, no_run: bool, should_ignore: bool,
527 as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
528 line: usize, filename: FileName, allow_fail: bool) {
529 let name = self.generate_name(line, &filename);
530 let cfgs = self.cfgs.clone();
531 let libs = self.libs.clone();
532 let cg = self.cg.clone();
533 let externs = self.externs.clone();
534 let cratename = self.cratename.to_string();
535 let opts = self.opts.clone();
536 let maybe_sysroot = self.maybe_sysroot.clone();
537 let linker = self.linker.clone();
538 let edition = self.edition;
539 debug!("Creating test {}: {}", name, test);
540 self.tests.push(testing::TestDescAndFn {
541 desc: testing::TestDesc {
542 name: testing::DynTestName(name),
543 ignore: should_ignore,
544 // compiler failures are test failures
545 should_panic: testing::ShouldPanic::No,
548 testfn: testing::DynTestFn(box move || {
549 let panic = io::set_panic(None);
550 let print = io::set_print(None);
552 rustc_driver::in_rustc_thread(move || with_globals(move || {
553 io::set_panic(panic);
554 io::set_print(print);
575 Err(err) => panic::resume_unwind(err),
581 pub fn get_line(&self) -> usize {
582 if let Some(ref codemap) = self.codemap {
583 let line = self.position.lo().to_usize();
584 let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
585 if line > 0 { line - 1 } else { line }
591 pub fn set_position(&mut self, position: Span) {
592 self.position = position;
595 pub fn get_filename(&self) -> FileName {
596 if let Some(ref codemap) = self.codemap {
597 let filename = codemap.span_to_filename(self.position);
598 if let FileName::Real(ref filename) = filename {
599 if let Ok(cur_dir) = env::current_dir() {
600 if let Ok(path) = filename.strip_prefix(&cur_dir) {
601 return path.to_owned().into();
606 } else if let Some(ref filename) = self.filename {
607 filename.clone().into()
609 FileName::Custom("input".to_owned())
613 pub fn register_header(&mut self, name: &str, level: u32) {
614 if self.use_headers {
615 // we use these headings as test names, so it's good if
616 // they're valid identifiers.
617 let name = name.chars().enumerate().map(|(i, c)| {
618 if (i == 0 && c.is_xid_start()) ||
619 (i != 0 && c.is_xid_continue()) {
624 }).collect::<String>();
626 // Here we try to efficiently assemble the header titles into the
627 // test name in the form of `h1::h2::h3::h4::h5::h6`.
629 // Suppose originally `self.names` contains `[h1, h2, h3]`...
630 let level = level as usize;
631 if level <= self.names.len() {
632 // ... Consider `level == 2`. All headers in the lower levels
633 // are irrelevant in this new level. So we should reset
634 // `self.names` to contain headers until <h2>, and replace that
635 // slot with the new name: `[h1, name]`.
636 self.names.truncate(level);
637 self.names[level - 1] = name;
639 // ... On the other hand, consider `level == 5`. This means we
640 // need to extend `self.names` to contain five headers. We fill
641 // in the missing level (<h4>) with `_`. Thus `self.names` will
642 // become `[h1, h2, h3, "_", name]`.
643 if level - 1 > self.names.len() {
644 self.names.resize(level - 1, "_".to_owned());
646 self.names.push(name);
652 struct HirCollector<'a, 'hir: 'a> {
653 sess: &'a session::Session,
654 collector: &'a mut Collector,
655 map: &'a hir::map::Map<'hir>
658 impl<'a, 'hir> HirCollector<'a, 'hir> {
659 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
661 attrs: &[ast::Attribute],
663 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
664 if let Some(ref cfg) = attrs.cfg {
665 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
670 let has_name = !name.is_empty();
672 self.collector.names.push(name);
675 attrs.collapse_doc_comments();
676 attrs.unindent_doc_comments();
677 // the collapse-docs pass won't combine sugared/raw doc attributes, or included files with
678 // anything else, this will combine them for us
679 if let Some(doc) = attrs.collapsed_doc_value() {
680 markdown::find_testable_code(&doc,
682 attrs.span.unwrap_or(DUMMY_SP),
689 self.collector.names.pop();
694 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
695 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
696 intravisit::NestedVisitorMap::All(&self.map)
699 fn visit_item(&mut self, item: &'hir hir::Item) {
700 let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
701 self.map.node_to_pretty_string(ty.id)
703 item.name.to_string()
706 self.visit_testable(name, &item.attrs, |this| {
707 intravisit::walk_item(this, item);
711 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
712 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
713 intravisit::walk_trait_item(this, item);
717 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
718 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
719 intravisit::walk_impl_item(this, item);
723 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
724 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
725 intravisit::walk_foreign_item(this, item);
729 fn visit_variant(&mut self,
730 v: &'hir hir::Variant,
731 g: &'hir hir::Generics,
732 item_id: ast::NodeId) {
733 self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
734 intravisit::walk_variant(this, v, g, item_id);
738 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
739 self.visit_testable(f.name.to_string(), &f.attrs, |this| {
740 intravisit::walk_struct_field(this, f);
744 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
745 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());
751 use super::{TestOptions, make_test};
754 fn make_test_basic() {
755 //basic use: wraps with `fn main`, adds `#![allow(unused)]`
756 let opts = TestOptions::default();
758 "assert_eq!(2+2, 4);";
764 let output = make_test(input, None, false, &opts);
765 assert_eq!(output, (expected.clone(), 2));
769 fn make_test_crate_name_no_use() {
770 //if you give a crate name but *don't* use it within the test, it won't bother inserting
771 //the `extern crate` statement
772 let opts = TestOptions::default();
774 "assert_eq!(2+2, 4);";
780 let output = make_test(input, Some("asdf"), false, &opts);
781 assert_eq!(output, (expected, 2));
785 fn make_test_crate_name() {
786 //if you give a crate name and use it within the test, it will insert an `extern crate`
787 //statement before `fn main`
788 let opts = TestOptions::default();
791 assert_eq!(2+2, 4);";
799 let output = make_test(input, Some("asdf"), false, &opts);
800 assert_eq!(output, (expected, 3));
804 fn make_test_no_crate_inject() {
805 //even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
807 let opts = TestOptions {
808 no_crate_inject: true,
809 display_warnings: false,
814 assert_eq!(2+2, 4);";
821 let output = make_test(input, Some("asdf"), false, &opts);
822 assert_eq!(output, (expected, 2));
826 fn make_test_ignore_std() {
827 //even if you include a crate name, and use it in the doctest, we still won't include an
828 //`extern crate` statement if the crate is "std" - that's included already by the compiler!
829 let opts = TestOptions::default();
832 assert_eq!(2+2, 4);";
839 let output = make_test(input, Some("std"), false, &opts);
840 assert_eq!(output, (expected, 2));
844 fn make_test_manual_extern_crate() {
845 //when you manually include an `extern crate` statement in your doctest, make_test assumes
846 //you've included one for your own crate too
847 let opts = TestOptions::default();
851 assert_eq!(2+2, 4);";
859 let output = make_test(input, Some("asdf"), false, &opts);
860 assert_eq!(output, (expected, 2));
864 fn make_test_manual_extern_crate_with_macro_use() {
865 let opts = TestOptions::default();
867 "#[macro_use] extern crate asdf;
869 assert_eq!(2+2, 4);";
872 #[macro_use] extern crate asdf;
877 let output = make_test(input, Some("asdf"), false, &opts);
878 assert_eq!(output, (expected, 2));
882 fn make_test_opts_attrs() {
883 //if you supplied some doctest attributes with #![doc(test(attr(...)))], it will use those
884 //instead of the stock #![allow(unused)]
885 let mut opts = TestOptions::default();
886 opts.attrs.push("feature(sick_rad)".to_string());
889 assert_eq!(2+2, 4);";
891 "#![feature(sick_rad)]
897 let output = make_test(input, Some("asdf"), false, &opts);
898 assert_eq!(output, (expected, 3));
900 //adding more will also bump the returned line offset
901 opts.attrs.push("feature(hella_dope)".to_string());
903 "#![feature(sick_rad)]
904 #![feature(hella_dope)]
910 let output = make_test(input, Some("asdf"), false, &opts);
911 assert_eq!(output, (expected, 4));
915 fn make_test_crate_attrs() {
916 //including inner attributes in your doctest will apply them to the whole "crate", pasting
917 //them outside the generated main function
918 let opts = TestOptions::default();
920 "#![feature(sick_rad)]
921 assert_eq!(2+2, 4);";
924 #![feature(sick_rad)]
928 let output = make_test(input, None, false, &opts);
929 assert_eq!(output, (expected, 2));
933 fn make_test_with_main() {
934 //including your own `fn main` wrapper lets the test use it verbatim
935 let opts = TestOptions::default();
945 let output = make_test(input, None, false, &opts);
946 assert_eq!(output, (expected, 1));
950 fn make_test_fake_main() {
951 //...but putting it in a comment will still provide a wrapper
952 let opts = TestOptions::default();
954 "//Ceci n'est pas une `fn main`
955 assert_eq!(2+2, 4);";
959 //Ceci n'est pas une `fn main`
962 let output = make_test(input, None, false, &opts);
963 assert_eq!(output, (expected.clone(), 2));
967 fn make_test_dont_insert_main() {
968 //even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper
969 let opts = TestOptions::default();
971 "//Ceci n'est pas une `fn main`
972 assert_eq!(2+2, 4);";
975 //Ceci n'est pas une `fn main`
976 assert_eq!(2+2, 4);".to_string();
977 let output = make_test(input, None, true, &opts);
978 assert_eq!(output, (expected.clone(), 1));
982 fn make_test_display_warnings() {
983 //if the user is asking to display doctest warnings, suppress the default allow(unused)
984 let mut opts = TestOptions::default();
985 opts.display_warnings = true;
987 "assert_eq!(2+2, 4);";
992 let output = make_test(input, None, false, &opts);
993 assert_eq!(output, (expected.clone(), 1));