diff options
Diffstat (limited to 'crates/test_utils/src')
-rw-r--r-- | crates/test_utils/src/fixture.rs | 142 | ||||
-rw-r--r-- | crates/test_utils/src/lib.rs | 501 | ||||
-rw-r--r-- | crates/test_utils/src/mark.rs | 4 |
3 files changed, 260 insertions, 387 deletions
diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs new file mode 100644 index 000000000..ed764046b --- /dev/null +++ b/crates/test_utils/src/fixture.rs | |||
@@ -0,0 +1,142 @@ | |||
1 | //! Defines `Fixture` -- a convenient way to describe the initial state of | ||
2 | //! rust-analyzer database from a single string. | ||
3 | |||
4 | use rustc_hash::FxHashMap; | ||
5 | use stdx::{lines_with_ends, split_delim, trim_indent}; | ||
6 | |||
7 | #[derive(Debug, Eq, PartialEq)] | ||
8 | pub struct Fixture { | ||
9 | pub path: String, | ||
10 | pub text: String, | ||
11 | pub krate: 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 | |||
19 | impl 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 = trim_indent(ra_fixture); | ||
30 | |||
31 | let mut res: Vec<Fixture> = Vec::new(); | ||
32 | |||
33 | let default = if ra_fixture.contains("//-") { None } else { Some("//- /main.rs") }; | ||
34 | |||
35 | for (ix, line) in default.into_iter().chain(lines_with_ends(&fixture)).enumerate() { | ||
36 | if line.contains("//-") { | ||
37 | assert!( | ||
38 | line.starts_with("//-"), | ||
39 | "Metadata line {} has invalid indentation. \ | ||
40 | All metadata lines need to have the same indentation.\n\ | ||
41 | The offending line: {:?}", | ||
42 | ix, | ||
43 | line | ||
44 | ); | ||
45 | } | ||
46 | |||
47 | if line.starts_with("//-") { | ||
48 | let meta = Fixture::parse_meta_line(line); | ||
49 | res.push(meta) | ||
50 | } else if let Some(entry) = res.last_mut() { | ||
51 | entry.text.push_str(line); | ||
52 | } | ||
53 | } | ||
54 | |||
55 | res | ||
56 | } | ||
57 | |||
58 | //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo | ||
59 | fn parse_meta_line(meta: &str) -> Fixture { | ||
60 | assert!(meta.starts_with("//-")); | ||
61 | let meta = meta["//-".len()..].trim(); | ||
62 | let components = meta.split_ascii_whitespace().collect::<Vec<_>>(); | ||
63 | |||
64 | let path = components[0].to_string(); | ||
65 | assert!(path.starts_with('/')); | ||
66 | |||
67 | let mut krate = None; | ||
68 | let mut deps = Vec::new(); | ||
69 | let mut edition = None; | ||
70 | let mut cfg_atoms = Vec::new(); | ||
71 | let mut cfg_key_values = Vec::new(); | ||
72 | let mut env = FxHashMap::default(); | ||
73 | for component in components[1..].iter() { | ||
74 | let (key, value) = split_delim(component, ':').unwrap(); | ||
75 | match key { | ||
76 | "crate" => krate = Some(value.to_string()), | ||
77 | "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), | ||
78 | "edition" => edition = Some(value.to_string()), | ||
79 | "cfg" => { | ||
80 | for entry in value.split(',') { | ||
81 | match split_delim(entry, '=') { | ||
82 | Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())), | ||
83 | None => cfg_atoms.push(entry.to_string()), | ||
84 | } | ||
85 | } | ||
86 | } | ||
87 | "env" => { | ||
88 | for key in value.split(',') { | ||
89 | if let Some((k, v)) = split_delim(key, '=') { | ||
90 | env.insert(k.into(), v.into()); | ||
91 | } | ||
92 | } | ||
93 | } | ||
94 | _ => panic!("bad component: {:?}", component), | ||
95 | } | ||
96 | } | ||
97 | |||
98 | Fixture { | ||
99 | path, | ||
100 | text: String::new(), | ||
101 | krate: krate, | ||
102 | deps, | ||
103 | cfg_atoms, | ||
104 | cfg_key_values, | ||
105 | edition, | ||
106 | env, | ||
107 | } | ||
108 | } | ||
109 | } | ||
110 | |||
111 | #[test] | ||
112 | #[should_panic] | ||
113 | fn parse_fixture_checks_further_indented_metadata() { | ||
114 | Fixture::parse( | ||
115 | r" | ||
116 | //- /lib.rs | ||
117 | mod bar; | ||
118 | |||
119 | fn foo() {} | ||
120 | //- /bar.rs | ||
121 | pub fn baz() {} | ||
122 | ", | ||
123 | ); | ||
124 | } | ||
125 | |||
126 | #[test] | ||
127 | fn parse_fixture_gets_full_meta() { | ||
128 | let parsed = Fixture::parse( | ||
129 | r" | ||
130 | //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo | ||
131 | mod m; | ||
132 | ", | ||
133 | ); | ||
134 | assert_eq!(1, parsed.len()); | ||
135 | |||
136 | let meta = &parsed[0]; | ||
137 | assert_eq!("mod m;\n", meta.text); | ||
138 | |||
139 | assert_eq!("foo", meta.krate.as_ref().unwrap()); | ||
140 | assert_eq!("/lib.rs", meta.path); | ||
141 | assert_eq!(2, meta.env.len()); | ||
142 | } | ||
diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index 1bd97215c..ad586c882 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs | |||
@@ -8,20 +8,22 @@ | |||
8 | 8 | ||
9 | #[macro_use] | 9 | #[macro_use] |
10 | pub mod mark; | 10 | pub mod mark; |
11 | mod fixture; | ||
11 | 12 | ||
12 | use std::{ | 13 | use std::{ |
13 | fs, | 14 | convert::{TryFrom, TryInto}, |
14 | path::{Path, PathBuf}, | 15 | env, fs, |
16 | path::PathBuf, | ||
15 | }; | 17 | }; |
16 | 18 | ||
17 | pub use ra_cfg::CfgOptions; | ||
18 | |||
19 | pub use relative_path::{RelativePath, RelativePathBuf}; | ||
20 | pub use rustc_hash::FxHashMap; | ||
21 | use serde_json::Value; | 19 | use serde_json::Value; |
20 | use stdx::lines_with_ends; | ||
22 | use text_size::{TextRange, TextSize}; | 21 | use text_size::{TextRange, TextSize}; |
23 | 22 | ||
24 | pub use difference::Changeset as __Changeset; | 23 | pub use difference::Changeset as __Changeset; |
24 | pub use rustc_hash::FxHashMap; | ||
25 | |||
26 | pub use crate::fixture::Fixture; | ||
25 | 27 | ||
26 | pub const CURSOR_MARKER: &str = "<|>"; | 28 | pub const CURSOR_MARKER: &str = "<|>"; |
27 | 29 | ||
@@ -43,7 +45,7 @@ macro_rules! assert_eq_text { | |||
43 | if left.trim() == right.trim() { | 45 | if left.trim() == right.trim() { |
44 | eprintln!("Left:\n{:?}\n\nRight:\n{:?}\n\nWhitespace difference\n", left, right); | 46 | eprintln!("Left:\n{:?}\n\nRight:\n{:?}\n\nWhitespace difference\n", left, right); |
45 | } else { | 47 | } else { |
46 | let changeset = $crate::__Changeset::new(right, left, "\n"); | 48 | let changeset = $crate::__Changeset::new(left, right, "\n"); |
47 | eprintln!("Left:\n{}\n\nRight:\n{}\n\nDiff:\n{}\n", left, right, changeset); | 49 | eprintln!("Left:\n{}\n\nRight:\n{}\n\nDiff:\n{}\n", left, right, changeset); |
48 | } | 50 | } |
49 | eprintln!($($tt)*); | 51 | eprintln!($($tt)*); |
@@ -97,7 +99,7 @@ impl From<RangeOrOffset> for TextRange { | |||
97 | fn from(selection: RangeOrOffset) -> Self { | 99 | fn from(selection: RangeOrOffset) -> Self { |
98 | match selection { | 100 | match selection { |
99 | RangeOrOffset::Range(it) => it, | 101 | RangeOrOffset::Range(it) => it, |
100 | RangeOrOffset::Offset(it) => TextRange::new(it, it), | 102 | RangeOrOffset::Offset(it) => TextRange::empty(it), |
101 | } | 103 | } |
102 | } | 104 | } |
103 | } | 105 | } |
@@ -116,8 +118,8 @@ pub fn extract_range_or_offset(text: &str) -> (RangeOrOffset, String) { | |||
116 | } | 118 | } |
117 | 119 | ||
118 | /// Extracts ranges, marked with `<tag> </tag>` pairs from the `text` | 120 | /// Extracts ranges, marked with `<tag> </tag>` pairs from the `text` |
119 | pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) { | 121 | pub fn extract_tags(mut text: &str, tag: &str) -> (Vec<(TextRange, Option<String>)>, String) { |
120 | let open = format!("<{}>", tag); | 122 | let open = format!("<{}", tag); |
121 | let close = format!("</{}>", tag); | 123 | let close = format!("</{}>", tag); |
122 | let mut ranges = Vec::new(); | 124 | let mut ranges = Vec::new(); |
123 | let mut res = String::new(); | 125 | let mut res = String::new(); |
@@ -132,22 +134,35 @@ pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) { | |||
132 | res.push_str(&text[..i]); | 134 | res.push_str(&text[..i]); |
133 | text = &text[i..]; | 135 | text = &text[i..]; |
134 | if text.starts_with(&open) { | 136 | if text.starts_with(&open) { |
135 | text = &text[open.len()..]; | 137 | let close_open = text.find('>').unwrap(); |
138 | let attr = text[open.len()..close_open].trim(); | ||
139 | let attr = if attr.is_empty() { None } else { Some(attr.to_string()) }; | ||
140 | text = &text[close_open + '>'.len_utf8()..]; | ||
136 | let from = TextSize::of(&res); | 141 | let from = TextSize::of(&res); |
137 | stack.push(from); | 142 | stack.push((from, attr)); |
138 | } else if text.starts_with(&close) { | 143 | } else if text.starts_with(&close) { |
139 | text = &text[close.len()..]; | 144 | text = &text[close.len()..]; |
140 | let from = stack.pop().unwrap_or_else(|| panic!("unmatched </{}>", tag)); | 145 | let (from, attr) = |
146 | stack.pop().unwrap_or_else(|| panic!("unmatched </{}>", tag)); | ||
141 | let to = TextSize::of(&res); | 147 | let to = TextSize::of(&res); |
142 | ranges.push(TextRange::new(from, to)); | 148 | ranges.push((TextRange::new(from, to), attr)); |
149 | } else { | ||
150 | res.push('<'); | ||
151 | text = &text['<'.len_utf8()..]; | ||
143 | } | 152 | } |
144 | } | 153 | } |
145 | } | 154 | } |
146 | } | 155 | } |
147 | assert!(stack.is_empty(), "unmatched <{}>", tag); | 156 | assert!(stack.is_empty(), "unmatched <{}>", tag); |
148 | ranges.sort_by_key(|r| (r.start(), r.end())); | 157 | ranges.sort_by_key(|r| (r.0.start(), r.0.end())); |
149 | (ranges, res) | 158 | (ranges, res) |
150 | } | 159 | } |
160 | #[test] | ||
161 | fn test_extract_tags() { | ||
162 | let (tags, text) = extract_tags(r#"<tag fn>fn <tag>main</tag>() {}</tag>"#, "tag"); | ||
163 | let actual = tags.into_iter().map(|(range, attr)| (&text[range], attr)).collect::<Vec<_>>(); | ||
164 | assert_eq!(actual, vec![("fn main() {}", Some("fn".into())), ("main", None),]); | ||
165 | } | ||
151 | 166 | ||
152 | /// Inserts `<|>` marker into the `text` at `offset`. | 167 | /// Inserts `<|>` marker into the `text` at `offset`. |
153 | pub fn add_cursor(text: &str, offset: TextSize) -> String { | 168 | pub fn add_cursor(text: &str, offset: TextSize) -> String { |
@@ -159,294 +174,108 @@ pub fn add_cursor(text: &str, offset: TextSize) -> String { | |||
159 | res | 174 | res |
160 | } | 175 | } |
161 | 176 | ||
162 | #[derive(Debug, Eq, PartialEq)] | 177 | /// Extracts `//^ some text` annotations |
163 | pub struct FixtureEntry { | 178 | pub fn extract_annotations(text: &str) -> Vec<(TextRange, String)> { |
164 | pub meta: FixtureMeta, | 179 | let mut res = Vec::new(); |
165 | pub text: String, | 180 | let mut prev_line_start: Option<TextSize> = None; |
166 | } | 181 | let mut line_start: TextSize = 0.into(); |
167 | 182 | let mut prev_line_annotations: Vec<(TextSize, usize)> = Vec::new(); | |
168 | #[derive(Debug, Eq, PartialEq)] | 183 | for line in lines_with_ends(text) { |
169 | pub enum FixtureMeta { | 184 | let mut this_line_annotations = Vec::new(); |
170 | Root { path: RelativePathBuf }, | 185 | if let Some(idx) = line.find("//") { |
171 | File(FileMeta), | 186 | let annotation_offset = TextSize::of(&line[..idx + "//".len()]); |
172 | } | 187 | for annotation in extract_line_annotations(&line[idx + "//".len()..]) { |
173 | 188 | match annotation { | |
174 | #[derive(Debug, Eq, PartialEq)] | 189 | LineAnnotation::Annotation { mut range, content } => { |
175 | pub struct FileMeta { | 190 | range += annotation_offset; |
176 | pub path: RelativePathBuf, | 191 | this_line_annotations.push((range.end(), res.len())); |
177 | pub crate_name: Option<String>, | 192 | res.push((range + prev_line_start.unwrap(), content)) |
178 | pub deps: Vec<String>, | 193 | } |
179 | pub cfg: CfgOptions, | 194 | LineAnnotation::Continuation { mut offset, content } => { |
180 | pub edition: Option<String>, | 195 | offset += annotation_offset; |
181 | pub env: FxHashMap<String, String>, | 196 | let &(_, idx) = prev_line_annotations |
182 | } | 197 | .iter() |
183 | 198 | .find(|&&(off, _idx)| off == offset) | |
184 | impl FixtureMeta { | 199 | .unwrap(); |
185 | pub fn path(&self) -> &RelativePath { | 200 | res[idx].1.push('\n'); |
186 | match self { | 201 | res[idx].1.push_str(&content); |
187 | FixtureMeta::Root { path } => &path, | 202 | res[idx].1.push('\n'); |
188 | FixtureMeta::File(f) => &f.path, | 203 | } |
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 | } | 204 | } |
226 | } | 205 | } |
227 | } | 206 | } |
228 | 207 | ||
229 | impl<'a> Iterator for EnvIter<'a> { | 208 | prev_line_start = Some(line_start); |
230 | type Item = (&'a String, &'a String); | 209 | line_start += TextSize::of(line); |
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 | 210 | ||
240 | /// Parses text which looks like this: | 211 | prev_line_annotations = this_line_annotations; |
241 | /// | ||
242 | /// ```not_rust | ||
243 | /// //- some meta | ||
244 | /// line 1 | ||
245 | /// line 2 | ||
246 | /// // - other meta | ||
247 | /// ``` | ||
248 | pub 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. | ||
263 | The 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 | } | 212 | } |
286 | res | 213 | res |
287 | } | 214 | } |
288 | 215 | ||
289 | //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo | 216 | enum LineAnnotation { |
290 | fn parse_meta(meta: &str) -> FixtureMeta { | 217 | Annotation { range: TextRange, content: String }, |
291 | let components = meta.split_ascii_whitespace().collect::<Vec<_>>(); | 218 | Continuation { offset: TextSize, content: String }, |
292 | 219 | } | |
293 | if components[0] == "root" { | ||
294 | let path: RelativePathBuf = components[1].into(); | ||
295 | assert!(path.starts_with("/") && path.ends_with("/")); | ||
296 | return FixtureMeta::Root { path }; | ||
297 | } | ||
298 | 220 | ||
299 | let path: RelativePathBuf = components[0].into(); | 221 | fn extract_line_annotations(mut line: &str) -> Vec<LineAnnotation> { |
300 | assert!(path.starts_with("/")); | 222 | let mut res = Vec::new(); |
301 | 223 | let mut offset: TextSize = 0.into(); | |
302 | let mut krate = None; | 224 | let marker: fn(char) -> bool = if line.contains('^') { |c| c == '^' } else { |c| c == '|' }; |
303 | let mut deps = Vec::new(); | 225 | loop { |
304 | let mut edition = None; | 226 | match line.find(marker) { |
305 | let mut cfg = CfgOptions::default(); | 227 | Some(idx) => { |
306 | let mut env = FxHashMap::default(); | 228 | offset += TextSize::try_from(idx).unwrap(); |
307 | for component in components[1..].iter() { | 229 | line = &line[idx..]; |
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 | } | 230 | } |
328 | _ => panic!("bad component: {:?}", component), | 231 | None => break, |
232 | }; | ||
233 | |||
234 | let mut len = line.chars().take_while(|&it| it == '^').count(); | ||
235 | let mut continuation = false; | ||
236 | if len == 0 { | ||
237 | assert!(line.starts_with('|')); | ||
238 | continuation = true; | ||
239 | len = 1; | ||
329 | } | 240 | } |
241 | let range = TextRange::at(offset, len.try_into().unwrap()); | ||
242 | let next = line[len..].find(marker).map_or(line.len(), |it| it + len); | ||
243 | let content = line[len..][..next - len].trim().to_string(); | ||
244 | |||
245 | let annotation = if continuation { | ||
246 | LineAnnotation::Continuation { offset: range.end(), content } | ||
247 | } else { | ||
248 | LineAnnotation::Annotation { range, content } | ||
249 | }; | ||
250 | res.push(annotation); | ||
251 | |||
252 | line = &line[next..]; | ||
253 | offset += TextSize::try_from(next).unwrap(); | ||
330 | } | 254 | } |
331 | 255 | ||
332 | FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env }) | 256 | res |
333 | } | ||
334 | |||
335 | fn split1(haystack: &str, delim: char) -> Option<(&str, &str)> { | ||
336 | let idx = haystack.find(delim)?; | ||
337 | Some((&haystack[..idx], &haystack[idx + delim.len_utf8()..])) | ||
338 | } | ||
339 | |||
340 | /// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. | ||
341 | /// This allows fixtures to start off in a different indentation, e.g. to align the first line with | ||
342 | /// the other lines visually: | ||
343 | /// ``` | ||
344 | /// let fixture = "//- /lib.rs | ||
345 | /// mod foo; | ||
346 | /// //- /foo.rs | ||
347 | /// fn bar() {} | ||
348 | /// "; | ||
349 | /// assert_eq!(fixture_margin(fixture), | ||
350 | /// " //- /lib.rs | ||
351 | /// mod foo; | ||
352 | /// //- /foo.rs | ||
353 | /// fn bar() {} | ||
354 | /// ") | ||
355 | /// ``` | ||
356 | fn indent_first_line(fixture: &str) -> String { | ||
357 | if fixture.is_empty() { | ||
358 | return String::new(); | ||
359 | } | ||
360 | let mut lines = fixture.lines(); | ||
361 | let first_line = lines.next().unwrap(); | ||
362 | if first_line.contains("//-") { | ||
363 | let rest = lines.collect::<Vec<_>>().join("\n"); | ||
364 | let fixed_margin = fixture_margin(&rest); | ||
365 | let fixed_indent = fixed_margin - indent_len(first_line); | ||
366 | format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest) | ||
367 | } else { | ||
368 | fixture.to_owned() | ||
369 | } | ||
370 | } | ||
371 | |||
372 | fn fixture_margin(fixture: &str) -> usize { | ||
373 | fixture | ||
374 | .lines() | ||
375 | .filter(|it| it.trim_start().starts_with("//-")) | ||
376 | .map(indent_len) | ||
377 | .next() | ||
378 | .expect("empty fixture") | ||
379 | } | ||
380 | |||
381 | fn indent_len(s: &str) -> usize { | ||
382 | s.len() - s.trim_start().len() | ||
383 | } | 257 | } |
384 | 258 | ||
385 | #[test] | 259 | #[test] |
386 | #[should_panic] | 260 | fn test_extract_annotations() { |
387 | fn parse_fixture_checks_further_indented_metadata() { | 261 | let text = stdx::trim_indent( |
388 | parse_fixture( | 262 | r#" |
389 | r" | 263 | fn main() { |
390 | //- /lib.rs | 264 | let (x, y) = (9, 2); |
391 | mod bar; | 265 | //^ def ^ def |
392 | 266 | zoo + 1 | |
393 | fn foo() {} | 267 | } //^^^ type: |
394 | //- /bar.rs | 268 | // | i32 |
395 | pub fn baz() {} | 269 | "#, |
396 | ", | ||
397 | ); | 270 | ); |
398 | } | 271 | let res = extract_annotations(&text) |
399 | 272 | .into_iter() | |
400 | #[test] | 273 | .map(|(range, ann)| (&text[range], ann)) |
401 | fn parse_fixture_can_handle_dedented_first_line() { | 274 | .collect::<Vec<_>>(); |
402 | let fixture = "//- /lib.rs | ||
403 | mod foo; | ||
404 | //- /foo.rs | ||
405 | struct Bar; | ||
406 | "; | ||
407 | assert_eq!( | 275 | assert_eq!( |
408 | parse_fixture(fixture), | 276 | res, |
409 | parse_fixture( | 277 | vec![("x", "def".into()), ("y", "def".into()), ("zoo", "type:\ni32\n".into()),] |
410 | "//- /lib.rs | ||
411 | mod foo; | ||
412 | //- /foo.rs | ||
413 | struct Bar; | ||
414 | " | ||
415 | ) | ||
416 | ) | ||
417 | } | ||
418 | |||
419 | #[test] | ||
420 | fn parse_fixture_gets_full_meta() { | ||
421 | let parsed = parse_fixture( | ||
422 | r" | ||
423 | //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo | ||
424 | mod m; | ||
425 | ", | ||
426 | ); | 278 | ); |
427 | assert_eq!(1, parsed.len()); | ||
428 | |||
429 | let parsed = &parsed[0]; | ||
430 | assert_eq!("mod m;\n\n", parsed.text); | ||
431 | |||
432 | let meta = &parsed.meta; | ||
433 | assert_eq!("foo", meta.crate_name().unwrap()); | ||
434 | assert_eq!("/lib.rs", meta.path()); | ||
435 | assert!(meta.cfg_options().is_some()); | ||
436 | assert_eq!(2, meta.env().count()); | ||
437 | } | ||
438 | |||
439 | /// Same as `parse_fixture`, except it allow empty fixture | ||
440 | pub fn parse_single_fixture(ra_fixture: &str) -> Option<FixtureEntry> { | ||
441 | if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) { | ||
442 | return None; | ||
443 | } | ||
444 | |||
445 | let fixtures = parse_fixture(ra_fixture); | ||
446 | if fixtures.len() > 1 { | ||
447 | panic!("too many fixtures"); | ||
448 | } | ||
449 | fixtures.into_iter().nth(0) | ||
450 | } | 279 | } |
451 | 280 | ||
452 | // Comparison functionality borrowed from cargo: | 281 | // Comparison functionality borrowed from cargo: |
@@ -536,85 +365,6 @@ pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a | |||
536 | } | 365 | } |
537 | } | 366 | } |
538 | 367 | ||
539 | /// Calls callback `f` with input code and file paths for each `.rs` file in `test_data_dir` | ||
540 | /// subdirectories defined by `paths`. | ||
541 | /// | ||
542 | /// If the content of the matching output file differs from the output of `f()` | ||
543 | /// the test will fail. | ||
544 | /// | ||
545 | /// If there is no matching output file it will be created and filled with the | ||
546 | /// output of `f()`, but the test will fail. | ||
547 | pub fn dir_tests<F>(test_data_dir: &Path, paths: &[&str], outfile_extension: &str, f: F) | ||
548 | where | ||
549 | F: Fn(&str, &Path) -> String, | ||
550 | { | ||
551 | for (path, input_code) in collect_rust_files(test_data_dir, paths) { | ||
552 | let actual = f(&input_code, &path); | ||
553 | let path = path.with_extension(outfile_extension); | ||
554 | if !path.exists() { | ||
555 | println!("\nfile: {}", path.display()); | ||
556 | println!("No .txt file with expected result, creating...\n"); | ||
557 | println!("{}\n{}", input_code, actual); | ||
558 | fs::write(&path, &actual).unwrap(); | ||
559 | panic!("No expected result"); | ||
560 | } | ||
561 | let expected = read_text(&path); | ||
562 | assert_equal_text(&expected, &actual, &path); | ||
563 | } | ||
564 | } | ||
565 | |||
566 | /// Collects all `.rs` files from `dir` subdirectories defined by `paths`. | ||
567 | pub fn collect_rust_files(root_dir: &Path, paths: &[&str]) -> Vec<(PathBuf, String)> { | ||
568 | paths | ||
569 | .iter() | ||
570 | .flat_map(|path| { | ||
571 | let path = root_dir.to_owned().join(path); | ||
572 | rust_files_in_dir(&path).into_iter() | ||
573 | }) | ||
574 | .map(|path| { | ||
575 | let text = read_text(&path); | ||
576 | (path, text) | ||
577 | }) | ||
578 | .collect() | ||
579 | } | ||
580 | |||
581 | /// Collects paths to all `.rs` files from `dir` in a sorted `Vec<PathBuf>`. | ||
582 | fn rust_files_in_dir(dir: &Path) -> Vec<PathBuf> { | ||
583 | let mut acc = Vec::new(); | ||
584 | for file in fs::read_dir(&dir).unwrap() { | ||
585 | let file = file.unwrap(); | ||
586 | let path = file.path(); | ||
587 | if path.extension().unwrap_or_default() == "rs" { | ||
588 | acc.push(path); | ||
589 | } | ||
590 | } | ||
591 | acc.sort(); | ||
592 | acc | ||
593 | } | ||
594 | |||
595 | /// Returns the path to the root directory of `rust-analyzer` project. | ||
596 | pub fn project_dir() -> PathBuf { | ||
597 | let dir = env!("CARGO_MANIFEST_DIR"); | ||
598 | PathBuf::from(dir).parent().unwrap().parent().unwrap().to_owned() | ||
599 | } | ||
600 | |||
601 | /// Read file and normalize newlines. | ||
602 | /// | ||
603 | /// `rustc` seems to always normalize `\r\n` newlines to `\n`: | ||
604 | /// | ||
605 | /// ``` | ||
606 | /// let s = " | ||
607 | /// "; | ||
608 | /// assert_eq!(s.as_bytes(), &[10]); | ||
609 | /// ``` | ||
610 | /// | ||
611 | /// so this should always be correct. | ||
612 | pub fn read_text(path: &Path) -> String { | ||
613 | fs::read_to_string(path) | ||
614 | .unwrap_or_else(|_| panic!("File at {:?} should be valid", path)) | ||
615 | .replace("\r\n", "\n") | ||
616 | } | ||
617 | |||
618 | /// Returns `false` if slow tests should not run, otherwise returns `true` and | 368 | /// Returns `false` if slow tests should not run, otherwise returns `true` and |
619 | /// also creates a file at `./target/.slow_tests_cookie` which serves as a flag | 369 | /// also creates a file at `./target/.slow_tests_cookie` which serves as a flag |
620 | /// that slow tests did run. | 370 | /// that slow tests did run. |
@@ -629,27 +379,8 @@ pub fn skip_slow_tests() -> bool { | |||
629 | should_skip | 379 | should_skip |
630 | } | 380 | } |
631 | 381 | ||
632 | const REWRITE: bool = false; | 382 | /// Returns the path to the root directory of `rust-analyzer` project. |
633 | 383 | pub fn project_dir() -> PathBuf { | |
634 | /// Asserts that `expected` and `actual` strings are equal. If they differ only | 384 | let dir = env!("CARGO_MANIFEST_DIR"); |
635 | /// in trailing or leading whitespace the test won't fail and | 385 | PathBuf::from(dir).parent().unwrap().parent().unwrap().to_owned() |
636 | /// the contents of `actual` will be written to the file located at `path`. | ||
637 | fn assert_equal_text(expected: &str, actual: &str, path: &Path) { | ||
638 | if expected == actual { | ||
639 | return; | ||
640 | } | ||
641 | let dir = project_dir(); | ||
642 | let pretty_path = path.strip_prefix(&dir).unwrap_or_else(|_| path); | ||
643 | if expected.trim() == actual.trim() { | ||
644 | println!("whitespace difference, rewriting"); | ||
645 | println!("file: {}\n", pretty_path.display()); | ||
646 | fs::write(path, actual).unwrap(); | ||
647 | return; | ||
648 | } | ||
649 | if REWRITE { | ||
650 | println!("rewriting {}", pretty_path.display()); | ||
651 | fs::write(path, actual).unwrap(); | ||
652 | return; | ||
653 | } | ||
654 | assert_eq_text!(expected, actual, "file: {}", pretty_path.display()); | ||
655 | } | 386 | } |
diff --git a/crates/test_utils/src/mark.rs b/crates/test_utils/src/mark.rs index 7c309a894..97f5a93ad 100644 --- a/crates/test_utils/src/mark.rs +++ b/crates/test_utils/src/mark.rs | |||
@@ -62,7 +62,7 @@ pub struct MarkChecker { | |||
62 | 62 | ||
63 | impl MarkChecker { | 63 | impl MarkChecker { |
64 | pub fn new(mark: &'static AtomicUsize) -> MarkChecker { | 64 | pub fn new(mark: &'static AtomicUsize) -> MarkChecker { |
65 | let value_on_entry = mark.load(Ordering::SeqCst); | 65 | let value_on_entry = mark.load(Ordering::Relaxed); |
66 | MarkChecker { mark, value_on_entry } | 66 | MarkChecker { mark, value_on_entry } |
67 | } | 67 | } |
68 | } | 68 | } |
@@ -72,7 +72,7 @@ impl Drop for MarkChecker { | |||
72 | if std::thread::panicking() { | 72 | if std::thread::panicking() { |
73 | return; | 73 | return; |
74 | } | 74 | } |
75 | let value_on_exit = self.mark.load(Ordering::SeqCst); | 75 | let value_on_exit = self.mark.load(Ordering::Relaxed); |
76 | assert!(value_on_exit > self.value_on_entry, "mark was not hit") | 76 | assert!(value_on_exit > self.value_on_entry, "mark was not hit") |
77 | } | 77 | } |
78 | } | 78 | } |