diff --git a/Cargo.lock b/Cargo.lock index f2069c55e36..9ea1765cb58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1664,7 +1664,6 @@ name = "test_utils" version = "0.1.0" dependencies = [ "difference", - "ra_cfg", "rustc-hash", "serde_json", "stdx", diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index f7d9118a9a3..20f29156830 100644 --- a/crates/ra_db/src/fixture.rs +++ b/crates/ra_db/src/fixture.rs @@ -61,7 +61,7 @@ use ra_cfg::CfgOptions; use rustc_hash::FxHashMap; -use test_utils::{extract_offset, parse_fixture, parse_single_fixture, FixtureMeta, CURSOR_MARKER}; +use test_utils::{extract_offset, Fixture, CURSOR_MARKER}; use vfs::{file_set::FileSet, VfsPath}; use crate::{ @@ -80,14 +80,14 @@ fn with_single_file(text: &str) -> (Self, FileId) { fn with_files(ra_fixture: &str) -> Self { let mut db = Self::default(); - let pos = with_files(&mut db, ra_fixture); + let (pos, _) = with_files(&mut db, ra_fixture); assert!(pos.is_none()); db } fn with_position(ra_fixture: &str) -> (Self, FilePosition) { let mut db = Self::default(); - let pos = with_files(&mut db, ra_fixture); + let (pos, _) = with_files(&mut db, ra_fixture); (db, pos.unwrap()) } @@ -109,12 +109,10 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId let source_root = SourceRoot::new_local(file_set); - let fixture = parse_single_fixture(ra_fixture); - - let crate_graph = if let Some(entry) = fixture { - let meta = match ParsedMeta::from(&entry.meta) { + let crate_graph = if let Some(meta) = ra_fixture.lines().find(|it| it.contains("//-")) { + let entry = Fixture::parse_single(meta.trim()); + let meta = match ParsedMeta::from(&entry) { ParsedMeta::File(it) => it, - _ => panic!("with_single_file only support file meta"), }; let mut crate_graph = CrateGraph::default(); @@ -150,30 +148,27 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId file_id } -fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option { - let fixture = parse_fixture(fixture); +fn with_files( + db: &mut dyn SourceDatabaseExt, + fixture: &str, +) -> (Option, Vec) { + let fixture = Fixture::parse(fixture); + let mut files = Vec::new(); let mut crate_graph = CrateGraph::default(); let mut crates = FxHashMap::default(); let mut crate_deps = Vec::new(); let mut default_crate_root: Option = None; let mut file_set = FileSet::default(); - let mut source_root_id = WORKSPACE; - let mut source_root_prefix = "/".to_string(); + let source_root_id = WORKSPACE; + let source_root_prefix = "/".to_string(); let mut file_id = FileId(0); let mut file_position = None; for entry in fixture.iter() { - let meta = match ParsedMeta::from(&entry.meta) { - ParsedMeta::Root { path } => { - let file_set = std::mem::replace(&mut file_set, FileSet::default()); - db.set_source_root(source_root_id, Arc::new(SourceRoot::new_local(file_set))); - source_root_id.0 += 1; - source_root_prefix = path; - continue; - } + let meta = match ParsedMeta::from(entry) { ParsedMeta::File(it) => it, }; assert!(meta.path.starts_with(&source_root_prefix)); @@ -210,7 +205,7 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option Option for ParsedMeta { - fn from(meta: &FixtureMeta) -> Self { - match meta { - FixtureMeta::Root { path } => { - // `Self::Root` causes a false warning: 'variant is never constructed: `Root` ' - // see https://github.com/rust-lang/rust/issues/69018 - ParsedMeta::Root { path: path.to_owned() } - } - FixtureMeta::File(f) => Self::File(FileMeta { - path: f.path.to_owned(), - krate: f.crate_name.to_owned(), - deps: f.deps.to_owned(), - cfg: f.cfg.to_owned(), - edition: f - .edition - .as_ref() - .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), - env: Env::from(f.env.iter()), - }), - } +impl From<&Fixture> for ParsedMeta { + fn from(f: &Fixture) -> Self { + let mut cfg = CfgOptions::default(); + f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into())); + f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into())); + + Self::File(FileMeta { + path: f.path.to_owned(), + krate: f.crate_name.to_owned(), + deps: f.deps.to_owned(), + cfg, + edition: f + .edition + .as_ref() + .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), + env: Env::from(f.env.iter()), + }) } } diff --git a/crates/ra_hir_def/src/nameres/tests.rs b/crates/ra_hir_def/src/nameres/tests.rs index 05cd0297d1e..503099fb74f 100644 --- a/crates/ra_hir_def/src/nameres/tests.rs +++ b/crates/ra_hir_def/src/nameres/tests.rs @@ -423,31 +423,6 @@ fn extern_crate_rename_2015_edition() { ); } -#[test] -fn import_across_source_roots() { - let map = def_map( - " - //- /main.rs crate:main deps:test_crate - use test_crate::a::b::C; - - //- root /test_crate/ - - //- /test_crate/lib.rs crate:test_crate - pub mod a { - pub mod b { - pub struct C; - } - } - - ", - ); - - assert_snapshot!(map, @r###" - ⋮crate - ⋮C: t v - "###); -} - #[test] fn reexport_across_crates() { let map = def_map( diff --git a/crates/ra_ide/src/mock_analysis.rs b/crates/ra_ide/src/mock_analysis.rs index 58fafecab0c..981bdf924d6 100644 --- a/crates/ra_ide/src/mock_analysis.rs +++ b/crates/ra_ide/src/mock_analysis.rs @@ -3,7 +3,7 @@ use ra_cfg::CfgOptions; use ra_db::{CrateName, Env, FileSet, SourceRoot, VfsPath}; -use test_utils::{extract_offset, extract_range, parse_fixture, FixtureEntry, CURSOR_MARKER}; +use test_utils::{extract_offset, extract_range, Fixture, CURSOR_MARKER}; use crate::{ Analysis, AnalysisChange, AnalysisHost, CrateGraph, Edition, FileId, FilePosition, FileRange, @@ -12,7 +12,7 @@ #[derive(Debug)] enum MockFileData { Plain { path: String, content: String }, - Fixture(FixtureEntry), + Fixture(Fixture), } impl MockFileData { @@ -25,7 +25,7 @@ fn new(path: String, content: String) -> Self { fn path(&self) -> &str { match self { MockFileData::Plain { path, .. } => path.as_str(), - MockFileData::Fixture(f) => f.meta.path(), + MockFileData::Fixture(f) => f.path.as_str(), } } @@ -39,7 +39,10 @@ fn content(&self) -> &str { fn cfg_options(&self) -> CfgOptions { match self { MockFileData::Fixture(f) => { - f.meta.cfg_options().map_or_else(Default::default, |o| o.clone()) + let mut cfg = CfgOptions::default(); + f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into())); + f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into())); + cfg } _ => CfgOptions::default(), } @@ -48,7 +51,7 @@ fn cfg_options(&self) -> CfgOptions { fn edition(&self) -> Edition { match self { MockFileData::Fixture(f) => { - f.meta.edition().map_or(Edition::Edition2018, |v| Edition::from_str(v).unwrap()) + f.edition.as_ref().map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()) } _ => Edition::Edition2018, } @@ -56,14 +59,14 @@ fn edition(&self) -> Edition { fn env(&self) -> Env { match self { - MockFileData::Fixture(f) => Env::from(f.meta.env()), + MockFileData::Fixture(f) => Env::from(f.env.iter()), _ => Env::default(), } } } -impl From for MockFileData { - fn from(fixture: FixtureEntry) -> Self { +impl From for MockFileData { + fn from(fixture: Fixture) -> Self { Self::Fixture(fixture) } } @@ -91,7 +94,7 @@ pub fn new() -> MockAnalysis { /// ``` pub fn with_files(fixture: &str) -> MockAnalysis { let mut res = MockAnalysis::new(); - for entry in parse_fixture(fixture) { + for entry in Fixture::parse(fixture) { res.add_file_fixture(entry); } res @@ -102,7 +105,7 @@ pub fn with_files(fixture: &str) -> MockAnalysis { pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) { let mut position = None; let mut res = MockAnalysis::new(); - for entry in parse_fixture(fixture) { + for entry in Fixture::parse(fixture) { if entry.text.contains(CURSOR_MARKER) { assert!(position.is_none(), "only one marker (<|>) per fixture is allowed"); position = Some(res.add_file_fixture_with_position(entry)); @@ -114,13 +117,13 @@ pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) { (res, position) } - pub fn add_file_fixture(&mut self, fixture: FixtureEntry) -> FileId { + pub fn add_file_fixture(&mut self, fixture: Fixture) -> FileId { let file_id = self.next_id(); self.files.push(MockFileData::from(fixture)); file_id } - pub fn add_file_fixture_with_position(&mut self, mut fixture: FixtureEntry) -> FilePosition { + pub fn add_file_fixture_with_position(&mut self, mut fixture: Fixture) -> FilePosition { let (offset, text) = extract_offset(&fixture.text); fixture.text = text; let file_id = self.next_id(); diff --git a/crates/rust-analyzer/tests/heavy_tests/support.rs b/crates/rust-analyzer/tests/heavy_tests/support.rs index bb85853552c..e80ffe5d146 100644 --- a/crates/rust-analyzer/tests/heavy_tests/support.rs +++ b/crates/rust-analyzer/tests/heavy_tests/support.rs @@ -17,7 +17,7 @@ use serde::Serialize; use serde_json::{to_string_pretty, Value}; use tempfile::TempDir; -use test_utils::{find_mismatch, parse_fixture}; +use test_utils::{find_mismatch, Fixture}; use ra_project_model::ProjectManifest; use rust_analyzer::{ @@ -68,8 +68,8 @@ pub fn server(self) -> Server { let mut paths = vec![]; - for entry in parse_fixture(self.fixture) { - let path = tmp_dir.path().join(&entry.meta.path()['/'.len_utf8()..]); + for entry in Fixture::parse(self.fixture) { + let path = tmp_dir.path().join(&entry.path['/'.len_utf8()..]); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path.as_path(), entry.text.as_bytes()).unwrap(); paths.push((path, entry.text)); diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml index afd2005f82b..6821db1e811 100644 --- a/crates/test_utils/Cargo.toml +++ b/crates/test_utils/Cargo.toml @@ -8,10 +8,9 @@ authors = ["rust-analyzer developers"] doctest = false [dependencies] +# Avoid adding deps here, this crate is widely used in tests it should compile fast! difference = "2.0.0" text-size = "1.0.0" serde_json = "1.0.48" rustc-hash = "1.1.0" - -ra_cfg = { path = "../ra_cfg" } stdx = { path = "../stdx" } diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs new file mode 100644 index 00000000000..9108e49d966 --- /dev/null +++ b/crates/test_utils/src/fixture.rs @@ -0,0 +1,216 @@ +//! Defines `Fixture` -- a convenient way to describe the initial state of +//! rust-analyzer database from a single string. + +use rustc_hash::FxHashMap; +use stdx::split1; + +#[derive(Debug, Eq, PartialEq)] +pub struct Fixture { + pub path: String, + pub text: String, + pub crate_name: Option, + pub deps: Vec, + pub cfg_atoms: Vec, + pub cfg_key_values: Vec<(String, String)>, + pub edition: Option, + pub env: FxHashMap, +} + +impl Fixture { + /// Parses text which looks like this: + /// + /// ```not_rust + /// //- some meta + /// line 1 + /// line 2 + /// // - other meta + /// ``` + pub fn parse(ra_fixture: &str) -> Vec { + let fixture = indent_first_line(ra_fixture); + let margin = fixture_margin(&fixture); + + let mut lines = fixture + .split('\n') // don't use `.lines` to not drop `\r\n` + .enumerate() + .filter_map(|(ix, line)| { + if line.len() >= margin { + assert!(line[..margin].trim().is_empty()); + let line_content = &line[margin..]; + if !line_content.starts_with("//-") { + assert!( + !line_content.contains("//-"), + r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation. +The offending line: {:?}"#, + ix, + line + ); + } + Some(line_content) + } else { + assert!(line.trim().is_empty()); + None + } + }); + + let mut res: Vec = Vec::new(); + for line in lines.by_ref() { + if line.starts_with("//-") { + let meta = Fixture::parse_single(line); + res.push(meta) + } else if let Some(entry) = res.last_mut() { + entry.text.push_str(line); + entry.text.push('\n'); + } + } + res + } + + //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo + pub fn parse_single(meta: &str) -> Fixture { + assert!(meta.starts_with("//-")); + let meta = meta["//-".len()..].trim(); + let components = meta.split_ascii_whitespace().collect::>(); + + let path = components[0].to_string(); + assert!(path.starts_with("/")); + + let mut krate = None; + let mut deps = Vec::new(); + let mut edition = None; + let mut cfg_atoms = Vec::new(); + let mut cfg_key_values = Vec::new(); + let mut env = FxHashMap::default(); + for component in components[1..].iter() { + let (key, value) = split1(component, ':').unwrap(); + match key { + "crate" => krate = Some(value.to_string()), + "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), + "edition" => edition = Some(value.to_string()), + "cfg" => { + for entry in value.split(',') { + match split1(entry, '=') { + Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())), + None => cfg_atoms.push(entry.to_string()), + } + } + } + "env" => { + for key in value.split(',') { + if let Some((k, v)) = split1(key, '=') { + env.insert(k.into(), v.into()); + } + } + } + _ => panic!("bad component: {:?}", component), + } + } + + Fixture { + path, + text: String::new(), + crate_name: krate, + deps, + cfg_atoms, + cfg_key_values, + edition, + env, + } + } +} + +/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. +/// This allows fixtures to start off in a different indentation, e.g. to align the first line with +/// the other lines visually: +/// ``` +/// let fixture = "//- /lib.rs +/// mod foo; +/// //- /foo.rs +/// fn bar() {} +/// "; +/// assert_eq!(fixture_margin(fixture), +/// " //- /lib.rs +/// mod foo; +/// //- /foo.rs +/// fn bar() {} +/// ") +/// ``` +fn indent_first_line(fixture: &str) -> String { + if fixture.is_empty() { + return String::new(); + } + let mut lines = fixture.lines(); + let first_line = lines.next().unwrap(); + if first_line.contains("//-") { + let rest = lines.collect::>().join("\n"); + let fixed_margin = fixture_margin(&rest); + let fixed_indent = fixed_margin - indent_len(first_line); + format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest) + } else { + fixture.to_owned() + } +} + +fn fixture_margin(fixture: &str) -> usize { + fixture + .lines() + .filter(|it| it.trim_start().starts_with("//-")) + .map(indent_len) + .next() + .expect("empty fixture") +} + +fn indent_len(s: &str) -> usize { + s.len() - s.trim_start().len() +} + +#[test] +#[should_panic] +fn parse_fixture_checks_further_indented_metadata() { + Fixture::parse( + r" + //- /lib.rs + mod bar; + + fn foo() {} + //- /bar.rs + pub fn baz() {} + ", + ); +} + +#[test] +fn parse_fixture_can_handle_dedented_first_line() { + let fixture = "//- /lib.rs + mod foo; + //- /foo.rs + struct Bar; +"; + assert_eq!( + Fixture::parse(fixture), + Fixture::parse( + "//- /lib.rs +mod foo; +//- /foo.rs +struct Bar; +" + ) + ) +} + +#[test] +fn parse_fixture_gets_full_meta() { + let parsed = Fixture::parse( + r" + //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo + mod m; + ", + ); + assert_eq!(1, parsed.len()); + + let meta = &parsed[0]; + assert_eq!("mod m;\n\n", meta.text); + + assert_eq!("foo", meta.crate_name.as_ref().unwrap()); + assert_eq!("/lib.rs", meta.path); + assert_eq!(2, meta.env.len()); +} diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index fd917e43bbb..3fd8505ed22 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs @@ -8,6 +8,7 @@ #[macro_use] pub mod mark; +mod fixture; use std::{ env, fs, @@ -15,13 +16,12 @@ }; use serde_json::Value; -use stdx::split1; use text_size::{TextRange, TextSize}; -pub use ra_cfg::CfgOptions; +pub use difference::Changeset as __Changeset; pub use rustc_hash::FxHashMap; -pub use difference::Changeset as __Changeset; +pub use crate::fixture::Fixture; pub const CURSOR_MARKER: &str = "<|>"; @@ -97,7 +97,7 @@ impl From for TextRange { fn from(selection: RangeOrOffset) -> Self { match selection { RangeOrOffset::Range(it) => it, - RangeOrOffset::Offset(it) => TextRange::new(it, it), + RangeOrOffset::Offset(it) => TextRange::empty(it), } } } @@ -159,291 +159,6 @@ pub fn add_cursor(text: &str, offset: TextSize) -> String { res } -#[derive(Debug, Eq, PartialEq)] -pub struct FixtureEntry { - pub meta: FixtureMeta, - pub text: String, -} - -#[derive(Debug, Eq, PartialEq)] -pub enum FixtureMeta { - Root { path: String }, - File(FileMeta), -} - -#[derive(Debug, Eq, PartialEq)] -pub struct FileMeta { - pub path: String, - pub crate_name: Option, - pub deps: Vec, - pub cfg: CfgOptions, - pub edition: Option, - pub env: FxHashMap, -} - -impl FixtureMeta { - pub fn path(&self) -> &str { - match self { - FixtureMeta::Root { path } => &path, - FixtureMeta::File(f) => &f.path, - } - } - - pub fn crate_name(&self) -> Option<&String> { - match self { - FixtureMeta::File(f) => f.crate_name.as_ref(), - _ => None, - } - } - - pub fn cfg_options(&self) -> Option<&CfgOptions> { - match self { - FixtureMeta::File(f) => Some(&f.cfg), - _ => None, - } - } - - pub fn edition(&self) -> Option<&String> { - match self { - FixtureMeta::File(f) => f.edition.as_ref(), - _ => None, - } - } - - pub fn env(&self) -> impl Iterator { - struct EnvIter<'a> { - iter: Option>, - } - - impl<'a> EnvIter<'a> { - fn new(meta: &'a FixtureMeta) -> Self { - Self { - iter: match meta { - FixtureMeta::File(f) => Some(f.env.iter()), - _ => None, - }, - } - } - } - - impl<'a> Iterator for EnvIter<'a> { - type Item = (&'a String, &'a String); - fn next(&mut self) -> Option { - self.iter.as_mut().and_then(|i| i.next()) - } - } - - EnvIter::new(self) - } -} - -/// Parses text which looks like this: -/// -/// ```not_rust -/// //- some meta -/// line 1 -/// line 2 -/// // - other meta -/// ``` -pub fn parse_fixture(ra_fixture: &str) -> Vec { - let fixture = indent_first_line(ra_fixture); - let margin = fixture_margin(&fixture); - - let mut lines = fixture - .split('\n') // don't use `.lines` to not drop `\r\n` - .enumerate() - .filter_map(|(ix, line)| { - if line.len() >= margin { - assert!(line[..margin].trim().is_empty()); - let line_content = &line[margin..]; - if !line_content.starts_with("//-") { - assert!( - !line_content.contains("//-"), - r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation. -The offending line: {:?}"#, - ix, - line - ); - } - Some(line_content) - } else { - assert!(line.trim().is_empty()); - None - } - }); - - let mut res: Vec = Vec::new(); - for line in lines.by_ref() { - if line.starts_with("//-") { - let meta = line["//-".len()..].trim().to_string(); - let meta = parse_meta(&meta); - res.push(FixtureEntry { meta, text: String::new() }) - } else if let Some(entry) = res.last_mut() { - entry.text.push_str(line); - entry.text.push('\n'); - } - } - res -} - -//- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo -fn parse_meta(meta: &str) -> FixtureMeta { - let components = meta.split_ascii_whitespace().collect::>(); - - if components[0] == "root" { - let path = components[1].to_string(); - assert!(path.starts_with("/") && path.ends_with("/")); - return FixtureMeta::Root { path }; - } - - let path = components[0].to_string(); - assert!(path.starts_with("/")); - - let mut krate = None; - let mut deps = Vec::new(); - let mut edition = None; - let mut cfg = CfgOptions::default(); - let mut env = FxHashMap::default(); - for component in components[1..].iter() { - let (key, value) = split1(component, ':').unwrap(); - match key { - "crate" => krate = Some(value.to_string()), - "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), - "edition" => edition = Some(value.to_string()), - "cfg" => { - for key in value.split(',') { - match split1(key, '=') { - None => cfg.insert_atom(key.into()), - Some((k, v)) => cfg.insert_key_value(k.into(), v.into()), - } - } - } - "env" => { - for key in value.split(',') { - if let Some((k, v)) = split1(key, '=') { - env.insert(k.into(), v.into()); - } - } - } - _ => panic!("bad component: {:?}", component), - } - } - - FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env }) -} - -/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. -/// This allows fixtures to start off in a different indentation, e.g. to align the first line with -/// the other lines visually: -/// ``` -/// let fixture = "//- /lib.rs -/// mod foo; -/// //- /foo.rs -/// fn bar() {} -/// "; -/// assert_eq!(fixture_margin(fixture), -/// " //- /lib.rs -/// mod foo; -/// //- /foo.rs -/// fn bar() {} -/// ") -/// ``` -fn indent_first_line(fixture: &str) -> String { - if fixture.is_empty() { - return String::new(); - } - let mut lines = fixture.lines(); - let first_line = lines.next().unwrap(); - if first_line.contains("//-") { - let rest = lines.collect::>().join("\n"); - let fixed_margin = fixture_margin(&rest); - let fixed_indent = fixed_margin - indent_len(first_line); - format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest) - } else { - fixture.to_owned() - } -} - -fn fixture_margin(fixture: &str) -> usize { - fixture - .lines() - .filter(|it| it.trim_start().starts_with("//-")) - .map(indent_len) - .next() - .expect("empty fixture") -} - -fn indent_len(s: &str) -> usize { - s.len() - s.trim_start().len() -} - -#[test] -#[should_panic] -fn parse_fixture_checks_further_indented_metadata() { - parse_fixture( - r" - //- /lib.rs - mod bar; - - fn foo() {} - //- /bar.rs - pub fn baz() {} - ", - ); -} - -#[test] -fn parse_fixture_can_handle_dedented_first_line() { - let fixture = "//- /lib.rs - mod foo; - //- /foo.rs - struct Bar; -"; - assert_eq!( - parse_fixture(fixture), - parse_fixture( - "//- /lib.rs -mod foo; -//- /foo.rs -struct Bar; -" - ) - ) -} - -#[test] -fn parse_fixture_gets_full_meta() { - let parsed = parse_fixture( - r" - //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo - mod m; - ", - ); - assert_eq!(1, parsed.len()); - - let parsed = &parsed[0]; - assert_eq!("mod m;\n\n", parsed.text); - - let meta = &parsed.meta; - assert_eq!("foo", meta.crate_name().unwrap()); - assert_eq!("/lib.rs", meta.path()); - assert!(meta.cfg_options().is_some()); - assert_eq!(2, meta.env().count()); -} - -/// Same as `parse_fixture`, except it allow empty fixture -pub fn parse_single_fixture(ra_fixture: &str) -> Option { - if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) { - return None; - } - - let fixtures = parse_fixture(ra_fixture); - if fixtures.len() > 1 { - panic!("too many fixtures"); - } - fixtures.into_iter().nth(0) -} - // Comparison functionality borrowed from cargo: /// Compare a line with an expected pattern.