]> git.lizzy.rs Git - rust.git/blob - ui_test/src/lib.rs
Auto merge of #2232 - rust-lang:gesundheit, 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             let mut dump_stderr = true;
151             for error in errors {
152                 match error {
153                     Error::ExitStatus(mode, exit_status) => eprintln!("{mode:?} got {exit_status}"),
154                     Error::PatternNotFound { pattern, definition_line } => {
155                         eprintln!("`{pattern}` {} in stderr output", "not found".red());
156                         eprintln!(
157                             "expected because of pattern here: {}:{definition_line}",
158                             path.display().to_string().bold()
159                         );
160                     }
161                     Error::NoPatternsFound => {
162                         eprintln!("{}", "no error patterns found in failure test".red());
163                     }
164                     Error::PatternFoundInPassTest =>
165                         eprintln!("{}", "error pattern found in success test".red()),
166                     Error::OutputDiffers { path, actual, expected } => {
167                         if path.extension().unwrap() == "stderr" {
168                             dump_stderr = false;
169                         }
170                         eprintln!("actual output differed from expected {}", path.display());
171                         eprintln!("{}", pretty_assertions::StrComparison::new(expected, actual));
172                         eprintln!()
173                     }
174                     Error::ErrorsWithoutPattern { path: None, msgs } => {
175                         eprintln!(
176                             "There were {} unmatched diagnostics that occurred outside the testfile and had not pattern",
177                             msgs.len(),
178                         );
179                         for Message { level, message } in msgs {
180                             eprintln!("    {level:?}: {message}")
181                         }
182                     }
183                     Error::ErrorsWithoutPattern { path: Some((path, line)), msgs } => {
184                         eprintln!(
185                             "There were {} unmatched diagnostics at {}:{line}",
186                             msgs.len(),
187                             path.display()
188                         );
189                         for Message { level, message } in msgs {
190                             eprintln!("    {level:?}: {message}")
191                         }
192                     }
193                     Error::ErrorPatternWithoutErrorAnnotation(path, line) => {
194                         eprintln!(
195                             "Annotation at {}:{line} matched an error diagnostic but did not have `ERROR` before its message",
196                             path.display()
197                         );
198                     }
199                 }
200                 eprintln!();
201             }
202             // Unless we already dumped the stderr via an OutputDiffers diff, let's dump it here.
203             if dump_stderr {
204                 eprintln!("actual stderr:");
205                 eprintln!("{}", stderr);
206                 eprintln!();
207             }
208         }
209         eprintln!("{}", "failures:".red().underline());
210         for (path, _miri, _revision, _errors, _stderr) in &failures {
211             eprintln!("    {}", path.display());
212         }
213         eprintln!();
214         eprintln!(
215             "test result: {}. {} tests failed, {} tests passed, {} ignored, {} filtered out",
216             "FAIL".red(),
217             failures.len().to_string().red().bold(),
218             succeeded.to_string().green(),
219             ignored.to_string().yellow(),
220             filtered.to_string().yellow(),
221         );
222         std::process::exit(1);
223     }
224     eprintln!();
225     eprintln!(
226         "test result: {}. {} tests passed, {} ignored, {} filtered out",
227         "ok".green(),
228         succeeded.to_string().green(),
229         ignored.to_string().yellow(),
230         filtered.to_string().yellow(),
231     );
232     eprintln!();
233 }
234
235 #[derive(Debug)]
236 enum Error {
237     /// Got an invalid exit status for the given mode.
238     ExitStatus(Mode, ExitStatus),
239     PatternNotFound {
240         pattern: String,
241         definition_line: usize,
242     },
243     /// A ui test checking for failure does not have any failure patterns
244     NoPatternsFound,
245     /// A ui test checking for success has failure patterns
246     PatternFoundInPassTest,
247     /// Stderr/Stdout differed from the `.stderr`/`.stdout` file present.
248     OutputDiffers {
249         path: PathBuf,
250         actual: String,
251         expected: String,
252     },
253     ErrorsWithoutPattern {
254         msgs: Vec<Message>,
255         path: Option<(PathBuf, usize)>,
256     },
257     ErrorPatternWithoutErrorAnnotation(PathBuf, usize),
258 }
259
260 type Errors = Vec<Error>;
261
262 fn run_test(
263     path: &Path,
264     config: &Config,
265     target: &str,
266     revision: &str,
267     comments: &Comments,
268 ) -> (Command, Errors, String) {
269     // Run miri
270     let mut miri = Command::new(&config.program);
271     miri.args(config.args.iter());
272     miri.arg(path);
273     if !revision.is_empty() {
274         miri.arg(format!("--cfg={revision}"));
275     }
276     miri.arg("--error-format=json");
277     for arg in &comments.compile_flags {
278         miri.arg(arg);
279     }
280     for (k, v) in &comments.env_vars {
281         miri.env(k, v);
282     }
283     let output = miri.output().expect("could not execute miri");
284     let mut errors = config.mode.ok(output.status);
285     let stderr = check_test_result(
286         path,
287         config,
288         target,
289         revision,
290         comments,
291         &mut errors,
292         &output.stdout,
293         &output.stderr,
294     );
295     (miri, errors, stderr)
296 }
297
298 fn check_test_result(
299     path: &Path,
300     config: &Config,
301     target: &str,
302     revision: &str,
303     comments: &Comments,
304     errors: &mut Errors,
305     stdout: &[u8],
306     stderr: &[u8],
307 ) -> String {
308     // Always remove annotation comments from stderr.
309     let diagnostics = rustc_stderr::process(path, stderr);
310     let stdout = std::str::from_utf8(stdout).unwrap();
311     // Check output files (if any)
312     let revised = |extension: &str| {
313         if revision.is_empty() {
314             extension.to_string()
315         } else {
316             format!("{}.{}", revision, extension)
317         }
318     };
319     // Check output files against actual output
320     check_output(
321         &diagnostics.rendered,
322         path,
323         errors,
324         revised("stderr"),
325         target,
326         &config.stderr_filters,
327         &config,
328         comments,
329     );
330     check_output(
331         &stdout,
332         path,
333         errors,
334         revised("stdout"),
335         target,
336         &config.stdout_filters,
337         &config,
338         comments,
339     );
340     // Check error annotations in the source against output
341     check_annotations(
342         diagnostics.messages,
343         diagnostics.messages_from_unknown_file_or_line,
344         path,
345         errors,
346         config,
347         revision,
348         comments,
349     );
350     diagnostics.rendered
351 }
352
353 fn check_annotations(
354     mut messages: Vec<Vec<Message>>,
355     mut messages_from_unknown_file_or_line: Vec<Message>,
356     path: &Path,
357     errors: &mut Errors,
358     config: &Config,
359     revision: &str,
360     comments: &Comments,
361 ) {
362     if let Some((ref error_pattern, definition_line)) = comments.error_pattern {
363         let mut found = false;
364
365         // first check the diagnostics messages outside of our file. We check this first, so that
366         // you can mix in-file annotations with // error-pattern annotations, even if there is overlap
367         // in the messages.
368         if let Some(i) = messages_from_unknown_file_or_line
369             .iter()
370             .position(|msg| msg.message.contains(error_pattern))
371         {
372             messages_from_unknown_file_or_line.remove(i);
373             found = true;
374         }
375
376         // if nothing was found, check the ones inside our file. We permit this because some tests may have
377         // flaky line numbers for their messages.
378         if !found {
379             for line in &mut messages {
380                 if let Some(i) = line.iter().position(|msg| msg.message.contains(error_pattern)) {
381                     line.remove(i);
382                     found = true;
383                     break;
384                 }
385             }
386         }
387
388         if !found {
389             errors.push(Error::PatternNotFound {
390                 pattern: error_pattern.to_string(),
391                 definition_line,
392             });
393         }
394     }
395
396     // The order on `Level` is such that `Error` is the highest level.
397     // We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
398     // are matched.
399     let mut lowest_annotation_level = Level::Error;
400     for &ErrorMatch { ref matched, revision: ref rev, definition_line, line, level } in
401         &comments.error_matches
402     {
403         if let Some(rev) = rev {
404             if rev != revision {
405                 continue;
406             }
407         }
408         if let Some(level) = level {
409             // If we found a diagnostic with a level annotation, make sure that all
410             // diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
411             // for this pattern.
412             lowest_annotation_level = std::cmp::min(lowest_annotation_level, level);
413         }
414
415         if let Some(msgs) = messages.get_mut(line) {
416             let found = msgs.iter().position(|msg| {
417                 msg.message.contains(matched)
418                     // in case there is no level on the annotation, match any level.
419                     && level.map_or(true, |level| {
420                         msg.level == level
421                     })
422             });
423             if let Some(found) = found {
424                 let msg = msgs.remove(found);
425                 if msg.level == Level::Error && level.is_none() {
426                     errors
427                         .push(Error::ErrorPatternWithoutErrorAnnotation(path.to_path_buf(), line));
428                 }
429                 continue;
430             }
431         }
432
433         errors.push(Error::PatternNotFound { pattern: matched.to_string(), definition_line });
434     }
435
436     let filter = |msgs: Vec<Message>| -> Vec<_> {
437         msgs.into_iter().filter(|msg| msg.level >= lowest_annotation_level).collect()
438     };
439
440     let messages_from_unknown_file_or_line = filter(messages_from_unknown_file_or_line);
441     if !messages_from_unknown_file_or_line.is_empty() {
442         errors.push(Error::ErrorsWithoutPattern {
443             path: None,
444             msgs: messages_from_unknown_file_or_line,
445         });
446     }
447
448     for (line, msgs) in messages.into_iter().enumerate() {
449         let msgs = filter(msgs);
450         if !msgs.is_empty() {
451             errors
452                 .push(Error::ErrorsWithoutPattern { path: Some((path.to_path_buf(), line)), msgs });
453         }
454     }
455
456     match (config.mode, comments.error_pattern.is_some() || !comments.error_matches.is_empty()) {
457         (Mode::Pass, true) | (Mode::Panic, true) => errors.push(Error::PatternFoundInPassTest),
458         (Mode::Fail, false) => errors.push(Error::NoPatternsFound),
459         _ => {}
460     }
461 }
462
463 fn check_output(
464     output: &str,
465     path: &Path,
466     errors: &mut Errors,
467     kind: String,
468     target: &str,
469     filters: &Filter,
470     config: &Config,
471     comments: &Comments,
472 ) {
473     let output = normalize(path, output, filters, comments);
474     let path = output_path(path, comments, kind, target);
475     match config.output_conflict_handling {
476         OutputConflictHandling::Bless =>
477             if output.is_empty() {
478                 let _ = std::fs::remove_file(path);
479             } else {
480                 std::fs::write(path, &output).unwrap();
481             },
482         OutputConflictHandling::Error => {
483             let expected_output = std::fs::read_to_string(&path).unwrap_or_default();
484             if output != expected_output {
485                 errors.push(Error::OutputDiffers {
486                     path,
487                     actual: output,
488                     expected: expected_output,
489                 });
490             }
491         }
492         OutputConflictHandling::Ignore => {}
493     }
494 }
495
496 fn output_path(path: &Path, comments: &Comments, kind: String, target: &str) -> PathBuf {
497     if comments.stderr_per_bitwidth {
498         return path.with_extension(format!("{}.{kind}", get_pointer_width(target)));
499     }
500     path.with_extension(kind)
501 }
502
503 fn ignore_file(comments: &Comments, target: &str) -> bool {
504     for s in &comments.ignore {
505         if target.contains(s) {
506             return true;
507         }
508         if get_pointer_width(target) == s {
509             return true;
510         }
511     }
512     for s in &comments.only {
513         if !target.contains(s) {
514             return true;
515         }
516         /* FIXME(https://github.com/rust-lang/miri/issues/2206)
517         if get_pointer_width(target) != s {
518             return true;
519         } */
520     }
521     false
522 }
523
524 // Taken 1:1 from compiletest-rs
525 fn get_pointer_width(triple: &str) -> &'static str {
526     if (triple.contains("64") && !triple.ends_with("gnux32") && !triple.ends_with("gnu_ilp32"))
527         || triple.starts_with("s390x")
528     {
529         "64bit"
530     } else if triple.starts_with("avr") {
531         "16bit"
532     } else {
533         "32bit"
534     }
535 }
536
537 fn normalize(path: &Path, text: &str, filters: &Filter, comments: &Comments) -> String {
538     // Useless paths
539     let mut text = text.replace(&path.parent().unwrap().display().to_string(), "$DIR");
540     if let Some(lib_path) = option_env!("RUSTC_LIB_PATH") {
541         text = text.replace(lib_path, "RUSTLIB");
542     }
543
544     for (regex, replacement) in filters.iter() {
545         text = regex.replace_all(&text, *replacement).to_string();
546     }
547
548     for (from, to) in &comments.normalize_stderr {
549         text = from.replace_all(&text, to).to_string();
550     }
551     text
552 }
553
554 impl Config {
555     fn get_host(&self) -> String {
556         rustc_version::VersionMeta::for_command(std::process::Command::new(&self.program))
557             .expect("failed to parse rustc version info")
558             .host
559     }
560 }
561
562 #[derive(Copy, Clone, Debug)]
563 pub enum Mode {
564     // The test passes a full execution of the rustc driver
565     Pass,
566     // The rustc driver panicked
567     Panic,
568     // The rustc driver emitted an error
569     Fail,
570 }
571
572 impl Mode {
573     fn ok(self, status: ExitStatus) -> Errors {
574         match (status.code().unwrap(), self) {
575             (1, Mode::Fail) | (101, Mode::Panic) | (0, Mode::Pass) => vec![],
576             _ => vec![Error::ExitStatus(self, status)],
577         }
578     }
579 }