1 //! The JSON contract: strict in, compact and stable out.2 //!3 //! These tests define the API. The implementation must satisfy them without a4 //! change to this file.5 6 use inf3r_json::{JsonError, MAX_DEPTH, Value, encode, parse, parse_bytes, to_string};7 8 fn err(text: &str) -> JsonError {9 parse(text).expect_err("the text is not JSON")10 }11 12 /// A catalogue-shaped document, deep enough to exercise the reader.13 fn nested() -> Value {14 parse(15 r#"{16 "v": 1,17 "max_inflight": 8,18 "target": {"id": "gpu", "backend": "cuda", "arch": ["sm00"],19 "devices": 2, "vram_mb": [1024, 1024]},20 "models": [21 {"serve": "example", "alias_of": null,22 "capabilities": {"chat": {"vocab": "chat.v1",23 "parts": ["text", "image"],24 "channels": ["text", "tokens", "progress"]}}}25 ],26 "ratio": 0.75,27 "ok": true28 }"#,29 )30 .unwrap()31 }32 33 #[test]34 fn a_nested_document_round_trips() {35 let value = nested();36 let text = to_string(&value);37 assert_eq!(parse(&text).unwrap(), value);38 assert_eq!(to_string(&parse(&text).unwrap()), text);39 assert!(!text.contains('\n'));40 assert!(!text.contains(" "));41 42 let mut out = String::new();43 encode(&value, &mut out);44 assert_eq!(out, text);45 }46 47 #[test]48 fn the_catalogue_shape_reads_with_the_accessors() {49 let value = nested();50 assert_eq!(value.get("v").and_then(Value::as_i64), Some(1));51 assert_eq!(value.get("ok").and_then(Value::as_bool), Some(true));52 assert_eq!(value.get("ratio").and_then(Value::as_f64), Some(0.75));53 assert_eq!(54 value55 .get("models")56 .and_then(Value::as_array)57 .and_then(|a| a.first())58 .and_then(|m| m.get("alias_of")),59 Some(&Value::Null)60 );61 assert_eq!(62 value63 .get("models")64 .and_then(Value::as_array)65 .and_then(|a| a.first())66 .and_then(|m| m.get("serve"))67 .and_then(Value::as_str),68 Some("example")69 );70 assert_eq!(71 value72 .get("target")73 .and_then(|t| t.get("vram_mb"))74 .and_then(Value::as_array)75 .map(|a| a.len()),76 Some(2)77 );78 assert_eq!(value.get("absent"), None);79 assert_eq!(Value::int(1).get("k"), None);80 }81 82 #[test]83 fn empty_containers_read_and_write() {84 assert_eq!(parse("[]").unwrap(), Value::Array(Vec::new()));85 assert_eq!(parse("{}").unwrap(), Value::object().build());86 assert_eq!(parse("[ ]").unwrap(), Value::Array(Vec::new()));87 assert_eq!(to_string(&parse("[]").unwrap()), "[]");88 assert_eq!(to_string(&parse("{}").unwrap()), "{}");89 assert_eq!(to_string(&Value::object().build()), "{}");90 assert_eq!(91 to_string(&Value::Array(vec![Value::Array(Vec::new())])),92 "[[]]"93 );94 }95 96 #[test]97 fn every_escape_reads_and_writes() {98 let value = parse(r#""\b\f\n\r\t\/\\\"\u0041\u0000""#).unwrap();99 assert_eq!(value.as_str(), Some("\u{8}\u{c}\n\r\t/\\\"A\u{0}"));100 assert_eq!(to_string(&value), r#""\b\f\n\r\t/\\\"A\u0000""#);101 assert_eq!(parse(&to_string(&value)).unwrap(), value);102 }103 104 #[test]105 fn only_quote_backslash_and_control_characters_are_escaped() {106 assert_eq!(to_string(&Value::str("café 😀 / ✓")), "\"café 😀 / ✓\"");107 assert_eq!(to_string(&Value::str("\u{7f}")), "\"\u{7f}\"");108 assert_eq!(to_string(&Value::str("\u{1}\u{1f}")), r#""\u0001\u001f""#);109 assert_eq!(to_string(&Value::str("a\nb")), "\"a\\nb\"");110 assert_eq!(to_string(&Value::str("")), "\"\"");111 }112 113 #[test]114 fn a_surrogate_pair_becomes_one_character() {115 let pair = parse(r#""\ud83d\ude00""#).unwrap();116 assert_eq!(pair.as_str(), Some("😀"));117 assert_eq!(to_string(&pair), "\"😀\"");118 assert_eq!(parse("\"😀\"").unwrap(), pair);119 // The same code point as a pair and as one character is one value.120 assert_eq!(pair, parse("\"😀\"").unwrap());121 }122 123 #[test]124 fn a_lone_surrogate_is_refused() {125 for text in [r#""\ud800""#, r#""\udbff""#, r#""\udc00""#, r#""\udfff""#] {126 assert_eq!(err(text), JsonError::Escape { offset: 1 }, "{text}");127 }128 // A high surrogate needs a `\u` after it, and that one needs to be low.129 assert_eq!(err(r#""\ud83dx""#), JsonError::Escape { offset: 1 });130 assert_eq!(err(r#""\ud83dA""#), JsonError::Escape { offset: 1 });131 assert_eq!(err(r#""\ud83d\\x""#), JsonError::Escape { offset: 7 });132 assert_eq!(err(r#""\ud83d\\u0041""#), JsonError::Escape { offset: 7 });133 assert_eq!(err(r#""\ud83d\\ude0""#), JsonError::Escape { offset: 7 });134 assert_eq!(err(r#""\ud83"#), JsonError::Escape { offset: 1 });135 }136 137 #[test]138 fn an_escape_that_json_does_not_define_is_refused() {139 for text in [r#""\x""#, r#""\a""#, r#""\U0041""#, r#""\ ""#] {140 assert_eq!(err(text), JsonError::Escape { offset: 1 }, "{text}");141 }142 assert_eq!(err(r#""\u""#), JsonError::Escape { offset: 1 });143 assert_eq!(err(r#""\u00""#), JsonError::Escape { offset: 1 });144 assert_eq!(err(r#""\uZZ01""#), JsonError::Escape { offset: 1 });145 // A backslash that escapes the closing quote leaves the string open.146 assert_eq!(err(r#""\"#), JsonError::Eof { offset: 2 });147 }148 149 #[test]150 fn a_control_character_written_raw_is_refused() {151 assert_eq!(err("{\"a\tb\": 1}"), JsonError::Control { offset: 3 });152 assert_eq!(err("\"a\u{c}b\""), JsonError::Control { offset: 2 });153 assert_eq!(err("\"a\u{0}b\""), JsonError::Control { offset: 2 });154 // The same character as an escape is fine.155 assert_eq!(parse("\"a\\u0000b\"").unwrap(), Value::str("a\0b"));156 }157 158 #[test]159 fn a_duplicate_key_is_refused() {160 assert_eq!(161 err(r#"{"a": 1, "a": 2}"#),162 JsonError::DuplicateKey {163 offset: 9,164 key: "a".to_string(),165 }166 );167 assert_eq!(168 err(r#"{"serve": "a", "max_inflight": 1, "serve": "b"}"#),169 JsonError::DuplicateKey {170 offset: 34,171 key: "serve".to_string(),172 }173 );174 // The same key in two different objects is not a duplicate.175 assert!(parse(r#"{"a": {"b": 1}, "b": {"b": 2}}"#).is_ok());176 }177 178 #[test]179 fn nesting_is_capped_at_128_levels() {180 assert_eq!(MAX_DEPTH, 128);181 182 let arrays = "[".repeat(MAX_DEPTH) + &"]".repeat(MAX_DEPTH);183 assert!(parse(&arrays).is_ok());184 let too_deep = "[".repeat(MAX_DEPTH + 1) + &"]".repeat(MAX_DEPTH + 1);185 assert_eq!(err(&too_deep), JsonError::Depth { offset: MAX_DEPTH });186 187 let objects = "{\"k\": ".repeat(MAX_DEPTH) + "1" + &"}".repeat(MAX_DEPTH);188 assert!(parse(&objects).is_ok());189 let too_deep = "{\"k\": ".repeat(MAX_DEPTH + 1) + "1" + &"}".repeat(MAX_DEPTH + 1);190 assert!(191 matches!(err(&too_deep), JsonError::Depth { offset: 768 }),192 "{too_deep}"193 );194 }195 196 #[test]197 fn an_integer_too_big_for_i64_becomes_a_float() {198 assert_eq!(parse("9223372036854775807").unwrap(), Value::int(i64::MAX));199 assert_eq!(parse("-9223372036854775808").unwrap(), Value::int(i64::MIN));200 assert_eq!(201 parse("9223372036854775808").unwrap(),202 Value::float(9223372036854775808.0)203 );204 assert_eq!(parse("-99999999999999999999").unwrap(), Value::float(-1e20));205 let value = parse("9223372036854775808").unwrap();206 assert_eq!(parse(&to_string(&value)).unwrap(), value);207 }208 209 #[test]210 fn a_number_that_does_not_fit_f64_is_refused() {211 assert_eq!(err("1e400"), JsonError::Number { offset: 0 });212 assert_eq!(err("-1e400"), JsonError::Number { offset: 0 });213 assert_eq!(err(&"9".repeat(400)), JsonError::Number { offset: 0 });214 // An underflow is still a number, only zero.215 assert_eq!(parse("1e-400"), Ok(Value::float(0.0)));216 assert_eq!(parse("1e308"), Ok(Value::float(1e308)));217 }218 219 #[test]220 fn numbers_read_as_the_type_they_were_written_as() {221 assert_eq!(parse("0"), Ok(Value::int(0)));222 assert_eq!(parse("-0"), Ok(Value::int(0)));223 assert_eq!(parse("42"), Ok(Value::int(42)));224 assert_eq!(parse("-42"), Ok(Value::int(-42)));225 assert_eq!(parse("0.5"), Ok(Value::float(0.5)));226 assert_eq!(parse("-0.5"), Ok(Value::float(-0.5)));227 assert_eq!(parse("1e3"), Ok(Value::float(1000.0)));228 assert_eq!(parse("1E+3"), Ok(Value::float(1000.0)));229 assert_eq!(parse("1e-3"), Ok(Value::float(0.001)));230 assert_eq!(parse("1.5e0"), Ok(Value::float(1.5)));231 assert_eq!(parse("123.0"), Ok(Value::float(123.0)));232 }233 234 #[test]235 fn a_number_grammar_that_rfc_8259_does_not_allow_is_refused() {236 for text in [237 "01", "+1", "- 1", "-", "1.", ".5", "1e", "1e+", "1.2.3", "0x10",238 ] {239 let e = err(text);240 assert!(241 matches!(242 e,243 JsonError::Unexpected { .. } | JsonError::Eof { .. } | JsonError::Trailing { .. }244 ),245 "{text}: {e}"246 );247 }248 assert_eq!(err("1."), JsonError::Eof { offset: 2 });249 assert_eq!(250 err("1.x"),251 JsonError::Unexpected {252 offset: 2,253 byte: b'x'254 }255 );256 assert_eq!(257 err("[1e+]"),258 JsonError::Unexpected {259 offset: 4,260 byte: b']'261 }262 );263 assert_eq!(264 err("- 1"),265 JsonError::Unexpected {266 offset: 1,267 byte: b' '268 }269 );270 }271 272 #[test]273 fn integers_write_without_a_decimal_point() {274 assert_eq!(to_string(&Value::int(0)), "0");275 assert_eq!(to_string(&Value::int(i64::MIN)), "-9223372036854775808");276 assert_eq!(to_string(&Value::int(i64::MAX)), "9223372036854775807");277 assert_eq!(to_string(&Value::float(1.5)), "1.5");278 assert_eq!(to_string(&Value::float(0.001)), "0.001");279 // A whole float writes as an integer, so it reads back as one.280 assert_eq!(to_string(&Value::float(1.0)), "1");281 assert_eq!(282 parse(&to_string(&Value::float(1.0))).unwrap(),283 Value::int(1)284 );285 }286 287 #[test]288 fn a_non_finite_float_writes_as_null() {289 for value in [290 Value::float(f64::INFINITY),291 Value::float(f64::NEG_INFINITY),292 Value::float(f64::NAN),293 ] {294 assert_eq!(to_string(&value), "null");295 }296 }297 298 #[test]299 fn object_keys_are_sorted_and_stable() {300 assert_eq!(301 to_string(&parse(r#"{"b": 1, "a": 2, "c": {"z": 1, "y": 2}}"#).unwrap()),302 r#"{"a":2,"b":1,"c":{"y":2,"z":1}}"#303 );304 // The order the keys arrived in does not reach the bytes.305 let one = Value::object()306 .put("b", Value::int(1))307 .put("a", Value::int(2));308 let other = Value::object()309 .put("a", Value::int(2))310 .put("b", Value::int(1));311 assert_eq!(one.clone().build(), other.clone().build());312 assert_eq!(to_string(&one.build()), to_string(&other.build()));313 assert_eq!(314 to_string(&Value::object().put("k", Value::int(1)).build()),315 r#"{"k":1}"#316 );317 assert_eq!(318 Value::from(Value::object().put("k", Value::int(1))),319 parse(r#"{"k":1}"#).unwrap()320 );321 }322 323 #[test]324 fn a_trailing_comma_is_refused() {325 assert_eq!(326 err("[1, ]"),327 JsonError::Unexpected {328 offset: 4,329 byte: b']'330 }331 );332 assert_eq!(333 err("[,]"),334 JsonError::Unexpected {335 offset: 1,336 byte: b','337 }338 );339 assert_eq!(340 err(r#"{"a": 1, }"#),341 JsonError::Unexpected {342 offset: 9,343 byte: b'}'344 }345 );346 assert_eq!(347 err(r#"{"a": 1,, "b": 2}"#),348 JsonError::Unexpected {349 offset: 8,350 byte: b','351 }352 );353 }354 355 #[test]356 fn a_comment_is_refused() {357 assert_eq!(358 err("// hi"),359 JsonError::Unexpected {360 offset: 0,361 byte: b'/'362 }363 );364 assert_eq!(365 err("/* hi */ 1"),366 JsonError::Unexpected {367 offset: 0,368 byte: b'/'369 }370 );371 assert_eq!(372 err("[1 // two]"),373 JsonError::Unexpected {374 offset: 3,375 byte: b'/'376 }377 );378 assert_eq!(379 err("[1, // two]"),380 JsonError::Unexpected {381 offset: 4,382 byte: b'/'383 }384 );385 assert_eq!(err("1 /* tail */"), JsonError::Trailing { offset: 2 });386 }387 388 #[test]389 fn bytes_after_the_value_are_refused() {390 assert_eq!(err("{} []"), JsonError::Trailing { offset: 3 });391 assert_eq!(err("123 extra"), JsonError::Trailing { offset: 4 });392 assert_eq!(err("nullnull"), JsonError::Trailing { offset: 4 });393 assert_eq!(err("[1] [2]"), JsonError::Trailing { offset: 4 });394 assert_eq!(err("[1] x"), JsonError::Trailing { offset: 4 });395 assert_eq!(err("truex"), JsonError::Trailing { offset: 4 });396 assert_eq!(397 err("trux"),398 JsonError::Unexpected {399 offset: 3,400 byte: b'x'401 }402 );403 assert_eq!(404 err("nulx"),405 JsonError::Unexpected {406 offset: 3,407 byte: b'x'408 }409 );410 assert_eq!(411 err("[falsy]"),412 JsonError::Unexpected {413 offset: 5,414 byte: b'y'415 }416 );417 assert_eq!(err("tru"), JsonError::Eof { offset: 3 });418 assert!(parse("[1] ").is_ok());419 }420 421 #[test]422 fn text_that_is_not_utf_8_is_refused() {423 let mut bytes = b"\"a".to_vec();424 bytes.extend_from_slice(&[0xC3, 0x28, b'"']);425 assert_eq!(parse_bytes(&bytes), Err(JsonError::Utf8 { offset: 2 }));426 427 let mut bytes = b"{\"k\": \"".to_vec();428 bytes.extend_from_slice(&[0xE2, 0xA9]);429 assert_eq!(parse_bytes(&bytes), Err(JsonError::Utf8 { offset: 7 }));430 431 assert_eq!(parse_bytes(b"null"), Ok(Value::Null));432 assert_eq!(433 parse_bytes("\"😀\"".as_bytes()).unwrap().as_str(),434 Some("😀")435 );436 }437 438 #[test]439 fn a_document_that_ends_too_early_is_refused() {440 assert_eq!(err(""), JsonError::Eof { offset: 0 });441 assert_eq!(err(" "), JsonError::Eof { offset: 3 });442 assert_eq!(err("["), JsonError::Eof { offset: 1 });443 assert_eq!(err("[1"), JsonError::Eof { offset: 2 });444 assert_eq!(err(r#"{"a""#), JsonError::Eof { offset: 4 });445 assert_eq!(err(r#"{"a":"#), JsonError::Eof { offset: 5 });446 assert_eq!(447 err("[1:"),448 JsonError::Unexpected {449 offset: 2,450 byte: b':'451 }452 );453 }454 455 #[test]456 fn json_without_a_colon_or_a_comma_is_refused() {457 assert_eq!(458 err(r#"{"a" 1}"#),459 JsonError::Unexpected {460 offset: 5,461 byte: b'1'462 }463 );464 assert_eq!(465 err(r#"{"a"}"#),466 JsonError::Unexpected {467 offset: 4,468 byte: b'}'469 }470 );471 assert_eq!(472 err(r#"{a: 1}"#),473 JsonError::Unexpected {474 offset: 1,475 byte: b'a'476 }477 );478 assert_eq!(479 err("[1 2]"),480 JsonError::Unexpected {481 offset: 3,482 byte: b'2'483 }484 );485 assert_eq!(486 err("[1,,2]"),487 JsonError::Unexpected {488 offset: 3,489 byte: b','490 }491 );492 // A vertical tab and a form feed are not JSON whitespace.493 assert_eq!(494 err("[1\u{b}2]"),495 JsonError::Unexpected {496 offset: 2,497 byte: 0x0b498 }499 );500 assert_eq!(err("1\u{c}"), JsonError::Trailing { offset: 1 });501 }502 503 #[test]504 fn the_offset_of_an_error_points_at_the_fault() {505 let control = "{\"a\tb\": 1}";506 let cases: [(&str, usize); 8] = [507 (r#"{"a": 1, "a": 2}"#, 9),508 (r#"[1, ]"#, 4),509 (r#""\ud83d\\x""#, 7),510 (control, 3),511 ("// hi", 0),512 ("{} []", 3),513 ("1e400", 0),514 (r#""\u00""#, 1),515 ];516 for (text, want) in cases {517 let e = err(text);518 assert_eq!(e.offset(), want, "{text}: {e}");519 assert!(e.to_string().contains(&want.to_string()), "{text}: {e}");520 }521 assert!(err(r#"{"a": 1, "a": 2}"#).to_string().contains("twice"));522 }523 524 #[test]525 fn whitespace_between_the_tokens_is_free() {526 assert_eq!(527 parse(" \t\n\r [ 1 , 2 ] \n").unwrap(),528 Value::Array(vec![Value::int(1), Value::int(2)])529 );530 assert_eq!(531 parse("{\n \"a\" : [ 1 , { } ]\n}").unwrap(),532 Value::object()533 .put(534 "a",535 Value::Array(vec![Value::int(1), Value::object().build()])536 )537 .build()538 );539 }540 541 #[test]542 fn a_document_is_only_its_content() {543 assert_eq!(544 parse(" { \"a\" : 1 , \"b\" : [ 2 ] } ").unwrap(),545 parse(r#"{"b":[2],"a":1}"#).unwrap()546 );547 assert_eq!(548 to_string(&parse(" { \"a\" : 1 , \"b\" : [ 2 ] } ").unwrap()),549 to_string(&parse(r#"{"b":[2],"a":1}"#).unwrap())550 );551 }552 553 #[test]554 fn scalars_read_and_write() {555 assert_eq!(parse("null"), Ok(Value::Null));556 assert_eq!(parse("true"), Ok(Value::bool(true)));557 assert_eq!(parse("false"), Ok(Value::bool(false)));558 assert_eq!(parse("\"hi\""), Ok(Value::str("hi")));559 assert_eq!(parse("7"), Ok(Value::int(7)));560 assert_eq!(to_string(&Value::Null), "null");561 assert_eq!(to_string(&Value::bool(true)), "true");562 assert_eq!(to_string(&Value::bool(false)), "false");563 assert_eq!(to_string(&Value::str("hi")), "\"hi\"");564 }565 566 #[test]567 fn accessors_answer_only_for_the_type_they_read() {568 let value = parse(r#"{"a": 1, "b": [1], "c": "s", "d": 1.0, "e": true}"#).unwrap();569 assert_eq!(value.get("a").and_then(Value::as_i64), Some(1));570 assert_eq!(value.get("a").and_then(Value::as_u64), Some(1));571 assert_eq!(value.get("a").and_then(Value::as_f64), Some(1.0));572 assert_eq!(value.get("a").and_then(Value::as_str), None);573 assert_eq!(value.get("a").and_then(Value::as_bool), None);574 assert_eq!(value.get("a").and_then(Value::as_array), None);575 assert_eq!(value.get("a").and_then(Value::as_object), None);576 assert_eq!(577 value.get("b").and_then(Value::as_array).map(|a| a.len()),578 Some(1)579 );580 assert_eq!(value.get("c").and_then(Value::as_str), Some("s"));581 assert_eq!(value.get("c").and_then(Value::as_i64), None);582 // A whole float is not an integer to this codec.583 assert_eq!(value.get("d").and_then(Value::as_i64), None);584 assert_eq!(value.get("d").and_then(Value::as_f64), Some(1.0));585 assert_eq!(value.get("e").and_then(Value::as_bool), Some(true));586 assert_eq!(Value::int(-1).as_u64(), None);587 assert_eq!(Value::Null.as_str(), None);588 assert_eq!(Value::str("s").as_object(), None);589 }590 591 #[test]592 fn a_deep_document_under_the_cap_still_round_trips() {593 let text = "{\"k\": ".repeat(64) + "1" + &"}".repeat(64);594 let value = parse(&text).unwrap();595 assert_eq!(596 to_string(&value),597 "{\"k\":".repeat(64) + "1" + &"}".repeat(64)598 );599 assert_eq!(parse(&to_string(&value)).unwrap(), value);600 }601 602 #[test]603 fn a_string_keeps_its_text_across_a_round_trip() {604 let value = parse(r#""é \ud83c\udf00 \u00e9 \n\t\" \\""#).unwrap();605 assert_eq!(value.as_str(), Some("é 🌀 é \n\t\" \\"));606 assert_eq!(parse(&to_string(&value)).unwrap(), value);607 }