aboutsummaryrefslogtreecommitdiff
path: root/crates/test_utils
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2020-06-23 19:39:58 +0100
committerGitHub <[email protected]>2020-06-23 19:39:58 +0100
commit9caf810129589327cc614936a97a10cedc6f03a9 (patch)
treea3fc00ca2a19fa1294cf93030ff0d4a8d80f647f /crates/test_utils
parent0c12c4f9609ee72487af9b55a558b01af73ffe3e (diff)
parent295c8d4f7f9ce9d3dc67e8a988914d90424c1b7e (diff)
Merge #5011
5011: Simplify fixtures r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates/test_utils')
-rw-r--r--crates/test_utils/Cargo.toml3
-rw-r--r--crates/test_utils/src/fixture.rs216
-rw-r--r--crates/test_utils/src/lib.rs293
3 files changed, 221 insertions, 291 deletions
diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml
index afd2005f8..6821db1e8 100644
--- a/crates/test_utils/Cargo.toml
+++ b/crates/test_utils/Cargo.toml
@@ -8,10 +8,9 @@ authors = ["rust-analyzer developers"]
8doctest = false 8doctest = false
9 9
10[dependencies] 10[dependencies]
11# Avoid adding deps here, this crate is widely used in tests it should compile fast!
11difference = "2.0.0" 12difference = "2.0.0"
12text-size = "1.0.0" 13text-size = "1.0.0"
13serde_json = "1.0.48" 14serde_json = "1.0.48"
14rustc-hash = "1.1.0" 15rustc-hash = "1.1.0"
15
16ra_cfg = { path = "../ra_cfg" }
17stdx = { path = "../stdx" } 16stdx = { path = "../stdx" }
diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs
new file mode 100644
index 000000000..9108e49d9
--- /dev/null
+++ b/crates/test_utils/src/fixture.rs
@@ -0,0 +1,216 @@
1//! Defines `Fixture` -- a convenient way to describe the initial state of
2//! rust-analyzer database from a single string.
3
4use rustc_hash::FxHashMap;
5use stdx::split1;
6
7#[derive(Debug, Eq, PartialEq)]
8pub struct Fixture {
9 pub path: String,
10 pub text: String,
11 pub crate_name: Option<String>,
12 pub deps: Vec<String>,
13 pub cfg_atoms: Vec<String>,
14 pub cfg_key_values: Vec<(String, String)>,
15 pub edition: Option<String>,
16 pub env: FxHashMap<String, String>,
17}
18
19impl Fixture {
20 /// Parses text which looks like this:
21 ///
22 /// ```not_rust
23 /// //- some meta
24 /// line 1
25 /// line 2
26 /// // - other meta
27 /// ```
28 pub fn parse(ra_fixture: &str) -> Vec<Fixture> {
29 let fixture = indent_first_line(ra_fixture);
30 let margin = fixture_margin(&fixture);
31
32 let mut lines = fixture
33 .split('\n') // don't use `.lines` to not drop `\r\n`
34 .enumerate()
35 .filter_map(|(ix, line)| {
36 if line.len() >= margin {
37 assert!(line[..margin].trim().is_empty());
38 let line_content = &line[margin..];
39 if !line_content.starts_with("//-") {
40 assert!(
41 !line_content.contains("//-"),
42 r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation.
43The offending line: {:?}"#,
44 ix,
45 line
46 );
47 }
48 Some(line_content)
49 } else {
50 assert!(line.trim().is_empty());
51 None
52 }
53 });
54
55 let mut res: Vec<Fixture> = Vec::new();
56 for line in lines.by_ref() {
57 if line.starts_with("//-") {
58 let meta = Fixture::parse_single(line);
59 res.push(meta)
60 } else if let Some(entry) = res.last_mut() {
61 entry.text.push_str(line);
62 entry.text.push('\n');
63 }
64 }
65 res
66 }
67
68 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
69 pub fn parse_single(meta: &str) -> Fixture {
70 assert!(meta.starts_with("//-"));
71 let meta = meta["//-".len()..].trim();
72 let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
73
74 let path = components[0].to_string();
75 assert!(path.starts_with("/"));
76
77 let mut krate = None;
78 let mut deps = Vec::new();
79 let mut edition = None;
80 let mut cfg_atoms = Vec::new();
81 let mut cfg_key_values = Vec::new();
82 let mut env = FxHashMap::default();
83 for component in components[1..].iter() {
84 let (key, value) = split1(component, ':').unwrap();
85 match key {
86 "crate" => krate = Some(value.to_string()),
87 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
88 "edition" => edition = Some(value.to_string()),
89 "cfg" => {
90 for entry in value.split(',') {
91 match split1(entry, '=') {
92 Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
93 None => cfg_atoms.push(entry.to_string()),
94 }
95 }
96 }
97 "env" => {
98 for key in value.split(',') {
99 if let Some((k, v)) = split1(key, '=') {
100 env.insert(k.into(), v.into());
101 }
102 }
103 }
104 _ => panic!("bad component: {:?}", component),
105 }
106 }
107
108 Fixture {
109 path,
110 text: String::new(),
111 crate_name: krate,
112 deps,
113 cfg_atoms,
114 cfg_key_values,
115 edition,
116 env,
117 }
118 }
119}
120
121/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines.
122/// This allows fixtures to start off in a different indentation, e.g. to align the first line with
123/// the other lines visually:
124/// ```
125/// let fixture = "//- /lib.rs
126/// mod foo;
127/// //- /foo.rs
128/// fn bar() {}
129/// ";
130/// assert_eq!(fixture_margin(fixture),
131/// " //- /lib.rs
132/// mod foo;
133/// //- /foo.rs
134/// fn bar() {}
135/// ")
136/// ```
137fn indent_first_line(fixture: &str) -> String {
138 if fixture.is_empty() {
139 return String::new();
140 }
141 let mut lines = fixture.lines();
142 let first_line = lines.next().unwrap();
143 if first_line.contains("//-") {
144 let rest = lines.collect::<Vec<_>>().join("\n");
145 let fixed_margin = fixture_margin(&rest);
146 let fixed_indent = fixed_margin - indent_len(first_line);
147 format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest)
148 } else {
149 fixture.to_owned()
150 }
151}
152
153fn fixture_margin(fixture: &str) -> usize {
154 fixture
155 .lines()
156 .filter(|it| it.trim_start().starts_with("//-"))
157 .map(indent_len)
158 .next()
159 .expect("empty fixture")
160}
161
162fn indent_len(s: &str) -> usize {
163 s.len() - s.trim_start().len()
164}
165
166#[test]
167#[should_panic]
168fn parse_fixture_checks_further_indented_metadata() {
169 Fixture::parse(
170 r"
171 //- /lib.rs
172 mod bar;
173
174 fn foo() {}
175 //- /bar.rs
176 pub fn baz() {}
177 ",
178 );
179}
180
181#[test]
182fn parse_fixture_can_handle_dedented_first_line() {
183 let fixture = "//- /lib.rs
184 mod foo;
185 //- /foo.rs
186 struct Bar;
187";
188 assert_eq!(
189 Fixture::parse(fixture),
190 Fixture::parse(
191 "//- /lib.rs
192mod foo;
193//- /foo.rs
194struct Bar;
195"
196 )
197 )
198}
199
200#[test]
201fn parse_fixture_gets_full_meta() {
202 let parsed = Fixture::parse(
203 r"
204 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
205 mod m;
206 ",
207 );
208 assert_eq!(1, parsed.len());
209
210 let meta = &parsed[0];
211 assert_eq!("mod m;\n\n", meta.text);
212
213 assert_eq!("foo", meta.crate_name.as_ref().unwrap());
214 assert_eq!("/lib.rs", meta.path);
215 assert_eq!(2, meta.env.len());
216}
diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs
index fd917e43b..3fd8505ed 100644
--- a/crates/test_utils/src/lib.rs
+++ b/crates/test_utils/src/lib.rs
@@ -8,6 +8,7 @@
8 8
9#[macro_use] 9#[macro_use]
10pub mod mark; 10pub mod mark;
11mod fixture;
11 12
12use std::{ 13use std::{
13 env, fs, 14 env, fs,
@@ -15,13 +16,12 @@ use std::{
15}; 16};
16 17
17use serde_json::Value; 18use serde_json::Value;
18use stdx::split1;
19use text_size::{TextRange, TextSize}; 19use text_size::{TextRange, TextSize};
20 20
21pub use ra_cfg::CfgOptions; 21pub use difference::Changeset as __Changeset;
22pub use rustc_hash::FxHashMap; 22pub use rustc_hash::FxHashMap;
23 23
24pub use difference::Changeset as __Changeset; 24pub use crate::fixture::Fixture;
25 25
26pub const CURSOR_MARKER: &str = "<|>"; 26pub const CURSOR_MARKER: &str = "<|>";
27 27
@@ -97,7 +97,7 @@ impl From<RangeOrOffset> for TextRange {
97 fn from(selection: RangeOrOffset) -> Self { 97 fn from(selection: RangeOrOffset) -> Self {
98 match selection { 98 match selection {
99 RangeOrOffset::Range(it) => it, 99 RangeOrOffset::Range(it) => it,
100 RangeOrOffset::Offset(it) => TextRange::new(it, it), 100 RangeOrOffset::Offset(it) => TextRange::empty(it),
101 } 101 }
102 } 102 }
103} 103}
@@ -159,291 +159,6 @@ pub fn add_cursor(text: &str, offset: TextSize) -> String {
159 res 159 res
160} 160}
161 161
162#[derive(Debug, Eq, PartialEq)]
163pub struct FixtureEntry {
164 pub meta: FixtureMeta,
165 pub text: String,
166}
167
168#[derive(Debug, Eq, PartialEq)]
169pub enum FixtureMeta {
170 Root { path: String },
171 File(FileMeta),
172}
173
174#[derive(Debug, Eq, PartialEq)]
175pub struct FileMeta {
176 pub path: String,
177 pub crate_name: Option<String>,
178 pub deps: Vec<String>,
179 pub cfg: CfgOptions,
180 pub edition: Option<String>,
181 pub env: FxHashMap<String, String>,
182}
183
184impl FixtureMeta {
185 pub fn path(&self) -> &str {
186 match self {
187 FixtureMeta::Root { path } => &path,
188 FixtureMeta::File(f) => &f.path,
189 }
190 }
191
192 pub fn crate_name(&self) -> Option<&String> {
193 match self {
194 FixtureMeta::File(f) => f.crate_name.as_ref(),
195 _ => None,
196 }
197 }
198
199 pub fn cfg_options(&self) -> Option<&CfgOptions> {
200 match self {
201 FixtureMeta::File(f) => Some(&f.cfg),
202 _ => None,
203 }
204 }
205
206 pub fn edition(&self) -> Option<&String> {
207 match self {
208 FixtureMeta::File(f) => f.edition.as_ref(),
209 _ => None,
210 }
211 }
212
213 pub fn env(&self) -> impl Iterator<Item = (&String, &String)> {
214 struct EnvIter<'a> {
215 iter: Option<std::collections::hash_map::Iter<'a, String, String>>,
216 }
217
218 impl<'a> EnvIter<'a> {
219 fn new(meta: &'a FixtureMeta) -> Self {
220 Self {
221 iter: match meta {
222 FixtureMeta::File(f) => Some(f.env.iter()),
223 _ => None,
224 },
225 }
226 }
227 }
228
229 impl<'a> Iterator for EnvIter<'a> {
230 type Item = (&'a String, &'a String);
231 fn next(&mut self) -> Option<Self::Item> {
232 self.iter.as_mut().and_then(|i| i.next())
233 }
234 }
235
236 EnvIter::new(self)
237 }
238}
239
240/// Parses text which looks like this:
241///
242/// ```not_rust
243/// //- some meta
244/// line 1
245/// line 2
246/// // - other meta
247/// ```
248pub fn parse_fixture(ra_fixture: &str) -> Vec<FixtureEntry> {
249 let fixture = indent_first_line(ra_fixture);
250 let margin = fixture_margin(&fixture);
251
252 let mut lines = fixture
253 .split('\n') // don't use `.lines` to not drop `\r\n`
254 .enumerate()
255 .filter_map(|(ix, line)| {
256 if line.len() >= margin {
257 assert!(line[..margin].trim().is_empty());
258 let line_content = &line[margin..];
259 if !line_content.starts_with("//-") {
260 assert!(
261 !line_content.contains("//-"),
262 r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation.
263The offending line: {:?}"#,
264 ix,
265 line
266 );
267 }
268 Some(line_content)
269 } else {
270 assert!(line.trim().is_empty());
271 None
272 }
273 });
274
275 let mut res: Vec<FixtureEntry> = Vec::new();
276 for line in lines.by_ref() {
277 if line.starts_with("//-") {
278 let meta = line["//-".len()..].trim().to_string();
279 let meta = parse_meta(&meta);
280 res.push(FixtureEntry { meta, text: String::new() })
281 } else if let Some(entry) = res.last_mut() {
282 entry.text.push_str(line);
283 entry.text.push('\n');
284 }
285 }
286 res
287}
288
289//- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
290fn parse_meta(meta: &str) -> FixtureMeta {
291 let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
292
293 if components[0] == "root" {
294 let path = components[1].to_string();
295 assert!(path.starts_with("/") && path.ends_with("/"));
296 return FixtureMeta::Root { path };
297 }
298
299 let path = components[0].to_string();
300 assert!(path.starts_with("/"));
301
302 let mut krate = None;
303 let mut deps = Vec::new();
304 let mut edition = None;
305 let mut cfg = CfgOptions::default();
306 let mut env = FxHashMap::default();
307 for component in components[1..].iter() {
308 let (key, value) = split1(component, ':').unwrap();
309 match key {
310 "crate" => krate = Some(value.to_string()),
311 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
312 "edition" => edition = Some(value.to_string()),
313 "cfg" => {
314 for key in value.split(',') {
315 match split1(key, '=') {
316 None => cfg.insert_atom(key.into()),
317 Some((k, v)) => cfg.insert_key_value(k.into(), v.into()),
318 }
319 }
320 }
321 "env" => {
322 for key in value.split(',') {
323 if let Some((k, v)) = split1(key, '=') {
324 env.insert(k.into(), v.into());
325 }
326 }
327 }
328 _ => panic!("bad component: {:?}", component),
329 }
330 }
331
332 FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env })
333}
334
335/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines.
336/// This allows fixtures to start off in a different indentation, e.g. to align the first line with
337/// the other lines visually:
338/// ```
339/// let fixture = "//- /lib.rs
340/// mod foo;
341/// //- /foo.rs
342/// fn bar() {}
343/// ";
344/// assert_eq!(fixture_margin(fixture),
345/// " //- /lib.rs
346/// mod foo;
347/// //- /foo.rs
348/// fn bar() {}
349/// ")
350/// ```
351fn indent_first_line(fixture: &str) -> String {
352 if fixture.is_empty() {
353 return String::new();
354 }
355 let mut lines = fixture.lines();
356 let first_line = lines.next().unwrap();
357 if first_line.contains("//-") {
358 let rest = lines.collect::<Vec<_>>().join("\n");
359 let fixed_margin = fixture_margin(&rest);
360 let fixed_indent = fixed_margin - indent_len(first_line);
361 format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest)
362 } else {
363 fixture.to_owned()
364 }
365}
366
367fn fixture_margin(fixture: &str) -> usize {
368 fixture
369 .lines()
370 .filter(|it| it.trim_start().starts_with("//-"))
371 .map(indent_len)
372 .next()
373 .expect("empty fixture")
374}
375
376fn indent_len(s: &str) -> usize {
377 s.len() - s.trim_start().len()
378}
379
380#[test]
381#[should_panic]
382fn parse_fixture_checks_further_indented_metadata() {
383 parse_fixture(
384 r"
385 //- /lib.rs
386 mod bar;
387
388 fn foo() {}
389 //- /bar.rs
390 pub fn baz() {}
391 ",
392 );
393}
394
395#[test]
396fn parse_fixture_can_handle_dedented_first_line() {
397 let fixture = "//- /lib.rs
398 mod foo;
399 //- /foo.rs
400 struct Bar;
401";
402 assert_eq!(
403 parse_fixture(fixture),
404 parse_fixture(
405 "//- /lib.rs
406mod foo;
407//- /foo.rs
408struct Bar;
409"
410 )
411 )
412}
413
414#[test]
415fn parse_fixture_gets_full_meta() {
416 let parsed = parse_fixture(
417 r"
418 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
419 mod m;
420 ",
421 );
422 assert_eq!(1, parsed.len());
423
424 let parsed = &parsed[0];
425 assert_eq!("mod m;\n\n", parsed.text);
426
427 let meta = &parsed.meta;
428 assert_eq!("foo", meta.crate_name().unwrap());
429 assert_eq!("/lib.rs", meta.path());
430 assert!(meta.cfg_options().is_some());
431 assert_eq!(2, meta.env().count());
432}
433
434/// Same as `parse_fixture`, except it allow empty fixture
435pub fn parse_single_fixture(ra_fixture: &str) -> Option<FixtureEntry> {
436 if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) {
437 return None;
438 }
439
440 let fixtures = parse_fixture(ra_fixture);
441 if fixtures.len() > 1 {
442 panic!("too many fixtures");
443 }
444 fixtures.into_iter().nth(0)
445}
446
447// Comparison functionality borrowed from cargo: 162// Comparison functionality borrowed from cargo:
448 163
449/// Compare a line with an expected pattern. 164/// Compare a line with an expected pattern.