forked from marshmallow-code/marshmallow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_schema.py
1802 lines (1429 loc) · 59.3 KB
/
test_schema.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
import decimal
import random
from collections import namedtuple
import pytest
from marshmallow import (
Schema, fields, utils, MarshalResult, UnmarshalResult,
validates, validates_schema
)
from marshmallow.exceptions import ValidationError
from marshmallow.compat import OrderedDict
from tests.base import * # noqa
random.seed(1)
# Run tests with both verbose serializer and "meta" option serializer
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_serializing_basic_object(SchemaClass, user):
s = SchemaClass()
data, errors = s.dump(user)
assert data['name'] == user.name
assert_almost_equal(data['age'], 42.3)
assert data['registered']
def test_serializer_dump(user):
s = UserSchema()
result, errors = s.dump(user)
assert result['name'] == user.name
# Change strict mode
s.strict = True
bad_user = User(name='Monty', age='badage')
with pytest.raises(ValidationError):
s.dump(bad_user)
def test_dump_returns_dict_of_errors():
s = UserSchema()
bad_user = User(name='Monty', age='badage')
result, errors = s.dump(bad_user)
assert 'age' in errors
@pytest.mark.parametrize('SchemaClass',
[
UserSchema, UserMetaSchema
])
def test_dump_with_strict_mode_raises_error(SchemaClass):
s = SchemaClass(strict=True)
bad_user = User(name='Monty', homepage='http://www.foo.bar', email='invalid-email')
with pytest.raises(ValidationError) as excinfo:
s.dump(bad_user)
exc = excinfo.value
assert type(exc.fields[0]) == fields.Email
assert exc.field_names[0] == 'email'
assert type(exc.messages) == dict
assert exc.messages == {'email': ['Not a valid email address.']}
def test_dump_resets_errors():
class MySchema(Schema):
email = fields.Email()
schema = MySchema()
result = schema.dump(User('Joe', email='notvalid'))
assert len(result.errors['email']) == 1
assert 'Not a valid email address.' in result.errors['email'][0]
result = schema.dump(User('Steve', email='__invalid'))
assert len(result.errors['email']) == 1
assert 'Not a valid email address.' in result.errors['email'][0]
def test_load_resets_errors():
class MySchema(Schema):
email = fields.Email()
schema = MySchema()
result = schema.load({'name': 'Joe', 'email': 'notvalid'})
assert len(result.errors['email']) == 1
assert 'Not a valid email address.' in result.errors['email'][0]
result = schema.load({'name': 'Joe', 'email': '__invalid'})
assert len(result.errors['email']) == 1
assert 'Not a valid email address.' in result.errors['email'][0]
def test_dump_resets_error_fields():
class MySchema(Schema):
email = fields.Email()
schema = MySchema(strict=True)
with pytest.raises(ValidationError) as excinfo:
schema.dump(User('Joe', email='notvalid'))
exc = excinfo.value
assert len(exc.fields) == 1
assert len(exc.field_names) == 1
with pytest.raises(ValidationError) as excinfo:
schema.dump(User('Joe', email='__invalid'))
assert len(exc.fields) == 1
assert len(exc.field_names) == 1
def test_load_resets_error_fields():
class MySchema(Schema):
email = fields.Email()
schema = MySchema(strict=True)
with pytest.raises(ValidationError) as excinfo:
schema.load({'name': 'Joe', 'email': 'not-valid'})
exc = excinfo.value
assert len(exc.fields) == 1
assert len(exc.field_names) == 1
with pytest.raises(ValidationError) as excinfo:
schema.load({'name': 'Joe', 'email': '__invalid'})
assert len(exc.fields) == 1
assert len(exc.field_names) == 1
def test_errored_fields_do_not_appear_in_output():
class MyField(fields.Field):
# Make sure validation fails during serialization
def _serialize(self, val, attr, obj):
raise ValidationError('oops')
class MySchema(Schema):
foo = MyField(validate=lambda x: False)
sch = MySchema()
data, errors = sch.load({'foo': 2})
assert 'foo' in errors
assert 'foo' not in data
data, errors = sch.dump({'foo': 2})
assert 'foo' in errors
assert 'foo' not in data
def test_load_many_stores_error_indices():
s = UserSchema()
data = [
{'name': 'Mick', 'email': 'mick@stones.com'},
{'name': 'Keith', 'email': 'invalid-email', 'homepage': 'invalid-homepage'},
]
_, errors = s.load(data, many=True)
assert 0 not in errors
assert 1 in errors
assert 'email' in errors[1]
assert 'homepage' in errors[1]
def test_dump_many():
s = UserSchema()
u1, u2 = User('Mick'), User('Keith')
data, errors = s.dump([u1, u2], many=True)
assert len(data) == 2
assert data[0] == s.dump(u1).data
def test_multiple_errors_can_be_stored_for_a_given_index():
class MySchema(Schema):
foo = fields.Str(validate=lambda x: len(x) > 3)
bar = fields.Int(validate=lambda x: x > 3)
sch = MySchema()
valid = {'foo': 'loll', 'bar': 42}
invalid = {'foo': 'lol', 'bar': 3}
errors = sch.validate([valid, invalid], many=True)
assert 1 in errors
assert len(errors[1]) == 2
assert 'foo' in errors[1]
assert 'bar' in errors[1]
def test_dump_many_stores_error_indices():
s = UserSchema()
u1, u2 = User('Mick', email='mick@stones.com'), User('Keith', email='invalid')
_, errors = s.dump([u1, u2], many=True)
assert 1 in errors
assert len(errors[1]) == 1
assert 'email' in errors[1]
def test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false():
class NoIndex(Schema):
email = fields.Email()
class Meta:
index_errors = False
s = NoIndex()
u1, u2 = User('Mick', email='mick@stones.com'), User('Keith', email='invalid')
_, errors = s.dump([u1, u2], many=True)
assert 1 not in errors
assert 'email' in errors
def test_dump_returns_a_marshalresult(user):
s = UserSchema()
result = s.dump(user)
assert type(result) == MarshalResult
data = result.data
assert type(data) == dict
errors = result.errors
assert type(errors) == dict
def test_dumps_returns_a_marshalresult(user):
s = UserSchema()
result = s.dumps(user)
assert type(result) == MarshalResult
assert type(result.data) == str
assert type(result.errors) == dict
def test_dumping_single_object_with_collection_schema():
s = UserSchema(many=True)
user = UserSchema('Mick')
result = s.dump(user, many=False)
assert type(result.data) == dict
assert result.data == UserSchema().dump(user).data
def test_loading_single_object_with_collection_schema():
s = UserSchema(many=True)
in_data = {'name': 'Mick', 'email': 'mick@stones.com'}
result = s.load(in_data, many=False)
assert type(result.data) == User
assert result.data.name == UserSchema().load(in_data).data.name
def test_dumps_many():
s = UserSchema()
u1, u2 = User('Mick'), User('Keith')
json_result = s.dumps([u1, u2], many=True)
data = json.loads(json_result.data)
assert len(data) == 2
assert data[0] == s.dump(u1).data
def test_load_returns_an_unmarshalresult():
s = UserSchema()
result = s.load({'name': 'Monty'})
assert type(result) == UnmarshalResult
assert type(result.data) == User
assert type(result.errors) == dict
def test_load_many():
s = UserSchema()
in_data = [{'name': 'Mick'}, {'name': 'Keith'}]
result = s.load(in_data, many=True)
assert type(result.data) == list
assert type(result.data[0]) == User
assert result.data[0].name == 'Mick'
def test_loads_returns_an_unmarshalresult(user):
s = UserSchema()
result = s.loads(json.dumps({'name': 'Monty'}))
assert type(result) == UnmarshalResult
assert type(result.data) == User
assert type(result.errors) == dict
def test_loads_many():
s = UserSchema()
in_data = [{'name': 'Mick'}, {'name': 'Keith'}]
in_json_data = json.dumps(in_data)
result = s.loads(in_json_data, many=True)
assert type(result.data) == list
assert result.data[0].name == 'Mick'
def test_loads_deserializes_from_json():
user_dict = {'name': 'Monty', 'age': '42.3'}
user_json = json.dumps(user_dict)
result, errors = UserSchema().loads(user_json)
assert isinstance(result, User)
assert result.name == 'Monty'
assert_almost_equal(result.age, 42.3)
def test_serializing_none():
class MySchema(Schema):
id = fields.Str(default='no-id')
num = fields.Int()
name = fields.Str()
s = UserSchema().dump(None)
assert s.data == {'id': 'no-id'}
assert s.errors == {}
def test_default_many_symmetry():
"""The dump/load(s) methods should all default to the many value of the schema."""
s_many = UserSchema(many=True, only=('name',))
s_single = UserSchema(only=('name',))
u1, u2 = User('King Arthur'), User('Sir Lancelot')
s_single.load(s_single.dump(u1).data)
s_single.loads(s_single.dumps(u1).data)
s_many.load(s_many.dump([u1, u2]).data)
s_many.loads(s_many.dumps([u1, u2]).data)
def test_on_bind_field_hook():
class MySchema(Schema):
foo = fields.Str()
def on_bind_field(self, field_name, field_obj):
field_obj.metadata['fname'] = field_name
schema = MySchema()
assert schema.fields['foo'].metadata['fname'] == 'foo'
class TestValidate:
def test_validate_returns_errors_dict(self):
s = UserSchema()
errors = s.validate({'email': 'bad-email', 'name': 'Valid Name'})
assert type(errors) is dict
assert 'email' in errors
assert 'name' not in errors
valid_data = {'name': 'Valid Name', 'email': 'valid@email.com'}
errors = s.validate(valid_data)
assert errors == {}
def test_validate_many(self):
s = UserSchema(many=True)
in_data = [
{'name': 'Valid Name', 'email': 'validemail@hotmail.com'},
{'name': 'Valid Name2', 'email': 'invalid'}
]
errors = s.validate(in_data, many=True)
assert 1 in errors
assert 'email' in errors[1]
def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self):
class NoIndex(Schema):
email = fields.Email()
class Meta:
index_errors = False
s = NoIndex()
in_data = [
{'name': 'Valid Name', 'email': 'validemail@hotmail.com'},
{'name': 'Valid Name2', 'email': 'invalid'}
]
errors = s.validate(in_data, many=True)
assert 1 not in errors
assert 'email' in errors
def test_validate_strict(self):
s = UserSchema(strict=True)
with pytest.raises(ValidationError) as excinfo:
s.validate({'email': 'bad-email'})
exc = excinfo.value
assert exc.messages == {'email': ['Not a valid email address.']}
assert type(exc.fields[0]) == fields.Email
def test_validate_required(self):
class MySchema(Schema):
foo = fields.Field(required=True)
s = MySchema()
errors = s.validate({'bar': 42})
assert 'foo' in errors
assert 'required' in errors['foo'][0]
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_fields_are_not_copies(SchemaClass):
s = SchemaClass(User('Monty', age=42))
s2 = SchemaClass(User('Monty', age=43))
assert s.fields is not s2.fields
def test_dumps_returns_json(user):
ser = UserSchema()
serialized, errors = ser.dump(user)
json_data, errors = ser.dumps(user)
assert type(json_data) == str
expected = json.dumps(serialized)
assert json_data == expected
def test_naive_datetime_field(user, serialized_user):
expected = utils.isoformat(user.created)
assert serialized_user.data['created'] == expected
def test_datetime_formatted_field(user, serialized_user):
result = serialized_user.data['created_formatted']
assert result == user.created.strftime("%Y-%m-%d")
def test_datetime_iso_field(user, serialized_user):
assert serialized_user.data['created_iso'] == utils.isoformat(user.created)
def test_tz_datetime_field(user, serialized_user):
# Datetime is corrected back to GMT
expected = utils.isoformat(user.updated)
assert serialized_user.data['updated'] == expected
def test_local_datetime_field(user, serialized_user):
expected = utils.isoformat(user.updated, localtime=True)
assert serialized_user.data['updated_local'] == expected
def test_class_variable(serialized_user):
assert serialized_user.data['species'] == 'Homo sapiens'
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_serialize_many(SchemaClass):
user1 = User(name="Mick", age=123)
user2 = User(name="Keith", age=456)
users = [user1, user2]
serialized = SchemaClass(many=True).dump(users)
assert len(serialized.data) == 2
assert serialized.data[0]['name'] == "Mick"
assert serialized.data[1]['name'] == "Keith"
def test_inheriting_schema(user):
sch = ExtendedUserSchema()
result = sch.dump(user)
assert result.data['name'] == user.name
user.is_old = True
result = sch.dump(user)
assert result.data['is_old'] is True
def test_custom_field(serialized_user, user):
assert serialized_user.data['uppername'] == user.name.upper()
def test_url_field(serialized_user, user):
assert serialized_user.data['homepage'] == user.homepage
def test_relative_url_field():
u = {'name': 'John', 'homepage': '/foo'}
result, errors = UserRelativeUrlSchema().load(u)
assert 'homepage' not in errors
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_stores_invalid_url_error(SchemaClass):
user = {'name': 'Steve', 'homepage': 'www.foo.com'}
result = SchemaClass().load(user)
assert "homepage" in result.errors
expected = ['Not a valid URL.']
assert result.errors['homepage'] == expected
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_email_field(SchemaClass):
u = User("John", email="john@example.com")
s = SchemaClass().dump(u)
assert s.data['email'] == "john@example.com"
def test_stored_invalid_email():
u = {'name': 'John', 'email': 'johnexample.com'}
s = UserSchema().load(u)
assert "email" in s.errors
assert s.errors['email'][0] == 'Not a valid email address.'
def test_integer_field():
u = User("John", age=42.3)
serialized = UserIntSchema().dump(u)
assert type(serialized.data['age']) == int
assert serialized.data['age'] == 42
def test_as_string():
u = User("John", age=42.3)
serialized = UserFloatStringSchema().dump(u)
assert type(serialized.data['age']) == str
assert_almost_equal(float(serialized.data['age']), 42.3)
def test_extra():
user = User("Joe", email="joe@foo.com")
data, errors = UserSchema(extra={"fav_color": "blue"}).dump(user)
assert data['fav_color'] == "blue"
def test_extra_many():
users = [User('Fred'), User('Brian')]
data, errs = UserSchema(many=True, extra={'band': 'Queen'}).dump(users)
assert data[0]['band'] == 'Queen'
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_method_field(SchemaClass, serialized_user):
assert serialized_user.data['is_old'] is False
u = User("Joe", age=81)
assert SchemaClass().dump(u).data['is_old'] is True
def test_function_field(serialized_user, user):
assert serialized_user.data['lowername'] == user.name.lower()
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_prefix(SchemaClass, user):
s = SchemaClass(prefix="usr_").dump(user)
assert s.data['usr_name'] == user.name
def test_fields_must_be_declared_as_instances(user):
class BadUserSchema(Schema):
name = fields.String
with pytest.raises(TypeError) as excinfo:
BadUserSchema().dump(user)
assert 'must be declared as a Field instance' in str(excinfo)
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_serializing_generator(SchemaClass):
users = [User("Foo"), User("Bar")]
user_gen = (u for u in users)
s = SchemaClass(many=True).dump(user_gen)
assert len(s.data) == 2
assert s.data[0] == SchemaClass().dump(users[0]).data
def test_serializing_empty_list_returns_empty_list():
assert UserSchema(many=True).dump([]).data == []
assert UserMetaSchema(many=True).dump([]).data == []
def test_serializing_dict():
user = {"name": "foo", "email": "foo@bar.com", "age": 'badage', "various_data": {"foo": "bar"}}
s = UserSchema().dump(user)
assert s.data['name'] == "foo"
assert 'age' in s.errors
assert 'age' not in s.data
assert s.data['various_data'] == {"foo": "bar"}
def test_serializing_dict_with_meta_fields():
class MySchema(Schema):
class Meta:
fields = ('foo', 'bar')
sch = MySchema()
data, errors = sch.dump({'foo': 42, 'bar': 24, 'baz': 424})
assert not errors
assert data['foo'] == 42
assert data['bar'] == 24
assert 'baz' not in data
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_exclude_in_init(SchemaClass, user):
s = SchemaClass(exclude=('age', 'homepage')).dump(user)
assert 'homepage' not in s.data
assert 'age' not in s.data
assert 'name' in s.data
@pytest.mark.parametrize('SchemaClass',
[UserSchema, UserMetaSchema])
def test_only_in_init(SchemaClass, user):
s = SchemaClass(only=('name', 'age')).dump(user)
assert 'homepage' not in s.data
assert 'name' in s.data
assert 'age' in s.data
def test_invalid_only_param(user):
with pytest.raises(AttributeError):
UserSchema(only=("_invalid", "name")).dump(user)
def test_can_serialize_uuid(serialized_user, user):
assert serialized_user.data['uid'] == str(user.uid)
def test_can_serialize_time(user, serialized_user):
expected = user.time_registered.isoformat()[:12]
assert serialized_user.data['time_registered'] == expected
def test_invalid_time():
u = User('Joe', time_registered='foo')
s = UserSchema().dump(u)
assert '"foo" cannot be formatted as a time.' in s.errors['time_registered']
def test_invalid_date():
u = User("Joe", birthdate='foo')
s = UserSchema().dump(u)
assert '"foo" cannot be formatted as a date.' in s.errors['birthdate']
def test_invalid_email():
u = User('Joe', email='bademail')
s = UserSchema().dump(u)
assert 'email' in s.errors
assert 'Not a valid email address.' in s.errors['email'][0]
def test_invalid_url():
u = User('Joe', homepage='badurl')
s = UserSchema().dump(u)
assert 'homepage' in s.errors
assert 'Not a valid URL.' in s.errors['homepage'][0]
def test_invalid_dict_but_okay():
u = User('Joe', various_data='baddict')
s = UserSchema().dump(u)
assert 'various_data' not in s.errors
def test_custom_json():
class UserJSONSchema(Schema):
name = fields.String()
class Meta:
json_module = mockjson
user = User('Joe')
s = UserJSONSchema()
result, errors = s.dumps(user)
assert result == mockjson.dumps('val')
def test_custom_error_message():
class ErrorSchema(Schema):
email = fields.Email(error_messages={'invalid': 'Invalid email'})
homepage = fields.Url(error_messages={'invalid': 'Bad homepage.'})
balance = fields.Decimal(error_messages={'invalid': 'Bad balance.'})
u = {'email': 'joe.net', 'homepage': 'joe@example.com', 'balance': 'blah'}
s = ErrorSchema()
data, errors = s.load(u)
assert "Bad balance." in errors['balance']
assert "Bad homepage." in errors['homepage']
assert "Invalid email" in errors['email']
def test_load_errors_with_many():
class ErrorSchema(Schema):
email = fields.Email()
data = [
{'email': 'bademail'},
{'email': 'goo@email.com'},
{'email': 'anotherbademail'},
]
data, errors = ErrorSchema(many=True).load(data)
assert 0 in errors
assert 2 in errors
assert 'Not a valid email address.' in errors[0]['email'][0]
assert 'Not a valid email address.' in errors[2]['email'][0]
def test_error_raised_if_fields_option_is_not_list():
with pytest.raises(ValueError):
class BadSchema(Schema):
name = fields.String()
class Meta:
fields = 'name'
def test_error_raised_if_additional_option_is_not_list():
with pytest.raises(ValueError):
class BadSchema(Schema):
name = fields.String()
class Meta:
additional = 'email'
def test_only_and_exclude():
class MySchema(Schema):
foo = fields.Field()
bar = fields.Field()
baz = fields.Field()
sch = MySchema(only=('foo', 'bar'), exclude=('bar', ))
data = dict(foo=42, bar=24, baz=242)
result = sch.dump(data)
assert 'foo' in result.data
assert 'bar' not in result.data
def test_exclude_invalid_attribute():
class MySchema(Schema):
foo = fields.Field()
sch = MySchema(exclude=('bar', ))
assert sch.dump({'foo': 42}).data == {'foo': 42}
def test_only_with_invalid_attribute():
class MySchema(Schema):
foo = fields.Field()
sch = MySchema(only=('bar', ))
with pytest.raises(KeyError) as excinfo:
sch.dump(dict(foo=42))
assert '"bar" is not a valid field' in str(excinfo.value.args[0])
def test_only_bounded_by_fields():
class MySchema(Schema):
class Meta:
fields = ('foo', )
sch = MySchema(only=('baz', ))
assert sch.dump({'foo': 42}).data == {}
def test_nested_only_and_exclude():
class Inner(Schema):
foo = fields.Field()
bar = fields.Field()
baz = fields.Field()
class Outer(Schema):
inner = fields.Nested(Inner, only=('foo', 'bar'), exclude=('bar', ))
sch = Outer()
data = dict(inner=dict(foo=42, bar=24, baz=242))
result = sch.dump(data)
assert 'foo' in result.data['inner']
assert 'bar' not in result.data['inner']
def test_nested_with_sets():
class Inner(Schema):
foo = fields.Field()
class Outer(Schema):
inners = fields.Nested(Inner, many=True)
sch = Outer()
DataClass = namedtuple('DataClass', ['foo'])
data = dict(inners=set([DataClass(42), DataClass(2)]))
result = sch.dump(data)
assert len(result.data['inners']) == 2
def test_meta_serializer_fields():
u = User("John", age=42.3, email="john@example.com",
homepage="http://john.com")
result = UserMetaSchema().dump(u)
assert not result.errors
assert result.data['name'] == u.name
assert result.data['balance'] == decimal.Decimal('100.00')
assert result.data['uppername'] == "JOHN"
assert result.data['is_old'] is False
assert result.data['created'] == utils.isoformat(u.created)
assert result.data['updated_local'] == utils.isoformat(u.updated, localtime=True)
assert result.data['finger_count'] == 10
assert result.data['various_data'] == dict(u.various_data)
def test_meta_fields_mapping(user):
s = UserMetaSchema()
s.dump(user) # need to call dump to update fields
assert type(s.fields['name']) == fields.String
assert type(s.fields['created']) == fields.DateTime
assert type(s.fields['updated']) == fields.DateTime
assert type(s.fields['updated_local']) == fields.LocalDateTime
assert type(s.fields['age']) == fields.Float
assert type(s.fields['balance']) == fields.Decimal
assert type(s.fields['registered']) == fields.Boolean
assert type(s.fields['sex_choices']) == fields.Raw
assert type(s.fields['hair_colors']) == fields.Raw
assert type(s.fields['finger_count']) == fields.Integer
assert type(s.fields['uid']) == fields.UUID
assert type(s.fields['time_registered']) == fields.Time
assert type(s.fields['birthdate']) == fields.Date
assert type(s.fields['since_created']) == fields.TimeDelta
def test_meta_field_not_on_obj_raises_attribute_error(user):
class BadUserSchema(Schema):
class Meta:
fields = ('name', 'notfound')
with pytest.raises(AttributeError):
BadUserSchema().dump(user)
def test_exclude_fields(user):
s = UserExcludeSchema().dump(user)
assert "created" not in s.data
assert "updated" not in s.data
assert "name" in s.data
def test_fields_option_must_be_list_or_tuple(user):
with pytest.raises(ValueError):
class BadFields(Schema):
class Meta:
fields = "name"
def test_exclude_option_must_be_list_or_tuple(user):
with pytest.raises(ValueError):
class BadExclude(Schema):
class Meta:
exclude = "name"
def test_dateformat_option(user):
fmt = '%Y-%m'
class DateFormatSchema(Schema):
updated = fields.DateTime("%m-%d")
class Meta:
fields = ('created', 'updated')
dateformat = fmt
serialized = DateFormatSchema().dump(user)
assert serialized.data['created'] == user.created.strftime(fmt)
assert serialized.data['updated'] == user.updated.strftime("%m-%d")
def test_default_dateformat(user):
class DateFormatSchema(Schema):
updated = fields.DateTime(format="%m-%d")
class Meta:
fields = ('created', 'updated')
serialized = DateFormatSchema().dump(user)
assert serialized.data['created'] == utils.isoformat(user.created)
assert serialized.data['updated'] == user.updated.strftime("%m-%d")
def test_inherit_meta(user):
class InheritedMetaSchema(UserMetaSchema):
pass
result = InheritedMetaSchema().dump(user).data
expected = UserMetaSchema().dump(user).data
assert result == expected
def test_inherit_meta_override():
class Parent(Schema):
class Meta:
strict = True
fields = ('name', 'email')
class Child(Schema):
class Meta(Parent.Meta):
strict = False
child = Child()
assert child.opts.fields == ('name', 'email')
assert child.opts.strict is False
def test_additional(user):
s = UserAdditionalSchema().dump(user)
assert s.data['lowername'] == user.name.lower()
assert s.data['name'] == user.name
def test_cant_set_both_additional_and_fields(user):
with pytest.raises(ValueError):
class BadSchema(Schema):
name = fields.String()
class Meta:
fields = ("name", 'email')
additional = ('email', 'homepage')
def test_serializing_none_meta():
s = UserMetaSchema().dump(None)
assert s.data == {}
assert s.errors == {}
class CustomError(Exception):
pass
class MySchema(Schema):
name = fields.String()
email = fields.Email()
age = fields.Integer()
def handle_error(self, errors, obj):
raise CustomError('Something bad happened')
class TestErrorHandler:
def test_error_handler_decorator_is_deprecated(self):
def deprecated():
class MySchema(Schema):
pass
@MySchema.error_handler
def f(*args, **kwargs):
pass
pytest.deprecated_call(deprecated)
def test_dump_with_custom_error_handler(self, user):
user.age = 'notavalidage'
with pytest.raises(CustomError):
MySchema().dump(user)
def test_load_with_custom_error_handler(self):
in_data = {'email': 'invalid'}
class MySchema3(Schema):
email = fields.Email()
def handle_error(self, error, data):
assert type(error) is ValidationError
assert 'email' in error.messages
assert error.field_names == ['email']
assert error.fields == [self.fields['email']]
assert data == in_data
raise CustomError('Something bad happened')
with pytest.raises(CustomError):
MySchema3().load(in_data)
def test_load_with_custom_error_handler_and_partially_valid_data(self):
in_data = {'email': 'invalid', 'url': 'http://valid.com'}
class MySchema(Schema):
email = fields.Email()
url = fields.URL()
def handle_error(self, error, data):
assert type(error) is ValidationError
assert 'email' in error.messages
assert error.field_names == ['email']
assert error.fields == [self.fields['email']]
assert data == in_data
raise CustomError('Something bad happened')
with pytest.raises(CustomError):
MySchema().load(in_data)
def test_custom_error_handler_with_validates_decorator(self):
in_data = {'num': -1}
class MySchema(Schema):
num = fields.Int()
@validates('num')
def validate_num(self, value):
if value < 0:
raise ValidationError('Must be greater than 0.')
def handle_error(self, error, data):
assert type(error) is ValidationError
assert 'num' in error.messages
assert error.field_names == ['num']
assert error.fields == [self.fields['num']]
assert data == in_data
raise CustomError('Something bad happened')
with pytest.raises(CustomError):
MySchema().load(in_data)
def test_custom_error_handler_with_validates_schema_decorator(self):
in_data = {'num': -1}
class MySchema(Schema):
num = fields.Int()
@validates_schema
def validates_schema(self, data):
raise ValidationError('Invalid schema!')
def handle_error(self, error, data):
assert type(error) is ValidationError
assert '_schema' in error.messages
assert error.field_names == ['_schema']
assert error.fields == []
assert data == in_data
raise CustomError('Something bad happened')
with pytest.raises(CustomError):
MySchema().load(in_data)
def test_validate_with_custom_error_handler(self):
with pytest.raises(CustomError):
MySchema().validate({'age': 'notvalid', 'email': 'invalid'})
class TestFieldValidation:
def test_errors_are_cleared_after_loading_collection(self):
def always_fail(val):
raise ValidationError('lol')
class MySchema(Schema):
foo = fields.Str(validate=always_fail)
schema = MySchema()
_, errors = schema.load([
{'foo': 'bar'},
{'foo': 'baz'}
], many=True)
assert len(errors[0]['foo']) == 1
assert len(errors[1]['foo']) == 1
_, errors2 = schema.load({'foo': 'bar'})
assert len(errors2['foo']) == 1
def test_raises_error_with_list(self):
def validator(val):
raise ValidationError(['err1', 'err2'])
class MySchema(Schema):
foo = fields.Field(validate=validator)
s = MySchema()
errors = s.validate({'foo': 42})
assert errors['foo'] == ['err1', 'err2']
# https://github.com/marshmallow-code/marshmallow/issues/110
def test_raises_error_with_dict(self):
def validator(val):
raise ValidationError({'code': 'invalid_foo'})
class MySchema(Schema):
foo = fields.Field(validate=validator)