From 039175d3758e9203b70e0db1bf250c3fd34879e9 Mon Sep 17 00:00:00 2001 From: Adam Leventhal Date: Sat, 21 Oct 2023 01:19:33 -0700 Subject: [PATCH] handle null enumerated values properly (#83) --- CHANGELOG.md | 4 ++++ src/schema.rs | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 328e6aa..dd4974f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 2.0.0-rc.1 (2023-10-21) + +- Fix handling of null values in `enum` for string, number, integer, and boolean + ## 2.0.0-rc.0 (2023-10-21) - Bump `indexmap` dependency to 2.0.0 diff --git a/src/schema.rs b/src/schema.rs index e8a4899..20a3198 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -563,7 +563,7 @@ where F: Fn(&serde_json::Value) -> bool, { match enumeration { - Some(values) => values.iter().all(check), + Some(values) => values.iter().all(|value| value.is_null() || check(value)), None => true, } } @@ -796,7 +796,9 @@ impl FromStr for StringFormat { mod tests { use serde_json::json; - use crate::{AnySchema, Schema, SchemaData, SchemaKind}; + use crate::{ + AnySchema, Schema, SchemaData, SchemaKind, StringType, Type, VariantOrUnknownOrEmpty, + }; #[test] fn test_schema_with_extensions() { @@ -890,4 +892,31 @@ mod tests { _ => panic!("incorrect kind {:#?}", schema), } } + + #[test] + fn test_enum_with_null() { + let value = json! { + { + "type": "string", + "nullable": true, + "enum": [ null, "howdy" ] + } + }; + + let schema = serde_json::from_value::(value).unwrap(); + assert!(schema.schema_data.nullable); + + match schema.schema_kind { + SchemaKind::Type(Type::String(StringType { + format: VariantOrUnknownOrEmpty::Empty, + pattern: None, + enumeration, + min_length: None, + max_length: None, + })) => { + assert_eq!(enumeration, vec![None, Some("howdy".to_string())]); + } + _ => panic!("incorrect kind {:#?}", schema), + } + } }