test.rs 11.5 KB
Newer Older
1
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11
use std::cell::RefCell;
12
use std::char;
13 14
use std::dynamic_lib::DynamicLibrary;
use std::gc::GC;
15
use std::io::{Command, TempDir};
16
use std::io;
17 18
use std::os;
use std::str;
19
use std::string::String;
20

21
use std::collections::{HashSet, HashMap};
L
Liigo Zhuang 已提交
22
use testing;
A
Alex Crichton 已提交
23
use rustc::back::link;
N
Nick Cameron 已提交
24
use rustc::driver::config;
25 26
use rustc::driver::driver;
use rustc::driver::session;
27 28
use syntax::ast;
use syntax::codemap::{CodeMap, dummy_spanned};
29
use syntax::diagnostic;
30
use syntax::parse::token;
31 32 33 34 35 36 37 38 39

use core;
use clean;
use clean::Clean;
use fold::DocFolder;
use html::markdown;
use passes;
use visit_ast::RustdocVisitor;

40
pub fn run(input: &str,
41
           cfgs: Vec<String>,
42
           libs: HashSet<Path>,
43
           mut test_args: Vec<String>)
44
           -> int {
45 46
    let input_path = Path::new(input);
    let input = driver::FileInput(input_path.clone());
47

N
Nick Cameron 已提交
48
    let sessopts = config::Options {
E
Eduard Burtescu 已提交
49 50
        maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
        addl_lib_search_paths: RefCell::new(libs.clone()),
N
Nick Cameron 已提交
51 52
        crate_types: vec!(config::CrateTypeDylib),
        ..config::basic_options().clone()
53 54 55
    };


E
Eduard Burtescu 已提交
56
    let codemap = CodeMap::new();
57
    let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto);
58
    let span_diagnostic_handler =
E
Eduard Burtescu 已提交
59
    diagnostic::mk_span_handler(diagnostic_handler, codemap);
60

N
Nick Cameron 已提交
61
    let sess = session::build_session_(sessopts,
62
                                      Some(input_path.clone()),
63 64
                                      span_diagnostic_handler);

N
Nick Cameron 已提交
65
    let mut cfg = config::build_configuration(&sess);
66
    cfg.extend(cfgs.move_iter().map(|cfg_| {
67
        let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
68
        box(GC) dummy_spanned(ast::MetaWord(cfg_))
69
    }));
E
Eduard Burtescu 已提交
70
    let krate = driver::phase_1_parse_input(&sess, cfg, &input);
71
    let (krate, _) = driver::phase_2_configure_and_expand(&sess, krate,
E
Eduard Burtescu 已提交
72
                                                          &from_str("rustdoc-test").unwrap());
73

74
    let ctx = box(GC) core::DocContext {
75
        krate: krate,
E
Eduard Burtescu 已提交
76
        maybe_typed: core::NotTyped(sess),
77
        src: input_path,
78
        external_paths: RefCell::new(Some(HashMap::new())),
79 80
        external_traits: RefCell::new(None),
        external_typarams: RefCell::new(None),
81
        inlined: RefCell::new(None),
82
        populated_crate_impls: RefCell::new(HashSet::new()),
83
    };
84
    super::ctxtkey.replace(Some(ctx));
85

86
    let mut v = RustdocVisitor::new(&*ctx, None);
87 88 89
    v.visit(&ctx.krate);
    let krate = v.clean();
    let (krate, _) = passes::collapse_docs(krate);
90
    let (krate, _) = passes::unindent_comments(krate);
91

92
    let mut collector = Collector::new(krate.name.to_string(),
93 94
                                       libs,
                                       false);
95
    collector.fold_crate(krate);
96

97
    test_args.unshift("rustdoctest".to_string());
98

99
    testing::test_main(test_args.as_slice(),
100
                       collector.tests.move_iter().collect());
101 102 103
    0
}

