forked from stleary/JSON-Java-unit-test
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONObjectTest.java
More file actions
Latest commit
1758 lines (1655 loc) · 76.5 KB
/
Copy pathJSONObjectTest.java
File metadata and controls
1758 lines (1655 loc) · 76.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
packageorg.json.junit;
importstaticorg.junit.Assert.*;
importstaticorg.mockito.Mockito.*;
importjava.io.*;
importjava.math.BigDecimal;
importjava.math.BigInteger;
importjava.util.*;
importorg.json.*;
importorg.junit.*;
/**
* Used in testing when a JSONString is needed
*/
classMyJsonStringimplementsJSONString {
@Override
publicStringtoJSONString() {
return"my string";
}
}
/**
* Used in testing when Bean behavior is needed
*/
interfaceMyBean {
publicIntegergetIntKey();
publicDoublegetDoubleKey();
publicStringgetStringKey();
publicStringgetEscapeStringKey();
publicBooleanisTrueKey();
publicBooleanisFalseKey();
publicStringReadergetStringReaderKey();
};
/**
* Used in testing when a Bean containing big numbers is needed
*/
interfaceMyBigNumberBean {
publicBigIntegergetBigInteger();
publicBigDecimalgetBigDecimal();
}
/**
* JSONObject, along with JSONArray, are the central classes of the reference app.
* All of the other classes interact with them, and JSON functionality would
* otherwise be impossible.
*/
publicclassJSONObjectTest {
/**
* Need a class with some public data members for testing, so
* JSONObjectTest itself will be used for this purpose.
* TODO: Why not use MyBigNumberBean or MyBean?
*/
publicIntegerpublicInt = 42;
publicStringpublicString = "abc";
/**
* JSONObject built from a bean, but only using a null value.
* Nothing good is expected to happen.
* Expects NullPointerException
*/
@Test(expected=NullPointerException.class)
publicvoidjsonObjectByNullBean() {
MyBeanmyBean = null;
newJSONObject(myBean);
}
/**
* A JSONObject can be created with no content
*/
@Test
publicvoidemptyJsonObject() {
JSONObjectjsonObject = newJSONObject();
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* A JSONObject can be created from another JSONObject plus a list of names.
* In this test, some of the starting JSONObject keys are not in the
* names list.
*/
@Test
publicvoidjsonObjectByNames() {
Stringstr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"nullKey\":null,"+
"\"stringKey\":\"hello world!\","+
"\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
"\"intKey\":42,"+
"\"doubleKey\":-23.45e67"+
"}";
String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"};
StringexpectedStr =
"{"+
"\"falseKey\":false,"+
"\"nullKey\":null,"+
"\"stringKey\":\"hello world!\","+
"\"doubleKey\":-23.45e67"+
"}";
JSONObjectjsonObject = newJSONObject(str);
JSONObjectcopyJsonObject = newJSONObject(jsonObject, keys);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(copyJsonObject, expectedJsonObject);
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test the map is null.
* the JSONObject(JsonTokener) ctor is not tested directly since it already
* has full coverage from other tests.
*/
@Test
publicvoidjsonObjectByNullMap() {
Map<String, Object> map = null;
JSONObjectjsonObject = newJSONObject(map);
JSONObjectexpectedJsonObject = newJSONObject();
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test all of the map entries are valid JSON types.
*/
@Test
publicvoidjsonObjectByMap() {
StringexpectedStr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
"\"intKey\":42,"+
"\"doubleKey\":-23.45e67"+
"}";
Map<String, Object> jsonMap = newHashMap<String, Object>();
jsonMap.put("trueKey", newBoolean(true));
jsonMap.put("falseKey", newBoolean(false));
jsonMap.put("stringKey", "hello world!");
jsonMap.put("escapeStringKey", "h\be\tllo w\u1234orld!");
jsonMap.put("intKey", newLong(42));
jsonMap.put("doubleKey", newDouble(-23.45e67));
JSONObjectjsonObject = newJSONObject(jsonMap);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test the map entries are not valid JSON types.
* The actual conversion is kind of interesting.
*/
@Test
publicvoidjsonObjectByMapWithUnsupportedValues() {
StringexpectedStr =
"{"+
"\"key1\":{},"+
"\"key2\":\"java.lang.Exception\""+
"}";
Map<String, Object> jsonMap = newHashMap<String, Object>();
// Just insert some random objects
jsonMap.put("key1", newCDL());
jsonMap.put("key2", newException());
JSONObjectjsonObject = newJSONObject(jsonMap);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* JSONObjects can be built from a Map<String, Object>.
* In this test one of the map values is null
*/
@Test
publicvoidjsonObjectByMapWithNullValue() {
StringexpectedStr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
"\"intKey\":42,"+
"\"doubleKey\":-23.45e67"+
"}";
Map<String, Object> jsonMap = newHashMap<String, Object>();
jsonMap.put("trueKey", newBoolean(true));
jsonMap.put("falseKey", newBoolean(false));
jsonMap.put("stringKey", "hello world!");
jsonMap.put("nullKey", null);
jsonMap.put("escapeStringKey", "h\be\tllo w\u1234orld!");
jsonMap.put("intKey", newLong(42));
jsonMap.put("doubleKey", newDouble(-23.45e67));
JSONObjectjsonObject = newJSONObject(jsonMap);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* JSONObject built from a bean. In this case all but one of the
* bean getters return valid JSON types
*/
@Test
publicvoidjsonObjectByBean() {
StringexpectedStr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
"\"intKey\":42,"+
"\"doubleKey\":-23.45e7,"+
"\"stringReaderKey\":{},"+
"\"callbacks\":[{\"handler\":{}},{}]"+ // sorry, mockito artifact
"}";
/**
* Default access classes have to be mocked since JSONObject, which is
* not in the same package, cannot call MyBean methods by reflection.
*/
MyBeanmyBean = mock(MyBean.class);
when(myBean.getDoubleKey()).thenReturn(-23.45e7);
when(myBean.getIntKey()).thenReturn(42);
when(myBean.getStringKey()).thenReturn("hello world!");
when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!");
when(myBean.isTrueKey()).thenReturn(true);
when(myBean.isFalseKey()).thenReturn(false);
when(myBean.getStringReaderKey()).thenReturn(
newStringReader("") {
/**
* TODO: Need to understand why returning a string
* turns "this" into an empty JSONObject,
* but not overriding turns "this" into a string.
*/
@Override
publicStringtoString(){
return"Whatever";
}
});
JSONObjectjsonObject = newJSONObject(myBean);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* A bean is also an object. But in order to test the JSONObject
* ctor that takes an object and a list of names,
* this particular bean needs some public
* data members, which have been added to the class.
*/
@Test
publicvoidjsonObjectByObjectAndNames() {
StringexpectedStr =
"{"+
"\"publicString\":\"abc\","+
"\"publicInt\":42"+
"}";
String[] keys = {"publicString", "publicInt"};
// just need a class that has public data members
JSONObjectTestjsonObjectTest = newJSONObjectTest();
JSONObjectjsonObject = newJSONObject(jsonObjectTest, keys);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* Exercise the JSONObject from resource bundle functionality
*/
@Test
publicvoidjsonObjectByResourceBundle() {
// TODO: how to improve resource bundle testing?
StringexpectedStr =
"{"+
"\"greetings\": {"+
"\"hello\":\"Hello, \","+
"\"world\":\"World!\""+
"},"+
"\"farewells\": {"+
"\"later\":\"Later, \","+
"\"gator\":\"Alligator!\""+
"}"+
"}";
JSONObjectjsonObject = new
JSONObject("org.json.junit.StringsResourceBundle",
Locale.getDefault());
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* Exercise the JSONObject.accumulate() method
*/
@Test
publicvoidjsonObjectAccumulate() {
// TODO: should include an unsupported object
StringexpectedStr =
"{"+
"\"myArray\": ["+
"true,"+
"false,"+
"\"hello world!\","+
"\"h\be\tllo w\u1234orld!\","+
"42,"+
"-23.45e7"+
"]"+
"}";
JSONObjectjsonObject = newJSONObject();
jsonObject.accumulate("myArray", true);
jsonObject.accumulate("myArray", false);
jsonObject.accumulate("myArray", "hello world!");
jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!");
jsonObject.accumulate("myArray", 42);
jsonObject.accumulate("myArray", -23.45e7);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* Exercise the JSONObject append() functionality
*/
@Test
publicvoidjsonObjectAppend() {
// TODO: should include an unsupported object
StringexpectedStr =
"{"+
"\"myArray\": ["+
"true,"+
"false,"+
"\"hello world!\","+
"\"h\be\tllo w\u1234orld!\","+
"42,"+
"-23.45e7"+
"]"+
"}";
JSONObjectjsonObject = newJSONObject();
jsonObject.append("myArray", true);
jsonObject.append("myArray", false);
jsonObject.append("myArray", "hello world!");
jsonObject.append("myArray", "h\be\tllo w\u1234orld!");
jsonObject.append("myArray", 42);
jsonObject.append("myArray", -23.45e7);
JSONObjectexpectedJsonObject = newJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject);
}
/**
* Exercise the JSONObject doubleToString() method
*/
@Test
publicvoidjsonObjectDoubleToString() {
String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" };
Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67,
Double.NaN, Double.NEGATIVE_INFINITY };
for (inti = 0; i < expectedStrs.length; ++i) {
StringactualStr = JSONObject.doubleToString(doubles[i]);
assertTrue("value expected ["+expectedStrs[i]+
"] found ["+actualStr+ "]",
expectedStrs[i].equals(actualStr));
}
}
/**
* Exercise some JSONObject get[type] and opt[type] methods
*/
@Test
publicvoidjsonObjectValues() {
Stringstr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"trueStrKey\":\"true\","+
"\"falseStrKey\":\"false\","+
"\"stringKey\":\"hello world!\","+
"\"intKey\":42,"+
"\"intStrKey\":\"43\","+
"\"longKey\":1234567890123456789,"+
"\"longStrKey\":\"987654321098765432\","+
"\"doubleKey\":-23.45e7,"+
"\"doubleStrKey\":\"00001.000\","+
"\"arrayKey\":[0,1,2],"+
"\"objectKey\":{\"myKey\":\"myVal\"}"+
"}";
JSONObjectjsonObject = newJSONObject(str);
assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey"));
assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey"));
assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey"));
assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey"));
assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey"));
assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey"));
assertTrue("stringKey should be string",
jsonObject.getString("stringKey").equals("hello world!"));
assertTrue("doubleKey should be double",
jsonObject.getDouble("doubleKey") == -23.45e7);
assertTrue("doubleStrKey should be double",
jsonObject.getDouble("doubleStrKey") == 1);
assertTrue("opt doubleKey should be double",
jsonObject.optDouble("doubleKey") == -23.45e7);
assertTrue("opt doubleKey with Default should be double",
jsonObject.optDouble("doubleStrKey", Double.NaN) == 1);
assertTrue("intKey should be int",
jsonObject.optInt("intKey") == 42);
assertTrue("opt intKey should be int",
jsonObject.optInt("intKey", 0) == 42);
assertTrue("opt intKey with default should be int",
jsonObject.getInt("intKey") == 42);
assertTrue("intStrKey should be int",
jsonObject.getInt("intStrKey") == 43);
assertTrue("longKey should be long",
jsonObject.getLong("longKey") == 1234567890123456789L);
assertTrue("opt longKey should be long",
jsonObject.optLong("longKey") == 1234567890123456789L);
assertTrue("opt longKey with default should be long",
jsonObject.optLong("longKey", 0) == 1234567890123456789L);
assertTrue("longStrKey should be long",
jsonObject.getLong("longStrKey") == 987654321098765432L);
assertTrue("xKey should not exist",
jsonObject.isNull("xKey"));
assertTrue("stringKey should exist",
jsonObject.has("stringKey"));
assertTrue("opt stringKey should string",
jsonObject.optString("stringKey").equals("hello world!"));
assertTrue("opt stringKey with default should string",
jsonObject.optString("stringKey", "not found").equals("hello world!"));
JSONArrayjsonArray = jsonObject.getJSONArray("arrayKey");
assertTrue("arrayKey should be JSONArray",
jsonArray.getInt(0) == 0 &&
jsonArray.getInt(1) == 1 &&
jsonArray.getInt(2) == 2);
jsonArray = jsonObject.optJSONArray("arrayKey");
assertTrue("opt arrayKey should be JSONArray",
jsonArray.getInt(0) == 0 &&
jsonArray.getInt(1) == 1 &&
jsonArray.getInt(2) == 2);
JSONObjectjsonObjectInner = jsonObject.getJSONObject("objectKey");
assertTrue("objectKey should be JSONObject",
jsonObjectInner.get("myKey").equals("myVal"));
}
/**
* Check whether JSONObject handles large or high precision numbers correctly
*/
@Test
publicvoidstringToValueNumbersTest() {
assertTrue( "0.2 should be a Double!",
JSONObject.stringToValue( "0.2" ) instanceofDouble );
assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!",
JSONObject.stringToValue( newDouble( "0.2f" ).toString() ) instanceofDouble );
/**
* This test documents a need for BigDecimal conversion.
*/
Objectobj = JSONObject.stringToValue( "299792.457999999984" );
assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!",
obj.equals(newDouble(299792.458)) );
assertTrue( "1 should be an Integer!",
JSONObject.stringToValue( "1" ) instanceofInteger );
assertTrue( "Integer.MAX_VALUE should still be an Integer!",
JSONObject.stringToValue( newInteger( Integer.MAX_VALUE ).toString() ) instanceofInteger );
assertTrue( "Large integers should be a Long!",
JSONObject.stringToValue( newLong( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceofLong );
assertTrue( "Long.MAX_VALUE should still be an Integer!",
JSONObject.stringToValue( newLong( Long.MAX_VALUE ).toString() ) instanceofLong );
Stringstr = newBigInteger( newLong( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString();
assertTrue( "Really large integers currently evaluate to string",
JSONObject.stringToValue(str).equals("9223372036854775808"));
}
/**
* This test documents numeric values which could be numerically
* handled as BigDecimal or BigInteger. It helps determine what outputs
* will change if those types are supported.
*/
@Test
publicvoidjsonValidNumberValuesNeitherLongNorIEEE754Compatible() {
// Valid JSON Numbers, probably should return BigDecimal or BigInteger objects
Stringstr =
"{"+
"\"numberWithDecimals\":299792.457999999984,"+
"\"largeNumber\":12345678901234567890,"+
"\"preciseNumber\":0.2000000000000000111,"+
"\"largeExponent\":-23.45e2327"+
"}";
JSONObjectjsonObject = newJSONObject(str);
// Comes back as a double, but loses precision
assertTrue( "numberWithDecimals currently evaluates to double 299792.458",
jsonObject.get( "numberWithDecimals" ).equals( newDouble( "299792.458" ) ) );
Objectobj = jsonObject.get( "largeNumber" );
assertTrue("largeNumber currently evaluates to string",
"12345678901234567890".equals(obj));
// comes back as a double but loses precision
assertTrue( "preciseNumber currently evaluates to double 0.2",
jsonObject.get( "preciseNumber" ).equals(newDouble(0.2)));
obj = jsonObject.get( "largeExponent" );
assertTrue("largeExponent should currently evaluates as a string",
"-23.45e2327".equals(obj));
}
/**
* This test documents how JSON-Java handles invalid numeric input.
*/
@Test
publicvoidjsonInvalidNumberValues() {
// Number-notations supported by Java and invalid as JSON
Stringstr =
"{"+
"\"hexNumber\":-0x123,"+
"\"tooManyZeros\":00,"+
"\"negativeInfinite\":-Infinity,"+
"\"negativeNaN\":-NaN,"+
"\"negativeFraction\":-.01,"+
"\"tooManyZerosFraction\":00.001,"+
"\"negativeHexFloat\":-0x1.fffp1,"+
"\"hexFloat\":0x1.0P-1074,"+
"\"floatIdentifier\":0.1f,"+
"\"doubleIdentifier\":0.1d"+
"}";
JSONObjectjsonObject = newJSONObject(str);
Objectobj;
obj = jsonObject.get( "hexNumber" );
assertFalse( "hexNumber must not be a number (should throw exception!?)",
objinstanceofNumber );
assertTrue("hexNumber currently evaluates to string",
obj.equals("-0x123"));
assertTrue( "tooManyZeros currently evaluates to string",
jsonObject.get( "tooManyZeros" ).equals("00"));
obj = jsonObject.get("negativeInfinite");
assertTrue( "negativeInfinite currently evaluates to string",
obj.equals("-Infinity"));
obj = jsonObject.get("negativeNaN");
assertTrue( "negativeNaN currently evaluates to string",
obj.equals("-NaN"));
assertTrue( "negativeFraction currently evaluates to double -0.01",
jsonObject.get( "negativeFraction" ).equals(newDouble(-0.01)));
assertTrue( "tooManyZerosFraction currently evaluates to double 0.001",
jsonObject.get( "tooManyZerosFraction" ).equals(newDouble(0.001)));
assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875",
jsonObject.get( "negativeHexFloat" ).equals(newDouble(-3.99951171875)));
assertTrue("hexFloat currently evaluates to double 4.9E-324",
jsonObject.get("hexFloat").equals(newDouble(4.9E-324)));
assertTrue("floatIdentifier currently evaluates to double 0.1",
jsonObject.get("floatIdentifier").equals(newDouble(0.1)));
assertTrue("doubleIdentifier currently evaluates to double 0.1",
jsonObject.get("doubleIdentifier").equals(newDouble(0.1)));
}
/**
* Tests how JSONObject get[type] handles incorrect types
*/
@Test
publicvoidjsonObjectNonAndWrongValues() {
Stringstr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"trueStrKey\":\"true\","+
"\"falseStrKey\":\"false\","+
"\"stringKey\":\"hello world!\","+
"\"intKey\":42,"+
"\"intStrKey\":\"43\","+
"\"longKey\":1234567890123456789,"+
"\"longStrKey\":\"987654321098765432\","+
"\"doubleKey\":-23.45e7,"+
"\"doubleStrKey\":\"00001.000\","+
"\"arrayKey\":[0,1,2],"+
"\"objectKey\":{\"myKey\":\"myVal\"}"+
"}";
JSONObjectjsonObject = newJSONObject(str);
try {
jsonObject.getBoolean("nonKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("expecting an exception message",
"JSONObject[\"nonKey\"] not found.".equals(e.getMessage()));
}
try {
jsonObject.getBoolean("stringKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a Boolean.".
equals(e.getMessage()));
}
try {
jsonObject.getString("nonKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getString("trueKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"trueKey\"] not a string.".
equals(e.getMessage()));
}
try {
jsonObject.getDouble("nonKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getDouble("stringKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a number.".
equals(e.getMessage()));
}
try {
jsonObject.getInt("nonKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getInt("stringKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not an int.".
equals(e.getMessage()));
}
try {
jsonObject.getLong("nonKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getLong("stringKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a long.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONArray("nonKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONArray("stringKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a JSONArray.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONObject("nonKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"nonKey\"] not found.".
equals(e.getMessage()));
}
try {
jsonObject.getJSONObject("stringKey");
assertTrue("Expected an exception", false);
} catch (JSONExceptione) {
assertTrue("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a JSONObject.".
equals(e.getMessage()));
}
}
/**
* This test documents an unexpected numeric behavior.
* A double that ends with .0 is parsed, serialized, then
* parsed again. On the second parse, it has become an int.
*/
@Test
publicvoidunexpectedDoubleToIntConversion() {
Stringkey30 = "key30";
Stringkey31 = "key31";
JSONObjectjsonObject = newJSONObject();
jsonObject.put(key30, newDouble(3.0));
jsonObject.put(key31, newDouble(3.1));
assertTrue("3.0 should remain a double",
jsonObject.getDouble(key30) == 3);
assertTrue("3.1 should remain a double",
jsonObject.getDouble(key31) == 3.1);
// turns 3.0 into 3.
StringserializedString = jsonObject.toString();
JSONObjectdeserialized = newJSONObject(serializedString);
assertTrue("3.0 is now an int", deserialized.get(key30) instanceofInteger);
assertTrue("3.0 can still be interpreted as a double",
deserialized.getDouble(key30) == 3.0);
assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1);
}
/**
* Document behaviors of big numbers. Includes both JSONObject
* and JSONArray tests
*/
@Test
publicvoidbigNumberOperations() {
/**
* JSONObject tries to parse BigInteger as a bean, but it only has
* one getter, getLowestBitSet(). The value is lost and an unhelpful
* value is stored. This should be fixed.
*/
BigIntegerbigInteger = newBigInteger("123456789012345678901234567890");
JSONObjectjsonObject = newJSONObject(bigInteger);
Objectobj = jsonObject.get("lowestSetBit");
assertTrue("JSONObject only has 1 value", jsonObject.length() == 1);
assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet",
objinstanceofInteger);
assertTrue("this bigInteger lowestBitSet happens to be 1",
obj.equals(1));
/**
* JSONObject tries to parse BigDecimal as a bean, but it has
* no getters, The value is lost and no value is stored.
* This should be fixed.
*/
BigDecimalbigDecimal = newBigDecimal(
"123456789012345678901234567890.12345678901234567890123456789");
jsonObject = newJSONObject(bigDecimal);
assertTrue("large bigDecimal is not stored", jsonObject.length() == 0);
/**
* JSONObject put(String, Object) method stores and serializes
* bigInt and bigDec correctly. Nothing needs to change.
* TODO: New methods
* get|optBigInteger|BigDecimal() should work like other supported
* objects. Uncomment the get/opt methods after JSONObject is updated.
*/
jsonObject = newJSONObject();
jsonObject.put("bigInt", bigInteger);
assertTrue("jsonObject.put() handles bigInt correctly",
jsonObject.get("bigInt").equals(bigInteger));
// assertTrue("jsonObject.getBigInteger() handles bigInt correctly",
// jsonObject.getBigInteger("bigInt").equals(bigInteger));
// assertTrue("jsonObject.optBigInteger() handles bigInt correctly",
// jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger));
assertTrue("jsonObject serializes bigInt correctly",
jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}"));
jsonObject = newJSONObject();
jsonObject.put("bigDec", bigDecimal);
assertTrue("jsonObject.put() handles bigDec correctly",
jsonObject.get("bigDec").equals(bigDecimal));
// assertTrue("jsonObject.getBigDecimal() handles bigDec correctly",
// jsonObject.getBigDecimal("bigDec").equals(bigDecimal));
// assertTrue("jsonObject.optBigDecimal() handles bigDec correctly",
// jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal));
assertTrue("jsonObject serializes bigDec correctly",
jsonObject.toString().equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
JSONArrayjsonArray = newJSONArray();
/**
* JSONObject.numberToString() works correctly, nothing to change.
*/
Stringstr = JSONObject.numberToString(bigInteger);
assertTrue("numberToString() handles bigInteger correctly",
str.equals("123456789012345678901234567890"));
str = JSONObject.numberToString(bigDecimal);
assertTrue("numberToString() handles bigDecimal correctly",
str.equals("123456789012345678901234567890.12345678901234567890123456789"));
/**
* JSONObject.stringToValue() turns bigInt into an accurate string,
* and rounds bigDec. This incorrect, but users may have come to
* expect this behavior. Change would be marginally better, but
* might inconvenience users.
*/
obj = JSONObject.stringToValue(bigInteger.toString());
assertTrue("stringToValue() turns bigInteger string into string",
objinstanceofString);
obj = JSONObject.stringToValue(bigDecimal.toString());
assertTrue("stringToValue() changes bigDecimal string",
!obj.toString().equals(bigDecimal.toString()));
/**
* wrap() vs put() big number behavior is now the same.
*/
// bigInt map ctor
Map<String, Object> map = newHashMap<String, Object>();
map.put("bigInt", bigInteger);
jsonObject = newJSONObject(map);
StringactualFromMapStr = jsonObject.toString();
assertTrue("bigInt in map (or array or bean) is a string",
actualFromMapStr.equals(
"{\"bigInt\":123456789012345678901234567890}"));
// bigInt put
jsonObject = newJSONObject();
jsonObject.put("bigInt", bigInteger);
StringactualFromPutStr = jsonObject.toString();
assertTrue("bigInt from put is a number",
actualFromPutStr.equals(
"{\"bigInt\":123456789012345678901234567890}"));
// bigDec map ctor
map = newHashMap<String, Object>();
map.put("bigDec", bigDecimal);
jsonObject = newJSONObject(map);
actualFromMapStr = jsonObject.toString();
assertTrue("bigDec in map (or array or bean) is a bigDec",
actualFromMapStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigDec put
jsonObject = newJSONObject();
jsonObject.put("bigDec", bigDecimal);
actualFromPutStr = jsonObject.toString();
assertTrue("bigDec from put is a number",
actualFromPutStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigInt,bigDec put
jsonArray = newJSONArray();
jsonArray.put(bigInteger);
jsonArray.put(bigDecimal);
actualFromPutStr = jsonArray.toString();
assertTrue("bigInt, bigDec from put is a number",
actualFromPutStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger));
assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal));
assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger));
assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal));
jsonArray.put(Boolean.TRUE);
try {
jsonArray.getBigInteger(2);
assertTrue("should not be able to get big int", false);
} catch (Exceptionignored) {}
try {
jsonArray.getBigDecimal(2);
assertTrue("should not be able to get big dec", false);
} catch (Exceptionignored) {}
assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE));
assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE));
// bigInt,bigDec list ctor
List<Object> list = newArrayList<Object>();
list.add(bigInteger);
list.add(bigDecimal);
jsonArray = newJSONArray(list);
StringactualFromListStr = jsonArray.toString();
assertTrue("bigInt, bigDec in list is a bigInt, bigDec",
actualFromListStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
// bigInt bean ctor
MyBigNumberBeanmyBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigInteger()).thenReturn(newBigInteger("123456789012345678901234567890"));
jsonObject = newJSONObject(myBigNumberBean);
StringactualFromBeanStr = jsonObject.toString();
// can't do a full string compare because mockery adds an extra key/value
assertTrue("bigInt from bean ctor is a bigInt",
actualFromBeanStr.contains("123456789012345678901234567890"));
// bigDec bean ctor
myBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigDecimal()).thenReturn(newBigDecimal("123456789012345678901234567890.12345678901234567890123456789"));
jsonObject = newJSONObject(myBigNumberBean);
actualFromBeanStr = jsonObject.toString();
// can't do a full string compare because mockery adds an extra key/value
assertTrue("bigDec from bean ctor is a bigDec",
actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789"));
// bigInt,bigDec wrap()
obj = JSONObject.wrap(bigInteger);
assertTrue("wrap() returns big num",obj.equals(bigInteger));
obj = JSONObject.wrap(bigDecimal);
assertTrue("wrap() returns string",obj.equals(bigDecimal));
}
/**
* The purpose for the static method getNames() methods are not clear.
* This method is not called from within JSON-Java. Most likely
* uses are to prep names arrays for:
* JSONObject(JSONObject jo, String[] names)
* JSONObject(Object object, String names[]),
*/
@Test
publicvoidjsonObjectNames() {
JSONObjectjsonObject;
// getNames() from null JSONObject
assertTrue("null names from null Object",
null == JSONObject.getNames((Object)null));
// getNames() from object with no fields
assertTrue("null names from Object with no fields",
null == JSONObject.getNames(newMyJsonString()));
// getNames from new JSONOjbect
jsonObject = newJSONObject();
String [] names = JSONObject.getNames(jsonObject);
assertTrue("names should be null", names == null);
// getNames() from empty JSONObject
StringemptyStr = "{}";
jsonObject = newJSONObject(emptyStr);
assertTrue("empty JSONObject should have null names",
null == JSONObject.getNames(jsonObject));
// getNames() from JSONObject
Stringstr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"}";
String [] expectedNames = {"trueKey", "falseKey", "stringKey"};
jsonObject = newJSONObject(str);
names = JSONObject.getNames(jsonObject);
Util.compareActualVsExpectedStringArrays(names, expectedNames);
/**
* getNames() from an enum with properties has an interesting result.
* It returns the enum values, not the selected enum properties
*/
MyEnumFieldmyEnumField = MyEnumField.VAL1;
String[] enumExpectedNames = {"VAL1", "VAL2", "VAL3"};
names = JSONObject.getNames(myEnumField);
Util.compareActualVsExpectedStringArrays(names, enumExpectedNames);
/**
* A bean is also an object. But in order to test the static
* method getNames(), this particular bean needs some public
* data members, which have been added to the class.
*/
JSONObjectTestjsonObjectTest = newJSONObjectTest();
String [] jsonObjectTestExpectedNames = {"publicString", "publicInt"};
names = JSONObject.getNames(jsonObjectTest);
Util.compareActualVsExpectedStringArrays(names, jsonObjectTestExpectedNames);
}
/**
* Populate a JSONArray from an empty JSONObject names() method.
* It should be empty.
*/
@Test
publicvoidemptyJsonObjectNamesToJsonAray() {
JSONObjectjsonObject = newJSONObject();
JSONArrayjsonArray = jsonObject.names();
assertTrue("jsonArray should be null", jsonArray == null);
}
/**
* Populate a JSONArray from a JSONObject names() method.
* Confirm that it contains the expected names.
*/
@Test
publicvoidjsonObjectNamesToJsonAray() {
Stringstr =
"{"+
"\"trueKey\":true,"+
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"}";
String [] expectedNames = {"trueKey", "falseKey", "stringKey" };
JSONObjectjsonObject = newJSONObject(str);
JSONArrayjsonArray = jsonObject.names();
/**
* Cannot really compare to an expected JSONArray because the ordering
* of the JSONObject keys is not fixed, and JSONArray comparisons
* presume fixed. Since this test is limited to key strings, a
* string comparison will have to suffice.
*/
StringnamesStr = jsonArray.toString();
// remove square brackets, commas, and spaces
namesStr = namesStr.replaceAll("[\\]|\\[|\"]", "");
String [] names = namesStr.split(",");
Util.compareActualVsExpectedStringArrays(names, expectedNames);
}
/**
* Exercise the JSONObject increment() method.
*/
@Test
publicvoidjsonObjectIncrement() {
Stringstr =
"{"+