rust_analyzer/cli/
run_tests.rs

1//! Run all tests in a project, similar to `cargo test`, but using the mir interpreter.
2
3use hir::{Crate, Module};
4use hir_ty::db::HirDatabase;
5use ide_db::{LineIndexDatabase, base_db::SourceDatabase};
6use profile::StopWatch;
7use project_model::{CargoConfig, RustLibSource};
8use syntax::TextRange;
9
10use load_cargo::{LoadCargoConfig, ProcMacroServerChoice, load_workspace_at};
11
12use crate::cli::{Result, flags, full_name_of_item};
13
14impl flags::RunTests {
15    pub fn run(self) -> Result<()> {
16        let cargo_config = CargoConfig {
17            sysroot: Some(RustLibSource::Discover),
18            all_targets: true,
19            set_test: true,
20            ..Default::default()
21        };
22        let load_cargo_config = LoadCargoConfig {
23            load_out_dirs_from_check: true,
24            with_proc_macro_server: ProcMacroServerChoice::Sysroot,
25            prefill_caches: false,
26        };
27        let (ref db, _vfs, _proc_macro) =
28            load_workspace_at(&self.path, &cargo_config, &load_cargo_config, &|_| {})?;
29
30        let tests = all_modules(db)
31            .into_iter()
32            .flat_map(|x| x.declarations(db))
33            .filter_map(|x| match x {
34                hir::ModuleDef::Function(f) => Some(f),
35                _ => None,
36            })
37            .filter(|x| x.is_test(db));
38        let span_formatter = |file_id, text_range: TextRange| {
39            let line_col = match db.line_index(file_id).try_line_col(text_range.start()) {
40                None => " (unknown line col)".to_owned(),
41                Some(x) => format!("#{}:{}", x.line + 1, x.col),
42            };
43            let source_root = db.file_source_root(file_id).source_root_id(db);
44            let source_root = db.source_root(source_root).source_root(db);
45
46            let path = source_root.path_for_file(&file_id).map(|x| x.to_string());
47            let path = path.as_deref().unwrap_or("<unknown file>");
48            format!("file://{path}{line_col}")
49        };
50        let mut pass_count = 0;
51        let mut ignore_count = 0;
52        let mut fail_count = 0;
53        let mut sw_all = StopWatch::start();
54        for test in tests {
55            let full_name = full_name_of_item(db, test.module(db), test.name(db));
56            println!("test {full_name}");
57            if test.is_ignore(db) {
58                println!("ignored");
59                ignore_count += 1;
60                continue;
61            }
62            let mut sw_one = StopWatch::start();
63            let result = test.eval(db, span_formatter);
64            match &result {
65                Ok(result) if result.trim() == "pass" => pass_count += 1,
66                _ => fail_count += 1,
67            }
68            println!("{result:?}");
69            eprintln!("{:<20} {}", format!("test {}", full_name), sw_one.elapsed());
70        }
71        println!("{pass_count} passed, {fail_count} failed, {ignore_count} ignored");
72        eprintln!("{:<20} {}", "All tests", sw_all.elapsed());
73        Ok(())
74    }
75}
76
77fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
78    let mut worklist: Vec<_> = Crate::all(db)
79        .into_iter()
80        .filter(|x| x.origin(db).is_local())
81        .map(|krate| krate.root_module())
82        .collect();
83    let mut modules = Vec::new();
84
85    while let Some(module) = worklist.pop() {
86        modules.push(module);
87        worklist.extend(module.children(db));
88    }
89
90    modules
91}