]> git.lizzy.rs Git - rust.git/blob - crates/test_utils/src/lib.rs
translate \n -> \r\n on the way out
[rust.git] / crates / test_utils / src / lib.rs
1 #[macro_use]
2 pub mod marks;
3
4 use std::{
5     fs,
6     path::{Path, PathBuf},
7 };
8
9 use serde_json::Value;
10 use text_unit::{TextRange, TextUnit};
11
12 pub use difference::Changeset as __Changeset;
13
14 pub const CURSOR_MARKER: &str = "<|>";
15
16 #[macro_export]
17 macro_rules! assert_eq_text {
18     ($left:expr, $right:expr) => {
19         assert_eq_text!($left, $right,)
20     };
21     ($left:expr, $right:expr, $($tt:tt)*) => {{
22         let left = $left;
23         let right = $right;
24         if left != right {
25             if left.trim() == right.trim() {
26                 eprintln!("Left:\n{:?}\n\nRight:\n{:?}\n\nWhitespace difference\n", left, right);
27             } else {
28                 let changeset = $crate::__Changeset::new(right, left, "\n");
29                 eprintln!("Left:\n{}\n\nRight:\n{}\n\nDiff:\n{}\n", left, right, changeset);
30             }
31             eprintln!($($tt)*);
32             panic!("text differs");
33         }
34     }};
35 }
36
37 pub fn extract_offset(text: &str) -> (TextUnit, String) {
38     match try_extract_offset(text) {
39         None => panic!("text should contain cursor marker"),
40         Some(result) => result,
41     }
42 }
43
44 pub fn try_extract_offset(text: &str) -> Option<(TextUnit, String)> {
45     let cursor_pos = text.find(CURSOR_MARKER)?;
46     let mut new_text = String::with_capacity(text.len() - CURSOR_MARKER.len());
47     new_text.push_str(&text[..cursor_pos]);
48     new_text.push_str(&text[cursor_pos + CURSOR_MARKER.len()..]);
49     let cursor_pos = TextUnit::from(cursor_pos as u32);
50     Some((cursor_pos, new_text))
51 }
52
53 pub fn extract_range(text: &str) -> (TextRange, String) {
54     match try_extract_range(text) {
55         None => panic!("text should contain cursor marker"),
56         Some(result) => result,
57     }
58 }
59
60 pub fn try_extract_range(text: &str) -> Option<(TextRange, String)> {
61     let (start, text) = try_extract_offset(text)?;
62     let (end, text) = try_extract_offset(&text)?;
63     Some((TextRange::from_to(start, end), text))
64 }
65
66 /// Extracts ranges, marked with `<tag> </tag>` paris from the `text`
67 pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) {
68     let open = format!("<{}>", tag);
69     let close = format!("</{}>", tag);
70     let mut ranges = Vec::new();
71     let mut res = String::new();
72     let mut stack = Vec::new();
73     loop {
74         match text.find('<') {
75             None => {
76                 res.push_str(text);
77                 break;
78             }
79             Some(i) => {
80                 res.push_str(&text[..i]);
81                 text = &text[i..];
82                 if text.starts_with(&open) {
83                     text = &text[open.len()..];
84                     let from = TextUnit::of_str(&res);
85                     stack.push(from);
86                 } else if text.starts_with(&close) {
87                     text = &text[close.len()..];
88                     let from = stack.pop().unwrap_or_else(|| panic!("unmatched </{}>", tag));
89                     let to = TextUnit::of_str(&res);
90                     ranges.push(TextRange::from_to(from, to));
91                 }
92             }
93         }
94     }
95     assert!(stack.is_empty(), "unmatched <{}>", tag);
96     ranges.sort_by_key(|r| (r.start(), r.end()));
97     (ranges, res)
98 }
99
100 pub fn add_cursor(text: &str, offset: TextUnit) -> String {
101     let offset: u32 = offset.into();
102     let offset: usize = offset as usize;
103     let mut res = String::new();
104     res.push_str(&text[..offset]);
105     res.push_str("<|>");
106     res.push_str(&text[offset..]);
107     res
108 }
109
110 #[derive(Debug)]
111 pub struct FixtureEntry {
112     pub meta: String,
113     pub text: String,
114 }
115
116 /// Parses text which looks like this:
117 ///
118 ///  ```not_rust
119 ///  //- some meta
120 ///  line 1
121 ///  line 2
122 ///  // - other meta
123 ///  ```
124 pub fn parse_fixture(fixture: &str) -> Vec<FixtureEntry> {
125     let mut res = Vec::new();
126     let mut buf = String::new();
127     let mut meta: Option<&str> = None;
128
129     macro_rules! flush {
130         () => {
131             if let Some(meta) = meta {
132                 res.push(FixtureEntry { meta: meta.to_string(), text: buf.clone() });
133                 buf.clear();
134             }
135         };
136     };
137
138     let margin = fixture
139         .lines()
140         .filter(|it| it.trim_start().starts_with("//-"))
141         .map(|it| it.len() - it.trim_start().len())
142         .next()
143         .expect("empty fixture");
144
145     let lines = fixture
146         .split('\n') // don't use `.lines` to not drop `\r\n`
147         .filter_map(|line| {
148             if line.len() >= margin {
149                 assert!(line[..margin].trim().is_empty());
150                 Some(&line[margin..])
151             } else {
152                 assert!(line.trim().is_empty());
153                 None
154             }
155         });
156
157     for line in lines {
158         if line.starts_with("//-") {
159             flush!();
160             buf.clear();
161             meta = Some(line["//-".len()..].trim());
162             continue;
163         }
164         buf.push_str(line);
165         buf.push('\n');
166     }
167     flush!();
168     res
169 }
170
171 // Comparison functionality borrowed from cargo:
172
173 /// Compare a line with an expected pattern.
174 /// - Use `[..]` as a wildcard to match 0 or more characters on the same line
175 ///   (similar to `.*` in a regex).
176 pub fn lines_match(expected: &str, actual: &str) -> bool {
177     // Let's not deal with / vs \ (windows...)
178     // First replace backslash-escaped backslashes with forward slashes
179     // which can occur in, for example, JSON output
180     let expected = expected.replace("\\\\", "/").replace("\\", "/");
181     let mut actual: &str = &actual.replace("\\\\", "/").replace("\\", "/");
182     for (i, part) in expected.split("[..]").enumerate() {
183         match actual.find(part) {
184             Some(j) => {
185                 if i == 0 && j != 0 {
186                     return false;
187                 }
188                 actual = &actual[j + part.len()..];
189             }
190             None => return false,
191         }
192     }
193     actual.is_empty() || expected.ends_with("[..]")
194 }
195
196 #[test]
197 fn lines_match_works() {
198     assert!(lines_match("a b", "a b"));
199     assert!(lines_match("a[..]b", "a b"));
200     assert!(lines_match("a[..]", "a b"));
201     assert!(lines_match("[..]", "a b"));
202     assert!(lines_match("[..]b", "a b"));
203
204     assert!(!lines_match("[..]b", "c"));
205     assert!(!lines_match("b", "c"));
206     assert!(!lines_match("b", "cb"));
207 }
208
209 // Compares JSON object for approximate equality.
210 // You can use `[..]` wildcard in strings (useful for OS dependent things such
211 // as paths).  You can use a `"{...}"` string literal as a wildcard for
212 // arbitrary nested JSON (useful for parts of object emitted by other programs
213 // (e.g. rustc) rather than Cargo itself).  Arrays are sorted before comparison.
214 pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a Value, &'a Value)> {
215     use serde_json::Value::*;
216     match (expected, actual) {
217         (&Number(ref l), &Number(ref r)) if l == r => None,
218         (&Bool(l), &Bool(r)) if l == r => None,
219         (&String(ref l), &String(ref r)) if lines_match(l, r) => None,
220         (&Array(ref l), &Array(ref r)) => {
221             if l.len() != r.len() {
222                 return Some((expected, actual));
223             }
224
225             let mut l = l.iter().collect::<Vec<_>>();
226             let mut r = r.iter().collect::<Vec<_>>();
227
228             l.retain(|l| match r.iter().position(|r| find_mismatch(l, r).is_none()) {
229                 Some(i) => {
230                     r.remove(i);
231                     false
232                 }
233                 None => true,
234             });
235
236             if !l.is_empty() {
237                 assert!(!r.is_empty());
238                 Some((&l[0], &r[0]))
239             } else {
240                 assert_eq!(r.len(), 0);
241                 None
242             }
243         }
244         (&Object(ref l), &Object(ref r)) => {
245             let same_keys = l.len() == r.len() && l.keys().all(|k| r.contains_key(k));
246             if !same_keys {
247                 return Some((expected, actual));
248             }
249
250             l.values().zip(r.values()).filter_map(|(l, r)| find_mismatch(l, r)).nth(0)
251         }
252         (&Null, &Null) => None,
253         // magic string literal "{...}" acts as wildcard for any sub-JSON
254         (&String(ref l), _) if l == "{...}" => None,
255         _ => Some((expected, actual)),
256     }
257 }
258
259 pub fn dir_tests<F>(test_data_dir: &Path, paths: &[&str], f: F)
260 where
261     F: Fn(&str, &Path) -> String,
262 {
263     for (path, input_code) in collect_tests(test_data_dir, paths) {
264         let parse_tree = f(&input_code, &path);
265         let path = path.with_extension("txt");
266         if !path.exists() {
267             println!("\nfile: {}", path.display());
268             println!("No .txt file with expected result, creating...\n");
269             println!("{}\n{}", input_code, parse_tree);
270             fs::write(&path, &parse_tree).unwrap();
271             panic!("No expected result")
272         }
273         let expected = read_text(&path);
274         let expected = expected.as_str();
275         let parse_tree = parse_tree.as_str();
276         assert_equal_text(expected, parse_tree, &path);
277     }
278 }
279
280 pub fn collect_tests(test_data_dir: &Path, paths: &[&str]) -> Vec<(PathBuf, String)> {
281     paths
282         .iter()
283         .flat_map(|path| {
284             let path = test_data_dir.to_owned().join(path);
285             test_from_dir(&path).into_iter()
286         })
287         .map(|path| {
288             let text = read_text(&path);
289             (path, text)
290         })
291         .collect()
292 }
293
294 fn test_from_dir(dir: &Path) -> Vec<PathBuf> {
295     let mut acc = Vec::new();
296     for file in fs::read_dir(&dir).unwrap() {
297         let file = file.unwrap();
298         let path = file.path();
299         if path.extension().unwrap_or_default() == "rs" {
300             acc.push(path);
301         }
302     }
303     acc.sort();
304     acc
305 }
306
307 pub fn project_dir() -> PathBuf {
308     let dir = env!("CARGO_MANIFEST_DIR");
309     PathBuf::from(dir).parent().unwrap().parent().unwrap().to_owned()
310 }
311
312 /// Read file and normalize newlines.
313 ///
314 /// `rustc` seems to always normalize `\r\n` newlines to `\n`:
315 ///
316 /// ```
317 /// let s = "
318 /// ";
319 /// assert_eq!(s.as_bytes(), &[10]);
320 /// ```
321 ///
322 /// so this should always be correct.
323 pub fn read_text(path: &Path) -> String {
324     fs::read_to_string(path)
325         .unwrap_or_else(|_| panic!("File at {:?} should be valid", path))
326         .replace("\r\n", "\n")
327 }
328
329 const REWRITE: bool = false;
330
331 fn assert_equal_text(expected: &str, actual: &str, path: &Path) {
332     if expected == actual {
333         return;
334     }
335     let dir = project_dir();
336     let pretty_path = path.strip_prefix(&dir).unwrap_or_else(|_| path);
337     if expected.trim() == actual.trim() {
338         println!("whitespace difference, rewriting");
339         println!("file: {}\n", pretty_path.display());
340         fs::write(path, actual).unwrap();
341         return;
342     }
343     if REWRITE {
344         println!("rewriting {}", pretty_path.display());
345         fs::write(path, actual).unwrap();
346         return;
347     }
348     assert_eq_text!(expected, actual, "file: {}", pretty_path.display());
349 }