aboutsummaryrefslogtreecommitdiff
path: root/crates/test_utils/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/test_utils/src')
-rw-r--r--crates/test_utils/src/lib.rs35
1 files changed, 34 insertions, 1 deletions
diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs
index 27b05e34b..7f122b13e 100644
--- a/crates/test_utils/src/lib.rs
+++ b/crates/test_utils/src/lib.rs
@@ -14,7 +14,7 @@ mod fixture;
14use std::{ 14use std::{
15 convert::{TryFrom, TryInto}, 15 convert::{TryFrom, TryInto},
16 env, fs, 16 env, fs,
17 path::PathBuf, 17 path::{Path, PathBuf},
18}; 18};
19 19
20use profile::StopWatch; 20use profile::StopWatch;
@@ -353,3 +353,36 @@ pub fn bench(label: &'static str) -> impl Drop {
353 353
354 Bencher { sw: StopWatch::start(), label } 354 Bencher { sw: StopWatch::start(), label }
355} 355}
356
357/// Checks that the `file` has the specified `contents`. If that is not the
358/// case, updates the file and then fails the test.
359pub fn ensure_file_contents(file: &Path, contents: &str) {
360 if let Err(()) = try_ensure_file_contents(file, contents) {
361 panic!("Some files were not up-to-date");
362 }
363}
364
365/// Checks that the `file` has the specified `contents`. If that is not the
366/// case, updates the file and return an Error.
367pub fn try_ensure_file_contents(file: &Path, contents: &str) -> Result<(), ()> {
368 match std::fs::read_to_string(file) {
369 Ok(old_contents) if normalize_newlines(&old_contents) == normalize_newlines(contents) => {
370 return Ok(())
371 }
372 _ => (),
373 }
374 let display_path = file.strip_prefix(&project_dir()).unwrap_or(file);
375 eprintln!(
376 "\n\x1b[31;1merror\x1b[0m: {} was not up-to-date, updating\n",
377 display_path.display()
378 );
379 if let Some(parent) = file.parent() {
380 let _ = std::fs::create_dir_all(parent);
381 }
382 std::fs::write(file, contents).unwrap();
383 Err(())
384}
385
386fn normalize_newlines(s: &str) -> String {
387 s.replace("\r\n", "\n")
388}