1 #![allow(rustc::internal)]
3 use json::DecoderError::*;
4 use json::ErrorCode::*;
6 use json::JsonEvent::*;
7 use json::ParserError::*;
9 from_str, DecodeResult, Decoder, DecoderError, Encoder, EncoderError, Json, JsonEvent, Parser,
12 use rustc_macros::{Decodable, Encodable};
13 use rustc_serialize::json;
14 use rustc_serialize::{Decodable, Encodable};
16 use std::collections::BTreeMap;
17 use std::io::prelude::*;
21 #[derive(Decodable, Eq, PartialEq, Debug)]
27 fn test_decode_option_none() {
29 let obj: OptionData = json::decode(s).unwrap();
30 assert_eq!(obj, OptionData { opt: None });
34 fn test_decode_option_some() {
35 let s = "{ \"opt\": 10 }";
36 let obj: OptionData = json::decode(s).unwrap();
37 assert_eq!(obj, OptionData { opt: Some(10) });
41 fn test_decode_option_malformed() {
42 check_err::<OptionData>(
44 ExpectedError("Number".to_string(), "[]".to_string()),
46 check_err::<OptionData>(
48 ExpectedError("Number".to_string(), "false".to_string()),
52 #[derive(PartialEq, Encodable, Decodable, Debug)]
55 Frog(string::String, isize),
58 #[derive(PartialEq, Encodable, Decodable, Debug)]
62 c: Vec<string::String>,
65 #[derive(PartialEq, Encodable, Decodable, Debug)]
70 fn mk_object(items: &[(string::String, Json)]) -> Json {
71 let mut d = BTreeMap::new();
75 (ref key, ref value) => {
76 d.insert((*key).clone(), (*value).clone());
85 fn test_from_str_trait() {
87 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
91 fn test_write_null() {
92 assert_eq!(Null.to_string(), "null");
93 assert_eq!(Null.pretty().to_string(), "null");
98 assert_eq!(U64(0).to_string(), "0");
99 assert_eq!(U64(0).pretty().to_string(), "0");
101 assert_eq!(U64(1234).to_string(), "1234");
102 assert_eq!(U64(1234).pretty().to_string(), "1234");
104 assert_eq!(I64(-5678).to_string(), "-5678");
105 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
107 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
108 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
112 fn test_write_f64() {
113 assert_eq!(F64(3.0).to_string(), "3.0");
114 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
116 assert_eq!(F64(3.1).to_string(), "3.1");
117 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
119 assert_eq!(F64(-1.5).to_string(), "-1.5");
120 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
122 assert_eq!(F64(0.5).to_string(), "0.5");
123 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
125 assert_eq!(F64(f64::NAN).to_string(), "null");
126 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
128 assert_eq!(F64(f64::INFINITY).to_string(), "null");
129 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
131 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
132 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
136 fn test_write_str() {
137 assert_eq!(String("".to_string()).to_string(), "\"\"");
138 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
140 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
141 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
145 fn test_write_bool() {
146 assert_eq!(Boolean(true).to_string(), "true");
147 assert_eq!(Boolean(true).pretty().to_string(), "true");
149 assert_eq!(Boolean(false).to_string(), "false");
150 assert_eq!(Boolean(false).pretty().to_string(), "false");
154 fn test_write_array() {
155 assert_eq!(Array(vec![]).to_string(), "[]");
156 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
158 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
160 Array(vec![Boolean(true)]).pretty().to_string(),
167 let long_test_array =
168 Array(vec![Boolean(false), Null, Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
170 assert_eq!(long_test_array.to_string(), "[false,null,[\"foo\\nbar\",3.5]]");
172 long_test_array.pretty().to_string(),
186 fn test_write_object() {
187 assert_eq!(mk_object(&[]).to_string(), "{}");
188 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
190 assert_eq!(mk_object(&[("a".to_string(), Boolean(true))]).to_string(), "{\"a\":true}");
192 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
199 let complex_obj = mk_object(&[(
202 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
203 mk_object(&[("d".to_string(), String("".to_string()))]),
208 complex_obj.to_string(),
217 complex_obj.pretty().to_string(),
222 \"c\": \"\\f\\r\"\n \
232 ("a".to_string(), Boolean(true)),
236 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
237 mk_object(&[("d".to_string(), String("".to_string()))]),
242 // We can't compare the strings directly because the object fields be
243 // printed in a different order.
244 assert_eq!(a.clone(), a.to_string().parse().unwrap());
245 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
249 fn test_write_enum() {
251 assert_eq!(json::as_json(&animal).to_string(), "\"Dog\"");
252 assert_eq!(json::as_pretty_json(&animal).to_string(), "\"Dog\"");
254 let animal = Frog("Henry".to_string(), 349);
256 json::as_json(&animal).to_string(),
257 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
260 json::as_pretty_json(&animal).to_string(),
262 \"variant\": \"Frog\",\n \
271 macro_rules! check_encoder_for_simple {
272 ($value:expr, $expected:expr) => {{
273 let s = json::as_json(&$value).to_string();
274 assert_eq!(s, $expected);
276 let s = json::as_pretty_json(&$value).to_string();
277 assert_eq!(s, $expected);
282 fn test_write_some() {
283 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
287 fn test_write_none() {
288 check_encoder_for_simple!(None::<string::String>, "null");
292 fn test_write_char() {
293 check_encoder_for_simple!('a', "\"a\"");
294 check_encoder_for_simple!('\t', "\"\\t\"");
295 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
296 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
297 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
298 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
299 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
300 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
304 fn test_trailing_characters() {
305 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
306 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
307 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
308 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
309 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
310 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
314 fn test_read_identifiers() {
315 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
316 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
317 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
318 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
319 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
320 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
322 assert_eq!(from_str("null"), Ok(Null));
323 assert_eq!(from_str("true"), Ok(Boolean(true)));
324 assert_eq!(from_str("false"), Ok(Boolean(false)));
325 assert_eq!(from_str(" null "), Ok(Null));
326 assert_eq!(from_str(" true "), Ok(Boolean(true)));
327 assert_eq!(from_str(" false "), Ok(Boolean(false)));
331 fn test_decode_identifiers() {
332 let v: () = json::decode("null").unwrap();
335 let v: bool = json::decode("true").unwrap();
338 let v: bool = json::decode("false").unwrap();
339 assert_eq!(v, false);
343 fn test_read_number() {
344 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
345 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
346 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
347 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
348 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
349 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
350 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
351 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
353 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
354 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
356 assert_eq!(from_str("3"), Ok(U64(3)));
357 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
358 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
359 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
360 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
361 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
362 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
363 assert_eq!(from_str(" 3 "), Ok(U64(3)));
365 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
366 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
367 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
371 fn test_decode_numbers() {
372 let v: f64 = json::decode("3").unwrap();
375 let v: f64 = json::decode("3.1").unwrap();
378 let v: f64 = json::decode("-1.2").unwrap();
381 let v: f64 = json::decode("0.4").unwrap();
384 let v: f64 = json::decode("0.4e5").unwrap();
385 assert_eq!(v, 0.4e5);
387 let v: f64 = json::decode("0.4e15").unwrap();
388 assert_eq!(v, 0.4e15);
390 let v: f64 = json::decode("0.4e-01").unwrap();
391 assert_eq!(v, 0.4e-01);
393 let v: u64 = json::decode("0").unwrap();
396 let v: u64 = json::decode("18446744073709551615").unwrap();
397 assert_eq!(v, u64::MAX);
399 let v: i64 = json::decode("-9223372036854775808").unwrap();
400 assert_eq!(v, i64::MIN);
402 let v: i64 = json::decode("9223372036854775807").unwrap();
403 assert_eq!(v, i64::MAX);
405 let res: DecodeResult<i64> = json::decode("765.25");
406 assert_eq!(res, Err(ExpectedError("Integer".to_string(), "765.25".to_string())));
411 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
412 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
414 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
415 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
416 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
417 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
418 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
419 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
420 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
421 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
422 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
423 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
427 fn test_decode_str() {
436 ("\"\\u12ab\"", "\u{12ab}"),
437 ("\"\\uAB12\"", "\u{AB12}"),
441 let v: string::String = json::decode(i).unwrap();
447 fn test_read_array() {
448 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
449 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
450 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
451 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
452 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
454 assert_eq!(from_str("[]"), Ok(Array(vec![])));
455 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
456 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
457 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
458 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
459 assert_eq!(from_str("[3, 1]"), Ok(Array(vec![U64(3), U64(1)])));
460 assert_eq!(from_str("\n[3, 2]\n"), Ok(Array(vec![U64(3), U64(2)])));
461 assert_eq!(from_str("[2, [4, 1]]"), Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
465 fn test_decode_array() {
466 let v: Vec<()> = json::decode("[]").unwrap();
469 let v: Vec<()> = json::decode("[null]").unwrap();
472 let v: Vec<bool> = json::decode("[true]").unwrap();
473 assert_eq!(v, [true]);
475 let v: Vec<isize> = json::decode("[3, 1]").unwrap();
476 assert_eq!(v, [3, 1]);
478 let v: Vec<Vec<usize>> = json::decode("[[3], [1, 2]]").unwrap();
479 assert_eq!(v, [vec![3], vec![1, 2]]);
483 fn test_decode_tuple() {
484 let t: (usize, usize, usize) = json::decode("[1, 2, 3]").unwrap();
485 assert_eq!(t, (1, 2, 3));
487 let t: (usize, string::String) = json::decode("[1, \"two\"]").unwrap();
488 assert_eq!(t, (1, "two".to_string()));
492 fn test_decode_tuple_malformed_types() {
493 assert!(json::decode::<(usize, string::String)>("[1, 2]").is_err());
497 fn test_decode_tuple_malformed_length() {
498 assert!(json::decode::<(usize, usize)>("[1, 2, 3]").is_err());
502 fn test_read_object() {
503 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
504 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
505 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
506 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
507 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
508 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
510 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
511 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
512 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
513 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
514 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
516 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
517 assert_eq!(from_str("{\"a\": 3}").unwrap(), mk_object(&[("a".to_string(), U64(3))]));
520 from_str("{ \"a\": null, \"b\" : true }").unwrap(),
521 mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
524 from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
525 mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
528 from_str("{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
529 mk_object(&[("a".to_string(), F64(1.0)), ("b".to_string(), Array(vec![Boolean(true)]))])
538 { \"c\": {\"d\": null} } \
544 ("a".to_string(), F64(1.0)),
549 String("foo\nbar".to_string()),
550 mk_object(&[("c".to_string(), mk_object(&[("d".to_string(), Null)]))])
558 fn test_decode_struct() {
561 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
565 let v: Outer = json::decode(s).unwrap();
568 Outer { inner: vec![Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }] }
578 fn test_decode_struct_with_nan() {
579 let s = "{\"f\":null,\"a\":[null,123]}";
580 let obj: FloatStruct = json::decode(s).unwrap();
581 assert!(obj.f.is_nan());
582 assert!(obj.a[0].is_nan());
583 assert_eq!(obj.a[1], 123f64);
587 fn test_decode_option() {
588 let value: Option<string::String> = json::decode("null").unwrap();
589 assert_eq!(value, None);
591 let value: Option<string::String> = json::decode("\"jodhpurs\"").unwrap();
592 assert_eq!(value, Some("jodhpurs".to_string()));
596 fn test_decode_enum() {
597 let value: Animal = json::decode("\"Dog\"").unwrap();
598 assert_eq!(value, Dog);
600 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
601 let value: Animal = json::decode(s).unwrap();
602 assert_eq!(value, Frog("Henry".to_string(), 349));
606 fn test_decode_map() {
607 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
608 \"fields\":[\"Henry\", 349]}}";
609 let mut map: BTreeMap<string::String, Animal> = json::decode(s).unwrap();
611 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
612 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
616 fn test_multiline_errors() {
617 assert_eq!(from_str("{\n \"foo\":\n \"bar\""), Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
622 struct DecodeStruct {
626 w: Vec<DecodeStruct>,
633 fn check_err<T: Decodable<Decoder>>(to_parse: &'static str, expected: DecoderError) {
634 let res: DecodeResult<T> = match from_str(to_parse) {
635 Err(e) => Err(ParseError(e)),
636 Ok(json) => Decodable::decode(&mut Decoder::new(json)),
639 Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`", to_parse, expected),
640 Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}", to_parse, e),
642 assert_eq!(e, expected);
647 fn test_decode_errors_struct() {
648 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
649 check_err::<DecodeStruct>(
650 "{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
651 ExpectedError("Number".to_string(), "true".to_string()),
653 check_err::<DecodeStruct>(
654 "{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
655 ExpectedError("Boolean".to_string(), "[]".to_string()),
657 check_err::<DecodeStruct>(
658 "{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
659 ExpectedError("String".to_string(), "{}".to_string()),
661 check_err::<DecodeStruct>(
662 "{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
663 ExpectedError("Array".to_string(), "null".to_string()),
665 check_err::<DecodeStruct>(
666 "{\"x\": 1, \"y\": true, \"z\": \"\"}",
667 MissingFieldError("w".to_string()),
671 fn test_decode_errors_enum() {
672 check_err::<DecodeEnum>("{}", MissingFieldError("variant".to_string()));
673 check_err::<DecodeEnum>(
675 ExpectedError("String".to_string(), "1".to_string()),
677 check_err::<DecodeEnum>("{\"variant\": \"A\"}", MissingFieldError("fields".to_string()));
678 check_err::<DecodeEnum>(
679 "{\"variant\": \"A\", \"fields\": null}",
680 ExpectedError("Array".to_string(), "null".to_string()),
682 check_err::<DecodeEnum>(
683 "{\"variant\": \"C\", \"fields\": []}",
684 UnknownVariantError("C".to_string()),
690 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
691 let found_str = json_value.find("dog");
692 assert!(found_str.unwrap().as_string().unwrap() == "cat");
696 fn test_find_path() {
697 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
698 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
699 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
704 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
705 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
706 assert!(found_str.unwrap() == "cheese");
711 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
712 let ref array = json_value["animals"];
713 assert_eq!(array[0].as_string().unwrap(), "dog");
714 assert_eq!(array[1].as_string().unwrap(), "cat");
715 assert_eq!(array[2].as_string().unwrap(), "mouse");
719 fn test_is_object() {
720 let json_value = from_str("{}").unwrap();
721 assert!(json_value.is_object());
725 fn test_as_object() {
726 let json_value = from_str("{}").unwrap();
727 let json_object = json_value.as_object();
728 assert!(json_object.is_some());
733 let json_value = from_str("[1, 2, 3]").unwrap();
734 assert!(json_value.is_array());
739 let json_value = from_str("[1, 2, 3]").unwrap();
740 let json_array = json_value.as_array();
741 let expected_length = 3;
742 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
746 fn test_is_string() {
747 let json_value = from_str("\"dog\"").unwrap();
748 assert!(json_value.is_string());
752 fn test_as_string() {
753 let json_value = from_str("\"dog\"").unwrap();
754 let json_str = json_value.as_string();
755 let expected_str = "dog";
756 assert_eq!(json_str, Some(expected_str));
760 fn test_is_number() {
761 let json_value = from_str("12").unwrap();
762 assert!(json_value.is_number());
767 let json_value = from_str("-12").unwrap();
768 assert!(json_value.is_i64());
770 let json_value = from_str("12").unwrap();
771 assert!(!json_value.is_i64());
773 let json_value = from_str("12.0").unwrap();
774 assert!(!json_value.is_i64());
779 let json_value = from_str("12").unwrap();
780 assert!(json_value.is_u64());
782 let json_value = from_str("-12").unwrap();
783 assert!(!json_value.is_u64());
785 let json_value = from_str("12.0").unwrap();
786 assert!(!json_value.is_u64());
791 let json_value = from_str("12").unwrap();
792 assert!(!json_value.is_f64());
794 let json_value = from_str("-12").unwrap();
795 assert!(!json_value.is_f64());
797 let json_value = from_str("12.0").unwrap();
798 assert!(json_value.is_f64());
800 let json_value = from_str("-12.0").unwrap();
801 assert!(json_value.is_f64());
806 let json_value = from_str("-12").unwrap();
807 let json_num = json_value.as_i64();
808 assert_eq!(json_num, Some(-12));
813 let json_value = from_str("12").unwrap();
814 let json_num = json_value.as_u64();
815 assert_eq!(json_num, Some(12));
820 let json_value = from_str("12.0").unwrap();
821 let json_num = json_value.as_f64();
822 assert_eq!(json_num, Some(12f64));
826 fn test_is_boolean() {
827 let json_value = from_str("false").unwrap();
828 assert!(json_value.is_boolean());
832 fn test_as_boolean() {
833 let json_value = from_str("false").unwrap();
834 let json_bool = json_value.as_boolean();
835 let expected_bool = false;
836 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
841 let json_value = from_str("null").unwrap();
842 assert!(json_value.is_null());
847 let json_value = from_str("null").unwrap();
848 let json_null = json_value.as_null();
849 let expected_null = ();
850 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
854 fn test_encode_hashmap_with_numeric_key() {
855 use std::collections::HashMap;
856 use std::str::from_utf8;
857 let mut hm: HashMap<usize, bool> = HashMap::new();
859 let mut mem_buf = Vec::new();
860 write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
861 let json_str = from_utf8(&mem_buf[..]).unwrap();
862 match from_str(json_str) {
863 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
864 _ => {} // it parsed and we are good to go
869 fn test_prettyencode_hashmap_with_numeric_key() {
870 use std::collections::HashMap;
871 use std::str::from_utf8;
872 let mut hm: HashMap<usize, bool> = HashMap::new();
874 let mut mem_buf = Vec::new();
875 write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
876 let json_str = from_utf8(&mem_buf[..]).unwrap();
877 match from_str(json_str) {
878 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
879 _ => {} // it parsed and we are good to go
884 fn test_prettyencoder_indent_level_param() {
885 use std::collections::BTreeMap;
886 use std::str::from_utf8;
888 let mut tree = BTreeMap::new();
890 tree.insert("hello".to_string(), String("guten tag".to_string()));
891 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
894 // The following layout below should look a lot like
895 // the pretty-printed JSON (indent * x)
898 String("greetings".to_string()), // 1x
899 Object(tree), // 1x + 2x + 2x + 1x
901 // End JSON array (7 lines)
904 // Helper function for counting indents
905 fn indents(source: &str) -> usize {
906 let trimmed = source.trim_start_matches(' ');
907 source.len() - trimmed.len()
910 // Test up to 4 spaces of indents (more?)
912 let mut writer = Vec::new();
913 write!(&mut writer, "{}", json::as_pretty_json(&json).indent(i)).unwrap();
915 let printed = from_utf8(&writer[..]).unwrap();
917 // Check for indents at each line
918 let lines: Vec<&str> = printed.lines().collect();
919 assert_eq!(lines.len(), 7); // JSON should be 7 lines
921 assert_eq!(indents(lines[0]), 0 * i); // [
922 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
923 assert_eq!(indents(lines[2]), 1 * i); // {
924 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
925 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
926 assert_eq!(indents(lines[5]), 1 * i); // },
927 assert_eq!(indents(lines[6]), 0 * i); // ]
929 // Finally, test that the pretty-printed JSON is valid
930 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
935 fn test_hashmap_with_enum_key() {
936 use std::collections::HashMap;
937 #[derive(Encodable, Eq, Hash, PartialEq, Decodable, Debug)]
943 let mut map = HashMap::new();
944 map.insert(Enum::Foo, 0);
945 let result = json::encode(&map).unwrap();
946 assert_eq!(&result[..], r#"{"Foo":0}"#);
947 let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
948 assert_eq!(map, decoded);
952 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
953 use std::collections::HashMap;
954 let json_str = "{\"1\":true}";
955 let json_obj = match from_str(json_str) {
956 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
959 let mut decoder = Decoder::new(json_obj);
960 let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
964 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
965 use std::collections::HashMap;
966 let json_str = "{\"a\":true}";
967 let json_obj = match from_str(json_str) {
968 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
971 let mut decoder = Decoder::new(json_obj);
972 let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder);
973 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
976 fn assert_stream_equal(src: &str, expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) {
977 let mut parser = Parser::new(src.chars());
980 let evt = match parser.next() {
986 let (ref expected_evt, ref expected_stack) = expected[i];
987 if !parser.stack().is_equal_to(expected_stack) {
988 panic!("Parser stack is not equal to {:?}", expected_stack);
990 assert_eq!(&evt, expected_evt);
995 fn test_streaming_parser() {
997 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
999 (ObjectStart, vec![]),
1000 (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
1001 (ArrayStart, vec![StackElement::Key("array")]),
1002 (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
1003 (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
1004 (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
1005 (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
1006 (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
1007 (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
1008 (ArrayEnd, vec![StackElement::Key("array")]),
1009 (ArrayStart, vec![StackElement::Key("idents")]),
1010 (NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]),
1011 (BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]),
1012 (BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]),
1013 (ArrayEnd, vec![StackElement::Key("idents")]),
1014 (ObjectEnd, vec![]),
1018 fn last_event(src: &str) -> JsonEvent {
1019 let mut parser = Parser::new(src.chars());
1020 let mut evt = NullValue;
1022 evt = match parser.next() {
1030 fn test_read_object_streaming() {
1031 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
1032 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
1033 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1034 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
1035 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1037 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
1038 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
1039 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
1040 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
1041 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
1042 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
1044 assert_stream_equal("{}", vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]);
1045 assert_stream_equal(
1048 (ObjectStart, vec![]),
1049 (U64Value(3), vec![StackElement::Key("a")]),
1050 (ObjectEnd, vec![]),
1053 assert_stream_equal(
1054 "{ \"a\": null, \"b\" : true }",
1056 (ObjectStart, vec![]),
1057 (NullValue, vec![StackElement::Key("a")]),
1058 (BooleanValue(true), vec![StackElement::Key("b")]),
1059 (ObjectEnd, vec![]),
1062 assert_stream_equal(
1063 "{\"a\" : 1.0 ,\"b\": [ true ]}",
1065 (ObjectStart, vec![]),
1066 (F64Value(1.0), vec![StackElement::Key("a")]),
1067 (ArrayStart, vec![StackElement::Key("b")]),
1068 (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
1069 (ArrayEnd, vec![StackElement::Key("b")]),
1070 (ObjectEnd, vec![]),
1073 assert_stream_equal(
1079 { "c": {"d": null} }
1083 (ObjectStart, vec![]),
1084 (F64Value(1.0), vec![StackElement::Key("a")]),
1085 (ArrayStart, vec![StackElement::Key("b")]),
1086 (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
1088 StringValue("foo\nbar".to_string()),
1089 vec![StackElement::Key("b"), StackElement::Index(1)],
1091 (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]),
1094 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
1099 StackElement::Key("b"),
1100 StackElement::Index(2),
1101 StackElement::Key("c"),
1102 StackElement::Key("d"),
1107 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
1109 (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]),
1110 (ArrayEnd, vec![StackElement::Key("b")]),
1111 (ObjectEnd, vec![]),
1116 fn test_read_array_streaming() {
1117 assert_stream_equal("[]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
1118 assert_stream_equal("[ ]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
1119 assert_stream_equal(
1122 (ArrayStart, vec![]),
1123 (BooleanValue(true), vec![StackElement::Index(0)]),
1127 assert_stream_equal(
1130 (ArrayStart, vec![]),
1131 (BooleanValue(false), vec![StackElement::Index(0)]),
1135 assert_stream_equal(
1137 vec![(ArrayStart, vec![]), (NullValue, vec![StackElement::Index(0)]), (ArrayEnd, vec![])],
1139 assert_stream_equal(
1142 (ArrayStart, vec![]),
1143 (U64Value(3), vec![StackElement::Index(0)]),
1144 (U64Value(1), vec![StackElement::Index(1)]),
1148 assert_stream_equal(
1151 (ArrayStart, vec![]),
1152 (U64Value(3), vec![StackElement::Index(0)]),
1153 (U64Value(2), vec![StackElement::Index(1)]),
1157 assert_stream_equal(
1160 (ArrayStart, vec![]),
1161 (U64Value(2), vec![StackElement::Index(0)]),
1162 (ArrayStart, vec![StackElement::Index(1)]),
1163 (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
1164 (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
1165 (ArrayEnd, vec![StackElement::Index(1)]),
1170 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
1172 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
1173 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
1174 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
1175 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1176 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1179 fn test_trailing_characters_streaming() {
1180 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1181 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1182 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
1183 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
1184 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1185 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1188 fn test_read_identifiers_streaming() {
1189 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
1190 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
1191 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
1193 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1194 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1195 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1196 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1197 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1198 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
1204 use std::collections::{BTreeMap, HashMap};
1206 let array2 = Array(vec![U64(1), U64(2)]);
1207 let array3 = Array(vec![U64(1), U64(2), U64(3)]);
1209 let mut tree_map = BTreeMap::new();
1210 tree_map.insert("a".to_string(), U64(1));
1211 tree_map.insert("b".to_string(), U64(2));
1215 assert_eq!(array2.to_json(), array2);
1216 assert_eq!(object.to_json(), object);
1217 assert_eq!(3_isize.to_json(), I64(3));
1218 assert_eq!(4_i8.to_json(), I64(4));
1219 assert_eq!(5_i16.to_json(), I64(5));
1220 assert_eq!(6_i32.to_json(), I64(6));
1221 assert_eq!(7_i64.to_json(), I64(7));
1222 assert_eq!(8_usize.to_json(), U64(8));
1223 assert_eq!(9_u8.to_json(), U64(9));
1224 assert_eq!(10_u16.to_json(), U64(10));
1225 assert_eq!(11_u32.to_json(), U64(11));
1226 assert_eq!(12_u64.to_json(), U64(12));
1227 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
1228 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
1229 assert_eq!(().to_json(), Null);
1230 assert_eq!(f32::INFINITY.to_json(), Null);
1231 assert_eq!(f64::NAN.to_json(), Null);
1232 assert_eq!(true.to_json(), Boolean(true));
1233 assert_eq!(false.to_json(), Boolean(false));
1234 assert_eq!("abc".to_json(), String("abc".to_string()));
1235 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
1236 assert_eq!((1_usize, 2_usize).to_json(), array2);
1237 assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
1238 assert_eq!([1_usize, 2_usize].to_json(), array2);
1239 assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
1240 assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
1241 assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
1242 let mut tree_map = BTreeMap::new();
1243 tree_map.insert("a".to_string(), 1 as usize);
1244 tree_map.insert("b".to_string(), 2);
1245 assert_eq!(tree_map.to_json(), object);
1246 let mut hash_map = HashMap::new();
1247 hash_map.insert("a".to_string(), 1 as usize);
1248 hash_map.insert("b".to_string(), 2);
1249 assert_eq!(hash_map.to_json(), object);
1250 assert_eq!(Some(15).to_json(), I64(15));
1251 assert_eq!(Some(15 as usize).to_json(), U64(15));
1252 assert_eq!(None::<isize>.to_json(), Null);
1256 fn test_encode_hashmap_with_arbitrary_key() {
1257 use std::collections::HashMap;
1258 #[derive(PartialEq, Eq, Hash, Encodable)]
1259 struct ArbitraryType(usize);
1260 let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
1261 hm.insert(ArbitraryType(1), true);
1262 let mut mem_buf = string::String::new();
1263 let mut encoder = Encoder::new(&mut mem_buf);
1264 let result = hm.encode(&mut encoder);
1265 match result.unwrap_err() {
1266 EncoderError::BadHashmapKey => (),
1267 _ => panic!("expected bad hash map key"),