Skip to content

Commit

Permalink
fix #139 in json validator
Browse files Browse the repository at this point in the history
  • Loading branch information
anweiss committed Oct 4, 2022
1 parent 16e5938 commit 3b4479e
Showing 1 changed file with 66 additions and 17 deletions.
83 changes: 66 additions & 17 deletions src/validator/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1897,8 +1897,38 @@ impl<'a> Visitor<'a, Error> for JSONValidator<'a> {
Ok(())
}
Value::Array(_) => self.validate_array_items(&ArrayItemToken::Identifier(ident)),
Value::Object(o) => {
if let Some(occur) = &self.occurrence {
Value::Object(o) => match &self.occurrence {
#[cfg(feature = "ast-span")]
Some(Occur::Optional(_)) | None => {
if token::lookup_ident(ident.ident)
.in_standard_prelude()
.is_some()
{
self.add_error(format!(
"expected object value of type {}, got object",
ident.ident
));
return Ok(());
}

self.visit_value(&token::Value::TEXT(ident.ident.into()))
}
#[cfg(not(feature = "ast-span"))]
Some(Occur::Optional) | None => {
if token::lookup_ident(ident.ident)
.in_standard_prelude()
.is_some()
{
self.add_error(format!(
"expected object value of type {}, got object",
ident.ident
));
return Ok(());
}

self.visit_value(&token::Value::TEXT(ident.ident.into()))
}
Some(occur) => {
if is_ident_string_data_type(self.cddl, ident) {
let values_to_validate = o
.iter()
Expand Down Expand Up @@ -2026,22 +2056,9 @@ impl<'a> Visitor<'a, Error> for JSONValidator<'a> {
}
}

return Ok(());
}

if token::lookup_ident(ident.ident)
.in_standard_prelude()
.is_some()
{
self.add_error(format!(
"expected object value of type {}, got object",
ident.ident
));
return Ok(());
Ok(())
}

self.visit_value(&token::Value::TEXT(ident.ident.into()))
}
},
_ => {
if let Some(cut_value) = self.cut_value.take() {
self.add_error(format!(
Expand Down Expand Up @@ -2727,4 +2744,36 @@ mod tests {

Ok(())
}

#[test]
fn validate_optional_occurrences_in_object() -> std::result::Result<(), Box<dyn std::error::Error>>
{
let cddl = indoc!(
r#"
argument = {
name: text,
? valid: "yes" / "no",
}
"#
);

let json = r#"{
"name": "foo",
"valid": "no"
}"#;

let cddl = cddl_from_str(cddl, true).map_err(json::Error::CDDLParsing);
if let Err(e) = &cddl {
println!("{}", e);
}

let json = serde_json::from_str::<serde_json::Value>(json).map_err(json::Error::JSONParsing)?;

let cddl = cddl.unwrap();

let mut jv = JSONValidator::new(&cddl, json, None);
jv.validate().unwrap();

Ok(())
}
}

0 comments on commit 3b4479e

Please sign in to comment.