diff options
author | Aleksey Kladov <[email protected]> | 2021-03-08 14:20:36 +0000 |
---|---|---|
committer | Aleksey Kladov <[email protected]> | 2021-03-08 18:45:06 +0000 |
commit | b6ba0dec0c08dd2afcda951b09966b457f2c8bc3 (patch) | |
tree | 7cbc9679d81509e2dece8eedfea27d2682907ccd /crates/test_utils/src | |
parent | 0f6f458cc1b460076093efda903bf1a1b9062697 (diff) |
Generalize file ensuring infrastructure
Diffstat (limited to 'crates/test_utils/src')
-rw-r--r-- | crates/test_utils/src/lib.rs | 35 |
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; | |||
14 | use std::{ | 14 | use 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 | ||
20 | use profile::StopWatch; | 20 | use 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. | ||
359 | pub 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. | ||
367 | pub 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 | |||
386 | fn normalize_newlines(s: &str) -> String { | ||
387 | s.replace("\r\n", "\n") | ||
388 | } | ||