| 1 |
use anyhow::{Context, Result}; |
| 2 |
use pretty_assertions::assert_eq; |
| 3 |
use std::{fs, path::Path}; |
| 4 |
use wit_component::WitPrinter; |
| 5 |
use wit_parser::Resolve; |
| 6 |
|
| 7 |
/// This is a test which iterates over the `tests/merge` directory and treats |
| 8 |
/// each subdirectory as its own test. Each subdirectory has an `into` and a |
| 9 |
/// `from` folder which represent two different `Resolve` sets, each with their |
| 10 |
/// own set of dependencies as well. |
| 11 |
/// |
| 12 |
/// Each test will merge the `from` into the `into` and assert that everything |
| 13 |
/// is valid along the way. On successful merge the resulting documents |
| 14 |
/// are printed and asserted against expectations. Failures assert the |
| 15 |
/// correct error message. |
| 16 |
#[test] |
| 17 |
fn merging() -> Result<()> { |
| 18 |
drop(env_logger::try_init()); |
| 19 |
|
| 20 |
for entry in fs::read_dir("tests/merge")? { |
| 21 |
let path = entry?.path(); |
| 22 |
if !path.is_dir() { |
| 23 |
continue; |
| 24 |
} |
| 25 |
|
| 26 |
let test_case = path.file_stem().unwrap().to_str().unwrap(); |
| 27 |
println!("testing {test_case}"); |
| 28 |
|
| 29 |
let mut from = Resolve::default(); |
| 30 |
from.push_dir(&path.join("from"))?; |
| 31 |
let mut into = Resolve::default(); |
| 32 |
into.push_dir(&path.join("into"))?; |
| 33 |
|
| 34 |
from.assert_valid(); |
| 35 |
into.assert_valid(); |
| 36 |
|
| 37 |
match into.merge(from) { |
| 38 |
Ok(_) => { |
| 39 |
assert!( |
| 40 |
!test_case.starts_with("bad-"), |
| 41 |
"should have failed to merge" |
| 42 |
); |
| 43 |
into.assert_valid(); |
| 44 |
for (id, pkg) in into.packages.iter() { |
| 45 |
let expected = path |
| 46 |
.join("merge") |
| 47 |
.join(&pkg.name.name) |
| 48 |
.with_extension("wit"); |
| 49 |
let mut printer = WitPrinter::default(); |
| 50 |
printer.print(&into, id, &[])?; |
| 51 |
let output = printer.output.to_string(); |
| 52 |
assert_output(&expected, &output)?; |
| 53 |
} |
| 54 |
} |
| 55 |
Err(e) => { |
| 56 |
assert!(test_case.starts_with("bad-"), "failed to merge with {e:?}"); |
| 57 |
assert_output(&path.join("error.txt"), &format!("{e:#}"))?; |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
Ok(()) |
| 63 |
} |
| 64 |
|
| 65 |
fn assert_output(expected: &Path, actual: &str) -> Result<()> { |
| 66 |
if std::env::var_os("BLESS").is_some() { |
| 67 |
fs::create_dir_all(expected.parent().unwrap())?; |
| 68 |
fs::write(expected, actual).with_context(|| format!("failed to write {expected:?}"))?; |
| 69 |
} else { |
| 70 |
assert_eq!( |
| 71 |
fs::read_to_string(expected) |
| 72 |
.with_context(|| format!("failed to read {expected:?}"))? |
| 73 |
.replace("\r\n", "\n"), |
| 74 |
actual, |
| 75 |
"expectation `{}` did not match actual", |
| 76 |
expected.display(), |
| 77 |
); |
| 78 |
} |
| 79 |
Ok(()) |
| 80 |
} |