]> git.lizzy.rs Git - rust.git/blob - src/libserialize/tests/json.rs
Auto merge of #62756 - newpavlov:stabilize_dur_float, r=alexcrichton
[rust.git] / src / libserialize / tests / json.rs
1 extern crate serialize as rustc_serialize;
2
3 use rustc_serialize::{Encodable, Decodable};
4 use rustc_serialize::json;
5 use json::Json::*;
6 use json::ErrorCode::*;
7 use json::ParserError::*;
8 use json::DecoderError::*;
9 use json::JsonEvent::*;
10 use json::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, StackElement,
11            Decoder, Encoder, EncoderError};
12
13 use Animal::*;
14 use std::{i64, u64, f32, f64};
15 use std::io::prelude::*;
16 use std::collections::BTreeMap;
17 use std::string;
18
19 #[derive(RustcDecodable, Eq, PartialEq, Debug)]
20 struct OptionData {
21     opt: Option<usize>,
22 }
23
24 #[test]
25 fn test_decode_option_none() {
26     let s ="{}";
27     let obj: OptionData = json::decode(s).unwrap();
28     assert_eq!(obj, OptionData { opt: None });
29 }
30
31 #[test]
32 fn test_decode_option_some() {
33     let s = "{ \"opt\": 10 }";
34     let obj: OptionData = json::decode(s).unwrap();
35     assert_eq!(obj, OptionData { opt: Some(10) });
36 }
37
38 #[test]
39 fn test_decode_option_malformed() {
40     check_err::<OptionData>("{ \"opt\": [] }",
41                             ExpectedError("Number".to_string(), "[]".to_string()));
42     check_err::<OptionData>("{ \"opt\": false }",
43                             ExpectedError("Number".to_string(), "false".to_string()));
44 }
45
46 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
47 enum Animal {
48     Dog,
49     Frog(string::String, isize)
50 }
51
52 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
53 struct Inner {
54     a: (),
55     b: usize,
56     c: Vec<string::String>,
57 }
58
59 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
60 struct Outer {
61     inner: Vec<Inner>,
62 }
63
64 fn mk_object(items: &[(string::String, Json)]) -> Json {
65     let mut d = BTreeMap::new();
66
67     for item in items {
68         match *item {
69             (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
70         }
71     };
72
73     Object(d)
74 }
75
76 #[test]
77 fn test_from_str_trait() {
78     let s = "null";
79     assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
80 }
81
82 #[test]
83 fn test_write_null() {
84     assert_eq!(Null.to_string(), "null");
85     assert_eq!(Null.pretty().to_string(), "null");
86 }
87
88 #[test]
89 fn test_write_i64() {
90     assert_eq!(U64(0).to_string(), "0");
91     assert_eq!(U64(0).pretty().to_string(), "0");
92
93     assert_eq!(U64(1234).to_string(), "1234");
94     assert_eq!(U64(1234).pretty().to_string(), "1234");
95
96     assert_eq!(I64(-5678).to_string(), "-5678");
97     assert_eq!(I64(-5678).pretty().to_string(), "-5678");
98
99     assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
100     assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
101 }
102
103 #[test]
104 fn test_write_f64() {
105     assert_eq!(F64(3.0).to_string(), "3.0");
106     assert_eq!(F64(3.0).pretty().to_string(), "3.0");
107
108     assert_eq!(F64(3.1).to_string(), "3.1");
109     assert_eq!(F64(3.1).pretty().to_string(), "3.1");
110
111     assert_eq!(F64(-1.5).to_string(), "-1.5");
112     assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
113
114     assert_eq!(F64(0.5).to_string(), "0.5");
115     assert_eq!(F64(0.5).pretty().to_string(), "0.5");
116
117     assert_eq!(F64(f64::NAN).to_string(), "null");
118     assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
119
120     assert_eq!(F64(f64::INFINITY).to_string(), "null");
121     assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
122
123     assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
124     assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
125 }
126
127 #[test]
128 fn test_write_str() {
129     assert_eq!(String("".to_string()).to_string(), "\"\"");
130     assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
131
132     assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
133     assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
134 }
135
136 #[test]
137 fn test_write_bool() {
138     assert_eq!(Boolean(true).to_string(), "true");
139     assert_eq!(Boolean(true).pretty().to_string(), "true");
140
141     assert_eq!(Boolean(false).to_string(), "false");
142     assert_eq!(Boolean(false).pretty().to_string(), "false");
143 }
144
145 #[test]
146 fn test_write_array() {
147     assert_eq!(Array(vec![]).to_string(), "[]");
148     assert_eq!(Array(vec![]).pretty().to_string(), "[]");
149
150     assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
151     assert_eq!(
152         Array(vec![Boolean(true)]).pretty().to_string(),
153         "\
154         [\n  \
155             true\n\
156         ]"
157     );
158
159     let long_test_array = Array(vec![
160         Boolean(false),
161         Null,
162         Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
163
164     assert_eq!(long_test_array.to_string(),
165         "[false,null,[\"foo\\nbar\",3.5]]");
166     assert_eq!(
167         long_test_array.pretty().to_string(),
168         "\
169         [\n  \
170             false,\n  \
171             null,\n  \
172             [\n    \
173                 \"foo\\nbar\",\n    \
174                 3.5\n  \
175             ]\n\
176         ]"
177     );
178 }
179
180 #[test]
181 fn test_write_object() {
182     assert_eq!(mk_object(&[]).to_string(), "{}");
183     assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
184
185     assert_eq!(
186         mk_object(&[
187             ("a".to_string(), Boolean(true))
188         ]).to_string(),
189         "{\"a\":true}"
190     );
191     assert_eq!(
192         mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
193         "\
194         {\n  \
195             \"a\": true\n\
196         }"
197     );
198
199     let complex_obj = mk_object(&[
200             ("b".to_string(), Array(vec![
201                 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
202                 mk_object(&[("d".to_string(), String("".to_string()))])
203             ]))
204         ]);
205
206     assert_eq!(
207         complex_obj.to_string(),
208         "{\
209             \"b\":[\
210                 {\"c\":\"\\f\\r\"},\
211                 {\"d\":\"\"}\
212             ]\
213         }"
214     );
215     assert_eq!(
216         complex_obj.pretty().to_string(),
217         "\
218         {\n  \
219             \"b\": [\n    \
220                 {\n      \
221                     \"c\": \"\\f\\r\"\n    \
222                 },\n    \
223                 {\n      \
224                     \"d\": \"\"\n    \
225                 }\n  \
226             ]\n\
227         }"
228     );
229
230     let a = mk_object(&[
231         ("a".to_string(), Boolean(true)),
232         ("b".to_string(), Array(vec![
233             mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
234             mk_object(&[("d".to_string(), String("".to_string()))])
235         ]))
236     ]);
237
238     // We can't compare the strings directly because the object fields be
239     // printed in a different order.
240     assert_eq!(a.clone(), a.to_string().parse().unwrap());
241     assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
242 }
243
244 #[test]
245 fn test_write_enum() {
246     let animal = Dog;
247     assert_eq!(
248         json::as_json(&animal).to_string(),
249         "\"Dog\""
250     );
251     assert_eq!(
252         json::as_pretty_json(&animal).to_string(),
253         "\"Dog\""
254     );
255
256     let animal = Frog("Henry".to_string(), 349);
257     assert_eq!(
258         json::as_json(&animal).to_string(),
259         "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
260     );
261     assert_eq!(
262         json::as_pretty_json(&animal).to_string(),
263         "{\n  \
264            \"variant\": \"Frog\",\n  \
265            \"fields\": [\n    \
266              \"Henry\",\n    \
267              349\n  \
268            ]\n\
269          }"
270     );
271 }
272
273 macro_rules! check_encoder_for_simple {
274     ($value:expr, $expected:expr) => ({
275         let s = json::as_json(&$value).to_string();
276         assert_eq!(s, $expected);
277
278         let s = json::as_pretty_json(&$value).to_string();
279         assert_eq!(s, $expected);
280     })
281 }
282
283 #[test]
284 fn test_write_some() {
285     check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
286 }
287
288 #[test]
289 fn test_write_none() {
290     check_encoder_for_simple!(None::<string::String>, "null");
291 }
292
293 #[test]
294 fn test_write_char() {
295     check_encoder_for_simple!('a', "\"a\"");
296     check_encoder_for_simple!('\t', "\"\\t\"");
297     check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
298     check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
299     check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
300     check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
301     check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
302     check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
303 }
304
305 #[test]
306 fn test_trailing_characters() {
307     assert_eq!(from_str("nulla"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
308     assert_eq!(from_str("truea"),  Err(SyntaxError(TrailingCharacters, 1, 5)));
309     assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
310     assert_eq!(from_str("1a"),     Err(SyntaxError(TrailingCharacters, 1, 2)));
311     assert_eq!(from_str("[]a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
312     assert_eq!(from_str("{}a"),    Err(SyntaxError(TrailingCharacters, 1, 3)));
313 }
314
315 #[test]
316 fn test_read_identifiers() {
317     assert_eq!(from_str("n"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
318     assert_eq!(from_str("nul"),  Err(SyntaxError(InvalidSyntax, 1, 4)));
319     assert_eq!(from_str("t"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
320     assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
321     assert_eq!(from_str("f"),    Err(SyntaxError(InvalidSyntax, 1, 2)));
322     assert_eq!(from_str("faz"),  Err(SyntaxError(InvalidSyntax, 1, 3)));
323
324     assert_eq!(from_str("null"), Ok(Null));
325     assert_eq!(from_str("true"), Ok(Boolean(true)));
326     assert_eq!(from_str("false"), Ok(Boolean(false)));
327     assert_eq!(from_str(" null "), Ok(Null));
328     assert_eq!(from_str(" true "), Ok(Boolean(true)));
329     assert_eq!(from_str(" false "), Ok(Boolean(false)));
330 }
331
332 #[test]
333 fn test_decode_identifiers() {
334     let v: () = json::decode("null").unwrap();
335     assert_eq!(v, ());
336
337     let v: bool = json::decode("true").unwrap();
338     assert_eq!(v, true);
339
340     let v: bool = json::decode("false").unwrap();
341     assert_eq!(v, false);
342 }
343
344 #[test]
345 fn test_read_number() {
346     assert_eq!(from_str("+"),   Err(SyntaxError(InvalidSyntax, 1, 1)));
347     assert_eq!(from_str("."),   Err(SyntaxError(InvalidSyntax, 1, 1)));
348     assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
349     assert_eq!(from_str("-"),   Err(SyntaxError(InvalidNumber, 1, 2)));
350     assert_eq!(from_str("00"),  Err(SyntaxError(InvalidNumber, 1, 2)));
351     assert_eq!(from_str("1."),  Err(SyntaxError(InvalidNumber, 1, 3)));
352     assert_eq!(from_str("1e"),  Err(SyntaxError(InvalidNumber, 1, 3)));
353     assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
354
355     assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
356     assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
357
358     assert_eq!(from_str("3"), Ok(U64(3)));
359     assert_eq!(from_str("3.1"), Ok(F64(3.1)));
360     assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
361     assert_eq!(from_str("0.4"), Ok(F64(0.4)));
362     assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
363     assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
364     assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
365     assert_eq!(from_str(" 3 "), Ok(U64(3)));
366
367     assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
368     assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
369     assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
370 }
371
372 #[test]
373 fn test_decode_numbers() {
374     let v: f64 = json::decode("3").unwrap();
375     assert_eq!(v, 3.0);
376
377     let v: f64 = json::decode("3.1").unwrap();
378     assert_eq!(v, 3.1);
379
380     let v: f64 = json::decode("-1.2").unwrap();
381     assert_eq!(v, -1.2);
382
383     let v: f64 = json::decode("0.4").unwrap();
384     assert_eq!(v, 0.4);
385
386     let v: f64 = json::decode("0.4e5").unwrap();
387     assert_eq!(v, 0.4e5);
388
389     let v: f64 = json::decode("0.4e15").unwrap();
390     assert_eq!(v, 0.4e15);
391
392     let v: f64 = json::decode("0.4e-01").unwrap();
393     assert_eq!(v, 0.4e-01);
394
395     let v: u64 = json::decode("0").unwrap();
396     assert_eq!(v, 0);
397
398     let v: u64 = json::decode("18446744073709551615").unwrap();
399     assert_eq!(v, u64::MAX);
400
401     let v: i64 = json::decode("-9223372036854775808").unwrap();
402     assert_eq!(v, i64::MIN);
403
404     let v: i64 = json::decode("9223372036854775807").unwrap();
405     assert_eq!(v, i64::MAX);
406
407     let res: DecodeResult<i64> = json::decode("765.25");
408     assert_eq!(res, Err(ExpectedError("Integer".to_string(),
409                                       "765.25".to_string())));
410 }
411
412 #[test]
413 fn test_read_str() {
414     assert_eq!(from_str("\""),    Err(SyntaxError(EOFWhileParsingString, 1, 2)));
415     assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
416
417     assert_eq!(from_str("\"\""), Ok(String("".to_string())));
418     assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
419     assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
420     assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
421     assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
422     assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
423     assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
424     assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
425     assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
426     assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
427 }
428
429 #[test]
430 fn test_decode_str() {
431     let s = [("\"\"", ""),
432              ("\"foo\"", "foo"),
433              ("\"\\\"\"", "\""),
434              ("\"\\b\"", "\x08"),
435              ("\"\\n\"", "\n"),
436              ("\"\\r\"", "\r"),
437              ("\"\\t\"", "\t"),
438              ("\"\\u12ab\"", "\u{12ab}"),
439              ("\"\\uAB12\"", "\u{AB12}")];
440
441     for &(i, o) in &s {
442         let v: string::String = json::decode(i).unwrap();
443         assert_eq!(v, o);
444     }
445 }
446
447 #[test]
448 fn test_read_array() {
449     assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
450     assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
451     assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
452     assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
453     assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
454
455     assert_eq!(from_str("[]"), Ok(Array(vec![])));
456     assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
457     assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
458     assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
459     assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
460     assert_eq!(from_str("[3, 1]"),
461                  Ok(Array(vec![U64(3), U64(1)])));
462     assert_eq!(from_str("\n[3, 2]\n"),
463                  Ok(Array(vec![U64(3), U64(2)])));
464     assert_eq!(from_str("[2, [4, 1]]"),
465            Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
466 }
467
468 #[test]
469 fn test_decode_array() {
470     let v: Vec<()> = json::decode("[]").unwrap();
471     assert_eq!(v, []);
472
473     let v: Vec<()> = json::decode("[null]").unwrap();
474     assert_eq!(v, [()]);
475
476     let v: Vec<bool> = json::decode("[true]").unwrap();
477     assert_eq!(v, [true]);
478
479     let v: Vec<isize> = json::decode("[3, 1]").unwrap();
480     assert_eq!(v, [3, 1]);
481
482     let v: Vec<Vec<usize>> = json::decode("[[3], [1, 2]]").unwrap();
483     assert_eq!(v, [vec![3], vec![1, 2]]);
484 }
485
486 #[test]
487 fn test_decode_tuple() {
488     let t: (usize, usize, usize) = json::decode("[1, 2, 3]").unwrap();
489     assert_eq!(t, (1, 2, 3));
490
491     let t: (usize, string::String) = json::decode("[1, \"two\"]").unwrap();
492     assert_eq!(t, (1, "two".to_string()));
493 }
494
495 #[test]
496 fn test_decode_tuple_malformed_types() {
497     assert!(json::decode::<(usize, string::String)>("[1, 2]").is_err());
498 }
499
500 #[test]
501 fn test_decode_tuple_malformed_length() {
502     assert!(json::decode::<(usize, usize)>("[1, 2, 3]").is_err());
503 }
504
505 #[test]
506 fn test_read_object() {
507     assert_eq!(from_str("{"),       Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
508     assert_eq!(from_str("{ "),      Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
509     assert_eq!(from_str("{1"),      Err(SyntaxError(KeyMustBeAString,      1, 2)));
510     assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
511     assert_eq!(from_str("{\"a\""),  Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
512     assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
513
514     assert_eq!(from_str("{\"a\" 1"),   Err(SyntaxError(ExpectedColon,         1, 6)));
515     assert_eq!(from_str("{\"a\":"),    Err(SyntaxError(EOFWhileParsingValue,  1, 6)));
516     assert_eq!(from_str("{\"a\":1"),   Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
517     assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax,         1, 8)));
518     assert_eq!(from_str("{\"a\":1,"),  Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
519
520     assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
521     assert_eq!(from_str("{\"a\": 3}").unwrap(),
522                 mk_object(&[("a".to_string(), U64(3))]));
523
524     assert_eq!(from_str(
525                     "{ \"a\": null, \"b\" : true }").unwrap(),
526                 mk_object(&[
527                     ("a".to_string(), Null),
528                     ("b".to_string(), Boolean(true))]));
529     assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
530                 mk_object(&[
531                     ("a".to_string(), Null),
532                     ("b".to_string(), Boolean(true))]));
533     assert_eq!(from_str(
534                     "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
535                 mk_object(&[
536                     ("a".to_string(), F64(1.0)),
537                     ("b".to_string(), Array(vec![Boolean(true)]))
538                 ]));
539     assert_eq!(from_str(
540                     "{\
541                         \"a\": 1.0, \
542                         \"b\": [\
543                             true,\
544                             \"foo\\nbar\", \
545                             { \"c\": {\"d\": null} } \
546                         ]\
547                     }").unwrap(),
548                 mk_object(&[
549                     ("a".to_string(), F64(1.0)),
550                     ("b".to_string(), Array(vec![
551                         Boolean(true),
552                         String("foo\nbar".to_string()),
553                         mk_object(&[
554                             ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
555                         ])
556                     ]))
557                 ]));
558 }
559
560 #[test]
561 fn test_decode_struct() {
562     let s = "{
563         \"inner\": [
564             { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
565         ]
566     }";
567
568     let v: Outer = json::decode(s).unwrap();
569     assert_eq!(
570         v,
571         Outer {
572             inner: vec![
573                 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
574             ]
575         }
576     );
577 }
578
579 #[derive(RustcDecodable)]
580 struct FloatStruct {
581     f: f64,
582     a: Vec<f64>
583 }
584 #[test]
585 fn test_decode_struct_with_nan() {
586     let s = "{\"f\":null,\"a\":[null,123]}";
587     let obj: FloatStruct = json::decode(s).unwrap();
588     assert!(obj.f.is_nan());
589     assert!(obj.a[0].is_nan());
590     assert_eq!(obj.a[1], 123f64);
591 }
592
593 #[test]
594 fn test_decode_option() {
595     let value: Option<string::String> = json::decode("null").unwrap();
596     assert_eq!(value, None);
597
598     let value: Option<string::String> = json::decode("\"jodhpurs\"").unwrap();
599     assert_eq!(value, Some("jodhpurs".to_string()));
600 }
601
602 #[test]
603 fn test_decode_enum() {
604     let value: Animal = json::decode("\"Dog\"").unwrap();
605     assert_eq!(value, Dog);
606
607     let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
608     let value: Animal = json::decode(s).unwrap();
609     assert_eq!(value, Frog("Henry".to_string(), 349));
610 }
611
612 #[test]
613 fn test_decode_map() {
614     let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
615               \"fields\":[\"Henry\", 349]}}";
616     let mut map: BTreeMap<string::String, Animal> = json::decode(s).unwrap();
617
618     assert_eq!(map.remove(&"a".to_string()), Some(Dog));
619     assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
620 }
621
622 #[test]
623 fn test_multiline_errors() {
624     assert_eq!(from_str("{\n  \"foo\":\n \"bar\""),
625         Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
626 }
627
628 #[derive(RustcDecodable)]
629 #[allow(dead_code)]
630 struct DecodeStruct {
631     x: f64,
632     y: bool,
633     z: string::String,
634     w: Vec<DecodeStruct>
635 }
636 #[derive(RustcDecodable)]
637 enum DecodeEnum {
638     A(f64),
639     B(string::String)
640 }
641 fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
642     let res: DecodeResult<T> = match from_str(to_parse) {
643         Err(e) => Err(ParseError(e)),
644         Ok(json) => Decodable::decode(&mut Decoder::new(json))
645     };
646     match res {
647         Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
648                            to_parse, expected),
649         Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
650                                         to_parse, e),
651         Err(e) => {
652             assert_eq!(e, expected);
653         }
654     }
655 }
656 #[test]
657 fn test_decode_errors_struct() {
658     check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
659     check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
660                               ExpectedError("Number".to_string(), "true".to_string()));
661     check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
662                               ExpectedError("Boolean".to_string(), "[]".to_string()));
663     check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
664                               ExpectedError("String".to_string(), "{}".to_string()));
665     check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
666                               ExpectedError("Array".to_string(), "null".to_string()));
667     check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
668                               MissingFieldError("w".to_string()));
669 }
670 #[test]
671 fn test_decode_errors_enum() {
672     check_err::<DecodeEnum>("{}",
673                             MissingFieldError("variant".to_string()));
674     check_err::<DecodeEnum>("{\"variant\": 1}",
675                             ExpectedError("String".to_string(), "1".to_string()));
676     check_err::<DecodeEnum>("{\"variant\": \"A\"}",
677                             MissingFieldError("fields".to_string()));
678     check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
679                             ExpectedError("Array".to_string(), "null".to_string()));
680     check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
681                             UnknownVariantError("C".to_string()));
682 }
683
684 #[test]
685 fn test_find(){
686     let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
687     let found_str = json_value.find("dog");
688     assert!(found_str.unwrap().as_string().unwrap() == "cat");
689 }
690
691 #[test]
692 fn test_find_path(){
693     let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
694     let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
695     assert!(found_str.unwrap().as_string().unwrap() == "cheese");
696 }
697
698 #[test]
699 fn test_search(){
700     let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
701     let found_str = json_value.search("mouse").and_then(|j| j.as_string());
702     assert!(found_str.unwrap() == "cheese");
703 }
704
705 #[test]
706 fn test_index(){
707     let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
708     let ref array = json_value["animals"];
709     assert_eq!(array[0].as_string().unwrap(), "dog");
710     assert_eq!(array[1].as_string().unwrap(), "cat");
711     assert_eq!(array[2].as_string().unwrap(), "mouse");
712 }
713
714 #[test]
715 fn test_is_object(){
716     let json_value = from_str("{}").unwrap();
717     assert!(json_value.is_object());
718 }
719
720 #[test]
721 fn test_as_object(){
722     let json_value = from_str("{}").unwrap();
723     let json_object = json_value.as_object();
724     assert!(json_object.is_some());
725 }
726
727 #[test]
728 fn test_is_array(){
729     let json_value = from_str("[1, 2, 3]").unwrap();
730     assert!(json_value.is_array());
731 }
732
733 #[test]
734 fn test_as_array(){
735     let json_value = from_str("[1, 2, 3]").unwrap();
736     let json_array = json_value.as_array();
737     let expected_length = 3;
738     assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
739 }
740
741 #[test]
742 fn test_is_string(){
743     let json_value = from_str("\"dog\"").unwrap();
744     assert!(json_value.is_string());
745 }
746
747 #[test]
748 fn test_as_string(){
749     let json_value = from_str("\"dog\"").unwrap();
750     let json_str = json_value.as_string();
751     let expected_str = "dog";
752     assert_eq!(json_str, Some(expected_str));
753 }
754
755 #[test]
756 fn test_is_number(){
757     let json_value = from_str("12").unwrap();
758     assert!(json_value.is_number());
759 }
760
761 #[test]
762 fn test_is_i64(){
763     let json_value = from_str("-12").unwrap();
764     assert!(json_value.is_i64());
765
766     let json_value = from_str("12").unwrap();
767     assert!(!json_value.is_i64());
768
769     let json_value = from_str("12.0").unwrap();
770     assert!(!json_value.is_i64());
771 }
772
773 #[test]
774 fn test_is_u64(){
775     let json_value = from_str("12").unwrap();
776     assert!(json_value.is_u64());
777
778     let json_value = from_str("-12").unwrap();
779     assert!(!json_value.is_u64());
780
781     let json_value = from_str("12.0").unwrap();
782     assert!(!json_value.is_u64());
783 }
784
785 #[test]
786 fn test_is_f64(){
787     let json_value = from_str("12").unwrap();
788     assert!(!json_value.is_f64());
789
790     let json_value = from_str("-12").unwrap();
791     assert!(!json_value.is_f64());
792
793     let json_value = from_str("12.0").unwrap();
794     assert!(json_value.is_f64());
795
796     let json_value = from_str("-12.0").unwrap();
797     assert!(json_value.is_f64());
798 }
799
800 #[test]
801 fn test_as_i64(){
802     let json_value = from_str("-12").unwrap();
803     let json_num = json_value.as_i64();
804     assert_eq!(json_num, Some(-12));
805 }
806
807 #[test]
808 fn test_as_u64(){
809     let json_value = from_str("12").unwrap();
810     let json_num = json_value.as_u64();
811     assert_eq!(json_num, Some(12));
812 }
813
814 #[test]
815 fn test_as_f64(){
816     let json_value = from_str("12.0").unwrap();
817     let json_num = json_value.as_f64();
818     assert_eq!(json_num, Some(12f64));
819 }
820
821 #[test]
822 fn test_is_boolean(){
823     let json_value = from_str("false").unwrap();
824     assert!(json_value.is_boolean());
825 }
826
827 #[test]
828 fn test_as_boolean(){
829     let json_value = from_str("false").unwrap();
830     let json_bool = json_value.as_boolean();
831     let expected_bool = false;
832     assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
833 }
834
835 #[test]
836 fn test_is_null(){
837     let json_value = from_str("null").unwrap();
838     assert!(json_value.is_null());
839 }
840
841 #[test]
842 fn test_as_null(){
843     let json_value = from_str("null").unwrap();
844     let json_null = json_value.as_null();
845     let expected_null = ();
846     assert!(json_null.is_some() && json_null.unwrap() == expected_null);
847 }
848
849 #[test]
850 fn test_encode_hashmap_with_numeric_key() {
851     use std::str::from_utf8;
852     use std::collections::HashMap;
853     let mut hm: HashMap<usize, bool> = HashMap::new();
854     hm.insert(1, true);
855     let mut mem_buf = Vec::new();
856     write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
857     let json_str = from_utf8(&mem_buf[..]).unwrap();
858     match from_str(json_str) {
859         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
860         _ => {} // it parsed and we are good to go
861     }
862 }
863
864 #[test]
865 fn test_prettyencode_hashmap_with_numeric_key() {
866     use std::str::from_utf8;
867     use std::collections::HashMap;
868     let mut hm: HashMap<usize, bool> = HashMap::new();
869     hm.insert(1, true);
870     let mut mem_buf = Vec::new();
871     write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
872     let json_str = from_utf8(&mem_buf[..]).unwrap();
873     match from_str(json_str) {
874         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
875         _ => {} // it parsed and we are good to go
876     }
877 }
878
879 #[test]
880 fn test_prettyencoder_indent_level_param() {
881     use std::str::from_utf8;
882     use std::collections::BTreeMap;
883
884     let mut tree = BTreeMap::new();
885
886     tree.insert("hello".to_string(), String("guten tag".to_string()));
887     tree.insert("goodbye".to_string(), String("sayonara".to_string()));
888
889     let json = Array(
890         // The following layout below should look a lot like
891         // the pretty-printed JSON (indent * x)
892         vec!
893         ( // 0x
894             String("greetings".to_string()), // 1x
895             Object(tree), // 1x + 2x + 2x + 1x
896         ) // 0x
897         // End JSON array (7 lines)
898     );
899
900     // Helper function for counting indents
901     fn indents(source: &str) -> usize {
902         let trimmed = source.trim_start_matches(' ');
903         source.len() - trimmed.len()
904     }
905
906     // Test up to 4 spaces of indents (more?)
907     for i in 0..4 {
908         let mut writer = Vec::new();
909         write!(&mut writer, "{}",
910                 json::as_pretty_json(&json).indent(i)).unwrap();
911
912         let printed = from_utf8(&writer[..]).unwrap();
913
914         // Check for indents at each line
915         let lines: Vec<&str> = printed.lines().collect();
916         assert_eq!(lines.len(), 7); // JSON should be 7 lines
917
918         assert_eq!(indents(lines[0]), 0 * i); // [
919         assert_eq!(indents(lines[1]), 1 * i); //   "greetings",
920         assert_eq!(indents(lines[2]), 1 * i); //   {
921         assert_eq!(indents(lines[3]), 2 * i); //     "hello": "guten tag",
922         assert_eq!(indents(lines[4]), 2 * i); //     "goodbye": "sayonara"
923         assert_eq!(indents(lines[5]), 1 * i); //   },
924         assert_eq!(indents(lines[6]), 0 * i); // ]
925
926         // Finally, test that the pretty-printed JSON is valid
927         from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
928     }
929 }
930
931 #[test]
932 fn test_hashmap_with_enum_key() {
933     use std::collections::HashMap;
934     #[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Debug)]
935     enum Enum {
936         Foo,
937         #[allow(dead_code)]
938         Bar,
939     }
940     let mut map = HashMap::new();
941     map.insert(Enum::Foo, 0);
942     let result = json::encode(&map).unwrap();
943     assert_eq!(&result[..], r#"{"Foo":0}"#);
944     let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
945     assert_eq!(map, decoded);
946 }
947
948 #[test]
949 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
950     use std::collections::HashMap;
951     let json_str = "{\"1\":true}";
952     let json_obj = match from_str(json_str) {
953         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
954         Ok(o) => o
955     };
956     let mut decoder = Decoder::new(json_obj);
957     let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
958 }
959
960 #[test]
961 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
962     use std::collections::HashMap;
963     let json_str = "{\"a\":true}";
964     let json_obj = match from_str(json_str) {
965         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
966         Ok(o) => o
967     };
968     let mut decoder = Decoder::new(json_obj);
969     let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder);
970     assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
971 }
972
973 fn assert_stream_equal(src: &str,
974                         expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) {
975     let mut parser = Parser::new(src.chars());
976     let mut i = 0;
977     loop {
978         let evt = match parser.next() {
979             Some(e) => e,
980             None => { break; }
981         };
982         let (ref expected_evt, ref expected_stack) = expected[i];
983         if !parser.stack().is_equal_to(expected_stack) {
984             panic!("Parser stack is not equal to {:?}", expected_stack);
985         }
986         assert_eq!(&evt, expected_evt);
987         i+=1;
988     }
989 }
990 #[test]
991 fn test_streaming_parser() {
992     assert_stream_equal(
993         r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
994         vec![
995             (ObjectStart,             vec![]),
996               (StringValue("bar".to_string()),   vec![StackElement::Key("foo")]),
997               (ArrayStart,            vec![StackElement::Key("array")]),
998                 (U64Value(0),         vec![StackElement::Key("array"), StackElement::Index(0)]),
999                 (U64Value(1),         vec![StackElement::Key("array"), StackElement::Index(1)]),
1000                 (U64Value(2),         vec![StackElement::Key("array"), StackElement::Index(2)]),
1001                 (U64Value(3),         vec![StackElement::Key("array"), StackElement::Index(3)]),
1002                 (U64Value(4),         vec![StackElement::Key("array"), StackElement::Index(4)]),
1003                 (U64Value(5),         vec![StackElement::Key("array"), StackElement::Index(5)]),
1004               (ArrayEnd,              vec![StackElement::Key("array")]),
1005               (ArrayStart,            vec![StackElement::Key("idents")]),
1006                 (NullValue,           vec![StackElement::Key("idents"),
1007                                            StackElement::Index(0)]),
1008                 (BooleanValue(true),  vec![StackElement::Key("idents"),
1009                                            StackElement::Index(1)]),
1010                 (BooleanValue(false), vec![StackElement::Key("idents"),
1011                                            StackElement::Index(2)]),
1012               (ArrayEnd,              vec![StackElement::Key("idents")]),
1013             (ObjectEnd,               vec![]),
1014         ]
1015     );
1016 }
1017 fn last_event(src: &str) -> JsonEvent {
1018     let mut parser = Parser::new(src.chars());
1019     let mut evt = NullValue;
1020     loop {
1021         evt = match parser.next() {
1022             Some(e) => e,
1023             None => return evt,
1024         }
1025     }
1026 }
1027
1028 #[test]
1029 fn test_read_object_streaming() {
1030     assert_eq!(last_event("{ "),      Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
1031     assert_eq!(last_event("{1"),      Error(SyntaxError(KeyMustBeAString,      1, 2)));
1032     assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1033     assert_eq!(last_event("{\"a\""),  Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
1034     assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1035
1036     assert_eq!(last_event("{\"a\" 1"),   Error(SyntaxError(ExpectedColon,         1, 6)));
1037     assert_eq!(last_event("{\"a\":"),    Error(SyntaxError(EOFWhileParsingValue,  1, 6)));
1038     assert_eq!(last_event("{\"a\":1"),   Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
1039     assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax,         1, 8)));
1040     assert_eq!(last_event("{\"a\":1,"),  Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
1041     assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
1042
1043     assert_stream_equal(
1044         "{}",
1045         vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
1046     );
1047     assert_stream_equal(
1048         "{\"a\": 3}",
1049         vec![
1050             (ObjectStart,        vec![]),
1051               (U64Value(3),      vec![StackElement::Key("a")]),
1052             (ObjectEnd,          vec![]),
1053         ]
1054     );
1055     assert_stream_equal(
1056         "{ \"a\": null, \"b\" : true }",
1057         vec![
1058             (ObjectStart,           vec![]),
1059               (NullValue,           vec![StackElement::Key("a")]),
1060               (BooleanValue(true),  vec![StackElement::Key("b")]),
1061             (ObjectEnd,             vec![]),
1062         ]
1063     );
1064     assert_stream_equal(
1065         "{\"a\" : 1.0 ,\"b\": [ true ]}",
1066         vec![
1067             (ObjectStart,           vec![]),
1068               (F64Value(1.0),       vec![StackElement::Key("a")]),
1069               (ArrayStart,          vec![StackElement::Key("b")]),
1070                 (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]),
1071               (ArrayEnd,            vec![StackElement::Key("b")]),
1072             (ObjectEnd,             vec![]),
1073         ]
1074     );
1075     assert_stream_equal(
1076         r#"{
1077             "a": 1.0,
1078             "b": [
1079                 true,
1080                 "foo\nbar",
1081                 { "c": {"d": null} }
1082             ]
1083         }"#,
1084         vec![
1085             (ObjectStart,                   vec![]),
1086               (F64Value(1.0),               vec![StackElement::Key("a")]),
1087               (ArrayStart,                  vec![StackElement::Key("b")]),
1088                 (BooleanValue(true),        vec![StackElement::Key("b"),
1089                                                 StackElement::Index(0)]),
1090                 (StringValue("foo\nbar".to_string()),  vec![StackElement::Key("b"),
1091                                                             StackElement::Index(1)]),
1092                 (ObjectStart,               vec![StackElement::Key("b"),
1093                                                  StackElement::Index(2)]),
1094                   (ObjectStart,             vec![StackElement::Key("b"),
1095                                                  StackElement::Index(2),
1096                                                  StackElement::Key("c")]),
1097                     (NullValue,             vec![StackElement::Key("b"),
1098                                                  StackElement::Index(2),
1099                                                  StackElement::Key("c"),
1100                                                  StackElement::Key("d")]),
1101                   (ObjectEnd,               vec![StackElement::Key("b"),
1102                                                  StackElement::Index(2),
1103                                                  StackElement::Key("c")]),
1104                 (ObjectEnd,                 vec![StackElement::Key("b"),
1105                                                  StackElement::Index(2)]),
1106               (ArrayEnd,                    vec![StackElement::Key("b")]),
1107             (ObjectEnd,                     vec![]),
1108         ]
1109     );
1110 }
1111 #[test]
1112 fn test_read_array_streaming() {
1113     assert_stream_equal(
1114         "[]",
1115         vec![
1116             (ArrayStart, vec![]),
1117             (ArrayEnd,   vec![]),
1118         ]
1119     );
1120     assert_stream_equal(
1121         "[ ]",
1122         vec![
1123             (ArrayStart, vec![]),
1124             (ArrayEnd,   vec![]),
1125         ]
1126     );
1127     assert_stream_equal(
1128         "[true]",
1129         vec![
1130             (ArrayStart,             vec![]),
1131                 (BooleanValue(true), vec![StackElement::Index(0)]),
1132             (ArrayEnd,               vec![]),
1133         ]
1134     );
1135     assert_stream_equal(
1136         "[ false ]",
1137         vec![
1138             (ArrayStart,              vec![]),
1139                 (BooleanValue(false), vec![StackElement::Index(0)]),
1140             (ArrayEnd,                vec![]),
1141         ]
1142     );
1143     assert_stream_equal(
1144         "[null]",
1145         vec![
1146             (ArrayStart,    vec![]),
1147                 (NullValue, vec![StackElement::Index(0)]),
1148             (ArrayEnd,      vec![]),
1149         ]
1150     );
1151     assert_stream_equal(
1152         "[3, 1]",
1153         vec![
1154             (ArrayStart,      vec![]),
1155                 (U64Value(3), vec![StackElement::Index(0)]),
1156                 (U64Value(1), vec![StackElement::Index(1)]),
1157             (ArrayEnd,        vec![]),
1158         ]
1159     );
1160     assert_stream_equal(
1161         "\n[3, 2]\n",
1162         vec![
1163             (ArrayStart,      vec![]),
1164                 (U64Value(3), vec![StackElement::Index(0)]),
1165                 (U64Value(2), vec![StackElement::Index(1)]),
1166             (ArrayEnd,        vec![]),
1167         ]
1168     );
1169     assert_stream_equal(
1170         "[2, [4, 1]]",
1171         vec![
1172             (ArrayStart,           vec![]),
1173                 (U64Value(2),      vec![StackElement::Index(0)]),
1174                 (ArrayStart,       vec![StackElement::Index(1)]),
1175                     (U64Value(4),  vec![StackElement::Index(1), StackElement::Index(0)]),
1176                     (U64Value(1),  vec![StackElement::Index(1), StackElement::Index(1)]),
1177                 (ArrayEnd,         vec![StackElement::Index(1)]),
1178             (ArrayEnd,             vec![]),
1179         ]
1180     );
1181
1182     assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1,  2)));
1183
1184     assert_eq!(from_str("["),     Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
1185     assert_eq!(from_str("[1"),    Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
1186     assert_eq!(from_str("[1,"),   Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
1187     assert_eq!(from_str("[1,]"),  Err(SyntaxError(InvalidSyntax,        1, 4)));
1188     assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax,        1, 4)));
1189
1190 }
1191 #[test]
1192 fn test_trailing_characters_streaming() {
1193     assert_eq!(last_event("nulla"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
1194     assert_eq!(last_event("truea"),  Error(SyntaxError(TrailingCharacters, 1, 5)));
1195     assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
1196     assert_eq!(last_event("1a"),     Error(SyntaxError(TrailingCharacters, 1, 2)));
1197     assert_eq!(last_event("[]a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
1198     assert_eq!(last_event("{}a"),    Error(SyntaxError(TrailingCharacters, 1, 3)));
1199 }
1200 #[test]
1201 fn test_read_identifiers_streaming() {
1202     assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
1203     assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
1204     assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
1205
1206     assert_eq!(last_event("n"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
1207     assert_eq!(last_event("nul"),  Error(SyntaxError(InvalidSyntax, 1, 4)));
1208     assert_eq!(last_event("t"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
1209     assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1210     assert_eq!(last_event("f"),    Error(SyntaxError(InvalidSyntax, 1, 2)));
1211     assert_eq!(last_event("faz"),  Error(SyntaxError(InvalidSyntax, 1, 3)));
1212 }
1213
1214 #[test]
1215 fn test_to_json() {
1216     use std::collections::{HashMap,BTreeMap};
1217     use json::ToJson;
1218
1219     let array2 = Array(vec![U64(1), U64(2)]);
1220     let array3 = Array(vec![U64(1), U64(2), U64(3)]);
1221     let object = {
1222         let mut tree_map = BTreeMap::new();
1223         tree_map.insert("a".to_string(), U64(1));
1224         tree_map.insert("b".to_string(), U64(2));
1225         Object(tree_map)
1226     };
1227
1228     assert_eq!(array2.to_json(), array2);
1229     assert_eq!(object.to_json(), object);
1230     assert_eq!(3_isize.to_json(), I64(3));
1231     assert_eq!(4_i8.to_json(), I64(4));
1232     assert_eq!(5_i16.to_json(), I64(5));
1233     assert_eq!(6_i32.to_json(), I64(6));
1234     assert_eq!(7_i64.to_json(), I64(7));
1235     assert_eq!(8_usize.to_json(), U64(8));
1236     assert_eq!(9_u8.to_json(), U64(9));
1237     assert_eq!(10_u16.to_json(), U64(10));
1238     assert_eq!(11_u32.to_json(), U64(11));
1239     assert_eq!(12_u64.to_json(), U64(12));
1240     assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
1241     assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
1242     assert_eq!(().to_json(), Null);
1243     assert_eq!(f32::INFINITY.to_json(), Null);
1244     assert_eq!(f64::NAN.to_json(), Null);
1245     assert_eq!(true.to_json(), Boolean(true));
1246     assert_eq!(false.to_json(), Boolean(false));
1247     assert_eq!("abc".to_json(), String("abc".to_string()));
1248     assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
1249     assert_eq!((1_usize, 2_usize).to_json(), array2);
1250     assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
1251     assert_eq!([1_usize, 2_usize].to_json(), array2);
1252     assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
1253     assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
1254     assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
1255     let mut tree_map = BTreeMap::new();
1256     tree_map.insert("a".to_string(), 1 as usize);
1257     tree_map.insert("b".to_string(), 2);
1258     assert_eq!(tree_map.to_json(), object);
1259     let mut hash_map = HashMap::new();
1260     hash_map.insert("a".to_string(), 1 as usize);
1261     hash_map.insert("b".to_string(), 2);
1262     assert_eq!(hash_map.to_json(), object);
1263     assert_eq!(Some(15).to_json(), I64(15));
1264     assert_eq!(Some(15 as usize).to_json(), U64(15));
1265     assert_eq!(None::<isize>.to_json(), Null);
1266 }
1267
1268 #[test]
1269 fn test_encode_hashmap_with_arbitrary_key() {
1270     use std::collections::HashMap;
1271     #[derive(PartialEq, Eq, Hash, RustcEncodable)]
1272     struct ArbitraryType(usize);
1273     let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
1274     hm.insert(ArbitraryType(1), true);
1275     let mut mem_buf = string::String::new();
1276     let mut encoder = Encoder::new(&mut mem_buf);
1277     let result = hm.encode(&mut encoder);
1278     match result.unwrap_err() {
1279         EncoderError::BadHashmapKey => (),
1280         _ => panic!("expected bad hash map key")
1281     }
1282 }