Skip to main content

oicana_testing/
execution.rs

1use std::{
2    fs::{self, File},
3    io,
4    path::{Path, PathBuf},
5};
6
7use image::{GenericImageView, ImageError};
8use json_schema_ast::SchemaDocument;
9use json_schema_fuzz::{GenerationConfig, ValueGenerator};
10use log::{debug, error};
11use oicana::{CompileError, Template, TemplateInitializationError};
12use oicana_export::pdf::export_pdf;
13use oicana_export::png::{export_png, PngExportError};
14use oicana_files::native::{package_data_dir, NativeTemplate};
15use oicana_input::{InputDefinition, JsonInput, TemplateInputs};
16use oicana_template::manifest::TemplateManifest;
17use oicana_world::diagnostics::DiagnosticColor;
18use oicana_world::fonts::FontSource;
19use oicana_world::CompiledDocument;
20use oxipng::PngError;
21use thiserror::Error;
22
23use crate::{Snapshot, SnapshotMode, Test};
24
25/// Context for test runners
26pub struct TestRunnerContext {
27    packages: PathBuf,
28    fonts: Vec<FontSource>,
29}
30
31impl TestRunnerContext {
32    /// Create a new test runner
33    pub fn new() -> Result<Self, CreateTestRunnerError> {
34        Self::with_fonts(vec![])
35    }
36
37    /// Create a new test runner with additional fonts.
38    ///
39    /// The fonts are available to every template the context runs, mirroring a
40    /// host that registers them at runtime.
41    pub fn with_fonts(fonts: Vec<FontSource>) -> Result<Self, CreateTestRunnerError> {
42        let packages = package_data_dir().ok_or(CreateTestRunnerError::NoPackageDirectory)?;
43
44        Ok(TestRunnerContext { packages, fonts })
45    }
46
47    /// Prepare a runner for the template at the given path
48    pub fn get_runner(
49        &self,
50        path: &Path,
51        manifest: &TemplateManifest,
52    ) -> Result<TestRunner, TemplateInitializationError> {
53        Ok(TestRunner {
54            instance: Template::<NativeTemplate>::from_with_fonts(
55                path,
56                &self.packages,
57                manifest.clone(),
58                &self.fonts,
59            )?,
60            template_path: path.to_path_buf(),
61        })
62    }
63}
64
65/// Execution context for tests of a single template
66pub struct TestRunner {
67    instance: Template<NativeTemplate>,
68    template_path: PathBuf,
69}
70
71impl TestRunner {
72    /// Configure the coloring of diagnostic output from this template.
73    pub fn set_diagnostic_color(&mut self, color: DiagnosticColor) {
74        self.instance.set_diagnostic_color(color);
75    }
76
77    /// Reset file access tracking for the next compilation cycle.
78    ///
79    /// This clears the accessed flags on file slots but preserves cached data
80    /// and fingerprints, enabling efficient incremental recompilation.
81    pub fn reset(&mut self) {
82        self.instance.reset();
83    }
84
85    /// Return system paths of all files accessed during test compilations.
86    pub fn dependencies(&self) -> Vec<PathBuf> {
87        self.instance.dependencies()
88    }
89
90    /// Run the test case
91    pub fn run(&mut self, test: Test) -> Result<Vec<String>, TestExecutionError> {
92        if let Some(fuzzed_input) = test.fuzzed_inputs {
93            let fuzzed_json_input = self
94                .instance
95                .manifest()
96                .tool
97                .oicana
98                .inputs
99                .iter()
100                .filter_map(|input| {
101                    let InputDefinition::Json(json) = input else {
102                        return None;
103                    };
104                    Some(json)
105                })
106                .find(|input| input.key == fuzzed_input.key);
107            let Some(fuzzed_json_input) = fuzzed_json_input else {
108                return Err(TestExecutionError::FuzzingSetup(format!(
109                    "Fuzzed input '{}' has no input definition in the manifest!",
110                    fuzzed_input.key
111                )));
112            };
113            let Some(schema_path) = fuzzed_json_input.schema.clone() else {
114                return Err(TestExecutionError::FuzzingSetup(format!(
115                    "Fuzzed json input '{}' has no schema configured in the manifest!",
116                    fuzzed_input.key
117                )));
118            };
119            let schema = {
120                let schema_file = match File::open(self.template_path.join(&schema_path)) {
121                    Ok(file) => file,
122                    Err(error) => {
123                        return Err(TestExecutionError::FuzzingSetup(format!(
124                            "Failed to open schema file '{}': {}",
125                            schema_path, error
126                        )));
127                    }
128                };
129                let schema = match serde_json::from_reader(schema_file) {
130                    Ok(schema) => schema,
131                    Err(error) => {
132                        return Err(TestExecutionError::FuzzingSetup(format!(
133                            "Failed to parse schema file '{}': {}",
134                            schema_path, error
135                        )));
136                    }
137                };
138                match SchemaDocument::from_json(&schema) {
139                    Ok(schema) => schema,
140                    Err(error) => {
141                        return Err(TestExecutionError::FuzzingSetup(format!(
142                            "Failed to build schema '{}': {}",
143                            schema_path, error
144                        )));
145                    }
146                }
147            };
148
149            let mut rng = rand::rng();
150            let config = GenerationConfig::new(u8::MAX);
151
152            return (0..fuzzed_input.samples)
153                .map(|_| {
154                    let value =
155                        ValueGenerator::generate(&schema, config, &mut rng).map_err(|error| {
156                            TestExecutionError::FuzzingSetup(format!(
157                                "Failed to generate a value for '{}' from schema '{}': {}",
158                                fuzzed_input.key, schema_path, error
159                            ))
160                        })?;
161                    let mut inputs = test.inputs.clone();
162                    inputs.with_input(JsonInput::new(fuzzed_input.key.clone(), value.to_string()));
163                    debug!("Fuzzing the input '{}' with {}", fuzzed_input.key, value);
164
165                    self.run_with_inputs(inputs, &test.snapshot, test.pdf)
166                        .map_err(|error| TestExecutionError::FuzzedInput {
167                            key: fuzzed_input.key.clone(),
168                            value: value.to_string(),
169                            error: Box::new(error),
170                        })
171                })
172                .map(|res| res.map(|vec| vec.into_iter()))
173                .collect::<Result<Vec<_>, _>>()
174                .map(|iterators| iterators.into_iter().flatten().collect());
175        }
176
177        self.run_with_inputs(test.inputs, &test.snapshot, test.pdf)
178    }
179
180    fn run_with_inputs(
181        &mut self,
182        inputs: TemplateInputs,
183        snapshot: &Snapshot,
184        pdf: bool,
185    ) -> Result<Vec<String>, TestExecutionError> {
186        let CompiledDocument { document, warnings } = self.instance.compile(inputs)?;
187        let mut warnings: Vec<String> = warnings
188            .into_iter()
189            .map(|warning| warning.formatted)
190            .collect();
191
192        if pdf {
193            let standards = self.instance.manifest().pdf_standards().to_vec();
194            let tagged = self.instance.manifest().pdf_tagged();
195            export_pdf(&document, &self.instance, &standards, tagged, None).map_err(
196                |diagnostics| TestExecutionError::PdfExport {
197                    standards: standards
198                        .iter()
199                        .map(|standard| standard.to_string())
200                        .collect::<Vec<_>>()
201                        .join(", "),
202                    diagnostics: diagnostics.to_string(),
203                },
204            )?;
205        }
206
207        let image = export_png(&document, 1., None)?;
208        match snapshot {
209            Snapshot::Missing(path, mode) => match mode {
210                SnapshotMode::Update => {
211                    warnings.push(format!(
212                        "Writing snapshot file at {path:?}, because it was missing"
213                    ));
214                    fs::write(path, optimize_png(&image)?)?;
215                }
216                SnapshotMode::Compare => {
217                    return Err(TestExecutionError::SnapshotMissing(path.clone()))
218                }
219            },
220            Snapshot::Some(path, mode) => {
221                if !compare_images(path, &image, 1)? {
222                    let mut compare_path = path.clone();
223                    if let Some(stem) = compare_path.file_stem() {
224                        let mut new_name = stem.to_os_string();
225                        match mode {
226                            SnapshotMode::Compare => {
227                                new_name.push(".compare.png");
228                            }
229                            SnapshotMode::Update => {
230                                new_name.push(".png");
231                                warnings.push(format!("Overwriting snapshot file at '{path:?}'."));
232                            }
233                        }
234                        compare_path.set_file_name(new_name);
235                        fs::write(compare_path, optimize_png(&image)?)?;
236                    } else {
237                        error!("Snapshot file had no file stem!");
238                    }
239                    if matches!(mode, SnapshotMode::Compare) {
240                        return Err(TestExecutionError::SnapshotMismatch(path.clone()));
241                    }
242                }
243            }
244            Snapshot::None => (),
245        }
246
247        Ok(warnings)
248    }
249}
250
251/// Losslessly recompress a PNG byte buffer at oxipng's strongest preset before
252/// it lands on disk as a snapshot.
253fn optimize_png(image: &[u8]) -> Result<Vec<u8>, PngError> {
254    oxipng::optimize_from_memory(image, &oxipng::Options::max_compression())
255}
256
257/// Compare the image file at `path` with the given data. If there is a pixel value with a higher difference
258/// than `tolerance`, return `false`.
259pub fn compare_images(path: &Path, data: &[u8], tolerance: u8) -> Result<bool, ImageError> {
260    let img1 = image::open(path)?;
261    let img2 = image::load_from_memory(data)?;
262
263    if img1.dimensions() != img2.dimensions() {
264        return Ok(false);
265    }
266
267    let pixels1 = img1.pixels();
268    let pixels2 = img2.pixels();
269
270    for ((_, _, p1), (_, _, p2)) in pixels1.zip(pixels2) {
271        let diff =
272            p1.0.iter()
273                .zip(p2.0.iter())
274                .map(|(a, b)| (*a as i16 - *b as i16).unsigned_abs() as u8)
275                .max()
276                .unwrap_or(0);
277
278        if diff > tolerance {
279            return Ok(false);
280        }
281    }
282
283    Ok(true)
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use crate::{Snapshot, Test};
290    use std::fs;
291    use tempfile::{tempdir, TempDir};
292
293    /// Write a template that enforces PDF/UA-1 and renders the given body.
294    fn ua_1_template(body: &str) -> TempDir {
295        let dir = tempdir().unwrap();
296        fs::write(
297            dir.path().join("typst.toml"),
298            r#"
299            [package]
300            name = "ua-1-template"
301            version = "0.1.0"
302            entrypoint = "main.typ"
303
304            [tool.oicana]
305            manifest_version = 1
306
307            [tool.oicana.export.pdf]
308            standards = ["ua-1"]
309            "#,
310        )
311        .unwrap();
312        fs::write(dir.path().join("main.typ"), body).unwrap();
313
314        dir
315    }
316
317    fn run_template(dir: &TempDir, pdf: bool) -> Result<Vec<String>, TestExecutionError> {
318        let manifest_content = fs::read_to_string(dir.path().join("typst.toml")).unwrap();
319        let manifest = TemplateManifest::from_toml(&manifest_content).unwrap();
320        let mut runner = TestRunnerContext::new()
321            .unwrap()
322            .get_runner(dir.path(), &manifest)
323            .unwrap();
324
325        runner.run(Test {
326            inputs: TemplateInputs::new(),
327            fuzzed_inputs: None,
328            name: "pdf-standards".to_owned(),
329            snapshot: Snapshot::None,
330            pdf,
331            collection: dir.path().to_path_buf(),
332            descriptor: "pdf-standards".to_owned(),
333        })
334    }
335
336    #[test]
337    fn fails_for_document_violating_the_pdf_standard() {
338        let dir = ua_1_template("Hello");
339
340        let error = run_template(&dir, true).unwrap_err();
341
342        // PDF/UA-1 requires a document title.
343        assert!(
344            matches!(error, TestExecutionError::PdfExport { ref standards, .. } if standards == "ua-1"),
345            "Unexpected error: {error}"
346        );
347    }
348
349    #[test]
350    fn passes_for_document_conforming_to_the_pdf_standard() {
351        let dir = ua_1_template("#set document(title: \"Accessible\")\nHello");
352
353        run_template(&dir, true).expect("Test should pass for a conforming document");
354    }
355
356    #[test]
357    fn skips_pdf_export_when_disabled() {
358        let dir = ua_1_template("Hello");
359
360        run_template(&dir, false).expect("Test should pass when the PDF export is disabled");
361    }
362
363    #[test]
364    fn names_the_fuzzed_value_of_a_failing_sample() {
365        let dir = tempdir().unwrap();
366        fs::write(
367            dir.path().join("typst.toml"),
368            r#"
369            [package]
370            name = "fuzzed"
371            version = "0.1.0"
372            entrypoint = "main.typ"
373
374            [tool.oicana]
375            manifest_version = 1
376
377            [[tool.oicana.inputs]]
378            type = "json"
379            key = "data"
380            schema = "data.schema.json"
381            "#,
382        )
383        .unwrap();
384        fs::write(
385            dir.path().join("data.schema.json"),
386            r#"{"type": "boolean"}"#,
387        )
388        .unwrap();
389        fs::write(dir.path().join("main.typ"), "#panic(\"always fails\")").unwrap();
390        let manifest_content = fs::read_to_string(dir.path().join("typst.toml")).unwrap();
391        let manifest = TemplateManifest::from_toml(&manifest_content).unwrap();
392        let mut runner = TestRunnerContext::new()
393            .unwrap()
394            .get_runner(dir.path(), &manifest)
395            .unwrap();
396
397        let error = runner
398            .run(Test {
399                inputs: TemplateInputs::new(),
400                fuzzed_inputs: Some(crate::FuzzJson {
401                    samples: 1,
402                    key: "data".to_owned(),
403                }),
404                name: "fuzzed".to_owned(),
405                snapshot: Snapshot::None,
406                pdf: false,
407                collection: dir.path().to_path_buf(),
408                descriptor: "fuzzed".to_owned(),
409            })
410            .unwrap_err();
411
412        let TestExecutionError::FuzzedInput {
413            ref key, ref value, ..
414        } = error
415        else {
416            panic!("Unexpected error: {error}");
417        };
418        assert_eq!(key, "data");
419        assert!(value == "true" || value == "false", "{value}");
420        let message = error.to_string();
421        assert!(message.contains("always fails"), "{message}");
422        assert!(
423            message.contains(&format!("The fuzzed input 'data' had the value: {value}")),
424            "{message}"
425        );
426    }
427}
428
429/// Errors that can be produced when executing tests
430#[derive(Debug, Error)]
431pub enum CreateTestRunnerError {
432    /// Could not get the local Typst package directory
433    #[error("Failed to get Typst package directory.")]
434    NoPackageDirectory,
435}
436
437/// Errors that can be produced when executing tests
438#[derive(Debug, Error)]
439pub enum TestExecutionError {
440    /// A test failed to compile or validate
441    #[error("{0}")]
442    CompileError(#[from] CompileError),
443    /// Failed to export png image
444    #[error("{0}")]
445    ExportError(#[from] PngExportError),
446    /// The document does not conform to the PDF standards of the template manifest
447    #[error("Failed to export PDF for the standards '{standards}' configured in the template manifest:\n{diagnostics}")]
448    PdfExport {
449        /// The PDF standards that the export was attempted with
450        standards: String,
451        /// Diagnostics of the failed export
452        diagnostics: String,
453    },
454    /// The test failed for a generated value of a fuzzed input
455    #[error("{error}\nThe fuzzed input '{key}' had the value: {value}")]
456    FuzzedInput {
457        /// The key of the fuzzed input
458        key: String,
459        /// The generated JSON value
460        value: String,
461        /// Why the test failed
462        error: Box<TestExecutionError>,
463    },
464    /// Failure during fuzzing setup
465    #[error("{0}")]
466    FuzzingSetup(String),
467    /// Failed to write or read snapshot image
468    #[error("Failed to write or read snapshot image: {0}")]
469    Io(#[from] io::Error),
470    /// Failed to compare the snapshot
471    #[error("Failed to compare the snapshot: {0}")]
472    Comparison(#[from] ImageError),
473    /// Failed to optimize the snapshot PNG bytes before writing
474    #[error("Failed to optimize snapshot PNG: {0}")]
475    PngOptimization(#[from] PngError),
476    /// The snapshot does not match the result. Rerun with `--update`/`-u` to update it.
477    #[error("The snapshot '{0}' does not match the result. Rerun with --update/-u to update it.")]
478    SnapshotMismatch(PathBuf),
479    /// The snapshot file is missing. Rerun with `--update`/`-u` to create it.
480    #[error("The snapshot file '{0}' is missing. Rerun with --update/-u to create it.")]
481    SnapshotMissing(PathBuf),
482}