]> git.lizzy.rs Git - rust.git/blob - ui_test/src/lib.rs
Auto merge of #2175 - RalfJung:xargo, r=oli-obk
[rust.git] / ui_test / src / lib.rs
1 use std::fmt::Write;
2 use std::path::{Path, PathBuf};
3 use std::process::{Command, ExitStatus};
4 use std::sync::atomic::{AtomicUsize, Ordering};
5 use std::sync::Mutex;
6
7 use colored::*;
8 use comments::ErrorMatch;
9 use crossbeam::queue::SegQueue;
10 use regex::Regex;
11 use rustc_stderr::{Level, Message};
12
13 use crate::comments::Comments;
14
15 mod comments;
16 mod rustc_stderr;
17 #[cfg(test)]
18 mod tests;
19
20 #[derive(Debug)]
21 pub struct Config {
22     /// Arguments passed to the binary that is executed.
23     pub args: Vec<String>,
24     /// `None` to run on the host, otherwise a target triple
25     pub target: Option<String>,
26     /// Filters applied to stderr output before processing it
27     pub stderr_filters: Filter,
28     /// Filters applied to stdout output before processing it
29     pub stdout_filters: Filter,
30     /// The folder in which to start searching for .rs files
31     pub root_dir: PathBuf,
32     pub mode: Mode,
33     pub program: PathBuf,
34     pub output_conflict_handling: OutputConflictHandling,
35     /// Only run tests with one of these strings in their path/name
36     pub path_filter: Vec<String>,
37 }
38
39 #[derive(Debug)]
40 pub enum OutputConflictHandling {
41     /// The default: emit a diff of the expected/actual output.
42     Error,
43     /// Ignore mismatches in the stderr/stdout files.
44     Ignore,
45     /// Instead of erroring if the stderr/stdout differs from the expected
46     /// automatically replace it with the found output (after applying filters).
47     Bless,
48 }
49
50 pub type Filter = Vec<(Regex, &'static str)>;
51
52 pub fn run_tests(config: Config) {
53     eprintln!("   Compiler flags: {:?}", config.args);
54
55     // Get the triple with which to run the tests
56     let target = config.target.clone().unwrap_or_else(|| config.get_host());
57
58     // A queue for files or folders to process
59     let todo = SegQueue::new();
60     todo.push(config.root_dir.clone());
61
62     // Some statistics and failure reports.
63     let failures = Mutex::new(vec![]);
64     let succeeded = AtomicUsize::default();
65     let ignored = AtomicUsize::default();
66     let filtered = AtomicUsize::default();
67
68     crossbeam::scope(|s| {
69         for _ in 0..std::thread::available_parallelism().unwrap().get() {
70             s.spawn(|_| {
71                 while let Some(path) = todo.pop() {
72                     // Collect everything inside directories
73                     if path.is_dir() {
74                         for entry in std::fs::read_dir(path).unwrap() {
75                             todo.push(entry.unwrap().path());
76                         }
77                         continue;
78                     }
79                     // Only look at .rs files
80                     if !path.extension().map(|ext| ext == "rs").unwrap_or(false) {
81                         continue;
82                     }
83                     if !config.path_filter.is_empty() {
84                         let path_display = path.display().to_string();
85                         if !config.path_filter.iter().any(|filter| path_display.contains(filter)) {
86                             filtered.fetch_add(1, Ordering::Relaxed);
87                             continue;
88                         }
89                     }
90                     let comments = Comments::parse_file(&path);
91                     // Ignore file if only/ignore rules do (not) apply
92                     if ignore_file(&comments, &target) {
93                         ignored.fetch_add(1, Ordering::Relaxed);
94                         eprintln!(
95                             "{} ... {}",
96                             path.display(),
97                             "ignored (in-test comment)".yellow()
98                         );
99                         continue;
100                     }
101                     // Run the test for all revisions
102                     for revision in
103                         comments.revisions.clone().unwrap_or_else(|| vec![String::new()])
104                     {
105                         let (m, errors, stderr) =
106                             run_test(&path, &config, &target, &revision, &comments);
107
108                         // Using a single `eprintln!` to prevent messages from threads from getting intermingled.
109                         let mut msg = format!("{} ", path.display());
110                         if !revision.is_empty() {
111                             write!(msg, "(revision `{revision}`) ").unwrap();
112                         }
113                         write!(msg, "... ").unwrap();
114                         if errors.is_empty() {
115                             eprintln!("{msg}{}", "ok".green());
116                             succeeded.fetch_add(1, Ordering::Relaxed);
117                         } else {
118                             eprintln!("{msg}{}", "FAILED".red().bold());
119                             failures.lock().unwrap().push((
120                                 path.clone(),
121                                 m,
122                                 revision,
123                                 errors,
124                                 stderr,
125                             ));
126                         }
127                     }
128                 }
129             });
130         }
131     })
132     .unwrap();
133
134     // Print all errors in a single thread to show reliable output
135     let failures = failures.into_inner().unwrap();
136     let succeeded = succeeded.load(Ordering::Relaxed);
137     let ignored = ignored.load(Ordering::Relaxed);
138     let filtered = filtered.load(Ordering::Relaxed);
139     if !failures.is_empty() {
140         for (path, miri, revision, errors, stderr) in &failures {
141             eprintln!();
142             eprint!("{}", path.display().to_string().underline());
143             if !revision.is_empty() {
144                 eprint!(" (revision `{}`)", revision);
145             }
146             eprint!(" {}", "FAILED".red());
147             eprintln!();
148             eprintln!("command: {:?}", miri);
149             eprintln!();
150             // `None` means never dump, as we already dumped it for an `OutputDiffers`
151             // `Some(false)` means there's no reason to dump, as all errors are independent of the stderr
152             // `Some(true)` means that there was a pattern in the .rs file that was not found in the output.
153             let mut dump_stderr = Some(false);
154             for error in errors {
155                 match error {
156                     Error::ExitStatus(mode, exit_status) => eprintln!("{mode:?} got {exit_status}"),
157                     Error::PatternNotFound { pattern, definition_line } => {
158                         eprintln!("`{pattern}` {} in stderr output", "not found".red());
159                         eprintln!(
160                             "expected because of pattern here: {}:{definition_line}",
161                             path.display().to_string().bold()
162                         );
163                         dump_stderr = dump_stderr.map(|_| true);
164                     }
165                     Error::NoPatternsFound => {
166                         eprintln!("{}", "no error patterns found in failure test".red());
167                     }
168                     Error::PatternFoundInPassTest =>
169                         eprintln!("{}", "error pattern found in success test".red()),
170                     Error::OutputDiffers { path, actual, expected } => {
171                         if path.extension().unwrap() == "stderr" {
172                             dump_stderr = None;
173                         }
174                         eprintln!("actual output differed from expected {}", path.display());
175                         eprintln!("{}", pretty_assertions::StrComparison::new(expected, actual));
176                         eprintln!()
177                     }
178                     Error::ErrorsWithoutPattern { path: None, msgs } => {
179                         eprintln!(
180                             "There were {} unmatched diagnostics that occurred outside the testfile and had not pattern",
181                             msgs.len(),
182                         );
183                         for Message { level, message } in msgs {
184                             eprintln!("    {level:?}: {message}")
185                         }
186                     }
187                     Error::ErrorsWithoutPattern { path: Some((path, line)), msgs } => {
188                         eprintln!(
189                             "There were {} unmatched diagnostics at {}:{line}",
190                             msgs.len(),
191                             path.display()
192                         );
193                         for Message { level, message } in msgs {
194                             eprintln!("    {level:?}: {message}")
195                         }
196                     }
197                     Error::ErrorPatternWithoutErrorAnnotation(path, line) => {
198                         eprintln!(
199                             "Annotation at {}:{line} matched an error diagnostic but did not have `ERROR` before its message",
200                             path.display()
201                         );
202                     }
203                 }
204                 eprintln!();
205             }
206             if let Some(true) = dump_stderr {
207                 eprintln!("actual stderr:");
208                 eprintln!("{}", stderr);
209                 eprintln!();
210             }
211         }
212         eprintln!(
213             "test result: {}. {} tests failed, {} tests passed, {} ignored, {} filtered out",
214             "FAIL".red(),
215             failures.len().to_string().red().bold(),
216             succeeded.to_string().green(),
217             ignored.to_string().yellow(),
218             filtered.to_string().yellow(),
219         );
220         std::process::exit(1);
221     }
222     eprintln!();
223     eprintln!(
224         "test result: {}. {} tests passed, {} ignored, {} filtered out",
225         "ok".green(),
226         succeeded.to_string().green(),
227         ignored.to_string().yellow(),
228         filtered.to_string().yellow(),
229     );
230     eprintln!();
231 }
232
233 #[derive(Debug)]
234 enum Error {
235     /// Got an invalid exit status for the given mode.
236     ExitStatus(Mode, ExitStatus),
237     PatternNotFound {
238         pattern: String,
239         definition_line: usize,
240     },
241     /// A ui test checking for failure does not have any failure patterns
242     NoPatternsFound,
243     /// A ui test checking for success has failure patterns
244     PatternFoundInPassTest,
245     /// Stderr/Stdout differed from the `.stderr`/`.stdout` file present.
246     OutputDiffers {
247         path: PathBuf,
248         actual: String,
249         expected: String,
250     },
251     ErrorsWithoutPattern {
252         msgs: Vec<Message>,
253         path: Option<(PathBuf, usize)>,
254     },
255     ErrorPatternWithoutErrorAnnotation(PathBuf, usize),
256 }
257
258 type Errors = Vec<Error>;
259
260 fn run_test(
261     path: &Path,
262     config: &Config,
263     target: &str,
264     revision: &str,
265     comments: &Comments,
266 ) -> (Command, Errors, String) {
267     // Run miri
268     let mut miri = Command::new(&config.program);
269     miri.args(config.args.iter());
270     miri.arg(path);
271     if !revision.is_empty() {
272         miri.arg(format!("--cfg={revision}"));
273     }
274     miri.arg("--error-format=json");
275     for arg in &comments.compile_flags {
276         miri.arg(arg);
277     }
278     for (k, v) in &comments.env_vars {
279         miri.env(k, v);
280     }
281     let output = miri.output().expect("could not execute miri");
282     let mut errors = config.mode.ok(output.status);
283     let stderr = check_test_result(
284         path,
285         config,
286         target,
287         revision,
288         comments,
289         &mut errors,
290         &output.stdout,
291         &output.stderr,
292     );
293     (miri, errors, stderr)
294 }
295
296 fn check_test_result(
297     path: &Path,
298     config: &Config,
299     target: &str,
300     revision: &str,
301     comments: &Comments,
302     errors: &mut Errors,
303     stdout: &[u8],
304     stderr: &[u8],
305 ) -> String {
306     // Always remove annotation comments from stderr.
307     let diagnostics = rustc_stderr::process(path, stderr);
308     let stdout = std::str::from_utf8(stdout).unwrap();
309     // Check output files (if any)
310     let revised = |extension: &str| {
311         if revision.is_empty() {
312             extension.to_string()
313         } else {
314             format!("{}.{}", revision, extension)
315         }
316     };
317     // Check output files against actual output
318     check_output(
319         &diagnostics.rendered,
320         path,
321         errors,
322         revised("stderr"),
323         target,
324         &config.stderr_filters,
325         &config,
326         comments,
327     );
328     check_output(
329         &stdout,
330         path,
331         errors,
332         revised("stdout"),
333         target,
334         &config.stdout_filters,
335         &config,
336         comments,
337     );
338     // Check error annotations in the source against output
339     check_annotations(
340         diagnostics.messages,
341         diagnostics.messages_from_unknown_file_or_line,
342         path,
343         errors,
344         config,
345         revision,
346         comments,
347     );
348     diagnostics.rendered
349 }
350
351 fn check_annotations(
352     mut messages: Vec<Vec<Message>>,
353     mut messages_from_unknown_file_or_line: Vec<Message>,
354     path: &Path,
355     errors: &mut Errors,
356     config: &Config,
357     revision: &str,
358     comments: &Comments,
359 ) {
360     if let Some((ref error_pattern, definition_line)) = comments.error_pattern {
361         let mut found = false;
362
363         // first check the diagnostics messages outside of our file. We check this first, so that
364         // you can mix in-file annotations with // error-pattern annotations, even if there is overlap
365         // in the messages.
366         if let Some(i) = messages_from_unknown_file_or_line
367             .iter()
368             .position(|msg| msg.message.contains(error_pattern))
369         {
370             messages_from_unknown_file_or_line.remove(i);
371             found = true;
372         }
373
374         // if nothing was found, check the ones inside our file. We permit this because some tests may have
375         // flaky line numbers for their messages.
376         if !found {
377             for line in &mut messages {
378                 if let Some(i) = line.iter().position(|msg| msg.message.contains(error_pattern)) {
379                     line.remove(i);
380                     found = true;
381                     break;
382                 }
383             }
384         }
385
386         if !found {
387             errors.push(Error::PatternNotFound {
388                 pattern: error_pattern.to_string(),
389                 definition_line,
390             });
391         }
392     }
393
394     // The order on `Level` is such that `Error` is the highest level.
395     // We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
396     // are matched.
397     let mut lowest_annotation_level = Level::Error;
398     for &ErrorMatch { ref matched, revision: ref rev, definition_line, line, level } in
399         &comments.error_matches
400     {
401         if let Some(rev) = rev {
402             if rev != revision {
403                 continue;
404             }
405         }
406         if let Some(level) = level {
407             // If we found a diagnostic with a level annotation, make sure that all
408             // diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
409             // for this pattern.
410             lowest_annotation_level = std::cmp::min(lowest_annotation_level, level);
411         }
412
413         if let Some(msgs) = messages.get_mut(line) {
414             let found = msgs.iter().position(|msg| {
415                 msg.message.contains(matched)
416                     // in case there is no level on the annotation, match any level.
417                     && level.map_or(true, |level| {
418                         msg.level == level
419                     })
420             });
421             if let Some(found) = found {
422                 let msg = msgs.remove(found);
423                 if msg.level == Level::Error && level.is_none() {
424                     errors
425                         .push(Error::ErrorPatternWithoutErrorAnnotation(path.to_path_buf(), line));
426                 }
427                 continue;
428             }
429         }
430
431         errors.push(Error::PatternNotFound { pattern: matched.to_string(), definition_line });
432     }
433
434     let filter = |msgs: Vec<Message>| -> Vec<_> {
435         msgs.into_iter().filter(|msg| msg.level >= lowest_annotation_level).collect()
436     };
437
438     let messages_from_unknown_file_or_line = filter(messages_from_unknown_file_or_line);
439     if !messages_from_unknown_file_or_line.is_empty() {
440         errors.push(Error::ErrorsWithoutPattern {
441             path: None,
442             msgs: messages_from_unknown_file_or_line,
443         });
444     }
445
446     for (line, msgs) in messages.into_iter().enumerate() {
447         let msgs = filter(msgs);
448         if !msgs.is_empty() {
449             errors
450                 .push(Error::ErrorsWithoutPattern { path: Some((path.to_path_buf(), line)), msgs });
451         }
452     }
453
454     match (config.mode, comments.error_pattern.is_some() || !comments.error_matches.is_empty()) {
455         (Mode::Pass, true) | (Mode::Panic, true) => errors.push(Error::PatternFoundInPassTest),
456         (Mode::Fail, false) => errors.push(Error::NoPatternsFound),
457         _ => {}
458     }
459 }
460
461 fn check_output(
462     output: &str,
463     path: &Path,
464     errors: &mut Errors,
465     kind: String,
466     target: &str,
467     filters: &Filter,
468     config: &Config,
469     comments: &Comments,
470 ) {
471     let output = normalize(path, output, filters, comments);
472     let path = output_path(path, comments, kind, target);
473     match config.output_conflict_handling {
474         OutputConflictHandling::Bless =>
475             if output.is_empty() {
476                 let _ = std::fs::remove_file(path);
477             } else {
478                 std::fs::write(path, &output).unwrap();
479             },
480         OutputConflictHandling::Error => {
481             let expected_output = std::fs::read_to_string(&path).unwrap_or_default();
482             if output != expected_output {
483                 errors.push(Error::OutputDiffers {
484                     path,
485                     actual: output,
486                     expected: expected_output,
487                 });
488             }
489         }
490         OutputConflictHandling::Ignore => {}
491     }
492 }
493
494 fn output_path(path: &Path, comments: &Comments, kind: String, target: &str) -> PathBuf {
495     if comments.stderr_per_bitwidth {
496         return path.with_extension(format!("{}.{kind}", get_pointer_width(target)));
497     }
498     path.with_extension(kind)
499 }
500
501 fn ignore_file(comments: &Comments, target: &str) -> bool {
502     for s in &comments.ignore {
503         if target.contains(s) {
504             return true;
505         }
506         if get_pointer_width(target) == s {
507             return true;
508         }
509     }
510     for s in &comments.only {
511         if !target.contains(s) {
512             return true;
513         }
514         if get_pointer_width(target) != s {
515             return true;
516         }
517     }
518     false
519 }
520
521 // Taken 1:1 from compiletest-rs
522 fn get_pointer_width(triple: &str) -> &'static str {
523     if (triple.contains("64") && !triple.ends_with("gnux32") && !triple.ends_with("gnu_ilp32"))
524         || triple.starts_with("s390x")
525     {
526         "64bit"
527     } else if triple.starts_with("avr") {
528         "16bit"
529     } else {
530         "32bit"
531     }
532 }
533
534 fn normalize(path: &Path, text: &str, filters: &Filter, comments: &Comments) -> String {
535     // Useless paths
536     let mut text = text.replace(&path.parent().unwrap().display().to_string(), "$DIR");
537     if let Some(lib_path) = option_env!("RUSTC_LIB_PATH") {
538         text = text.replace(lib_path, "RUSTLIB");
539     }
540
541     for (regex, replacement) in filters.iter() {
542         text = regex.replace_all(&text, *replacement).to_string();
543     }
544
545     for (from, to) in &comments.normalize_stderr {
546         text = from.replace_all(&text, to).to_string();
547     }
548     text
549 }
550
551 impl Config {
552     fn get_host(&self) -> String {
553         rustc_version::VersionMeta::for_command(std::process::Command::new(&self.program))
554             .expect("failed to parse rustc version info")
555             .host
556     }
557 }
558
559 #[derive(Copy, Clone, Debug)]
560 pub enum Mode {
561     // The test passes a full execution of the rustc driver
562     Pass,
563     // The rustc driver panicked
564     Panic,
565     // The rustc driver emitted an error
566     Fail,
567 }
568
569 impl Mode {
570     fn ok(self, status: ExitStatus) -> Errors {
571         match (status.code().unwrap(), self) {
572             (1, Mode::Fail) | (101, Mode::Panic) | (0, Mode::Pass) => vec![],
573             _ => vec![Error::ExitStatus(self, status)],
574         }
575     }
576 }