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