|
| 1 | +//! Collection of assertions and assertion-related helpers. |
| 2 | +
|
| 3 | +use std::panic; |
| 4 | +use std::path::Path; |
| 5 | + |
| 6 | +use crate::fs; |
| 7 | + |
| 8 | +/// Assert that `actual` is equal to `expected`. |
| 9 | +#[track_caller] |
| 10 | +pub fn assert_equals<A: AsRef<str>, E: AsRef<str>>(actual: A, expected: E) { |
| 11 | + let actual = actual.as_ref(); |
| 12 | + let expected = expected.as_ref(); |
| 13 | + if actual != expected { |
| 14 | + eprintln!("=== ACTUAL TEXT ==="); |
| 15 | + eprintln!("{}", actual); |
| 16 | + eprintln!("=== EXPECTED ==="); |
| 17 | + eprintln!("{}", expected); |
| 18 | + panic!("expected text was not found in actual text"); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +/// Assert that `haystack` contains `needle`. |
| 23 | +#[track_caller] |
| 24 | +pub fn assert_contains<H: AsRef<str>, N: AsRef<str>>(haystack: H, needle: N) { |
| 25 | + let haystack = haystack.as_ref(); |
| 26 | + let needle = needle.as_ref(); |
| 27 | + if !haystack.contains(needle) { |
| 28 | + eprintln!("=== HAYSTACK ==="); |
| 29 | + eprintln!("{}", haystack); |
| 30 | + eprintln!("=== NEEDLE ==="); |
| 31 | + eprintln!("{}", needle); |
| 32 | + panic!("needle was not found in haystack"); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +/// Assert that `haystack` does not contain `needle`. |
| 37 | +#[track_caller] |
| 38 | +pub fn assert_not_contains<H: AsRef<str>, N: AsRef<str>>(haystack: H, needle: N) { |
| 39 | + let haystack = haystack.as_ref(); |
| 40 | + let needle = needle.as_ref(); |
| 41 | + if haystack.contains(needle) { |
| 42 | + eprintln!("=== HAYSTACK ==="); |
| 43 | + eprintln!("{}", haystack); |
| 44 | + eprintln!("=== NEEDLE ==="); |
| 45 | + eprintln!("{}", needle); |
| 46 | + panic!("needle was unexpectedly found in haystack"); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// Assert that all files in `dir1` exist and have the same content in `dir2` |
| 51 | +pub fn assert_dirs_are_equal(dir1: impl AsRef<Path>, dir2: impl AsRef<Path>) { |
| 52 | + let dir2 = dir2.as_ref(); |
| 53 | + fs::read_dir_entries(dir1, |entry_path| { |
| 54 | + let entry_name = entry_path.file_name().unwrap(); |
| 55 | + if entry_path.is_dir() { |
| 56 | + assert_dirs_are_equal(&entry_path, &dir2.join(entry_name)); |
| 57 | + } else { |
| 58 | + let path2 = dir2.join(entry_name); |
| 59 | + let file1 = fs::read(&entry_path); |
| 60 | + let file2 = fs::read(&path2); |
| 61 | + |
| 62 | + // We don't use `assert_eq!` because they are `Vec<u8>`, so not great for display. |
| 63 | + // Why not using String? Because there might be minified files or even potentially |
| 64 | + // binary ones, so that would display useless output. |
| 65 | + assert!( |
| 66 | + file1 == file2, |
| 67 | + "`{}` and `{}` have different content", |
| 68 | + entry_path.display(), |
| 69 | + path2.display(), |
| 70 | + ); |
| 71 | + } |
| 72 | + }); |
| 73 | +} |
0 commit comments