forked from pydantic/pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_main.py
1735 lines (1288 loc) · 47.3 KB
/
test_main.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 sys
from collections import defaultdict
from copy import deepcopy
from enum import Enum
from typing import (
Any,
Callable,
ClassVar,
Counter,
DefaultDict,
Dict,
List,
Mapping,
Optional,
Set,
Type,
TypeVar,
get_type_hints,
)
from uuid import UUID, uuid4
import pytest
from typing_extensions import Final, Literal
from pydantic import BaseModel, ConfigDict, Extra, Field, PrivateAttr, SecretStr, ValidationError, constr
def test_success():
# same as below but defined here so class definition occurs inside the test
class Model(BaseModel):
a: float
b: int = 10
m = Model(a=10.2)
assert m.a == 10.2
assert m.b == 10
class UltraSimpleModel(BaseModel):
a: float
b: int = 10
def test_ultra_simple_missing():
with pytest.raises(ValidationError) as exc_info:
UltraSimpleModel()
assert exc_info.value.errors() == [{'loc': ('a',), 'msg': 'Field required', 'type': 'missing', 'input': {}}]
assert str(exc_info.value) == (
'1 validation error for UltraSimpleModel\n'
'a\n'
' Field required [type=missing, input_value={}, input_type=dict]'
)
def test_ultra_simple_failed():
with pytest.raises(ValidationError) as exc_info:
UltraSimpleModel(a='x', b='x')
assert exc_info.value.errors() == [
{
'type': 'float_parsing',
'loc': ('a',),
'msg': 'Input should be a valid number, unable to parse string as an number',
'input': 'x',
},
{
'type': 'int_parsing',
'loc': ('b',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'x',
},
]
def test_ultra_simple_repr():
m = UltraSimpleModel(a=10.2)
assert str(m) == 'a=10.2 b=10'
assert repr(m) == 'UltraSimpleModel(a=10.2, b=10)'
assert repr(m.model_fields['a']) == 'FieldInfo(annotation=float, required=True)'
assert repr(m.model_fields['b']) == 'FieldInfo(annotation=int, required=False, default=10)'
assert dict(m) == {'a': 10.2, 'b': 10}
assert m.model_dump() == {'a': 10.2, 'b': 10}
assert m.model_dump_json() == b'{"a":10.2,"b":10}'
assert str(m) == 'a=10.2 b=10'
def test_default_factory_field():
def myfunc():
return 1
class Model(BaseModel):
a: int = Field(default_factory=myfunc)
m = Model()
assert str(m) == 'a=1'
assert repr(m.model_fields['a']) == 'FieldInfo(annotation=int, required=False, default_factory=myfunc)'
assert dict(m) == {'a': 1}
assert m.model_dump_json() == b'{"a":1}'
def test_comparing():
m = UltraSimpleModel(a=10.2, b='100')
assert m == {'a': 10.2, 'b': 100}
assert m == UltraSimpleModel(a=10.2, b=100)
@pytest.fixture(scope='session', name='NoneCheckModel')
def none_check_model_fix():
class NoneCheckModel(BaseModel):
existing_str_value: str = 'foo'
required_str_value: str = ...
required_str_none_value: Optional[str] = ...
existing_bytes_value: bytes = b'foo'
required_bytes_value: bytes = ...
required_bytes_none_value: Optional[bytes] = ...
return NoneCheckModel
def test_nullable_strings_success(NoneCheckModel):
m = NoneCheckModel(
required_str_value='v1', required_str_none_value=None, required_bytes_value='v2', required_bytes_none_value=None
)
assert m.required_str_value == 'v1'
assert m.required_str_none_value is None
assert m.required_bytes_value == b'v2'
assert m.required_bytes_none_value is None
def test_nullable_strings_fails(NoneCheckModel):
with pytest.raises(ValidationError) as exc_info:
NoneCheckModel(
required_str_value=None,
required_str_none_value=None,
required_bytes_value=None,
required_bytes_none_value=None,
)
assert exc_info.value.errors() == [
{
'type': 'string_type',
'loc': ('required_str_value',),
'msg': 'Input should be a valid string',
'input': None,
},
{
'type': 'bytes_type',
'loc': ('required_bytes_value',),
'msg': 'Input should be a valid bytes',
'input': None,
},
]
@pytest.fixture(name='ParentModel', scope='session')
def parent_sub_model_fixture():
class ParentModel(BaseModel):
grape: bool
banana: UltraSimpleModel
return ParentModel
def test_parent_sub_model(ParentModel):
m = ParentModel(grape=1, banana={'a': 1})
assert m.grape is True
assert m.banana.a == 1.0
assert m.banana.b == 10
assert repr(m) == 'ParentModel(grape=True, banana=UltraSimpleModel(a=1.0, b=10))'
def test_parent_sub_model_fails(ParentModel):
with pytest.raises(ValidationError):
ParentModel(grape=1, banana=123)
def test_not_required():
class Model(BaseModel):
a: float = None
assert Model(a=12.2).a == 12.2
assert Model().a is None
with pytest.raises(ValidationError) as exc_info:
Model(a=None)
assert exc_info.value.errors() == [
{
'type': 'float_type',
'loc': ('a',),
'msg': 'Input should be a valid number',
'input': None,
},
]
def test_allow_extra():
class Model(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
a: float = ...
assert Model(a='10.2', b=12).model_dump() == {'a': 10.2, 'b': 12}
def test_allow_extra_repr():
class Model(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
a: float = ...
assert str(Model(a='10.2', b=12)) == 'a=10.2 b=12'
def test_forbidden_extra_success():
class ForbiddenExtra(BaseModel):
model_config = ConfigDict(extra=Extra.forbid)
foo: str = 'whatever'
m = ForbiddenExtra()
assert m.foo == 'whatever'
def test_forbidden_extra_fails():
class ForbiddenExtra(BaseModel):
model_config = ConfigDict(extra=Extra.forbid)
foo: str = 'whatever'
with pytest.raises(ValidationError) as exc_info:
ForbiddenExtra(foo='ok', bar='wrong', spam='xx')
assert exc_info.value.errors() == [
{
'type': 'extra_forbidden',
'loc': ('bar',),
'msg': 'Extra inputs are not permitted',
'input': 'wrong',
},
{
'type': 'extra_forbidden',
'loc': ('spam',),
'msg': 'Extra inputs are not permitted',
'input': 'xx',
},
]
def test_assign_extra_no_validate():
class Model(BaseModel):
model_config = ConfigDict(validate_assignment=True)
a: float
model = Model(a=0.2)
with pytest.raises(ValidationError, match='Extra inputs are not permitted'):
model.b = 2
def test_assign_extra_validate():
class Model(BaseModel):
model_config = ConfigDict(validate_assignment=True)
a: float
model = Model(a=0.2)
with pytest.raises(ValidationError, match='Extra inputs are not permitted'):
model.b = 2
def test_extra_allowed():
class Model(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
a: float
model = Model(a=0.2, b=0.1)
assert model.b == 0.1
assert not hasattr(model, 'c')
model.c = 1
assert hasattr(model, 'c')
assert model.c == 1
def test_extra_ignored():
class Model(BaseModel):
model_config = ConfigDict(extra=Extra.ignore)
a: float
model = Model(a=0.2, b=0.1)
assert not hasattr(model, 'b')
with pytest.raises(ValueError, match='"Model" object has no field "c"'):
model.c = 1
def test_set_attr():
m = UltraSimpleModel(a=10.2)
assert m.model_dump() == {'a': 10.2, 'b': 10}
m.b = 20
assert m.model_dump() == {'a': 10.2, 'b': 20}
def test_set_attr_invalid():
class UltraSimpleModel(BaseModel):
a: float = ...
b: int = 10
m = UltraSimpleModel(a=10.2)
assert m.model_dump() == {'a': 10.2, 'b': 10}
with pytest.raises(ValueError) as exc_info:
m.c = 20
assert '"UltraSimpleModel" object has no field "c"' in exc_info.value.args[0]
def test_any():
class AnyModel(BaseModel):
a: Any = 10
b: object = 20
m = AnyModel()
assert m.a == 10
assert m.b == 20
m = AnyModel(a='foobar', b='barfoo')
assert m.a == 'foobar'
assert m.b == 'barfoo'
def test_population_by_field_name():
class Model(BaseModel):
model_config = ConfigDict(populate_by_name=True)
a: str = Field(alias='_a')
assert Model(a='different').a == 'different'
assert Model(a='different').model_dump() == {'a': 'different'}
assert Model(a='different').model_dump(by_alias=True) == {'_a': 'different'}
def test_field_order():
class Model(BaseModel):
c: float
b: int = 10
a: str
d: dict = {}
assert list(Model.model_fields.keys()) == ['c', 'b', 'a', 'd']
def test_required():
# same as below but defined here so class definition occurs inside the test
class Model(BaseModel):
a: float
b: int = 10
m = Model(a=10.2)
assert m.model_dump() == dict(a=10.2, b=10)
with pytest.raises(ValidationError) as exc_info:
Model()
assert exc_info.value.errors() == [{'type': 'missing', 'loc': ('a',), 'msg': 'Field required', 'input': {}}]
def test_mutability():
class TestModel(BaseModel):
a: int = 10
model_config = ConfigDict(extra=Extra.forbid, frozen=False)
m = TestModel()
assert m.a == 10
m.a = 11
assert m.a == 11
def test_frozen_model():
class FrozenModel(BaseModel):
model_config = ConfigDict(extra=Extra.forbid, frozen=True)
a: int = 10
m = FrozenModel()
assert m.a == 10
with pytest.raises(TypeError) as exc_info:
m.a = 11
assert '"FrozenModel" is frozen and does not support item assignment' in exc_info.value.args[0]
def test_not_frozen_are_not_hashable():
class TestModel(BaseModel):
a: int = 10
m = TestModel()
with pytest.raises(TypeError) as exc_info:
hash(m)
assert "unhashable type: 'TestModel'" in exc_info.value.args[0]
def test_with_declared_hash():
class Foo(BaseModel):
x: int
def __hash__(self):
return self.x**2
class Bar(Foo):
y: int
def __hash__(self):
return self.y**3
class Buz(Bar):
z: int
assert hash(Foo(x=2)) == 4
assert hash(Bar(x=2, y=3)) == 27
assert hash(Buz(x=2, y=3, z=4)) == 27
def test_frozen_with_hashable_fields_are_hashable():
class TestModel(BaseModel):
model_config = ConfigDict(frozen=True)
a: int = 10
m = TestModel()
assert m.__hash__ is not None
assert isinstance(hash(m), int)
def test_frozen_with_unhashable_fields_are_not_hashable():
class TestModel(BaseModel):
model_config = ConfigDict(frozen=True)
a: int = 10
y: List[int] = [1, 2, 3]
m = TestModel()
with pytest.raises(TypeError) as exc_info:
hash(m)
assert "unhashable type: 'list'" in exc_info.value.args[0]
def test_hash_function_give_different_result_for_different_object():
class TestModel(BaseModel):
model_config = ConfigDict(frozen=True)
a: int = 10
m = TestModel()
m2 = TestModel()
m3 = TestModel(a=11)
assert hash(m) == hash(m2)
assert hash(m) != hash(m3)
# Redefined `TestModel`
class TestModel(BaseModel):
model_config = ConfigDict(frozen=True)
a: int = 10
m4 = TestModel()
assert hash(m) != hash(m4)
@pytest.fixture(name='ValidateAssignmentModel', scope='session')
def validate_assignment_fixture():
class ValidateAssignmentModel(BaseModel):
model_config = ConfigDict(validate_assignment=True)
a: int = 2
b: constr(min_length=1)
return ValidateAssignmentModel
def test_validating_assignment_pass(ValidateAssignmentModel):
p = ValidateAssignmentModel(a=5, b='hello')
p.a = 2
assert p.a == 2
assert p.model_dump() == {'a': 2, 'b': 'hello'}
p.b = 'hi'
assert p.b == 'hi'
assert p.model_dump() == {'a': 2, 'b': 'hi'}
def test_validating_assignment_fail(ValidateAssignmentModel):
p = ValidateAssignmentModel(a=5, b='hello')
with pytest.raises(ValidationError) as exc_info:
p.a = 'b'
assert exc_info.value.errors() == [
{
'type': 'int_parsing',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'b',
},
]
with pytest.raises(ValidationError) as exc_info:
p.b = ''
assert exc_info.value.errors() == [
{
'type': 'string_too_short',
'loc': ('b',),
'msg': 'String should have at least 1 characters',
'input': '',
'ctx': {'min_length': 1},
}
]
def test_enum_values():
FooEnum = Enum('FooEnum', {'foo': 'foo', 'bar': 'bar'})
class Model(BaseModel):
model_config = ConfigDict(use_enum_values=True)
foo: FooEnum
m = Model(foo='foo')
# this is the actual value, so has not "values" field
assert m.foo == FooEnum.foo
assert isinstance(m.foo, FooEnum)
def test_literal_enum_values():
FooEnum = Enum('FooEnum', {'foo': 'foo_value', 'bar': 'bar_value'})
class Model(BaseModel):
baz: Literal[FooEnum.foo]
boo: str = 'hoo'
model_config = ConfigDict(use_enum_values=True)
m = Model(baz=FooEnum.foo)
assert m.model_dump() == {'baz': FooEnum.foo, 'boo': 'hoo'}
assert m.model_dump(mode='json') == {'baz': 'foo_value', 'boo': 'hoo'}
assert m.baz.value == 'foo_value'
with pytest.raises(ValidationError) as exc_info:
Model(baz=FooEnum.bar)
# insert_assert(exc_info.value.errors())
assert exc_info.value.errors() == [
{
'type': 'literal_error',
'loc': ('baz',),
'msg': "Input should be <FooEnum.foo: 'foo_value'>",
'input': FooEnum.bar,
'ctx': {'expected': "<FooEnum.foo: 'foo_value'>"},
}
]
def test_enum_raw():
FooEnum = Enum('FooEnum', {'foo': 'foo', 'bar': 'bar'})
class Model(BaseModel):
foo: FooEnum = None
m = Model(foo='foo')
assert isinstance(m.foo, FooEnum)
assert m.foo != 'foo'
assert m.foo.value == 'foo'
def test_set_tuple_values():
class Model(BaseModel):
foo: set
bar: tuple
m = Model(foo=['a', 'b'], bar=['c', 'd'])
assert m.foo == {'a', 'b'}
assert m.bar == ('c', 'd')
assert m.model_dump() == {'foo': {'a', 'b'}, 'bar': ('c', 'd')}
def test_default_copy():
class User(BaseModel):
friends: List[int] = Field(default_factory=lambda: [])
u1 = User()
u2 = User()
assert u1.friends is not u2.friends
class ArbitraryType:
pass
def test_arbitrary_type_allowed_validation_success():
class ArbitraryTypeAllowedModel(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
t: ArbitraryType
arbitrary_type_instance = ArbitraryType()
m = ArbitraryTypeAllowedModel(t=arbitrary_type_instance)
assert m.t == arbitrary_type_instance
class OtherClass:
pass
def test_arbitrary_type_allowed_validation_fails():
class ArbitraryTypeAllowedModel(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
t: ArbitraryType
input_value = OtherClass()
with pytest.raises(ValidationError) as exc_info:
ArbitraryTypeAllowedModel(t=input_value)
# insert_assert(exc_info.value.errors())
assert exc_info.value.errors() == [
{
'type': 'is_instance_of',
'loc': ('t',),
'msg': 'Input should be an instance of ArbitraryType',
'input': input_value,
'ctx': {'class': 'ArbitraryType'},
}
]
def test_arbitrary_types_not_allowed():
with pytest.raises(TypeError, match='Unable to generate pydantic-core schema for <class'):
class ArbitraryTypeNotAllowedModel(BaseModel):
t: ArbitraryType
@pytest.fixture(scope='session', name='TypeTypeModel')
def type_type_model_fixture():
class TypeTypeModel(BaseModel):
t: Type[ArbitraryType]
return TypeTypeModel
def test_type_type_validation_success(TypeTypeModel):
arbitrary_type_class = ArbitraryType
m = TypeTypeModel(t=arbitrary_type_class)
assert m.t == arbitrary_type_class
def test_type_type_subclass_validation_success(TypeTypeModel):
class ArbitrarySubType(ArbitraryType):
pass
arbitrary_type_class = ArbitrarySubType
m = TypeTypeModel(t=arbitrary_type_class)
assert m.t == arbitrary_type_class
@pytest.mark.parametrize('input_value', [OtherClass, 1])
def test_type_type_validation_fails(TypeTypeModel, input_value):
with pytest.raises(ValidationError) as exc_info:
TypeTypeModel(t=input_value)
# insert_assert(exc_info.value.errors())
assert exc_info.value.errors() == [
{
'type': 'is_subclass_of',
'loc': ('t',),
'msg': 'Input should be a subclass of ArbitraryType',
'input': input_value,
'ctx': {'class': 'ArbitraryType'},
}
]
@pytest.mark.parametrize('bare_type', [type, Type])
def test_bare_type_type_validation_success(bare_type):
class TypeTypeModel(BaseModel):
t: bare_type
arbitrary_type_class = ArbitraryType
m = TypeTypeModel(t=arbitrary_type_class)
assert m.t == arbitrary_type_class
@pytest.mark.parametrize('bare_type', [type, Type])
def test_bare_type_type_validation_fails(bare_type):
class TypeTypeModel(BaseModel):
t: bare_type
arbitrary_type = ArbitraryType()
with pytest.raises(ValidationError) as exc_info:
TypeTypeModel(t=arbitrary_type)
# insert_assert(exc_info.value.errors())
assert exc_info.value.errors() == [
{
'type': 'is_type',
'loc': ('t',),
'msg': 'Input should be a type',
'input': arbitrary_type,
}
]
def test_annotation_field_name_shadows_attribute():
with pytest.raises(NameError):
# When defining a model that has an attribute with the name of a built-in attribute, an exception is raised
class BadModel(BaseModel):
model_json_schema: str # This conflicts with the BaseModel's model_json_schema() class method
def test_value_field_name_shadows_attribute():
class BadModel(BaseModel):
model_json_schema = (
'abc' # This conflicts with the BaseModel's model_json_schema() class method, but has no annotation
)
assert len(BadModel.model_fields) == 0
def test_class_var():
class MyModel(BaseModel):
a: ClassVar
b: ClassVar[int] = 1
c: int = 2
assert list(MyModel.model_fields.keys()) == ['c']
class MyOtherModel(MyModel):
a = ''
b = 2
assert list(MyOtherModel.model_fields.keys()) == ['c']
def test_fields_set():
class MyModel(BaseModel):
a: int
b: int = 2
m = MyModel(a=5)
assert m.__fields_set__ == {'a'}
m.b = 2
assert m.__fields_set__ == {'a', 'b'}
m = MyModel(a=5, b=2)
assert m.__fields_set__ == {'a', 'b'}
def test_exclude_unset_dict():
class MyModel(BaseModel):
a: int
b: int = 2
m = MyModel(a=5)
assert m.model_dump(exclude_unset=True) == {'a': 5}
m = MyModel(a=5, b=3)
assert m.model_dump(exclude_unset=True) == {'a': 5, 'b': 3}
def test_exclude_unset_recursive():
class ModelA(BaseModel):
a: int
b: int = 1
class ModelB(BaseModel):
c: int
d: int = 2
e: ModelA
m = ModelB(c=5, e={'a': 0})
assert m.model_dump() == {'c': 5, 'd': 2, 'e': {'a': 0, 'b': 1}}
assert m.model_dump(exclude_unset=True) == {'c': 5, 'e': {'a': 0}}
assert dict(m) == {'c': 5, 'd': 2, 'e': {'a': 0, 'b': 1}}
def test_dict_exclude_unset_populated_by_alias():
class MyModel(BaseModel):
model_config = ConfigDict(populate_by_name=True)
a: str = Field('default', alias='alias_a')
b: str = Field('default', alias='alias_b')
m = MyModel(alias_a='a')
assert m.model_dump(exclude_unset=True) == {'a': 'a'}
assert m.model_dump(exclude_unset=True, by_alias=True) == {'alias_a': 'a'}
def test_dict_exclude_unset_populated_by_alias_with_extra():
class MyModel(BaseModel):
model_config = ConfigDict(extra='allow')
a: str = Field('default', alias='alias_a')
b: str = Field('default', alias='alias_b')
m = MyModel(alias_a='a', c='c')
assert m.model_dump(exclude_unset=True) == {'a': 'a', 'c': 'c'}
assert m.model_dump(exclude_unset=True, by_alias=True) == {'alias_a': 'a', 'c': 'c'}
def test_exclude_defaults():
class Model(BaseModel):
mandatory: str
nullable_mandatory: Optional[str] = ...
facultative: str = 'x'
nullable_facultative: Optional[str] = None
m = Model(mandatory='a', nullable_mandatory=None)
assert m.model_dump(exclude_defaults=True) == {
'mandatory': 'a',
'nullable_mandatory': None,
}
m = Model(mandatory='a', nullable_mandatory=None, facultative='y', nullable_facultative=None)
assert m.model_dump(exclude_defaults=True) == {
'mandatory': 'a',
'nullable_mandatory': None,
'facultative': 'y',
}
m = Model(mandatory='a', nullable_mandatory=None, facultative='y', nullable_facultative='z')
assert m.model_dump(exclude_defaults=True) == {
'mandatory': 'a',
'nullable_mandatory': None,
'facultative': 'y',
'nullable_facultative': 'z',
}
def test_dir_fields():
class MyModel(BaseModel):
attribute_a: int
attribute_b: int = 2
m = MyModel(attribute_a=5)
assert 'model_dump' in dir(m)
assert 'model_dump_json' in dir(m)
assert 'attribute_a' in dir(m)
assert 'attribute_b' in dir(m)
def test_dict_with_extra_keys():
class MyModel(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
a: str = Field(None, alias='alias_a')
m = MyModel(extra_key='extra')
assert m.model_dump() == {'a': None, 'extra_key': 'extra'}
assert m.model_dump(by_alias=True) == {'alias_a': None, 'extra_key': 'extra'}
def test_untouched_types():
from pydantic import BaseModel
class _ClassPropertyDescriptor:
def __init__(self, getter):
self.getter = getter
def __get__(self, instance, owner):
return self.getter(owner)
classproperty = _ClassPropertyDescriptor
class Model(BaseModel):
model_config = ConfigDict(keep_untouched=(classproperty,))
@classproperty
def class_name(cls) -> str:
return cls.__name__
assert Model.class_name == 'Model'
assert Model().class_name == 'Model'
def test_model_iteration():
class Foo(BaseModel):
a: int = 1
b: int = 2
class Bar(BaseModel):
c: int
d: Foo
m = Bar(c=3, d={})
assert m.model_dump() == {'c': 3, 'd': {'a': 1, 'b': 2}}
assert list(m) == [('c', 3), ('d', Foo())]
assert dict(m) == {'c': 3, 'd': Foo()}
@pytest.mark.parametrize(
'exclude,expected,raises_match',
[
pytest.param(
None,
{'c': 3, 'foos': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]},
None,
id='exclude nothing',
),
pytest.param(
{'foos': {0: {'a'}, 1: {'a'}}},
{'c': 3, 'foos': [{'b': 2}, {'b': 4}]},
None,
id='excluding fields of indexed list items',
),
pytest.param(
{'foos': {'a'}},
{'c': 3, 'foos': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]},
None,
id='Trying to exclude string keys on list field should be ignored (1)',
),
pytest.param(
{'foos': {0: ..., 'a': ...}},
{'c': 3, 'foos': [{'a': 3, 'b': 4}]},
None,
id='Trying to exclude string keys on list field should be ignored (2)',
),
pytest.param(
{'foos': {0: 1}},
TypeError,
'`exclude` argument must a set or dict',
id='value as int should be an error',
),
pytest.param(
{'foos': {'__all__': {1}}},
{'c': 3, 'foos': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]},
None,
id='excluding int in dict should have no effect',
),
pytest.param(
{'foos': {'__all__': {'a'}}},
{'c': 3, 'foos': [{'b': 2}, {'b': 4}]},
None,
id='using "__all__" to exclude specific nested field',
),
pytest.param(
{'foos': {0: {'b'}, '__all__': {'a'}}},
{'c': 3, 'foos': [{}, {'b': 4}]},
None,
id='using "__all__" to exclude specific nested field in combination with more specific exclude',
),
pytest.param(
{'foos': {'__all__'}},
{'c': 3, 'foos': []},
None,
id='using "__all__" to exclude all list items',
),
pytest.param(
{'foos': {1, '__all__'}},
{'c': 3, 'foos': []},
None,
id='using "__all__" and other items should get merged together, still excluding all list items',
),
pytest.param(
{'foos': {-1: {'b'}}},
{'c': 3, 'foos': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]},
None,
id='negative indexes are ignored',
),
],
)
def test_model_export_nested_list(exclude, expected, raises_match):
class Foo(BaseModel):
a: int = 1
b: int = 2
class Bar(BaseModel):
c: int
foos: List[Foo]
m = Bar(c=3, foos=[Foo(a=1, b=2), Foo(a=3, b=4)])
if raises_match is not None:
with pytest.raises(expected, match=raises_match):
m.model_dump(exclude=exclude)
else:
original_exclude = deepcopy(exclude)
assert m.model_dump(exclude=exclude) == expected
assert exclude == original_exclude
@pytest.mark.parametrize(
'excludes,expected',
[
pytest.param(
{'bars': {0}},
{'a': 1, 'bars': [{'y': 2}, {'w': -1, 'z': 3}]},
id='excluding first item from list field using index',
),
pytest.param({'bars': {'__all__'}}, {'a': 1, 'bars': []}, id='using "__all__" to exclude all list items'),
pytest.param(
{'bars': {'__all__': {'w'}}},
{'a': 1, 'bars': [{'x': 1}, {'y': 2}, {'z': 3}]},
id='exclude single dict key from all list items',
),
],
)
def test_model_export_dict_exclusion(excludes, expected):
class Foo(BaseModel):
a: int = 1
bars: List[Dict[str, int]]
m = Foo(a=1, bars=[{'w': 0, 'x': 1}, {'y': 2}, {'w': -1, 'z': 3}])
original_excludes = deepcopy(excludes)
assert m.model_dump(exclude=excludes) == expected
assert excludes == original_excludes
def test_field_exclude():
class User(BaseModel):
_priv: int = PrivateAttr()
id: int