104
fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool,
105 106 107 108
           no_run: bool, as_test_harness: bool) {
    // the test harness wants its own `main` & top level functions, so
    // never wrap the test in `fn main() { ... }`
    let test = maketest(test, Some(cratename), true, as_test_harness);
109
    let input = driver::StrInput(test.to_string());
110

N
Nick Cameron 已提交
111
    let sessopts = config::Options {
E
Eduard Burtescu 已提交
112 113
        maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
        addl_lib_search_paths: RefCell::new(libs),
N
Nick Cameron 已提交
114
        crate_types: vec!(config::CrateTypeExecutable),
115
        output_types: vec!(link::OutputTypeExe),
116
        no_trans: no_run,
N
Nick Cameron 已提交
117
        cg: config::CodegenOptions {
118
            prefer_dynamic: true,
N
Nick Cameron 已提交
119
            .. config::basic_codegen_options()
120
        },
121
        test: as_test_harness,
N
Nick Cameron 已提交
122
        ..config::basic_options().clone()
123 124
    };

125 126 127 128 129 130 131 132 133 134 135
    // Shuffle around a few input and output handles here. We're going to pass
    // an explicit handle into rustc to collect output messages, but we also
    // want to catch the error message that rustc prints when it fails.
    //
    // We take our task-local stderr (likely set by the test runner), and move
    // it into another task. This helper task then acts as a sink for both the
    // stderr of this task and stderr of rustc itself, copying all the info onto
    // the stderr channel we originally started with.
    //
    // The basic idea is to not use a default_handler() for rustc, and then also
    // not print things by default to the actual stderr.
136 137
    let (tx, rx) = channel();
    let w1 = io::ChanWriter::new(tx);
138
    let w2 = w1.clone();
139
    let old = io::stdio::set_stderr(box w1);
140
    spawn(proc() {
141
        let mut p = io::ChanReader::new(rx);
A
Alex Crichton 已提交
142
        let mut err = old.unwrap_or(box io::stderr() as Box<Writer + Send>);
143 144
        io::util::copy(&mut p, &mut err).unwrap();
    });
145
    let emitter = diagnostic::EmitterWriter::new(box w2);
146 147

    // Compile the code
E
Eduard Burtescu 已提交
148
    let codemap = CodeMap::new();
149
    let diagnostic_handler = diagnostic::mk_handler(box emitter);
150
    let span_diagnostic_handler =
E
Eduard Burtescu 已提交
151
        diagnostic::mk_span_handler(diagnostic_handler, codemap);
152

N
Nick Cameron 已提交
153
    let sess = session::build_session_(sessopts,
154
                                      None,
155 156 157 158
                                      span_diagnostic_handler);

    let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir");
    let out = Some(outdir.path().clone());
N
Nick Cameron 已提交
159
    let cfg = config::build_configuration(&sess);
F
Felix S. Klock II 已提交
160
    let libdir = sess.target_filesearch().get_lib_path();
161 162
    driver::compile_input(sess, cfg, &input, &out, &None);

163 164
    if no_run { return }

165
    // Run the code!
F
Felix S. Klock II 已提交
166 167 168 169 170 171 172 173 174 175 176 177
    //
    // We're careful to prepend the *target* dylib search path to the child's
    // environment to ensure that the target loads the right libraries at
    // runtime. It would be a sad day if the *host* libraries were loaded as a
    // mistake.
    let exe = outdir.path().join("rust_out");
    let env = {
        let mut path = DynamicLibrary::search_path();
        path.insert(0, libdir.clone());

        // Remove the previous dylib search path var
        let var = DynamicLibrary::envvar();
178
        let mut env: Vec<(String,String)> = os::env().move_iter().collect();
F
Felix S. Klock II 已提交
179 180 181 182 183 184 185
        match env.iter().position(|&(ref k, _)| k.as_slice() == var) {
            Some(i) => { env.remove(i); }
            None => {}
        };

        // Add the new dylib search path var
        let newpath = DynamicLibrary::create_path(path.as_slice());
R
Richo Healey 已提交
186 187
        env.push((var.to_string(),
                  str::from_utf8(newpath.as_slice()).unwrap().to_string()));
F
Felix S. Klock II 已提交
188 189 190
        env
    };
    match Command::new(exe).env(env.as_slice()).output() {
191 192 193 194
        Err(e) => fail!("couldn't run the test: {}{}", e,
                        if e.kind == io::PermissionDenied {
                            " - maybe your tempdir is mounted with noexec?"
                        } else { "" }),
A
Alex Crichton 已提交
195
        Ok(out) => {
196 197 198
            if should_fail && out.status.success() {
                fail!("test executable succeeded when it should have failed");
            } else if !should_fail && !out.status.success() {
S
Steven Fackler 已提交
199 200
                fail!("test executable failed:\n{}",
                      str::from_utf8(out.error.as_slice()));
201 202 203 204 205
            }
        }
    }
}

