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