-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonobject_test.py
856 lines (720 loc) · 33.2 KB
/
jsonobject_test.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
#!/usr/bin/env python
from builtins import int
from builtins import object
from builtins import str
from past.builtins import long
from past.builtins import unicode
import pytest
import jsonobject
from jsonobject import jsonproperty
class TestJSONSerializableObject(object):
def test_default_getter(self):
class SomeObject(jsonobject.JSONSerializableObject):
# @jsonproperty creates a property which is exported to a
# serialized JSON of SomeObject.
# It can decorate without any arguments.
@jsonproperty
def foo(self):
return 'FOO'
s = SomeObject()
# "foo" can be used as a normal getter.
assert s.foo == 'FOO'
# And is automatically exported.
assert s.json() == '{"foo": "FOO"}'
def test_named_getter(self):
class SomeObject(jsonobject.JSONSerializableObject):
# This field is exported as "field_foo".
# Note that in @jsonproperty specs, parameters should be named; you
# can't do this way:
# @jsonproperty('field_foo')
@jsonproperty(name='field_foo')
def foo(self):
return 'FOO'
s = SomeObject()
assert s.foo == 'FOO'
assert s.json() == '{"field_foo": "FOO"}'
def test_not_exported_if_omittable(self):
class SomeObject(jsonobject.JSONSerializableObject):
def __init__(self, value):
self.value = value
# If omittable is True, the property will not exported.
# This is the default behavior if omitted.
@jsonproperty(omittable=True)
def foo(self):
return self.value
assert SomeObject('FOO').json() == '{"foo": "FOO"}'
assert SomeObject('').json() == '{"foo": ""}'
assert SomeObject(0).json() == '{"foo": 0}'
assert SomeObject(None).json() == '{}'
def test_exported_if_not_omittable(self):
class SomeObject(jsonobject.JSONSerializableObject):
def __init__(self, value):
self.value = value
# If omittable is False, the property will always be exported.
@jsonproperty(omittable=False)
def foo(self):
return self.value
assert SomeObject('FOO').json() == '{"foo": "FOO"}'
assert SomeObject('').json() == '{"foo": ""}'
assert SomeObject(0).json() == '{"foo": 0}'
assert SomeObject(None).json() == '{"foo": null}'
def test_non_primitive_value(self):
class NonPrimitiveObject(object):
pass
class SomeObject(jsonobject.JSONSerializableObject):
# The getter cannot return a non JSON primitive value.
@jsonproperty
def foo(self):
return NonPrimitiveObject()
with pytest.raises(TypeError):
SomeObject().json()
def test_non_primitive_serializable_value_getter(self):
class NonPrimitiveSerializableObject(
jsonobject.JSONSerializableObject):
@jsonproperty
def child_foo(self):
return 'CHILD_FOO'
class SomeObject(jsonobject.JSONSerializableObject):
# OK if the non primitive value is JSON serializable.
@jsonproperty
def foo(self):
return NonPrimitiveSerializableObject()
assert SomeObject().json() == '{"foo": {"child_foo": "CHILD_FOO"}}'
def test_setter_and_deleter(self):
class SomeObject(jsonobject.JSONSerializableObject):
def __init__(self, foo):
self._foo = foo
@jsonproperty
def foo(self):
return self._foo
# Setter can be used just like the standard property.
@foo.setter
def foo(self, foo):
self._foo = foo
# The same for deleter. You should reset the value before caalling
# json(), though.
@foo.deleter
def foo(self):
del self._foo
s = SomeObject('FOO')
assert s.foo == 'FOO'
assert s.json() == '{"foo": "FOO"}'
s.foo = 'BAR'
assert s.foo == 'BAR'
assert s.json() == '{"foo": "BAR"}'
del s.foo
# Accessing a deleted property will raise AttributeError.
with pytest.raises(AttributeError):
s.foo
# And trying to convert the container object to JSON will raise
# TypeError.
with pytest.raises(TypeError):
s.json()
# Resetting the property will make the conversion possible again.
s.foo = "BAZ"
assert s.json() == '{"foo": "BAZ"}'
def test_json_property(self):
class SomeObject(jsonobject.JSONSerializableObject):
# This does the same thing as @jsonproperty getter, setter and
# deleter.
# Note that the JSON name is optional. If omitted, it is inferred
# from the Python field name.
foo = jsonobject.JSONProperty()
s = SomeObject()
# The property defaults to None.
assert s.foo is None
s.foo = 'FOO'
assert s.foo == 'FOO'
assert s.json() == '{"foo": "FOO"}'
# Deletion is not supported.
with pytest.raises(AttributeError):
del s.foo
def test_json_property_default(self):
class SomeObject(jsonobject.JSONSerializableObject):
# default speficies the default value of the property.
foo = jsonobject.JSONProperty(default='FOO')
s = SomeObject()
assert s.foo == 'FOO'
s.foo = 'BAR'
assert s.foo == 'BAR'
def test_json_property_non_reused_default_list(self):
class SomeObject(jsonobject.JSONSerializableObject):
# List passed as the default value. This should not be reused over
# object instances.
foo = jsonobject.JSONProperty(default=[])
s = SomeObject()
assert s.foo == []
s.foo.append('FOO')
assert s.foo == ['FOO']
t = SomeObject()
assert t.foo == []
t.foo.append('BAR')
assert t.foo == ['BAR']
assert s.foo == ['FOO']
def test_json_property_non_reused_default_list_consistency(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(default=[])
# The getter should return the same object regardless of the timing of
# member access.
s = SomeObject()
foo_id = id(s.foo)
foo_id_2 = id(s.foo)
assert foo_id == foo_id_2
def test_json_property_non_reused_default_dict(self):
class SomeObject(jsonobject.JSONSerializableObject):
# Dict passed as the default value. This should not be reused over
# object instances.
foo = jsonobject.JSONProperty(default={})
s = SomeObject()
assert s.foo == {}
s.foo['bar'] = 'BAR'
assert s.foo['bar'] == 'BAR'
t = SomeObject()
assert t.foo == {}
t.foo['bar'] = 'BAZ'
assert t.foo['bar'] == 'BAZ'
assert s.foo['bar'] == 'BAR'
def test_json_property_non_reused_default_object(self):
class ChildObject(jsonobject.JSONSerializableObject):
bar = jsonobject.JSONProperty(default='BAR')
class SomeObject(jsonobject.JSONSerializableObject):
# Dict passed as the default value. This should not be reused over
# object instances.
foo = jsonobject.JSONProperty(default=ChildObject())
s = SomeObject()
assert s.foo.bar == 'BAR'
s.foo.bar = 'BAZ'
assert s.foo.bar == 'BAZ'
t = SomeObject()
assert t.foo.bar == 'BAR'
t.foo.bar = 'QUX'
assert t.foo.bar == 'QUX'
assert s.foo.bar == 'BAZ'
def test_json_property_init(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty()
bar = object()
# JSONSerializableObject constructor accepts key-value specifications
# for JSONProperty.
s = SomeObject(foo='FOO')
assert s.foo == 'FOO'
# It doesn't accept setting a value to non-JSONProperty objects.
with pytest.raises(AttributeError):
s = SomeObject(bar='BAR')
# It also rejects creating a new member.
with pytest.raises(AttributeError):
s = SomeObject(baz='BAZ')
def test_json_property_not_shared_between_instances(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty()
s = SomeObject(foo='FOO')
t = SomeObject(foo='BAR')
assert s.foo == 'FOO'
assert t.foo == 'BAR'
def test_json_readonly_property(self):
class SomeObject(jsonobject.JSONSerializableObject):
def __init__(self, foo):
self._foo = foo
# This property exports SomeObject._foo in a readonly manner.
foo = jsonobject.ReadonlyJSONProperty(wrapped_variable='_foo')
s = SomeObject('FOO')
assert s.foo == 'FOO'
# Client code cannot assign a value to s.foo.
with pytest.raises(AttributeError):
s.foo = 'BAR'
assert s.json('{"foo": "FOO"}')
def test_json_readonly_property_omitted_variable_name(self):
class SomeObject(jsonobject.JSONSerializableObject):
# If wrapped_variable is omitted, the property tries to wrap one
# with a random unique name.
foo = jsonobject.ReadonlyJSONProperty()
s = SomeObject(foo='FOO')
assert s.foo == 'FOO'
with pytest.raises(AttributeError):
s.foo = 'BAR'
assert s.json('{"foo": "FOO"}')
def test_readonly_json_property_init(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.ReadonlyJSONProperty(wrapped_variable='_foo')
# This is a class variable whose name conflicts with the wrapped
# variable of foo.
_foo = 'CLASS_FOO'
# JSONSerializableObject constructor accepts key-value specifications
# for ReadonlyJSONProperty too. It creates a private variable with the
# name passed as the second argument (wrapped_variable).
s = SomeObject(foo='FOO')
assert s.foo == 'FOO'
assert s._foo == 'FOO'
# There is a class variable whose name conflicts with that.
# JSONSerializableObject's constructor never overwrite the class
# variable, but you may want to avoid these situations, as it looks
# very weird. (Of course, that looks like a design flaw to begin with.)
assert SomeObject._foo == 'CLASS_FOO'
def test_readonly_json_property_default(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.ReadonlyJSONProperty(default='FOO')
assert SomeObject().foo == 'FOO'
assert SomeObject(foo='BAR').foo == 'BAR'
def test_readonly_json_property_not_shared_between_instances(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.ReadonlyJSONProperty()
s = SomeObject(foo='FOO')
t = SomeObject(foo='BAR')
assert s.foo == 'FOO'
assert t.foo == 'BAR'
def test_nested_jsonobject(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(default='A')
b = jsonobject.ReadonlyJSONProperty(default='B')
@jsonproperty
def c(self):
return 'C'
# You can create a nested class from another serializable object class.
class AnotherObject(SomeObject):
d = jsonobject.JSONProperty(default='D')
e = jsonobject.ReadonlyJSONProperty(default='E')
@jsonproperty
def f(self):
return 'F'
s = SomeObject()
assert s.json(sort_keys=True) == '{"a": "A", "b": "B", "c": "C"}'
t = AnotherObject()
assert t.json(sort_keys=True) == ('{"a": "A", "b": "B", "c": "C", '
'"d": "D", "e": "E", "f": "F"}')
# You can initialize superclass' properties as well.
# Note that, however, properties created by @jsonproperty is not
# initializable from this syntax.
u = AnotherObject(a="AA", b="BB", d="DD", e="EE")
assert u.json(sort_keys=True) == ('{"a": "AA", "b": "BB", "c": "C", '
'"d": "DD", "e": "EE", "f": "F"}')
def test_overriding_jsonobject(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(default='A')
b = jsonobject.JSONProperty(default='B')
def update_a(self, value):
self.a = value
class AnotherObject(SomeObject):
# You can override some properties exported by the superclass.
a = jsonobject.JSONProperty(default='AA')
s = SomeObject()
assert s.json(sort_keys=True) == '{"a": "A", "b": "B"}'
t = AnotherObject()
assert t.json(sort_keys=True) == '{"a": "AA", "b": "B"}'
t.update_a('AAA')
assert t.json(sort_keys=True) == '{"a": "AAA", "b": "B"}'
u = AnotherObject(a='AAAA', b='BBBB')
assert u.json(sort_keys=True) == '{"a": "AAAA", "b": "BBBB"}'
def test_value_type(self):
class SomeObject(jsonobject.JSONSerializableObject):
# In Python 2, prefer using value_type of unicode if you pass text.
a = jsonobject.JSONProperty(default=u'A', value_type=unicode)
b = jsonobject.JSONProperty(default=123, value_type=int)
c = jsonobject.JSONProperty(default='C')
s = SomeObject()
assert s.json(sort_keys=True) == '{"a": "A", "b": 123, "c": "C"}'
# It's a value type violation when setting a value of different type.
with pytest.raises(TypeError):
s.a = 123
with pytest.raises(TypeError):
s.b = 'B'
# Though not recommended, it's OK to pass a Python 2 str (without
# encoding) even if value_type is Python 2 unicode. It's assumed that
# the string is encoded with UTF-8.
s.a = 'A'
# c doesn't declare the value type: any arbitrary type is acceptable.
s.c = 456
assert s.json(sort_keys=True) == '{"a": "A", "b": 123, "c": 456}'
def test_value_type_str_unicode(self):
class SomeObject(jsonobject.JSONSerializableObject):
# In Python 3, you use str everywhere. You can still pass unicode
# strings. Follow this style also if you need to support both
# Python 2 and 3.
# If you don't need to support Python 2, you would drop 'u' literal
# prefix.
a = jsonobject.JSONProperty(default=u'A', value_type=str)
s = SomeObject()
assert s.json(sort_keys=True) == '{"a": "A"}'
def test_value_type_default(self):
# It's also forbidden to have an incompatible default value.
# Note that this check happens when a class is being defined.
with pytest.raises(TypeError):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(default='A', value_type=int)
def test_value_type_long_ing(self):
# It is allowed to assign a large number to a field expecting an int.
# This is preferred type of value_type for integers, and works both in
# Python 2 and 3.
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(default=123, value_type=int)
s = SomeObject()
assert s.a == 123
s.a = 9223372036854775808 # 2^64
assert s.a == 9223372036854775808
def test_value_type_int_long(self):
# It is allowed to assign an int to a field expecting a long.
# Note: long is no longer available in Python 3. Always prefer to
# value_type=int.
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(default=123, value_type=long)
s = SomeObject()
assert s.a == 123
s.a = int(456)
assert s.a == 456
def test_value_type_readonly(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.ReadonlyJSONProperty(default='A', value_type=str)
with pytest.raises(TypeError):
SomeObject(a=123)
def test_value_type_readonly_wrapped_variable(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.ReadonlyJSONProperty(value_type=str,
wrapped_variable='_a')
s = SomeObject(a=None)
assert s._a is None
s._a = 123
# ReadonlyJSONProperty checks value type on read.
with pytest.raises(TypeError):
assert s.a == 123
def test_value_type_readonly_default(self):
with pytest.raises(TypeError):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(default='A', value_type=int)
def test_element_type_list(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(value_type=list, element_type=int)
s = SomeObject(a=[1, 2, 3])
with pytest.raises(TypeError):
s.a = ['1', '2', '3']
def test_element_type_tuple(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(value_type=tuple,
element_type=int)
s = SomeObject(a=(1, 2, 3))
with pytest.raises(TypeError):
s.a = ('1', '2', '3')
def test_element_type_dict(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(value_type=dict, element_type=int)
s = SomeObject(a={'a': 1, 'b': 2})
assert s.a['a'] == 1
assert s.a['b'] == 2
with pytest.raises(TypeError):
s.a = {'a': '1', 'b': '2'}
def test_key_type_dict(self):
class SomeObject(jsonobject.JSONSerializableObject):
a = jsonobject.JSONProperty(value_type=dict)
s = SomeObject(a={'a': 1, 'b': 2})
assert s.a['a'] == 1
assert s.a['b'] == 2
s.a = {u'a': 3, u'b': 4}
assert s.a['a'] == 3
assert s.a['b'] == 4
with pytest.raises(TypeError):
s.a = {1: 1, 2: 2}
def test_parse_text(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(default=u'FOO', value_type=str)
bar = jsonobject.JSONProperty(default=0, value_type=int)
s = SomeObject.parse_text('{"foo": "FOOFOO", "bar": 123}')
assert s.foo == u'FOOFOO'
assert s.bar == 123
t = SomeObject.parse_text('{}')
assert t.foo == u'FOO'
assert t.bar == 0
# Ill-formed JSON.
with pytest.raises(ValueError):
SomeObject.parse_text('{"foo": "FOO}')
# Value type mismatch.
with pytest.raises(TypeError):
SomeObject.parse_text('{"foo": 123}')
# Unknown field was found.
with pytest.raises(AttributeError):
SomeObject.parse_text('{"baz": 123}')
# Unknown field was found, but ignored.
u = SomeObject.parse_text('{"baz": 123}', _ignore_unknown=True)
assert u.json(sort_keys=True) == '{"bar": 0, "foo": "FOO"}'
def test_parse_overriding(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(default=u'FOO', value_type=str)
s = SomeObject.parse({'foo': u'FOOFOO'})
assert s.foo == u'FOOFOO'
t = SomeObject.parse({'foo': u'FOOFOO'}, foo=u'FOOFOOFOO')
assert t.foo == u'FOOFOOFOO'
def test_parse_nested(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(default=123, value_type=int)
class AnotherObject(jsonobject.JSONSerializableObject):
bar = jsonobject.JSONProperty(value_type=SomeObject)
s = AnotherObject.parse_text('{"bar": {"foo": 123}}')
assert isinstance(s.bar, SomeObject)
assert s.bar.foo == 123
def test_parse_dict_int(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(value_type=dict, element_type=int)
s = SomeObject.parse_text('{"foo": {"a": 1, "b": 2}}')
assert len(s.foo) == 2
assert s.foo['a'] == 1
assert s.foo['b'] == 2
def test_parse_dict_long(self):
# Element type declared as long, but it's acceptable to receive int
# values. They are always safe to upcast.
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(value_type=dict, element_type=int)
s = SomeObject.parse_text('{"foo": {"a": 1, "b": 2}}')
assert len(s.foo) == 2
assert s.foo['a'] == 1
assert s.foo['b'] == 2
def test_parse_dict_object(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(default=123, value_type=int)
class AnotherObject(jsonobject.JSONSerializableObject):
bar = jsonobject.JSONProperty(value_type=dict,
element_type=SomeObject)
s = AnotherObject.parse_text('{"bar": {"a": {"foo": 1}, '
'"b": {"foo": 2}}}')
assert len(s.bar) == 2
assert isinstance(s.bar['a'], SomeObject)
assert s.bar['a'].foo == 1
assert isinstance(s.bar['b'], SomeObject)
assert s.bar['b'].foo == 2
def test_parse_list(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(default=123, value_type=int)
class AnotherObject(jsonobject.JSONSerializableObject):
bar = jsonobject.JSONProperty(value_type=list,
element_type=SomeObject)
s = AnotherObject.parse_text('{"bar": [{"foo": 1}, {"foo": 2}]}')
assert len(s.bar) == 2
assert isinstance(s.bar[0], SomeObject)
assert s.bar[0].foo == 1
assert isinstance(s.bar[1], SomeObject)
assert s.bar[1].foo == 2
s.bar[0] = SomeObject(foo=3)
assert s.bar[0].foo == 3
def test_parse_tuple(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(default=123, value_type=int)
class AnotherObject(jsonobject.JSONSerializableObject):
bar = jsonobject.JSONProperty(value_type=tuple,
element_type=SomeObject)
s = AnotherObject.parse_text('{"bar": [{"foo": 1}, {"foo": 2}]}')
assert len(s.bar) == 2
assert isinstance(s.bar[0], SomeObject)
assert s.bar[0].foo == 1
assert isinstance(s.bar[1], SomeObject)
assert s.bar[1].foo == 2
# Tuple should not allow mutation.
with pytest.raises(TypeError):
s.bar[0] = SomeObject(foo=3)
def test_parse_different_name(self):
class SomeObject(jsonobject.JSONSerializableObject):
# There may be a case where the property name in Python and JSON
# differs, especially if the name is keywords like "or", "and" or
# such.
foo_ = jsonobject.JSONProperty(name='foo', value_type=int)
s = SomeObject.parse_text('{"foo": 123}')
assert s.foo_ == 123
# From Python code, foo_ should be accessible as is.
t = SomeObject(foo_=456)
assert t.foo_ == 456
def test_parse_swapped_name(self):
class SomeObject(jsonobject.JSONSerializableObject):
# These name are swapped in JSON world. Such a situation should
# never happen in reality, but in the specification, this is still
# allowed.
foo = jsonobject.JSONProperty(name='bar', value_type=int)
bar = jsonobject.JSONProperty(name='foo', value_type=int)
s = SomeObject.parse_text('{"foo": 123, "bar": 456}')
assert s.foo == 456
assert s.bar == 123
# From Python code, they should be treated as is.
t = SomeObject(foo=123, bar=456)
assert t.foo == 123
assert t.bar == 456
def test_parse_field_in_parent(self):
class SomeObject(jsonobject.JSONSerializableObject):
foo = jsonobject.JSONProperty(value_type=int)
class AnotherObject(SomeObject):
bar = jsonobject.JSONProperty(value_type=int)
s = AnotherObject.parse_text('{"foo": 123, "bar": 456}')
assert s.foo == 123
assert s.bar == 456
def test_instance_json_property(self):
class SomeObject(jsonobject.JSONSerializableObject):
# Though it's not recommended for most use cases, JSON properties
# can be created dynamically at instance creation time.
# This is sometimes useful for dynamically importing unknown JSON
# but do not abuse this. This is tricky. For readability, an
# ordinary property should be explicitly declared at the class
# level.
def __init__(self, **kwargs):
# Dynamically create a new type, because properties
# (to be precise, descriptors) works if and only if owned by a
# class object.
cls = type('__{}_{}'.format(self.__class__.__name__, id(self)),
(jsonobject.JSONSerializableObject,),
dict(self.__class__.__dict__))
# Change the class of this instance.
self.__class__ = cls
# Create properties dynamically and add to the dynamically
# created class object. You may want to import not from kwargs,
# and use JSON instead.
for key, value in kwargs.items():
if not hasattr(cls, key):
setattr(cls, key, jsonobject.JSONProperty(
name=key, default=value))
# Set the value using JSONSerializableObject's constructor.
super(cls, self).__init__(**kwargs)
# Note that, this class level property will be present in the new
# dynamically created class, because self.__class__.__dict__ is
# passed to type() above.
foo = jsonobject.JSONProperty(default='FOO')
s = SomeObject(bar='BAR')
assert s.foo == 'FOO'
assert s.bar == 'BAR'
assert s.json(sort_keys=True) == '{"bar": "BAR", "foo": "FOO"}'
# Confirm another instance won't suffer from any side effect.
t = SomeObject(baz='BAZ')
assert t.foo == 'FOO'
assert t.baz == 'BAZ'
assert t.json(sort_keys=True) == '{"baz": "BAZ", "foo": "FOO"}'
def test_instance_json_property_shared_class(self):
class SomeObject(jsonobject.JSONSerializableObject):
# Do not do something like this!
# This is a bad example of a dynamic property, where I store a
# property to a shared class object, which will produce a side
# effect for other instances.
def __init__(self, **kwargs):
cls = self.__class__
# Create properties dynamically and add to the shared class
# object.
for key, value in kwargs.items():
if not hasattr(cls, key):
setattr(cls, key, jsonobject.JSONProperty(
name=key, default=value))
# Set the value using JSONSerializableObject's constructor.
super(cls, self).__init__(**kwargs)
foo = jsonobject.JSONProperty(default='FOO')
s = SomeObject(bar='BAR')
# This is expected...
assert s.foo == 'FOO'
assert s.bar == 'BAR'
assert s.json(sort_keys=True) == '{"bar": "BAR", "foo": "FOO"}'
# Also this is fine...
t = SomeObject(baz='BAZ')
assert t.foo == 'FOO'
assert t.baz == 'BAZ'
# But what is this?! Why do I have bar here though I don't define it
# for t!
assert t.bar == 'BAR'
assert t.json(sort_keys=True) == ('{"bar": "BAR", "baz": "BAZ", '
'"foo": "FOO"}')
# That's why I put a property to the shared class object.
# So, use a dynamic class object like what's in
# test_instance_json_property. (But to begin with, avoid using a
# dynamic property as much as possible.)
def test_instance_json_property_simple(self):
class SomeObject(jsonobject.JSONSerializableObject):
# This is a bit simple version of dynamic property creation.
# This way the class definition is much simpler...
def __init__(self, **kwargs):
super(SomeObject, self).__init__(**kwargs)
# bar is a dynamically created property. You must provide the
# property name.
self.bar = jsonobject.JSONProperty(name='bar', default='BAR')
foo = jsonobject.JSONProperty(default='FOO')
s = SomeObject()
assert s.foo == 'FOO'
# However, you cannot manipulate bar naturally.
# You would call __get__(), __set__() to directly talk with this
# property (descriptor) object.
assert s.bar.__get__(s) == 'BAR'
# Serializing to JSON is still straightforward.
assert s.json(sort_keys=True) == '{"bar": "BAR", "foo": "FOO"}'
class TestDynamicJSONSerializableObject(object):
def test_invalid(self):
with pytest.raises(TypeError):
jsonobject.parse_text('null')
with pytest.raises(TypeError):
jsonobject.parse_text('"foo"')
with pytest.raises(TypeError):
jsonobject.parse_text('123')
with pytest.raises(TypeError):
jsonobject.parse_text('["foo", "bar"]')
with pytest.raises(ValueError):
# Looks like a map, but corrupted.
jsonobject.parse_text('{"foo": "bar}')
def test_readwrite_omittable(self):
s = jsonobject.parse_text('{"foo": "FOO", "bar": "BAR"}',
readonly=False, omittable=True)
assert s.foo == u'FOO'
assert s.bar == u'BAR'
assert s.json(sort_keys=True) == '{"bar": "BAR", "foo": "FOO"}'
s.foo = u'FOOFOO'
s.bar = None
# Note that every property is omittable.
assert s.json(sort_keys=True) == '{"foo": "FOOFOO"}'
def test_readwrite_not_omittable(self):
s = jsonobject.parse_text('{"foo": "FOO", "bar": "BAR"}',
readonly=False, omittable=False)
assert s.json(sort_keys=True) == '{"bar": "BAR", "foo": "FOO"}'
s.foo = u'FOOFOO'
s.bar = None
# No property is omittable.
assert s.json(sort_keys=True) == '{"bar": null, "foo": "FOOFOO"}'
def test_readonly_omittable(self):
s = jsonobject.parse_text('{"foo": "FOO", "bar": null}',
readonly=True, omittable=True)
assert s.foo == u'FOO'
assert s.bar is None
with pytest.raises(AttributeError):
s.foo = u'FOOFOO'
with pytest.raises(AttributeError):
s.bar = u'BARBAR'
# Every property is omittable, so bar should be omitted even though it
# appeared in the input.
assert s.json(sort_keys=True) == '{"foo": "FOO"}'
def test_readonly_not_omittable(self):
s = jsonobject.parse_text('{"foo": "FOO", "bar": null}',
readonly=True, omittable=False)
assert s.foo == u'FOO'
assert s.bar is None
# No property is omittable.
assert s.json(sort_keys=True) == '{"bar": null, "foo": "FOO"}'
def test_nested_map(self):
# Nested map should create a nested JSONSerializableObject.
s = jsonobject.parse_text('{"foo": "FOO", "bar": {"baz": "BAZ"}}')
assert s.foo == u'FOO'
assert s.bar.baz == u'BAZ'
def test_list(self):
# List should create a list of JSONSerializableObject.
s = jsonobject.parse_text('{"foo": [{"bar": 1}, {"bar": 2}]}')
assert len(s.foo) == 2
assert s.foo[0].bar == 1
assert s.foo[1].bar == 2
def test_value_overriding(self):
obj = {'foo': 'FOO', 'bar': 'BAR'}
s = jsonobject.parse(obj)
assert s.foo == u'FOO'
assert s.bar == u'BAR'
assert s.json(sort_keys=True) == '{"bar": "BAR", "foo": "FOO"}'
# With parse, you can override some values.
t = jsonobject.parse(obj, bar='BARBAR')
assert t.foo == u'FOO'
assert t.bar == u'BARBAR'
assert t.json(sort_keys=True) == '{"bar": "BARBAR", "foo": "FOO"}'
# If no value available in the input object, a new property will be
# created (no exception thrown).
u = jsonobject.parse(obj, baz='BAZ')
assert u.foo == u'FOO'
assert u.bar == u'BAR'
assert u.baz == u'BAZ'
assert u.json(sort_keys=True) == ('{"bar": "BAR", "baz": "BAZ", '
'"foo": "FOO"}')
def main():
import doctest
doctest.testmod(jsonobject)
import sys
sys.exit(pytest.main(args=[__file__.replace('.pyc', '.py')]))
if __name__ == '__main__':
main()