Skip to content

Commit

Permalink
test: add test to validate examples (from spec) and generated samples…
Browse files Browse the repository at this point in the history
… (arbitraries) against jsonschema

Signed-off-by: David Bernard <david.bernard.31@gmail.com>
  • Loading branch information
davidB committed Jan 28, 2024
1 parent 6beae16 commit c54dad8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions cdevents-sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ time = { version = "0.3", features = ["serde-human-readable"] }

[dev-dependencies]
assert-json-diff = "2.0"
boon = "0.5"
proptest = "1"
rstest = "0.18"

Expand Down
39 changes: 39 additions & 0 deletions cdevents-sdk/tests/specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use cdevents_sdk::CDEvent;
use rstest::rstest;
use std::fs;
use std::path::PathBuf;
use proptest::prelude::*;
use boon::{Schemas, Compiler};

#[rstest]
fn for_each_example(#[files("../cdevents-spec/examples/*.json")] path: PathBuf) {
Expand All @@ -27,3 +29,40 @@ fn for_each_example(#[files("../cdevents-spec/examples/*.json")] path: PathBuf)
dbg!(&cdevent_json);
assert_json_eq!(example_json, cdevent_json);
}

fn check_against_schema(json: &serde_json::Value, ty: &str) {
let (subject, predicate) = cdevents_sdk::extract_subject_predicate(ty).expect("valid type: {ty}");
let schemapath = format!("../cdevents-spec/schemas/{subject}{predicate}.json");
//TODO optimize to not recompile a previously read schema
let mut schemas = Schemas::new();
let mut compiler = Compiler::new();
let sch_index = compiler.compile(&schemapath, &mut schemas);
if let Err(err) = sch_index {
assert!(false, "{err:#}");
return; // to allow sch_index.unwrap()
}
let sch_index = sch_index.unwrap();
let result = schemas.validate(&json, sch_index);
if let Err(err) = result {
assert!(false, "{err}");
return;
}
}

#[rstest]
fn validate_example_against_schema(#[files("../cdevents-spec/examples/*.json")] path: PathBuf) {
let example_txt = fs::read_to_string(path).expect("to read file as string");
let example_json: serde_json::Value =
serde_json::from_str(&example_txt).expect("to parse as json");
let ty = example_json["context"]["type"].as_str().expect("valid context.type in json");
check_against_schema(&example_json, ty);
}

proptest! {
#[test]
#[cfg(feature = "testkit")]
fn arbitraries_check_jsonschema(s in any::<CDEvent>()) {
let json = serde_json::to_value(&s).unwrap();
check_against_schema(&json, s.ty());
}
}

0 comments on commit c54dad8

Please sign in to comment.