File: mod.rs

package info (click to toggle)
rust-schemars 0.8.22-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,324 kB
  • sloc: makefile: 2
file content (42 lines) | stat: -rw-r--r-- 1,404 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use pretty_assertions::assert_eq;
use schemars::{r#gen::SchemaSettings, schema::RootSchema, schema_for, JsonSchema};
use std::error::Error;
use std::fs;

pub type TestResult = Result<(), Box<dyn Error>>;

#[allow(dead_code)] // https://github.com/rust-lang/rust/issues/46379
pub fn test_generated_schema<T: JsonSchema>(file: &str, settings: SchemaSettings) -> TestResult {
    let actual = settings.into_generator().into_root_schema_for::<T>();
    test_schema(&actual, file)
}

#[allow(dead_code)] // https://github.com/rust-lang/rust/issues/46379
pub fn test_default_generated_schema<T: JsonSchema>(file: &str) -> TestResult {
    let actual = schema_for!(T);
    test_schema(&actual, file)
}

pub fn test_schema(actual: &RootSchema, file: &str) -> TestResult {
    let expected_json = match fs::read_to_string(format!("tests/expected/{}.json", file)) {
        Ok(j) => j,
        Err(e) => {
            write_actual_to_file(actual, file)?;
            return Err(Box::from(e));
        }
    };
    let expected = &serde_json::from_str(&expected_json)?;

    if actual != expected {
        write_actual_to_file(actual, file)?;
    }

    assert_eq!(expected, actual);
    Ok(())
}

fn write_actual_to_file(schema: &RootSchema, file: &str) -> TestResult {
    let actual_json = serde_json::to_string_pretty(&schema)?;
    fs::write(format!("tests/actual/{}.json", file), actual_json)?;
    Ok(())
}