use serde_fjson::{Document, Options, parse_with, stringify_with, syntax}; use serde_json::json; fn nested_arrays(depth: usize) -> String { format!("{}0{}", "[".repeat(depth), "]".repeat(depth)) } #[test] fn custom_limits_control_parsing() { let source = nested_arrays(4); parse_with(&source, &Options::new().with_max_depth(3)).unwrap(); let error = parse_with(&source, &Options::new().with_max_depth(2)).unwrap_err(); assert_eq!(error.kind, serde_fjson::ErrorKind::Nesting); assert!(error.message.contains("2 levels"), "{error}"); } #[test] fn custom_limits_control_printing_and_agree_with_parsing() { let mut value = json!(null); for _ in 0..6 { value = json!([value]); } let options = Options::new().with_max_depth(6); let text = stringify_with(&value, &options).unwrap(); assert_eq!(parse_with(&text, &options).unwrap(), value); let tight = Options::new().with_max_depth(4); assert_eq!( stringify_with(&value, &tight).unwrap_err().kind, serde_fjson::ErrorKind::Nesting ); assert!(parse_with(&text, &tight).is_err()); } #[test] fn syntax_parsers_accept_custom_limits() { let source = format!("value: {}", nested_arrays(4)); syntax::parse_object_with(&source, &Options::new().with_max_depth(5)).unwrap(); syntax::parse_object_with(&source, &Options::new().with_max_depth(3)).unwrap_err(); syntax::parse_with(&source, &Options::new().with_max_depth(5)).unwrap(); } #[test] fn documents_remember_their_options_for_later_edits() { let options = Options::new().with_max_depth(10); let mut document = Document::parse_with("value: [[[0]]]", &options).unwrap(); assert_eq!(document.options(), options); let mut deep = json!(null); for _ in 0..10 { deep = json!([deep]); } document.set(&["value".into()], &deep).unwrap(); assert_eq!(document.to_value().unwrap(), json!({"value": deep})); } #[test] fn defaults_reject_what_custom_options_allow() { assert_eq!(Options::default().max_depth, Options::DEFAULT_MAX_DEPTH); let source = nested_arrays(Options::DEFAULT_MAX_DEPTH + 2); assert!(syntax::parse(&source).is_err()); syntax::parse_with( &source, &Options::new().with_max_depth(Options::DEFAULT_MAX_DEPTH + 1), ) .unwrap(); }