206
pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
207 208 209
    let mut prog = String::new();
    if lints {
        prog.push_str(r"
210
#![deny(warnings)]
S
Steven Fackler 已提交
211
#![allow(unused_variable, dead_assignment, unused_mut, unused_attribute, dead_code)]
212
");
213
    }
214

215 216 217
    // Don't inject `extern crate std` because it's already injected by the
    // compiler.
    if !s.contains("extern crate") && cratename != Some("std") {
218 219 220 221 222 223 224 225
        match cratename {
            Some(cratename) => {
                if s.contains(cratename) {
                    prog.push_str(format!("extern crate {};\n",
                                          cratename).as_slice());
                }
            }
            None => {}
226
        }
227
    }
228
    if dont_insert_main || s.contains("fn main") {
229 230
        prog.push_str(s);
    } else {
231 232
        prog.push_str("fn main() {\n    ");
        prog.push_str(s.replace("\n", "\n    ").as_slice());
233 234 235
        prog.push_str("\n}");
    }

236
    return prog
237 238 239
}

pub struct Collector {
240
    pub tests: Vec<testing::TestDescAndFn>,
241
    names: Vec<String>,
242 243 244
    libs: HashSet<Path>,
    cnt: uint,
    use_headers: bool,
245 246
    current_header: Option<String>,
    cratename: String,
247 248 249
}

impl Collector {
250
    pub fn new(cratename: String, libs: HashSet<Path>,
251
               use_headers: bool) -> Collector {
252
        Collector {
253 254
            tests: Vec::new(),
            names: Vec::new(),
255 256 257 258
            libs: libs,
            cnt: 0,
            use_headers: use_headers,
            current_header: None,
259
            cratename: cratename,
260 261 262
        }
    }

263 264
    pub fn add_test(&mut self, test: String,
                    should_fail: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
265 266
        let name = if self.use_headers {
            let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
A
Alex Crichton 已提交
267
            format!("{}_{}", s, self.cnt)
268
        } else {
A
Alex Crichton 已提交
269
            format!("{}_{}", self.names.connect("::"), self.cnt)
270
        };
271
        self.cnt += 1;
E
Eduard Burtescu 已提交
272
        let libs = self.libs.clone();
R
Richo Healey 已提交
273
        let cratename = self.cratename.to_string();
274
        debug!("Creating test {}: {}", name, test);
L
Liigo Zhuang 已提交
275 276 277
        self.tests.push(testing::TestDescAndFn {
            desc: testing::TestDesc {
                name: testing::DynTestName(name),
278
                ignore: should_ignore,
279
                should_fail: false, // compiler failures are test failures
280
            },
L
Liigo Zhuang 已提交
281
            testfn: testing::DynTestFn(proc() {
282
                runtest(test.as_slice(),
283
                        cratename.as_slice(),
284 285
                        libs,
                        should_fail,
286 287
                        no_run,
                        as_test_harness);
288 289 290
            }),
        });
    }
291 292 293 294 295 296 297 298 299 300 301 302

    pub fn register_header(&mut self, name: &str, level: u32) {
        if self.use_headers && level == 1 {
            // we use these headings as test names, so it's good if
            // they're valid identifiers.
            let name = name.chars().enumerate().map(|(i, c)| {
                    if (i == 0 && char::is_XID_start(c)) ||
                        (i != 0 && char::is_XID_continue(c)) {
                        c
                    } else {
                        '_'
                    }
303
                }).collect::<String>();
304 305 306 307 308 309

            // new header => reset count.
            self.cnt = 0;
            self.current_header = Some(name);
        }
    }
310 311 312 313 314 315
}

impl DocFolder for Collector {
    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
        let pushed = match item.name {
            Some(ref name) if name.len() == 0 => false,
316
            Some(ref name) => { self.names.push(name.to_string()); true }
317 318 319 320 321
            None => false
        };
        match item.doc_value() {
            Some(doc) => {
                self.cnt = 0;
322
                markdown::find_testable_code(doc, &mut *self);
323 324 325 326 327 328 329 330 331 332
            }
            None => {}
        }
        let ret = self.fold_item_recur(item);
        if pushed {
            self.names.pop();
        }
        return ret;
    }
}