aboutsummaryrefslogtreecommitdiff
path: root/crates/test_utils/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/test_utils/src/lib.rs')
-rw-r--r--crates/test_utils/src/lib.rs133
1 files changed, 25 insertions, 108 deletions
diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs
index e32a0a0c3..e4aa894ac 100644
--- a/crates/test_utils/src/lib.rs
+++ b/crates/test_utils/src/lib.rs
@@ -13,7 +13,7 @@ mod fixture;
13use std::{ 13use std::{
14 convert::{TryFrom, TryInto}, 14 convert::{TryFrom, TryInto},
15 env, fs, 15 env, fs,
16 path::{Path, PathBuf}, 16 path::PathBuf,
17}; 17};
18 18
19use serde_json::Value; 19use serde_json::Value;
@@ -118,8 +118,8 @@ pub fn extract_range_or_offset(text: &str) -> (RangeOrOffset, String) {
118} 118}
119 119
120/// Extracts ranges, marked with `<tag> </tag>` pairs from the `text` 120/// Extracts ranges, marked with `<tag> </tag>` pairs from the `text`
121pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) { 121pub fn extract_tags(mut text: &str, tag: &str) -> (Vec<(TextRange, Option<String>)>, String) {
122 let open = format!("<{}>", tag); 122 let open = format!("<{}", tag);
123 let close = format!("</{}>", tag); 123 let close = format!("</{}>", tag);
124 let mut ranges = Vec::new(); 124 let mut ranges = Vec::new();
125 let mut res = String::new(); 125 let mut res = String::new();
@@ -134,22 +134,35 @@ pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) {
134 res.push_str(&text[..i]); 134 res.push_str(&text[..i]);
135 text = &text[i..]; 135 text = &text[i..];
136 if text.starts_with(&open) { 136 if text.starts_with(&open) {
137 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()..];
138 let from = TextSize::of(&res); 141 let from = TextSize::of(&res);
139 stack.push(from); 142 stack.push((from, attr));
140 } else if text.starts_with(&close) { 143 } else if text.starts_with(&close) {
141 text = &text[close.len()..]; 144 text = &text[close.len()..];
142 let from = stack.pop().unwrap_or_else(|| panic!("unmatched </{}>", tag)); 145 let (from, attr) =
146 stack.pop().unwrap_or_else(|| panic!("unmatched </{}>", tag));
143 let to = TextSize::of(&res); 147 let to = TextSize::of(&res);
144 ranges.push(TextRange::new(from, to)); 148 ranges.push((TextRange::new(from, to), attr));
149 } else {
150 res.push('<');
151 text = &text['<'.len_utf8()..];
145 } 152 }
146 } 153 }
147 } 154 }
148 } 155 }
149 assert!(stack.is_empty(), "unmatched <{}>", tag); 156 assert!(stack.is_empty(), "unmatched <{}>", tag);
150 ranges.sort_by_key(|r| (r.start(), r.end())); 157 ranges.sort_by_key(|r| (r.0.start(), r.0.end()));
151 (ranges, res) 158 (ranges, res)
152} 159}
160#[test]
161fn 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}
153 166
154/// Inserts `<|>` marker into the `text` at `offset`. 167/// Inserts `<|>` marker into the `text` at `offset`.
155pub fn add_cursor(text: &str, offset: TextSize) -> String { 168pub fn add_cursor(text: &str, offset: TextSize) -> String {
@@ -299,85 +312,6 @@ pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a
299 } 312 }
300} 313}
301 314
302/// Calls callback `f` with input code and file paths for each `.rs` file in `test_data_dir`
303/// subdirectories defined by `paths`.
304///
305/// If the content of the matching output file differs from the output of `f()`
306/// the test will fail.
307///
308/// If there is no matching output file it will be created and filled with the
309/// output of `f()`, but the test will fail.
310pub fn dir_tests<F>(test_data_dir: &Path, paths: &[&str], outfile_extension: &str, f: F)
311where
312 F: Fn(&str, &Path) -> String,
313{
314 for (path, input_code) in collect_rust_files(test_data_dir, paths) {
315 let actual = f(&input_code, &path);
316 let path = path.with_extension(outfile_extension);
317 if !path.exists() {
318 println!("\nfile: {}", path.display());
319 println!("No .txt file with expected result, creating...\n");
320 println!("{}\n{}", input_code, actual);
321 fs::write(&path, &actual).unwrap();
322 panic!("No expected result");
323 }
324 let expected = read_text(&path);
325 assert_equal_text(&expected, &actual, &path);
326 }
327}
328
329/// Collects all `.rs` files from `dir` subdirectories defined by `paths`.
330pub fn collect_rust_files(root_dir: &Path, paths: &[&str]) -> Vec<(PathBuf, String)> {
331 paths
332 .iter()
333 .flat_map(|path| {
334 let path = root_dir.to_owned().join(path);
335 rust_files_in_dir(&path).into_iter()
336 })
337 .map(|path| {
338 let text = read_text(&path);
339 (path, text)
340 })
341 .collect()
342}
343
344/// Collects paths to all `.rs` files from `dir` in a sorted `Vec<PathBuf>`.
345fn rust_files_in_dir(dir: &Path) -> Vec<PathBuf> {
346 let mut acc = Vec::new();
347 for file in fs::read_dir(&dir).unwrap() {
348 let file = file.unwrap();
349 let path = file.path();
350 if path.extension().unwrap_or_default() == "rs" {
351 acc.push(path);
352 }
353 }
354 acc.sort();
355 acc
356}
357
358/// Returns the path to the root directory of `rust-analyzer` project.
359pub fn project_dir() -> PathBuf {
360 let dir = env!("CARGO_MANIFEST_DIR");
361 PathBuf::from(dir).parent().unwrap().parent().unwrap().to_owned()
362}
363
364/// Read file and normalize newlines.
365///
366/// `rustc` seems to always normalize `\r\n` newlines to `\n`:
367///
368/// ```
369/// let s = "
370/// ";
371/// assert_eq!(s.as_bytes(), &[10]);
372/// ```
373///
374/// so this should always be correct.
375pub fn read_text(path: &Path) -> String {
376 fs::read_to_string(path)
377 .unwrap_or_else(|_| panic!("File at {:?} should be valid", path))
378 .replace("\r\n", "\n")
379}
380
381/// Returns `false` if slow tests should not run, otherwise returns `true` and 315/// Returns `false` if slow tests should not run, otherwise returns `true` and
382/// also creates a file at `./target/.slow_tests_cookie` which serves as a flag 316/// also creates a file at `./target/.slow_tests_cookie` which serves as a flag
383/// that slow tests did run. 317/// that slow tests did run.
@@ -392,25 +326,8 @@ pub fn skip_slow_tests() -> bool {
392 should_skip 326 should_skip
393} 327}
394 328
395/// Asserts that `expected` and `actual` strings are equal. If they differ only 329/// Returns the path to the root directory of `rust-analyzer` project.
396/// in trailing or leading whitespace the test won't fail and 330pub fn project_dir() -> PathBuf {
397/// the contents of `actual` will be written to the file located at `path`. 331 let dir = env!("CARGO_MANIFEST_DIR");
398fn assert_equal_text(expected: &str, actual: &str, path: &Path) { 332 PathBuf::from(dir).parent().unwrap().parent().unwrap().to_owned()
399 if expected == actual {
400 return;
401 }
402 let dir = project_dir();
403 let pretty_path = path.strip_prefix(&dir).unwrap_or_else(|_| path);
404 if expected.trim() == actual.trim() {
405 println!("whitespace difference, rewriting");
406 println!("file: {}\n", pretty_path.display());
407 fs::write(path, actual).unwrap();
408 return;
409 }
410 if env::var("UPDATE_EXPECTATIONS").is_ok() {
411 println!("rewriting {}", pretty_path.display());
412 fs::write(path, actual).unwrap();
413 return;
414 }
415 assert_eq_text!(expected, actual, "file: {}", pretty_path.display());
416} 333}