Debian Codegraph @

crates/wasm-compose/tests/compose.rs

raw
1 use anyhow::{Context, Result, bail};
2 use pretty_assertions::assert_eq;
3 use std::fs;
4 use std::io;
5 use wasm_compose::{composer::ComponentComposer, config::Config};
6 use wasmparser::{Validator, WasmFeatures};
7
8 /// Tests the composing of components.
9 ///
10 /// This test looks in the `compositions/` directory for test cases.
11 ///
12 /// The expected input files for a test case are:
13 /// * [required] `root.wat` - the root component being composed.
14 /// * [optional] `config.yml` - contains the composition configuration.
15 /// * [optional] `*.wat` - represents a component imported for the composition.
16 ///
17 /// And the output files are one of the following:
18 ///
19 /// * `composed.wat` - the composed component if the composition is expected to succeed.
20 /// * `error.txt` - the expected error message if the composition is expected to fail.
21 ///
22 /// The test composes a component based on the input files. If the encoding succeeds,
23 /// it expects the output to match `composed.wat`. If the encoding fails, it expects
24 /// the output to match `error.txt`.
25 ///
26 /// Run the test with the environment variable `BLESS` set to update
27 /// either `composed.wat` or `error.txt` depending on the outcome of the composition.
28 #[test]
29 fn component_composing() -> Result<()> {
30 for entry in fs::read_dir("tests/compositions")? {
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!("================ {test_case:30} ===============");
38 let root_path = path.join("root.wat");
39 let output_path = path.join("composed.wat");
40 let error_path = path.join("error.txt");
41 let config_path = path.join("config.yml");
42 let config = if config_path.is_file() {
43 Config::from_file(config_path)?
44 } else {
45 Config {
46 dir: path.clone(),
47 ..Default::default()
48 }
49 };
50 let composer = ComponentComposer::new(&root_path, &config);
51
52 let r = composer.compose();
53 let (output, baseline_path) = if error_path.is_file() {
54 match r {
55 Ok(_) => bail!("composition should fail for test case `{}`", test_case),
56 Err(e) => {
57 let mut err = format!("{e}");
58 let causes = e.chain();
59 let ncauses = causes.len();
60 if ncauses > 1 {
61 err.push_str("\n\nCaused by:");
62 }
63 for (i, cause) in causes.skip(1).enumerate() {
64 err.push_str("\n ");
65 if ncauses > 2 {
66 err.push_str(&format!("{i}: "))
67 }
68 match cause.downcast_ref::<io::Error>() {
69 Some(_) => {
70 err.push_str("platform-specific error");
71 }
72 None => {
73 err.push_str(&cause.to_string());
74 }
75 }
76 }
77 err.push_str("\n");
78 (err.replace('\\', "/"), &error_path)
79 }
80 }
81 } else {
82 let bytes =
83 r.with_context(|| format!("failed to encode for test case `{test_case}`"))?;
84
85 Validator::new_with_features(WasmFeatures::default() | WasmFeatures::COMPONENT_MODEL)
86 .validate_all(&bytes)
87 .with_context(|| {
88 format!("failed to validate component bytes for test case `{test_case}`")
89 })?;
90
91 wit_component::decode(&bytes).with_context(|| {
92 format!("failed to decode WIT from component bytes for test case `{test_case}`")
93 })?;
94
95 (
96 wasmprinter::print_bytes(&bytes).with_context(|| {
97 format!("failed to print component bytes for test case `{test_case}`")
98 })?,
99 &output_path,
100 )
101 };
102
103 if std::env::var_os("BLESS").is_some() {
104 fs::write(baseline_path, output)?;
105 } else {
106 assert_eq!(
107 fs::read_to_string(baseline_path)
108 .with_context(|| format!(
109 "failed to read component baseline `{}`",
110 baseline_path.display()
111 ))?
112 .replace("\r\n", "\n"),
113 output,
114 "failed baseline comparison for test case `{}` ({})",
115 test_case,
116 baseline_path.display(),
117 );
118 }
119 }
120
121 Ok(())
122 }