This repository has been archived by the owner on Apr 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_fields.py
1399 lines (1131 loc) · 48.2 KB
/
test_fields.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 collections
import datetime
import re
import uuid
from collections import deque
from pytest import raises
from serde import Model, fields, validators
from serde.exceptions import (
ContextError,
DeserializationError,
InstantiationError,
NormalizationError,
SerializationError,
ValidationError,
)
from serde.fields import (
BaseField,
Bool,
Bytes,
Choice,
Complex,
Constant,
Date,
DateTime,
Deque,
Dict,
Field,
Float,
FrozenSet,
Instance,
Int,
List,
Literal,
Nested,
Optional,
OrderedDict,
Regex,
Set,
Str,
Text,
Time,
Tuple,
Uuid,
_resolve_to_field_instance,
create,
)
Reversed = create( # noqa: N806
'Reversed',
base=Str,
serializers=[lambda x: x[::-1]],
deserializers=[lambda x: x[::-1]],
)
def test__resolve_to_field_instance_field():
# An instance of Field should be passed through.
field = Field()
assert _resolve_to_field_instance(field) is field
def test__resolve_to_field_instance_field_class():
# A Field class should be instantiated.
assert _resolve_to_field_instance(Field) == Field()
def test__resolve_to_field_instance_model_class():
# A Model class should become a Nested instance, wrapping the Model class.
class Example(Model):
pass
assert _resolve_to_field_instance(Example) == Nested(Example)
def test__resolve_to_field_instance_model():
# A Model instance should not be allowed.
class Example(Model):
pass
with raises(TypeError):
_resolve_to_field_instance(Example())
def test__resolve_to_field_instance_builtin_types():
# All the built-in types should resolve to an instance of their
# corresponding Field.
assert _resolve_to_field_instance(bool) == Bool()
assert _resolve_to_field_instance(bytes) == Bytes()
assert _resolve_to_field_instance(complex) == Complex()
assert _resolve_to_field_instance(dict) == Dict()
assert _resolve_to_field_instance(float) == Float()
assert _resolve_to_field_instance(int) == Int()
assert _resolve_to_field_instance(list) == List()
assert _resolve_to_field_instance(str) == Str()
assert _resolve_to_field_instance(tuple) == Tuple()
try:
assert _resolve_to_field_instance(basestring) == fields.BaseString()
except NameError:
pass
try:
assert _resolve_to_field_instance(long) == fields.Long()
except NameError:
pass
try:
assert _resolve_to_field_instance(unicode) == fields.Unicode()
except NameError:
pass
class TestBaseField:
def test___init___basic(self):
# Construct a basic Base and check values are set correctly.
base = BaseField()
assert base.id >= 0
assert base.serializers == []
assert base.deserializers == []
# A second Base instantiated should have a higher counter.
base2 = BaseField()
assert base2.id - base.id == 1
def test___init___options(self):
# A Base with extra options set.
base = BaseField(serializers=[None], deserializers=[1, 2, 3])
assert base.serializers == [None]
assert base.deserializers == [1, 2, 3]
def test___eq__(self):
# Bases with equal values should be equal.
assert BaseField() == BaseField()
assert BaseField(serializers=[None]) == BaseField(serializers=[None])
assert BaseField(deserializers=[None]) == BaseField(deserializers=[None])
def test___model__(self):
# Base.__model__ simply returns the _model_cls value.
obj = object()
base = BaseField()
base._model_cls = obj
assert base.__model__ is obj
def test__attrs(self):
# Returns a filtered dictionary of filtered attributes.
base = BaseField(serializers=[None], deserializers=[1, 2, 3])
assert base._attrs() == {'deserializers': [1, 2, 3], 'serializers': [None]}
def test__bind(self):
# Make sure _bind can't be called twice.
obj = object()
base = BaseField()
base._bind(obj)
assert base._model_cls is obj
with raises(ContextError) as e:
base._bind(object())
assert e.value.message == "'BaseField' instance used multiple times"
def test__serialize_with(self):
# Check that the Base field doesn't implement this method.
with raises(NotImplementedError):
BaseField()._serialize_with(object(), {})
def test__deserialize_with(self):
# Check that the Base field doesn't implement this method.
with raises(NotImplementedError):
BaseField()._deserialize_with(object(), {})
def test__serialize(self):
# Check that custom serializers are applied.
base = BaseField(serializers=[lambda x: x[::-1]])
assert base._serialize('testing') == 'gnitset'
def test__deserialize(self):
# Check that custom deserializers are applied.
base = BaseField(deserializers=[lambda x: x[::-1]])
assert base._deserialize('gnitset') == 'testing'
def test_serialize(self):
# Check that serialize simply passes a value through.
obj = object()
assert BaseField().serialize(obj) is obj
def test_deserialize(self):
# Check that deserialize simply passes a value through.
obj = object()
assert BaseField().deserialize(obj) is obj
class TestField:
def test___init___basic(self):
# Construct a basic Field and check values are set correctly.
field = Field()
assert field.id >= 0
assert field.rename is None
assert field.default is None
assert field.serializers == []
assert field.deserializers == []
assert field.normalizers == []
assert field.validators == []
# A second Field instantiated should have a higher counter.
field2 = Field()
assert field2.id - field.id == 1
def test___init___options(self):
# A Field with extra options set.
field = Field(
rename='test',
default=5,
serializers=[1, 2, 3],
deserializers=[0.5],
validators=[None],
)
assert field.rename == 'test'
assert field.default == 5
assert field.serializers == [1, 2, 3]
assert field.deserializers == [0.5]
assert field.validators == [None]
def test__default(self):
# Make sure default is correctly returned.
def returns_5():
return 5
assert Field(default=None)._default() is None
assert Field(default=5)._default() == 5
assert Field(default=returns_5)._default() == 5
def test__bind(self):
# Make sure _bind can't be called twice.
obj = object()
field = Field()
field._bind(obj, 'test')
assert field._model_cls is obj
assert field._attr_name == 'test'
assert field._serde_name == 'test'
with raises(ContextError) as e:
field._bind(object(), 'test')
assert e.value.message == "'Field' instance used multiple times"
def test__bind_with_rename(self):
# Make sure _bind rename overrides the passed in name.
obj = object()
field = Field(rename='hello')
field._bind(obj, 'test')
assert field._attr_name == 'test'
assert field._serde_name == 'hello'
def test__instantiate_with(self):
# Check a basic Field can instantiate a basic value.
model = Model()
field = Field(rename='hello')
field._bind(model.__class__, 'test')
kwargs = {'test': 'testing...'}
assert field._instantiate_with(model, kwargs) is None
assert kwargs == {}
assert model.test == 'testing...'
def test__instantiate_with_default(self):
# Check a basic Field can instantiate a default when not given.
model = Model()
field = Field(rename='hello', default='testing...')
field._bind(model.__class__, 'test')
kwargs = {}
assert field._instantiate_with(model, kwargs) is None
assert kwargs == {}
assert model.test == 'testing...'
def test__instantiate_with_none_and_default(self):
# Check a basic Field can instantiate a default.
model = Model()
field = Field(rename='hello', default='testing...')
field._bind(model.__class__, 'test')
kwargs = {'test': None}
assert field._instantiate_with(model, kwargs) is None
assert kwargs == {}
assert model.test == 'testing...'
def test__serialize_with(self):
# Check a basic Field simply serializes the attribute value.
model = Model()
model.test = 'testing...'
field = Field(rename='hello')
field._bind(model.__class__, 'test')
assert field._serialize_with(model, {}) == {'hello': 'testing...'}
def test__serialize_with_attribute_error(self):
# Check that the appropriate error is raised when the attr is missing.
model = Model()
field = Field(rename='hello')
field._bind(model.__class__, 'test')
with raises(SerializationError) as e:
field._serialize_with(model, {})
assert (
e.value.pretty()
== """\
SerializationError: expected attribute 'test'
Due to => field 'test' of type 'Field' on model 'Model'"""
)
def test__deserialize_with(self):
# Check a basic Field simply deserializes the dictionary value.
model = Model()
field = Field(rename='hello')
field._bind(model.__class__, 'test')
result = field._deserialize_with(model, {'hello': 'testing...'})
assert result == (model, {'hello': 'testing...'})
assert model.test == 'testing...'
def test__deserialize_with_index_error(self):
# Check that the appropriate error is raised when the key is missing.
model = Model()
field = Field(rename='hello')
field._bind(model.__class__, 'test')
with raises(DeserializationError) as e:
field._deserialize_with(model, {})
assert (
e.value.pretty()
== """\
DeserializationError: expected field 'hello'
Due to => field 'test' of type 'Field' on model 'Model'"""
)
def test__normalize_with(self):
# Check a basic Field simply serializes the attribute value.
model = Model()
model.test = 'testing...'
field = Field(rename='hello')
field._bind(model.__class__, 'test')
field._normalize_with(model)
def test__normalize_with_attribute_error(self):
# Check that the appropriate error is raised when the attr is missing.
model = Model()
field = Field(rename='hello')
field._bind(model.__class__, 'test')
with raises(NormalizationError) as e:
field._normalize_with(model)
assert (
e.value.pretty()
== """\
NormalizationError: expected attribute 'test'
Due to => field 'test' of type 'Field' on model 'Model'"""
)
def test__validate_with(self):
# Check a basic Field simply serializes the attribute value.
model = Model()
model.test = 'testing...'
field = Field(rename='hello')
field._bind(model.__class__, 'test')
field._validate_with(model)
def test__validate_with_attribute_error(self):
# Check that the appropriate error is raised when the attr is missing.
model = Model()
field = Field(rename='hello')
field._bind(model.__class__, 'test')
with raises(ValidationError) as e:
field._validate_with(model)
assert (
e.value.pretty()
== """\
ValidationError: expected attribute 'test'
Due to => field 'test' of type 'Field' on model 'Model'"""
)
def test_normalize(self):
# The base Field simply passes things through.
field = Field()
value = object()
assert field.normalize(value) == value
def test_validate(self):
# Any value is allowed on the base Field except None.
field = Field()
for value in (None, 0, 'string', object(), type):
field.validate(value)
def test_create_base():
# By default the created Field should subclass Field.
Example = create('Example') # noqa: N806
assert issubclass(Example, Field)
assert Example.__mro__[1] == Field
def test_create_str():
# You should be able to specify a different base Field.
Example = create('Example', base=Str) # noqa: N806
assert issubclass(Example, Str)
assert Example.__mro__[1] == Str
def test_create_args():
# You should be able to create a new Field, subclassing a Field that
# requires positional arguments.
Example = create('Example', base=Instance, args=(str,)) # noqa: N806
Example()
# This is what should happen if you don't give it the arguments!
Example = create('Example', base=Instance) # noqa: N806
with raises(TypeError):
Example()
def test_create_serializer_and_normalizer_and_deserializer():
# You should be able to create a new Field with extra serializers,
# normalizers, and deserializers.
def reverser(value):
return value[::-1]
Reversed = create( # noqa: N806
'Reversed',
base=Str,
serializers=[reverser],
deserializers=[reverser],
normalizers=[reverser],
)
class Example(Model):
a = Reversed()
field = Example(a='test')
assert field.a == 'tset'
field = Example.from_dict({'a': 'test'})
assert field.a == 'test'
assert field.to_dict() == {'a': 'tset'}
def test_create_validator():
# You should be able to create a Field with an arbitrary validate method.
def assert_is_not_derp(value):
assert value != 'derp'
NotDerp = create('NotDerp', Str, validators=[assert_is_not_derp]) # noqa: N806
class Example(Model):
a = NotDerp()
assert Example('notderp').a == 'notderp'
with raises(InstantiationError):
Example('derp')
class TestOptional:
def test___init___basic(self):
# Construct a basic Optional and check values are set correctly.
field = Optional()
assert field.inner == Field()
assert field.default is None
assert field.validators == []
def test___init___options(self):
# Construct an Optional with extra options and make sure values are
# passed to Field.
field = Optional(Str, default='test', validators=[None])
assert field.inner == Str()
assert field.default == 'test'
assert field.validators == [None]
def test__serialize_with(self):
# Check an Optional serializes using the inner Field.
model = Model()
model.test = 'testing...'
field = Optional(inner=Str, rename='hello')
field._bind(model.__class__, 'test')
assert field._serialize_with(model, {}) == {'hello': 'testing...'}
model.test = None
assert field._serialize_with(model, {}) == {}
def test__serialize_with_attribute_error(self):
# Check that the appropriate error is raised when the attr is missing.
model = Model()
field = Optional(rename='hello')
field._bind(model.__class__, 'test')
with raises(SerializationError) as e:
field._serialize_with(model, {})
assert (
e.value.pretty()
== """\
SerializationError: expected attribute 'test'
Due to => field 'test' of type 'Optional' on model 'Model'"""
)
def test__deserialize_with(self):
# Check an Optional deserializes using the inner Field.
model = Model()
field = Optional(rename='hello', default='testing...')
field._bind(model.__class__, 'test')
result = field._deserialize_with(model, {'hello': 'hmmmm'})
assert result == (model, {'hello': 'hmmmm'})
assert model.test == 'hmmmm'
del model.test
assert field._deserialize_with(model, {}) == (model, {})
assert not hasattr(model, 'test')
def test__normalize_with(self):
# Check an Optional simply normalizes the attribute value.
model = Model()
model.test = 'testing...'
field = Optional(rename='hello')
field._bind(model.__class__, 'test')
field._normalize_with(model)
def test__normalize_with_none(self):
# Check an Optional simply allows None.
model = Model()
field = Optional(rename='hello')
field._bind(model.__class__, 'test')
field._normalize_with(model)
assert model.test is None
def test__normalize_with_none_default(self):
# Check an Optional sets a default, if set.
model = Model()
field = Optional(rename='hello', default='testing...')
field._bind(model.__class__, 'test')
field._normalize_with(model)
assert model.test == 'testing...'
def test__normalize_with_none_default_callbable(self):
# Check an Optional sets a callable default, if set.
def test():
return 'testing...'
model = Model()
field = Optional(rename='hello', default=test)
field._bind(model.__class__, 'test')
field._normalize_with(model)
assert model.test == 'testing...'
def test__validate_with(self):
# Check a basic Field simply serializes the attribute value.
model = Model()
model.test = 'testing...'
field = Optional(rename='hello')
field._bind(model.__class__, 'test')
field._validate_with(model)
def test__validate_with_attribute_error(self):
# Check that the appropriate error is raised when the attr is missing.
model = Model()
field = Optional(rename='hello')
field._bind(model.__class__, 'test')
with raises(ValidationError) as e:
field._validate_with(model)
assert (
e.value.pretty()
== """\
ValidationError: expected attribute 'test'
Due to => field 'test' of type 'Optional' on model 'Model'"""
)
def test_serialize(self):
# An Optional should call the wrapped Field's _serialize method.
field = Optional(Reversed)
assert field.serialize('test') == 'tset'
def test_serialize_extra(self):
# An Optional should call the wrapped Field's _serialize method.
field = Optional(Reversed(serializers=[lambda x: x.strip()]))
assert field.serialize('test ') == 'tset'
def test_deserialize(self):
# An Optional should call the wrapped Field's _deserialize method.
field = Optional(Reversed)
assert field.deserialize('test') == 'tset'
def test_deserialize_extra(self):
# An Optional should call the wrapped Field's _deserialize method.
field = Optional(Field(deserializers=[lambda x: x.strip()]))
assert field.deserialize('test ') == 'test'
def test_normalize(self):
# An Optional should call the wrapped Field's _normalize method.
field = Optional(Reversed)
assert field.normalize('test') == 'test'
def test_validate(self):
# An Optional should call the wrapped Field's _validate method.
field = Optional(Reversed)
with raises(ValidationError):
assert field.validate(5)
def test_validate_extra(self):
# An Optional should call the wrapped Field's _validate method.
field = Optional(Field(validators=[validators.Between(10, 10)]))
with raises(ValidationError):
assert field.validate(5)
def test_integrate_contained(self):
# An Optional should be able to be contained by other container fields.
class Example(Model):
a = Dict(key=str, value=Optional(int))
assert Example(a={'x': 1234, 'y': None, 'z': 0}).a == {
'x': 1234,
'y': None,
'z': 0,
}
def test_integrate_contained_default(self):
# An Optional with a default should be able to be contained by other
# container fields.
class Example(Model):
a = Dict(key=str, value=Optional(int, default=0))
assert Example(a={'x': 1234, 'y': None, 'z': 0}).a == {
'x': 1234,
'y': 0,
'z': 0,
}
def test_integrate_contained_deserializers(self):
# An Optional with extra deserializers should be able to be contained by
# other container fields.
class Example(Model):
a = List(
Optional(int, deserializers=[lambda x: x * 2]),
deserializers=[lambda x: x[1:]],
)
assert Example.from_dict({'a': [1, 2, None, 3, 4]}).a == [4, None, 6, 8]
def test_integrate_contained_normalizers(self):
# An Optional with extra normalizers should be able to be contained by
# other container fields.
class Example(Model):
a = Dict(key=str, value=Optional(int, normalizers=[lambda x: x * 2]))
assert Example(a={'x': 1234, 'y': None, 'z': 0}).a == {
'x': 2468,
'y': None,
'z': 0,
}
assert Example.from_dict({'a': {'x': 1234, 'y': None, 'z': 0}}).a == {
'x': 2468,
'y': None,
'z': 0,
}
def test_integrate_contained_validators(self):
# An optional with extra validators shoudl be able to be contained by
# other container fields.
class Example(Model):
a = List(
Optional(str, validators=[validators.Length(1)]),
validators=[validators.LengthBetween(1, 5)],
)
with raises(InstantiationError) as e:
Example(a=['a', 'b', None, 'c', 'hello there'])
assert (
e.value.pretty()
== """\
InstantiationError: expected length 1 but got length 11 for value 'hello there'
Due to => ValidationError: expected length 1 but got length 11 for value 'hello there'
Due to => value ['a', 'b', None, 'c', 'hel... for field 'a' of type 'List' on model 'Example'\
"""
)
class TestInstance:
def test___init___basic(self):
# Construct a basic Instance and check values are set correctly.
field = Instance(int)
assert field.type == int
assert field.validators == []
def test___init___options(self):
# Construct an Instance and make sure values are passed to Field.
field = Instance(int, validators=[None])
assert field.type == int
assert field.validators == [None]
def test_validate(self):
# Check that it validates that the values are an instance of the
# specified type.
field = Instance(int)
for value in (-1000, 0, 1000):
assert field.validate(value) is None
for value in (None, 20.0, 'string', object, type):
with raises(ValidationError):
field.validate(value)
class TestNested:
def test___init___basic(self):
# Construct a basic Nested and check values are set correctly.
field = Nested(Model)
assert field.type == Model
assert field.validators == []
def test___init___options(self):
# Construct a Nested with extra options and make sure values are passed
# to Field.
field = Nested(Model, validators=[None])
assert field.type == Model
assert field.validators == [None]
def test_serialize(self):
# A Nested should serialize as a dictionary representation of the Model.
class Example(Model):
a = Field()
field = Nested(Example)
assert field.serialize(Example(a=0)) == collections.OrderedDict([('a', 0)])
def test_deserialize(self):
# A Nested should deserialize as a dictionary representation of the
# Model.
class Example(Model):
a = Field()
field = Nested(Example)
assert field.deserialize({'a': 0}) == Example(a=0)
with raises(DeserializationError):
field.deserialize({'b': 0, 'c': 1})
class TestLiteral:
def test___init___basic(self):
# Construct a basic Literal and check values are set correctly.
field = Literal(1)
assert field.value == 1
assert field.validators == []
def test___init___options(self):
# Construct a Literal with extra options and make sure values are
# passed to Field.
field = Literal(-1234, validators=[None])
assert field.value == -1234
assert field.validators == [None]
def test_validate(self):
# Check that values must be equal to the constant value.
field = Literal(True)
field.validate(True)
with raises(ValidationError):
assert field.validate(False)
class TestConstant:
def test___init__(self):
# Construct a basic Constant and check values are set correctly.
field = Constant(1)
assert field.value == 1
assert field.validators == []
class TestDeque:
def test___init__(self):
# Construct a basic Deque and check values are set correctly.
field = Deque()
assert field.element == Field()
assert field.kwargs == {'maxlen': None}
assert field.validators == []
def test___init___options(self):
# Construct a Deque with extra options and make sure values are passed
# to Field.
field = Deque(element=Str, maxlen=5, validators=[None])
assert field.element == Str()
assert field.kwargs == {'maxlen': 5}
assert field.validators == [None]
def test_serialize(self):
# A Deque should serialize values based on the element Field.
field = Deque(element=Reversed, maxlen=1)
assert field.serialize(deque(['test', 'hello'])) == deque(['olleh'])
def test_serialize_extra(self):
# A Deque should serialize values based on the element Field.
field = Deque(element=Field(serializers=[lambda x: x[::-1]]))
assert field.serialize(deque(['test', 'hello'], maxlen=1)) == deque(
['olleh'], maxlen=1
)
def test_deserialize(self):
# A Deque should deserialize values based on the element Field.
field = Deque(element=Reversed, maxlen=1)
assert field.deserialize(deque(['tset', 'olleh'])) == deque(['hello'], maxlen=1)
def test_deserialize_extra(self):
# A Deque should deserialize values based on the element Field.
field = Deque(element=Field(deserializers=[lambda x: x[::-1]]), maxlen=1)
assert field.deserialize(deque(['tset', 'olleh'])) == deque(['hello'], maxlen=1)
def test_normalize(self):
# A Deque should normalize values based on the element Field.
field = Deque(element=Field, maxlen=1)
assert field.normalize(deque(['test', 'hello'])) == deque(['hello'], maxlen=1)
def test_normalize_extra(self):
# A Deque should normalize values based on the element Field.
field = Deque(element=Field(normalizers=[lambda x: x[::-1]]), maxlen=1)
assert field.normalize(deque(['tset', 'olleh'])) == deque(['hello'], maxlen=1)
def test_validate(self):
# A Deque should validate values based on the element Field.
field = Deque(element=Int, maxlen=3)
field.validate(deque([0, 1, 2, 3, 4], maxlen=3))
with raises(ValidationError):
field.validate(deque(['1', '2', 'a', 'string']))
with raises(ValidationError):
field.validate(deque([0, 1], maxlen=2))
def test_validate_extra(self):
# A Deque should validate values based on the element Field.
field = Deque(element=Field(validators=[validators.Between(10, 10)]), maxlen=4)
field.validate(deque([10, 10, 10], maxlen=4))
with raises(ValidationError):
field.validate(deque([10, 11, 12, 13], maxlen=4))
class TestDict:
def test___init___basic(self):
# Construct a basic Dict and check values are set correctly.
field = Dict()
assert field.key == Field()
assert field.value == Field()
assert field.validators == []
def test___init___options(self):
# Construct a Dict with extra options and make sure values are passed to
# Field.
field = Dict(key=Str, value=Int, validators=[None])
assert field.key == Str()
assert field.value == Int()
assert field.validators == [None]
def test_serialize(self):
# A Dict should serialize values based on the key and value Fields.
field = Dict(key=Reversed, value=Reversed)
assert field.serialize({'ab': 'test', 'cd': 'hello'}) == {
'ba': 'tset',
'dc': 'olleh',
}
def test_serialize_extra(self):
# A Dict should serialize values based on the key and value Fields.
field = Dict(key=Field(serializers=[lambda x: x[::-1]]))
assert field.serialize({'ab': 'test', 'cd': 'hello'}) == {
'ba': 'test',
'dc': 'hello',
}
def test_deserialize(self):
# A Dict should deserialize values based on the key and value Fields.
field = Dict(key=Reversed, value=Reversed)
assert field.deserialize({'ba': 'tset', 'dc': 'olleh'}) == {
'ab': 'test',
'cd': 'hello',
}
def test_deserialize_extra(self):
# A Dict should serialize values based on the key and value Fields.
field = Dict(key=Field(deserializers=[lambda x: x[::-1]]))
assert field.deserialize({'ba': 'test', 'dc': 'hello'}) == {
'ab': 'test',
'cd': 'hello',
}
def test_normalize(self):
# A Dict should normalize values based on the key and value Fields.
field = Dict(key=Str, value=Str)
assert field.normalize({'ab': 'test', 'cd': 'hello'}) == {
'ab': 'test',
'cd': 'hello',
}
def test_normalize_extra(self):
# A Dict should normalize values based on the key and value Fields.
field = Dict(key=Field(normalizers=[lambda x: x[::-1]]))
assert field.normalize({'ba': 'test', 'dc': 'hello'}) == {
'ab': 'test',
'cd': 'hello',
}
def test_validate(self):
# A Dict should validate values based on the key and value Fields.
field = Dict(key=Int, value=Str)
field.validate({0: 'test', 1: 'hello'})
with raises(ValidationError):
field.validate({'test': 0})
def test_validate_extra(self):
# A Dict should validate values based on the key and value Fields.
field = Dict(value=Field(validators=[validators.Between(10, 10)]))
field.validate({'test': 10, 'hello': 10})
with raises(ValidationError):
field.validate({'test': 11})
class TestOrderedDict:
def test___init___basic(self):
# Construct a basic OrderedDict and check values are set correctly.
field = OrderedDict()
assert field.key == Field()
assert field.value == Field()
assert field.validators == []
def test___init___options(self):
# Construct a OrderedDict with extra options and make sure values are
# passed to Field.
field = OrderedDict(key=Str, value=Int, validators=[None])
assert field.key == Str()
assert field.value == Int()
assert field.validators == [None]
class TestFrozenSet:
def test___init___basic(self):
# Construct a basic FrozenSet and check values are set correctly.
field = FrozenSet()
assert field.element == Field()
assert field.validators == []
def test___init___options(self):
# Construct a FrozenSet with extra options and make sure values are passed to
# Field.
field = FrozenSet(element=Int, validators=[None])
assert field.element == Int()
assert field.validators == [None]
def test_serialize(self):
# A FrozenSet should serialize values based on the element Field.
field = FrozenSet(element=Reversed)
assert field.serialize(frozenset({'test', 'hello'})) == frozenset(
{'tset', 'olleh'}
)
def test_serialize_extra(self):
# A FrozenSet should serialize values based on the element Field.
field = FrozenSet(element=Field(serializers=[lambda x: x[::-1]]))
assert field.serialize(frozenset({'test', 'hello'})) == frozenset(
{'tset', 'olleh'}
)
def test_deserialize(self):
# A FrozenSet should deserialize values based on the element Field.
field = FrozenSet(element=Reversed)
assert field.deserialize(frozenset({'tset', 'olleh'})) == frozenset(
{'test', 'hello'}
)
def test_deserialize_extra(self):
# A FrozenSet should deserialize values based on the element Field.
field = FrozenSet(element=Field(deserializers=[lambda x: x[::-1]]))
assert field.deserialize(frozenset({'tset', 'olleh'})) == frozenset(
{'test', 'hello'}
)
def test_normalize(self):
# A FrozenSet should normalize values based on the element Field.
field = FrozenSet(element=Field)
assert field.normalize(frozenset({'test', 'hello'})) == frozenset(
{'test', 'hello'}