/
test_ujson.py
1125 lines (894 loc) · 31.9 KB
/
test_ujson.py
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
import ctypes
import datetime as dt
import decimal
import io
import json
import math
import os.path
import re
import subprocess
import sys
import uuid
from collections import OrderedDict
from pathlib import Path
import pytest
import ujson
def assert_almost_equal(a, b):
assert round(abs(a - b), 7) == 0
def test_encode_decimal():
sut = decimal.Decimal("1337.1337")
encoded = ujson.encode(sut)
decoded = ujson.decode(encoded)
assert decoded == 1337.1337
def test_encode_string_conversion():
test_input = "A string \\ / \b \f \n \r \t </script> &"
not_html_encoded = '"A string \\\\ \\/ \\b \\f \\n \\r \\t <\\/script> &"'
html_encoded = (
'"A string \\\\ \\/ \\b \\f \\n \\r \\t \\u003c\\/script\\u003e \\u0026"'
)
not_slashes_escaped = '"A string \\\\ / \\b \\f \\n \\r \\t </script> &"'
def helper(expected_output, **encode_kwargs):
output = ujson.encode(test_input, **encode_kwargs)
assert output == expected_output
if encode_kwargs.get("escape_forward_slashes", True):
assert test_input == json.loads(output)
assert test_input == ujson.decode(output)
# Default behavior assumes encode_html_chars=False.
helper(not_html_encoded, ensure_ascii=True)
helper(not_html_encoded, ensure_ascii=False)
# Make sure explicit encode_html_chars=False works.
helper(not_html_encoded, ensure_ascii=True, encode_html_chars=False)
helper(not_html_encoded, ensure_ascii=False, encode_html_chars=False)
# Make sure explicit encode_html_chars=True does the encoding.
helper(html_encoded, ensure_ascii=True, encode_html_chars=True)
helper(html_encoded, ensure_ascii=False, encode_html_chars=True)
# Do escape forward slashes if disabled.
helper(not_slashes_escaped, escape_forward_slashes=False)
def test_write_escaped_string():
assert "\"\\u003cimg src='\\u0026amp;'\\/\\u003e\"" == ujson.dumps(
"<img src='&'/>", encode_html_chars=True
)
def test_double_long_issue():
sut = {"a": -4342969734183514}
encoded = json.dumps(sut)
decoded = json.loads(encoded)
assert sut == decoded
encoded = ujson.encode(sut)
decoded = ujson.decode(encoded)
assert sut == decoded
def test_double_long_decimal_issue():
sut = {"a": -12345678901234.56789012}
encoded = json.dumps(sut)
decoded = json.loads(encoded)
assert sut == decoded
encoded = ujson.encode(sut)
decoded = ujson.decode(encoded)
assert sut == decoded
# NOTE: can't match exponents -9 to -5; Python 0-pads
@pytest.mark.parametrize("val", [1e-10, 1e-4, 1e10, 1e15, 1e16, 1e30])
def test_encode_float_string_rep(val):
assert ujson.dumps(val) == json.dumps(val)
def test_encode_decode_long_decimal():
sut = {"a": -528656961.4399388}
encoded = ujson.dumps(sut)
ujson.decode(encoded)
def test_decimal_decode_test():
sut = {"a": 4.56}
encoded = ujson.encode(sut)
decoded = ujson.decode(encoded)
assert_almost_equal(sut["a"], decoded["a"])
def test_encode_double_conversion():
test_input = math.pi
output = ujson.encode(test_input)
assert round(test_input, 5) == round(json.loads(output), 5)
assert round(test_input, 5) == round(ujson.decode(output), 5)
def test_encode_double_neg_conversion():
test_input = -math.pi
output = ujson.encode(test_input)
assert round(test_input, 5) == round(json.loads(output), 5)
assert round(test_input, 5) == round(ujson.decode(output), 5)
def test_encode_array_of_nested_arrays():
test_input = [[[[]]]] * 20
output = ujson.encode(test_input)
assert test_input == json.loads(output)
# assert output == json.dumps(test_input)
assert test_input == ujson.decode(output)
def test_encode_array_of_doubles():
test_input = [31337.31337, 31337.31337, 31337.31337, 31337.31337] * 10
output = ujson.encode(test_input)
assert test_input == json.loads(output)
# assert output == json.dumps(test_input)
assert test_input == ujson.decode(output)
def test_encode_string_conversion2():
test_input = "A string \\ / \b \f \n \r \t"
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert output == '"A string \\\\ \\/ \\b \\f \\n \\r \\t"'
assert test_input == ujson.decode(output)
def test_encode_control_escaping():
test_input = "\x19"
enc = ujson.encode(test_input)
dec = ujson.decode(enc)
assert test_input == dec
assert enc == json.dumps(test_input)
# Characters outside of Basic Multilingual Plane(larger than
# 16 bits) are represented as \UXXXXXXXX in python but should be encoded
# as \uXXXX\uXXXX in json.
def test_encode_unicode_bmp():
s = "\U0001f42e\U0001f42e\U0001F42D\U0001F42D" # 🐮🐮🐭🐭
encoded = ujson.dumps(s)
encoded_json = json.dumps(s)
if len(s) == 4:
assert len(encoded) == len(s) * 12 + 2
else:
assert len(encoded) == len(s) * 6 + 2
assert encoded == encoded_json
decoded = ujson.loads(encoded)
assert s == decoded
# ujson outputs a UTF-8 encoded str object
encoded = ujson.dumps(s, ensure_ascii=False)
# json outputs an unicode object
encoded_json = json.dumps(s, ensure_ascii=False)
assert len(encoded) == len(s) + 2 # original length + quotes
assert encoded == encoded_json
decoded = ujson.loads(encoded)
assert s == decoded
def test_encode_symbols():
s = "\u273f\u2661\u273f" # ✿♡✿
encoded = ujson.dumps(s)
encoded_json = json.dumps(s)
assert len(encoded) == len(s) * 6 + 2 # 6 characters + quotes
assert encoded == encoded_json
decoded = ujson.loads(encoded)
assert s == decoded
# ujson outputs a UTF-8 encoded str object
encoded = ujson.dumps(s, ensure_ascii=False)
# json outputs an unicode object
encoded_json = json.dumps(s, ensure_ascii=False)
assert len(encoded) == len(s) + 2 # original length + quotes
assert encoded == encoded_json
decoded = ujson.loads(encoded)
assert s == decoded
def test_encode_long_neg_conversion():
test_input = -9223372036854775808
output = ujson.encode(test_input)
json.loads(output)
ujson.decode(output)
assert test_input == json.loads(output)
assert output == json.dumps(test_input)
assert test_input == ujson.decode(output)
def test_encode_list_conversion():
test_input = [1, 2, 3, 4]
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert test_input == ujson.decode(output)
def test_encode_dict_conversion():
test_input = {"k1": 1, "k2": 2, "k3": 3, "k4": 4}
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert test_input == ujson.decode(output)
assert test_input == ujson.decode(output)
@pytest.mark.skipif(
hasattr(sys, "pypy_version_info"), reason="PyPy uses incompatible GC"
)
def test_encode_dict_values_ref_counting():
import gc
gc.collect()
value = ["abc"]
data = {"1": value}
ref_count = sys.getrefcount(value)
ujson.dumps(data)
assert ref_count == sys.getrefcount(value)
@pytest.mark.skipif(
hasattr(sys, "pypy_version_info"), reason="PyPy uses incompatible GC"
)
@pytest.mark.parametrize("key", ["key", b"key", 1, True, None])
@pytest.mark.parametrize("sort_keys", [False, True])
def test_encode_dict_key_ref_counting(key, sort_keys):
import gc
gc.collect()
data = {key: "abc"}
ref_count = sys.getrefcount(key)
ujson.dumps(data, sort_keys=sort_keys)
assert ref_count == sys.getrefcount(key)
def test_encode_to_utf8():
test_input = b"\xe6\x97\xa5\xd1\x88".decode("utf-8")
enc = ujson.encode(test_input, ensure_ascii=False)
dec = ujson.decode(enc)
assert enc == json.dumps(test_input, ensure_ascii=False)
assert dec == json.loads(enc)
@pytest.mark.parametrize(
"test_input",
[
'{\n "obj": 31337\n}',
"{}",
"[]",
'{\n "a": {}\n}',
"[\n []\n]",
],
)
def test_encode_indent(test_input):
obj = ujson.decode(test_input)
output = ujson.encode(obj, indent=4)
assert test_input == output
assert output == json.dumps(obj, indent=4)
def test_decode_from_unicode():
test_input = '{"obj": 31337}'
dec1 = ujson.decode(test_input)
dec2 = ujson.decode(str(test_input))
assert dec1 == dec2
def test_encode_recursion_max():
# 8 is the max recursion depth
class O2:
member = 0
def toDict(self):
return {"member": self.member}
class O1:
member = 0
def toDict(self):
return {"member": self.member}
test_input = O1()
test_input.member = O2()
test_input.member.member = test_input
with pytest.raises(OverflowError):
ujson.encode(test_input)
def test_decode_dict():
test_input = "{}"
obj = ujson.decode(test_input)
assert {} == obj
test_input = '{"one": 1, "two": 2, "three": 3}'
obj = ujson.decode(test_input)
assert {"one": 1, "two": 2, "three": 3} == obj
def test_encode_unicode_4_bytes_utf8_fail():
test_input = b"\xfd\xbf\xbf\xbf\xbf\xbf"
with pytest.raises(OverflowError):
ujson.encode(test_input, reject_bytes=False)
def test_encode_null_character():
test_input = "31337 \x00 1337"
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert output == json.dumps(test_input)
assert test_input == ujson.decode(output)
test_input = "\x00"
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert output == json.dumps(test_input)
assert test_input == ujson.decode(output)
assert '" \\u0000\\r\\n "' == ujson.dumps(" \u0000\r\n ")
def test_decode_null_character():
test_input = '"31337 \\u0000 31337"'
assert ujson.decode(test_input) == json.loads(test_input)
def test_dump_to_file():
f = io.StringIO()
ujson.dump([1, 2, 3], f)
assert "[1,2,3]" == f.getvalue()
def test_dump_to_file_like_object():
class FileLike:
def __init__(self):
self.bytes = ""
def write(self, bytes):
self.bytes += bytes
f = FileLike()
ujson.dump([1, 2, 3], f)
assert "[1,2,3]" == f.bytes
def test_dump_file_args_error():
with pytest.raises(TypeError):
ujson.dump([], "")
def test_load_file():
f = io.StringIO("[1,2,3,4]")
assert [1, 2, 3, 4] == ujson.load(f)
def test_load_file_like_object():
class FileLike:
def read(self):
try:
self.end
except AttributeError:
self.end = True
return "[1,2,3,4]"
f = FileLike()
assert [1, 2, 3, 4] == ujson.load(f)
def test_load_file_args_error():
with pytest.raises(TypeError):
ujson.load("[]")
def test_version():
assert re.search(
r"^\d+\.\d+(\.\d+)?", ujson.__version__
), "ujson.__version__ must be a string like '1.4.0'"
def test_decode_number_with32bit_sign_bit():
# Test that numbers that fit within 32 bits but would have the
# sign bit set (2**31 <= x < 2**32) are decoded properly.
docs = (
'{"id": 3590016419}',
'{"id": %s}' % 2**31,
'{"id": %s}' % 2**32,
'{"id": %s}' % ((2**32) - 1),
)
results = (3590016419, 2**31, 2**32, 2**32 - 1)
for doc, result in zip(docs, results):
assert ujson.decode(doc)["id"] == result
def test_encode_big_escape():
for x in range(10):
base = "\u00e5".encode()
test_input = base * 1024 * 1024 * 2
ujson.encode(test_input, reject_bytes=False)
def test_decode_big_escape():
for x in range(10):
base = "\u00e5".encode()
quote = b'"'
test_input = quote + (base * 1024 * 1024 * 2) + quote
ujson.decode(test_input)
def test_to_dict():
d = {"key": 31337}
class DictTest:
def toDict(self):
return d
def __json__(self):
return '"json defined"' # Fallback and shouldn't be called.
o = DictTest()
output = ujson.encode(o)
dec = ujson.decode(output)
assert dec == d
def test_object_with_json():
# If __json__ returns a string, then that string
# will be used as a raw JSON snippet in the object.
output_text = "this is the correct output"
class JSONTest:
def __json__(self):
return '"' + output_text + '"'
d = {"key": JSONTest()}
output = ujson.encode(d)
dec = ujson.decode(output)
assert dec == {"key": output_text}
def test_object_with_complex_json():
# If __json__ returns a string, then that string
# will be used as a raw JSON snippet in the object.
obj = {"foo": ["bar", "baz"]}
class JSONTest:
def __json__(self):
return ujson.encode(obj)
d = {"key": JSONTest()}
output = ujson.encode(d)
dec = ujson.decode(output)
assert dec == {"key": obj}
def test_object_with_json_type_error():
# __json__ must return a string, otherwise it should raise an error.
for return_value in (None, 1234, 12.34, True, {}):
class JSONTest:
def __json__(self):
return return_value
d = {"key": JSONTest()}
with pytest.raises(TypeError):
ujson.encode(d)
def test_object_with_json_attribute_error():
# If __json__ raises an error, make sure python actually raises it.
class JSONTest:
def __json__(self):
raise AttributeError
d = {"key": JSONTest()}
with pytest.raises(AttributeError):
ujson.encode(d)
def test_decode_array_empty():
test_input = "[]"
obj = ujson.decode(test_input)
assert [] == obj
def test_encode_surrogate_characters():
assert ujson.dumps("\udc7f") == r'"\udc7f"'
out = r'{"\ud800":"\udfff"}'
assert ujson.dumps({"\ud800": "\udfff"}) == out
assert ujson.dumps({"\ud800": "\udfff"}, sort_keys=True) == out
o = {b"\xed\xa0\x80": b"\xed\xbf\xbf"}
assert ujson.dumps(o, reject_bytes=False) == out
assert ujson.dumps(o, reject_bytes=False, sort_keys=True) == out
out2 = '{"\ud800":"\udfff"}'
assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False) == out2
assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False, sort_keys=True) == out2
@pytest.mark.xfail(
hasattr(sys, "pypy_version_info") and os.name == "nt",
"This feature needs fixing! See #552",
)
@pytest.mark.parametrize(
"test_input, expected",
[
# Normal cases
(r'"\uD83D\uDCA9"', "\U0001F4A9"),
(r'"a\uD83D\uDCA9b"', "a\U0001F4A9b"),
# Unpaired surrogates
(r'"\uD800"', "\uD800"),
(r'"a\uD800b"', "a\uD800b"),
(r'"\uDEAD"', "\uDEAD"),
(r'"a\uDEADb"', "a\uDEADb"),
(r'"\uD83D\uD83D\uDCA9"', "\uD83D\U0001F4A9"),
(r'"\uDCA9\uD83D\uDCA9"', "\uDCA9\U0001F4A9"),
(r'"\uD83D\uDCA9\uD83D"', "\U0001F4A9\uD83D"),
(r'"\uD83D\uDCA9\uDCA9"', "\U0001F4A9\uDCA9"),
(r'"\uD83D \uDCA9"', "\uD83D \uDCA9"),
# No decoding of actual surrogate characters (rather than escaped ones)
('"\uD800"', "\uD800"),
('"\uDEAD"', "\uDEAD"),
('"\uD800a\uDEAD"', "\uD800a\uDEAD"),
('"\uD83D\uDCA9"', "\uD83D\uDCA9"),
],
)
def test_decode_surrogate_characters(test_input, expected):
# FIXME Wrong output (combined char) on platforms with 16-bit wchar_t
if test_input == '"\uD83D\uDCA9"' and ctypes.sizeof(ctypes.c_wchar) == 2:
pytest.skip("Raw surrogate pairs are not supported with 16-bit wchar_t")
assert ujson.loads(test_input) == expected
assert ujson.loads(test_input.encode("utf-8", "surrogatepass")) == expected
# Ensure that this matches stdlib's behaviour
assert json.loads(test_input) == expected
def test_sort_keys():
data = {"a": 1, "c": 1, "b": 1, "e": 1, "f": 1, "d": 1}
sorted_keys = ujson.dumps(data, sort_keys=True)
assert sorted_keys == '{"a":1,"b":1,"c":1,"d":1,"e":1,"f":1}'
@pytest.mark.parametrize(
"test_input",
[
"[31337]", # array one item
"18446744073709551615", # long unsigned value
"9223372036854775807", # big value
"-9223372036854775808", # small value
"{}\n\t ", # trailing whitespaces
],
)
def test_decode_no_assert(test_input):
ujson.decode(test_input)
@pytest.mark.parametrize(
"test_input, expected",
[
("31337", 31337),
("-31337", -31337),
("100000000000000000000.0", 1e20),
],
)
def test_decode(test_input, expected):
assert ujson.decode(test_input) == expected
@pytest.mark.parametrize(
"test_input",
[
"1337E40",
"1.337E40",
"1337E+9",
"1.337e+40",
"1337E40",
"1337e40",
"1.337E-4",
"1.337e-4",
],
)
def test_decode_numeric_int_exp(test_input):
output = ujson.decode(test_input)
assert output == json.loads(test_input)
@pytest.mark.parametrize(
"test_input, expected",
[
('{{1337:""}}', ujson.JSONDecodeError), # broken dict key type leak test
('{{"key":"}', ujson.JSONDecodeError), # broken dict leak test
('{{"key":"}', ujson.JSONDecodeError), # broken dict leak test
("[[[true", ujson.JSONDecodeError), # broken list leak test
],
)
def test_decode_range_raises(test_input, expected):
for x in range(1000):
with pytest.raises(expected):
ujson.decode(test_input)
@pytest.mark.parametrize(
"test_input, expected",
[
("fdsa sda v9sa fdsa", ujson.JSONDecodeError), # jibberish
("[", ujson.JSONDecodeError), # broken array start
("{", ujson.JSONDecodeError), # broken object start
("]", ujson.JSONDecodeError), # broken array end
("}", ujson.JSONDecodeError), # broken object end
('{"one":1,}', ujson.JSONDecodeError), # object trailing comma fail
('"TESTING', ujson.JSONDecodeError), # string unterminated
('"TESTING\\"', ujson.JSONDecodeError), # string bad escape
("tru", ujson.JSONDecodeError), # true broken
("fa", ujson.JSONDecodeError), # false broken
("n", ujson.JSONDecodeError), # null broken
("{{{{31337}}}}", ujson.JSONDecodeError), # dict with no key
('{{{{"key"}}}}', ujson.JSONDecodeError), # dict with no colon or value
('{{{{"key":}}}}', ujson.JSONDecodeError), # dict with no value
("[31337,]", ujson.JSONDecodeError), # array trailing comma fail
("[,31337]", ujson.JSONDecodeError), # array leading comma fail
("[,]", ujson.JSONDecodeError), # array only comma fail
("[]]", ujson.JSONDecodeError), # array unmatched bracket fail
("18446744073709551616", ujson.JSONDecodeError), # too big value
("-90223372036854775809", ujson.JSONDecodeError), # too small value
("-23058430092136939529", ujson.JSONDecodeError), # too small value
("-11529215046068469760", ujson.JSONDecodeError), # too small value
("18446744073709551616", ujson.JSONDecodeError), # very too big value
("23058430092136939529", ujson.JSONDecodeError), # too big value
("-90223372036854775809", ujson.JSONDecodeError), # very too small value
("{}\n\t a", ujson.JSONDecodeError), # with trailing non whitespaces
("[18446744073709551616]", ujson.JSONDecodeError), # array with big int
('{"age", 44}', ujson.JSONDecodeError), # read bad object syntax
],
)
def test_decode_raises(test_input, expected):
with pytest.raises(expected):
ujson.decode(test_input)
@pytest.mark.parametrize(
"test_input, expected",
[
("[", ujson.JSONDecodeError), # array depth too big
("{", ujson.JSONDecodeError), # object depth too big
],
)
def test_decode_raises_for_long_input(test_input, expected):
with pytest.raises(expected):
ujson.decode(test_input * (1024 * 1024))
def test_decode_exception_is_value_error():
assert issubclass(ujson.JSONDecodeError, ValueError)
assert ujson.JSONDecodeError is not ValueError
@pytest.mark.parametrize(
"test_input, expected",
[
(True, "true"),
(False, "false"),
(None, "null"),
([True, False, None], "[true,false,null]"),
((True, False, None), "[true,false,null]"),
],
)
def test_dumps(test_input, expected):
assert ujson.dumps(test_input) == expected
class SomeObject:
def __init__(self, message, exception=None):
self._message = message
self._exception = exception
def __repr__(self):
if self._exception:
raise self._exception
return self._message
@pytest.mark.parametrize(
"test_input, expected_exception, expected_message",
[
(set(), TypeError, "set() is not JSON serializable"),
({1, 2, 3}, TypeError, "{1, 2, 3} is not JSON serializable"),
(SomeObject("Some Object"), TypeError, "Some Object is not JSON serializable"),
(SomeObject("\ud800"), UnicodeEncodeError, None),
(SomeObject(None, KeyboardInterrupt), KeyboardInterrupt, None),
],
)
def test_dumps_raises(test_input, expected_exception, expected_message):
with pytest.raises(expected_exception) as e:
ujson.dumps(test_input)
if expected_message:
assert str(e.value) == expected_message
@pytest.mark.parametrize(
"test_input, expected_exception",
[
(float("nan"), OverflowError),
(float("inf"), OverflowError),
(-float("inf"), OverflowError),
(12839128391289382193812939, OverflowError),
([12839128391289382193812939], OverflowError),
([12839128391289382193812939, 42], OverflowError),
({"a": 12839128391289382193812939}, OverflowError),
({"a": 12839128391289382193812939, "b": 42}, OverflowError),
],
)
def test_encode_raises_allow_nan(test_input, expected_exception):
with pytest.raises(expected_exception):
ujson.dumps(test_input, allow_nan=False)
def test_nan_inf_support():
# Test ported from pandas
text = '["a", NaN, "NaN", Infinity, "Infinity", -Infinity, "-Infinity"]'
data = ujson.loads(text)
expected = [
"a",
float("nan"),
"NaN",
float("inf"),
"Infinity",
-float("inf"),
"-Infinity",
]
for a, b in zip(data, expected):
assert a == b or math.isnan(a) and math.isnan(b)
def test_special_singletons():
pos_inf = ujson.loads("Infinity")
neg_inf = ujson.loads("-Infinity")
nan = ujson.loads("NaN")
null = ujson.loads("null")
assert math.isinf(pos_inf) and pos_inf > 0
assert math.isinf(neg_inf) and neg_inf < 0
assert math.isnan(nan)
assert null is None
@pytest.mark.parametrize(
"test_input, expected_message",
[
("n", "Unexpected character .* 'null'"),
("N", "Unexpected character .*'NaN'"),
("NA", "Unexpected character .* 'NaN'"),
("Na N", "Unexpected character .* 'NaN'"),
("nan", "Unexpected character .* 'null'"),
("none", "Unexpected character .* 'null'"),
("i", "Expected object or value"),
("I", "Unexpected character .* 'Infinity'"),
("Inf", "Unexpected character .* 'Infinity'"),
("InfinitY", "Unexpected character .* 'Infinity'"),
("-i", "Trailing data"),
("-I", "Unexpected character .* '-Infinity'"),
("-Inf", "Unexpected character .* '-Infinity'"),
("-InfinitY", "Unexpected character .* '-Infinity'"),
("- i", "Trailing data"),
("- I", "Trailing data"),
("- Inf", "Trailing data"),
("- InfinitY", "Trailing data"),
],
)
def test_incomplete_special_inputs(test_input, expected_message):
with pytest.raises(ujson.JSONDecodeError, match=expected_message):
ujson.loads(test_input)
@pytest.mark.parametrize(
"test_input, expected_message",
[
("NaNaNaN", "Trailing data"),
("Infinity and Beyond", "Trailing data"),
("-Infinity-and-Beyond", "Trailing data"),
("NaN!", "Trailing data"),
("Infinity!", "Trailing data"),
("-Infinity!", "Trailing data"),
],
)
def test_overcomplete_special_inputs(test_input, expected_message):
with pytest.raises(ujson.JSONDecodeError, match=expected_message):
ujson.loads(test_input)
@pytest.mark.parametrize(
"test_input",
[
{
"key1": "value1",
"key1": "value1",
"key1": "value1",
"key1": "value1",
"key1": "value1",
"key1": "value1",
},
{
"بن": "value1",
"بن": "value1",
"بن": "value1",
"بن": "value1",
"بن": "value1",
"بن": "value1",
"بن": "value1",
},
],
)
def test_encode_no_assert(test_input):
ujson.encode(test_input)
@pytest.mark.parametrize(
"test_input, expected",
[
(1.0, "1.0"),
(OrderedDict([(1, 1), (0, 0), (8, 8), (2, 2)]), '{"1":1,"0":0,"8":8,"2":2}'),
({"a": float("NaN")}, '{"a":NaN}'),
({"a": float("inf")}, '{"a":Inf}'),
({"a": -float("inf")}, '{"a":-Inf}'),
],
)
def test_encode(test_input, expected):
assert ujson.encode(test_input) == expected
@pytest.mark.parametrize(
"test_input",
[
[
9223372036854775807,
9223372036854775807,
9223372036854775807,
9223372036854775807,
9223372036854775807,
9223372036854775807,
],
[
18446744073709551615,
18446744073709551615,
18446744073709551615,
],
],
)
def test_encode_list_long_conversion(test_input):
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert test_input == ujson.decode(output)
@pytest.mark.parametrize(
"test_input",
[
9223372036854775807,
18446744073709551615,
],
)
def test_encode_long_conversion(test_input):
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert output == json.dumps(test_input)
assert test_input == ujson.decode(output)
@pytest.mark.parametrize(
"test_input",
[
[[[[]]]],
31337,
-31337,
None,
True,
False,
],
)
def test_encode_decode(test_input):
output = ujson.encode(test_input)
assert test_input == json.loads(output)
assert output == json.dumps(test_input)
assert test_input == ujson.decode(output)
@pytest.mark.parametrize(
"test_input",
[
"Räksmörgås اسامة بن محمد بن عوض بن لادن",
"\xe6\x97\xa5\xd1\x88",
"\xf0\x90\x8d\x86", # surrogate pair
"\xf0\x91\x80\xb0TRAILINGNORMAL", # 4 bytes UTF8
"\xf3\xbf\xbf\xbfTRAILINGNORMAL", # 4 bytes UTF8 highest
],
)
def test_encode_unicode(test_input):
enc = ujson.encode(test_input)
dec = ujson.decode(enc)
assert enc == json.dumps(test_input)
assert dec == json.loads(enc)
@pytest.mark.parametrize(
"test_input, expected",
[
("-1.1234567893", -1.1234567893),
("-1.234567893", -1.234567893),
("-1.34567893", -1.34567893),
("-1.4567893", -1.4567893),
("-1.567893", -1.567893),
("-1.67893", -1.67893),
("-1.7893", -1.7893),
("-1.893", -1.893),
("-1.3", -1.3),
("1.1234567893", 1.1234567893),
("1.234567893", 1.234567893),
("1.34567893", 1.34567893),
("1.4567893", 1.4567893),
("1.567893", 1.567893),
("1.67893", 1.67893),
("1.7893", 1.7893),
("1.893", 1.893),
("1.3", 1.3),
("true", True),
("false", False),
("null", None),
(" [ true, false,null] ", [True, False, None]),
],
)
def test_loads(test_input, expected):
assert ujson.loads(test_input) == expected
def test_reject_bytes_default():
data = {"a": b"b"}
with pytest.raises(TypeError):
ujson.dumps(data)
def test_reject_bytes_true():
data = {"a": b"b"}
with pytest.raises(TypeError):
ujson.dumps(data, reject_bytes=True)
def test_reject_bytes_false():
data = {"a": b"b"}
assert ujson.dumps(data, reject_bytes=False) == '{"a":"b"}'
def test_encode_none_key():
data = {None: None}
assert ujson.dumps(data) == '{"null":null}'
def test_default_function():
iso8601_time_format = "%Y-%m-%dT%H:%M:%S.%f"
class CustomObject:
pass
class UnjsonableObject:
pass
def default(value):
if isinstance(value, dt.datetime):
return value.strftime(iso8601_time_format)
elif isinstance(value, uuid.UUID):
return value.hex
elif isinstance(value, CustomObject):
raise ValueError("invalid value")
return value
now = dt.datetime.now()
expected_output = '"%s"' % now.strftime(iso8601_time_format)
assert ujson.dumps(now, default=default) == expected_output
uuid4 = uuid.uuid4()