Debian Codegraph @

crates/wit-component/tests/targets.rs

raw
1 use anyhow::{Context, Result};
2 use std::{fs, path::Path};
3 use wit_parser::{Resolve, WorldId};
4
5 /// Tests whether a component targets a world.
6 ///
7 /// This test looks in the `targets/` directory for test cases.
8 ///
9 /// The expected input files for a test case are:
10 ///
11 /// * [required] `test.wat` -- contains the component to test
12 /// encoded as a component produced via the `embed` and `new`
13 /// subcommands of `wasm-tools component`.
14 /// * [required] `test.wit` -- WIT package describing the target
15 /// world to use when checking conformance.
16 ///
17 /// And the output file is:
18 /// * `error.txt` - the expected error message if the synthetic
19 /// component constructed for testing is a invalid component encoding.
20 /// NOTE: an invalid encoding here indicates that the targets check has failed.
21 ///
22 /// Run the test with the environment variable `BLESS` set to update `error.txt`.
23 ///
24 /// Each test is effectively executing as:
25 /// `wasm-tools component targets -w foobar test.wit test.wat`
26 #[test]
27 fn targets() -> Result<()> {
28 drop(env_logger::try_init());
29
30 for entry in fs::read_dir("tests/targets")? {
31 let path = entry?.path();
32 if !path.is_dir() {
33 continue;
34 }
35
36 let test_case = path.file_stem().unwrap().to_str().unwrap();
37 println!("testing {test_case}");
38
39 let (resolve, world) = load_test_wit(&path)?;
40
41 let component = wat::parse_file(path.join("test.wat"))
42 .with_context(|| "failed to parse component WAT".to_string())?;
43
44 match wit_component::targets(&resolve, world, &component) {
45 Ok(_) => {
46 assert!(
47 !test_case.starts_with("error-"),
48 "should have failed targets check"
49 );
50 }
51 Err(e) => {
52 assert!(test_case.starts_with("error-"), "{e:?}");
53 assert_output(&path.join("error.txt"), &format!("{e:#}"))?;
54 }
55 }
56 }
57
58 Ok(())
59 }
60
61 fn assert_output(expected: &Path, actual: &str) -> Result<()> {
62 if std::env::var_os("BLESS").is_some() {
63 fs::create_dir_all(expected.parent().unwrap())?;
64 fs::write(expected, actual).with_context(|| format!("failed to write {expected:?}"))?;
65 } else {
66 assert_eq!(
67 fs::read_to_string(expected)
68 .with_context(|| format!("failed to read {expected:?}"))?
69 .replace("\r\n", "\n"),
70 actual,
71 "expectation `{}` did not match actual",
72 expected.display(),
73 );
74 }
75 Ok(())
76 }
77
78 fn load_test_wit(path: &Path) -> Result<(Resolve, WorldId)> {
79 const TEST_TARGET_WORLD_ID: &str = "foobar";
80
81 let test_wit_path = path.join("test.wit");
82 let mut resolve = Resolve::default();
83 let pkg = resolve.push_file(&test_wit_path)?;
84 let world_id = resolve
85 .select_world(&[pkg], Some(TEST_TARGET_WORLD_ID))
86 .with_context(|| "failed to select world from package".to_string())?;
87
88 Ok((resolve, world_id))
89 }