forked from pydantic/pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_dataclasses.py
3074 lines (2333 loc) · 84 KB
/
test_dataclasses.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 dataclasses
import inspect
import pickle
import re
import sys
import traceback
from collections.abc import Hashable
from dataclasses import InitVar
from datetime import date, datetime
from pathlib import Path
from typing import Any, Callable, ClassVar, Dict, FrozenSet, Generic, List, Optional, Set, TypeVar, Union
import pytest
from dirty_equals import HasRepr
from pydantic_core import ArgsKwargs, SchemaValidator
from typing_extensions import Annotated, Literal
import pydantic
from pydantic import (
BaseModel,
BeforeValidator,
ConfigDict,
PydanticDeprecatedSince20,
PydanticSchemaGenerationError,
PydanticUndefinedAnnotation,
PydanticUserError,
RootModel,
TypeAdapter,
ValidationError,
ValidationInfo,
computed_field,
field_serializer,
field_validator,
model_validator,
with_config,
)
from pydantic._internal._mock_val_ser import MockValSer
from pydantic.dataclasses import is_pydantic_dataclass, rebuild_dataclass
from pydantic.fields import Field, FieldInfo
from pydantic.json_schema import model_json_schema
def test_cannot_create_dataclass_from_basemodel_subclass():
msg = 'Cannot create a Pydantic dataclass from SubModel as it is already a Pydantic model'
with pytest.raises(PydanticUserError, match=msg):
@pydantic.dataclasses.dataclass
class SubModel(BaseModel):
pass
def test_simple():
@pydantic.dataclasses.dataclass
class MyDataclass:
a: int
b: float
d = MyDataclass('1', '2.5')
assert d.a == 1
assert d.b == 2.5
d = MyDataclass(b=10, a=20)
assert d.a == 20
assert d.b == 10
def test_model_name():
@pydantic.dataclasses.dataclass
class MyDataClass:
model_name: str
d = MyDataClass('foo')
assert d.model_name == 'foo'
d = MyDataClass(model_name='foo')
assert d.model_name == 'foo'
def test_value_error():
@pydantic.dataclasses.dataclass
class MyDataclass:
a: int
b: int
with pytest.raises(ValidationError) as exc_info:
MyDataclass(1, 'wrong')
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': (1,),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'wrong',
}
]
def test_frozen():
@pydantic.dataclasses.dataclass(frozen=True)
class MyDataclass:
a: int
d = MyDataclass(1)
assert d.a == 1
with pytest.raises(AttributeError):
d.a = 7
def test_validate_assignment():
@pydantic.dataclasses.dataclass(config=ConfigDict(validate_assignment=True))
class MyDataclass:
a: int
d = MyDataclass(1)
assert d.a == 1
d.a = '7'
assert d.a == 7
def test_validate_assignment_error():
@pydantic.dataclasses.dataclass(config=ConfigDict(validate_assignment=True))
class MyDataclass:
a: int
d = MyDataclass(1)
with pytest.raises(ValidationError) as exc_info:
d.a = 'xxx'
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'xxx',
}
]
def test_not_validate_assignment():
@pydantic.dataclasses.dataclass
class MyDataclass:
a: int
d = MyDataclass(1)
assert d.a == 1
d.a = '7'
assert d.a == '7'
def test_validate_assignment_value_change():
@pydantic.dataclasses.dataclass(config=ConfigDict(validate_assignment=True), frozen=False)
class MyDataclass:
a: int
@field_validator('a')
@classmethod
def double_a(cls, v: int) -> int:
return v * 2
d = MyDataclass(2)
assert d.a == 4
d.a = 3
assert d.a == 6
@pytest.mark.parametrize(
'config',
[
ConfigDict(validate_assignment=False),
ConfigDict(extra=None),
ConfigDict(extra='forbid'),
ConfigDict(extra='ignore'),
ConfigDict(validate_assignment=False, extra=None),
ConfigDict(validate_assignment=False, extra='forbid'),
ConfigDict(validate_assignment=False, extra='ignore'),
ConfigDict(validate_assignment=False, extra='allow'),
ConfigDict(validate_assignment=True, extra='allow'),
],
)
def test_validate_assignment_extra_unknown_field_assigned_allowed(config: ConfigDict):
@pydantic.dataclasses.dataclass(config=config)
class MyDataclass:
a: int
d = MyDataclass(1)
assert d.a == 1
d.extra_field = 123
assert d.extra_field == 123
@pytest.mark.parametrize(
'config',
[
ConfigDict(validate_assignment=True),
ConfigDict(validate_assignment=True, extra=None),
ConfigDict(validate_assignment=True, extra='forbid'),
ConfigDict(validate_assignment=True, extra='ignore'),
],
)
def test_validate_assignment_extra_unknown_field_assigned_errors(config: ConfigDict):
@pydantic.dataclasses.dataclass(config=config)
class MyDataclass:
a: int
d = MyDataclass(1)
assert d.a == 1
with pytest.raises(ValidationError) as exc_info:
d.extra_field = 1.23
assert exc_info.value.errors(include_url=False) == [
{
'type': 'no_such_attribute',
'loc': ('extra_field',),
'msg': "Object has no attribute 'extra_field'",
'input': 1.23,
'ctx': {'attribute': 'extra_field'},
}
]
def test_post_init():
post_init_called = False
@pydantic.dataclasses.dataclass
class MyDataclass:
a: int
def __post_init__(self):
nonlocal post_init_called
post_init_called = True
d = MyDataclass('1')
assert d.a == 1
assert post_init_called
def test_post_init_validation():
@dataclasses.dataclass
class DC:
a: int
def __post_init__(self):
self.a *= 2
assert DC(a='2').a == '22'
PydanticDC = pydantic.dataclasses.dataclass(DC)
assert DC(a='2').a == '22'
assert PydanticDC(a='2').a == 4
def test_convert_vanilla_dc():
@dataclasses.dataclass
class DC:
a: int
b: str = dataclasses.field(init=False)
def __post_init__(self):
self.a *= 2
self.b = 'hello'
dc1 = DC(a='2')
assert dc1.a == '22'
assert dc1.b == 'hello'
PydanticDC = pydantic.dataclasses.dataclass(DC)
dc2 = DC(a='2')
assert dc2.a == '22'
assert dc2.b == 'hello'
py_dc = PydanticDC(a='2')
assert py_dc.a == 4
assert py_dc.b == 'hello'
def test_std_dataclass_with_parent():
@dataclasses.dataclass
class DCParent:
a: int
@dataclasses.dataclass
class DC(DCParent):
b: int
def __post_init__(self):
self.a *= 2
assert dataclasses.asdict(DC(a='2', b='1')) == {'a': '22', 'b': '1'}
PydanticDC = pydantic.dataclasses.dataclass(DC)
assert dataclasses.asdict(DC(a='2', b='1')) == {'a': '22', 'b': '1'}
assert dataclasses.asdict(PydanticDC(a='2', b='1')) == {'a': 4, 'b': 1}
def test_post_init_inheritance_chain():
parent_post_init_called = False
post_init_called = False
@pydantic.dataclasses.dataclass
class ParentDataclass:
a: int
def __post_init__(self):
nonlocal parent_post_init_called
parent_post_init_called = True
@pydantic.dataclasses.dataclass
class MyDataclass(ParentDataclass):
b: int
def __post_init__(self):
super().__post_init__()
nonlocal post_init_called
post_init_called = True
d = MyDataclass(a=1, b=2)
assert d.a == 1
assert d.b == 2
assert parent_post_init_called
assert post_init_called
def test_post_init_post_parse():
with pytest.warns(PydanticDeprecatedSince20, match='Support for `__post_init_post_parse__` has been dropped'):
@pydantic.dataclasses.dataclass
class MyDataclass:
a: int
def __post_init_post_parse__(self):
pass
def test_post_init_assignment():
from dataclasses import field
# Based on: https://docs.python.org/3/library/dataclasses.html#post-init-processing
@pydantic.dataclasses.dataclass
class C:
a: float
b: float
c: float = field(init=False)
def __post_init__(self):
self.c = self.a + self.b
c = C(0.1, 0.2)
assert c.a == 0.1
assert c.b == 0.2
assert c.c == 0.30000000000000004
def test_inheritance():
@pydantic.dataclasses.dataclass
class A:
a: str = None
a_ = A(a=b'a')
assert a_.a == 'a'
@pydantic.dataclasses.dataclass
class B(A):
b: int = None
b = B(a='a', b=12)
assert b.a == 'a'
assert b.b == 12
with pytest.raises(ValidationError):
B(a='a', b='b')
a_ = A(a=b'a')
assert a_.a == 'a'
def test_validate_long_string_error():
@pydantic.dataclasses.dataclass(config=dict(str_max_length=3))
class MyDataclass:
a: str
with pytest.raises(ValidationError) as exc_info:
MyDataclass('xxxx')
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'string_too_long',
'loc': (0,),
'msg': 'String should have at most 3 characters',
'input': 'xxxx',
'ctx': {'max_length': 3},
}
]
def test_validate_assignment_long_string_error():
@pydantic.dataclasses.dataclass(config=ConfigDict(str_max_length=3, validate_assignment=True))
class MyDataclass:
a: str
d = MyDataclass('xxx')
with pytest.raises(ValidationError) as exc_info:
d.a = 'xxxx'
assert exc_info.value.errors(include_url=False) == [
{
'type': 'string_too_long',
'loc': ('a',),
'msg': 'String should have at most 3 characters',
'input': 'xxxx',
'ctx': {'max_length': 3},
}
]
def test_no_validate_assignment_long_string_error():
@pydantic.dataclasses.dataclass(config=ConfigDict(str_max_length=3, validate_assignment=False))
class MyDataclass:
a: str
d = MyDataclass('xxx')
d.a = 'xxxx'
assert d.a == 'xxxx'
def test_nested_dataclass():
@pydantic.dataclasses.dataclass
class Nested:
number: int
@pydantic.dataclasses.dataclass
class Outer:
n: Nested
navbar = Outer(n=Nested(number='1'))
assert isinstance(navbar.n, Nested)
assert navbar.n.number == 1
navbar = Outer(n={'number': '3'})
assert isinstance(navbar.n, Nested)
assert navbar.n.number == 3
with pytest.raises(ValidationError) as exc_info:
Outer(n='not nested')
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'dataclass_type',
'loc': ('n',),
'msg': 'Input should be a dictionary or an instance of Nested',
'input': 'not nested',
'ctx': {'class_name': 'Nested'},
}
]
with pytest.raises(ValidationError) as exc_info:
Outer(n={'number': 'x'})
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('n', 'number'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'x',
}
]
def test_arbitrary_types_allowed():
class Button:
def __init__(self, href: str):
self.href = href
@pydantic.dataclasses.dataclass(config=dict(arbitrary_types_allowed=True))
class Navbar:
button: Button
btn = Button(href='a')
navbar = Navbar(button=btn)
assert navbar.button.href == 'a'
with pytest.raises(ValidationError) as exc_info:
Navbar(button=('b',))
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'is_instance_of',
'loc': ('button',),
'msg': 'Input should be an instance of test_arbitrary_types_allowed.<locals>.Button',
'input': ('b',),
'ctx': {'class': 'test_arbitrary_types_allowed.<locals>.Button'},
}
]
def test_nested_dataclass_model():
@pydantic.dataclasses.dataclass
class Nested:
number: int
class Outer(BaseModel):
n: Nested
navbar = Outer(n=Nested(number='1'))
assert navbar.n.number == 1
def test_fields():
@pydantic.dataclasses.dataclass
class User:
id: int
name: str = 'John Doe'
signup_ts: datetime = None
user = User(id=123)
fields = user.__pydantic_fields__
assert fields['id'].is_required() is True
assert fields['name'].is_required() is False
assert fields['name'].default == 'John Doe'
assert fields['signup_ts'].is_required() is False
assert fields['signup_ts'].default is None
@pytest.mark.parametrize('field_constructor', [dataclasses.field, pydantic.dataclasses.Field])
def test_default_factory_field(field_constructor: Callable):
@pydantic.dataclasses.dataclass
class User:
id: int
other: Dict[str, str] = field_constructor(default_factory=lambda: {'John': 'Joey'})
user = User(id=123)
assert user.id == 123
assert user.other == {'John': 'Joey'}
fields = user.__pydantic_fields__
assert fields['id'].is_required() is True
assert repr(fields['id'].default) == 'PydanticUndefined'
assert fields['other'].is_required() is False
assert fields['other'].default_factory() == {'John': 'Joey'}
def test_default_factory_singleton_field():
class MySingleton:
pass
MY_SINGLETON = MySingleton()
@pydantic.dataclasses.dataclass(config=dict(arbitrary_types_allowed=True))
class Foo:
singleton: MySingleton = dataclasses.field(default_factory=lambda: MY_SINGLETON)
# Returning a singleton from a default_factory is supported
assert Foo().singleton is Foo().singleton
def test_schema():
@pydantic.dataclasses.dataclass
class User:
id: int
name: str = 'John Doe'
aliases: Dict[str, str] = dataclasses.field(default_factory=lambda: {'John': 'Joey'})
signup_ts: datetime = None
age: Optional[int] = dataclasses.field(
default=None, metadata=dict(title='The age of the user', description='do not lie!')
)
height: Optional[int] = pydantic.Field(None, title='The height in cm', ge=50, le=300)
User(id=123)
assert model_json_schema(User) == {
'properties': {
'age': {
'anyOf': [{'type': 'integer'}, {'type': 'null'}],
'default': None,
'title': 'The age of the user',
'description': 'do not lie!',
},
'aliases': {
'additionalProperties': {'type': 'string'},
'title': 'Aliases',
'type': 'object',
},
'height': {
'anyOf': [{'maximum': 300, 'minimum': 50, 'type': 'integer'}, {'type': 'null'}],
'default': None,
'title': 'The height in cm',
},
'id': {'title': 'Id', 'type': 'integer'},
'name': {'default': 'John Doe', 'title': 'Name', 'type': 'string'},
'signup_ts': {'default': None, 'format': 'date-time', 'title': 'Signup Ts', 'type': 'string'},
},
'required': ['id'],
'title': 'User',
'type': 'object',
}
def test_nested_schema():
@pydantic.dataclasses.dataclass
class Nested:
number: int
@pydantic.dataclasses.dataclass
class Outer:
n: Nested
assert model_json_schema(Outer) == {
'$defs': {
'Nested': {
'properties': {'number': {'title': 'Number', 'type': 'integer'}},
'required': ['number'],
'title': 'Nested',
'type': 'object',
}
},
'properties': {'n': {'$ref': '#/$defs/Nested'}},
'required': ['n'],
'title': 'Outer',
'type': 'object',
}
def test_initvar():
@pydantic.dataclasses.dataclass
class TestInitVar:
x: int
y: dataclasses.InitVar
tiv = TestInitVar(1, 2)
assert tiv.x == 1
with pytest.raises(AttributeError):
tiv.y
def test_derived_field_from_initvar():
@pydantic.dataclasses.dataclass
class DerivedWithInitVar:
plusone: int = dataclasses.field(init=False)
number: dataclasses.InitVar[int]
def __post_init__(self, number):
self.plusone = number + 1
derived = DerivedWithInitVar('1')
assert derived.plusone == 2
with pytest.raises(ValidationError, match='Input should be a valid integer, unable to parse string as an integer'):
DerivedWithInitVar('Not A Number')
def test_initvars_post_init():
@pydantic.dataclasses.dataclass
class PathDataPostInit:
path: Path
base_path: dataclasses.InitVar[Optional[Path]] = None
def __post_init__(self, base_path):
if base_path is not None:
self.path = base_path / self.path
path_data = PathDataPostInit('world')
assert 'path' in path_data.__dict__
assert 'base_path' not in path_data.__dict__
assert path_data.path == Path('world')
p = PathDataPostInit('world', base_path='/hello')
assert p.path == Path('/hello/world')
def test_classvar():
@pydantic.dataclasses.dataclass
class TestClassVar:
klassvar: ClassVar = "I'm a Class variable"
x: int
tcv = TestClassVar(2)
assert tcv.klassvar == "I'm a Class variable"
def test_frozenset_field():
@pydantic.dataclasses.dataclass
class TestFrozenSet:
set: FrozenSet[int]
test_set = frozenset({1, 2, 3})
object_under_test = TestFrozenSet(set=test_set)
assert object_under_test.set == test_set
def test_inheritance_post_init():
post_init_called = False
@pydantic.dataclasses.dataclass
class Base:
a: int
def __post_init__(self):
nonlocal post_init_called
post_init_called = True
@pydantic.dataclasses.dataclass
class Child(Base):
b: int
Child(a=1, b=2)
assert post_init_called
def test_hashable_required():
@pydantic.dataclasses.dataclass
class MyDataclass:
v: Hashable
MyDataclass(v=None)
with pytest.raises(ValidationError) as exc_info:
MyDataclass(v=[])
assert exc_info.value.errors(include_url=False) == [
{'input': [], 'loc': ('v',), 'msg': 'Input should be hashable', 'type': 'is_hashable'}
]
with pytest.raises(ValidationError) as exc_info:
# Should this raise a TypeError instead? https://github.com/pydantic/pydantic/issues/5487
MyDataclass()
assert exc_info.value.errors(include_url=False) == [
{'input': HasRepr('ArgsKwargs(())'), 'loc': ('v',), 'msg': 'Field required', 'type': 'missing'}
]
@pytest.mark.parametrize('default', [1, None])
def test_default_value(default):
@pydantic.dataclasses.dataclass
class MyDataclass:
v: int = default
assert dataclasses.asdict(MyDataclass()) == {'v': default}
assert dataclasses.asdict(MyDataclass(v=42)) == {'v': 42}
def test_default_value_ellipsis():
"""
https://github.com/pydantic/pydantic/issues/5488
"""
@pydantic.dataclasses.dataclass
class MyDataclass:
v: int = ...
assert dataclasses.asdict(MyDataclass(v=42)) == {'v': 42}
with pytest.raises(ValidationError, match='type=missing'):
MyDataclass()
def test_override_builtin_dataclass():
@dataclasses.dataclass
class File:
hash: str
name: Optional[str]
size: int
content: Optional[bytes] = None
ValidFile = pydantic.dataclasses.dataclass(File)
file = File(hash='xxx', name=b'whatever.txt', size='456')
valid_file = ValidFile(hash='xxx', name=b'whatever.txt', size='456')
assert file.name == b'whatever.txt'
assert file.size == '456'
assert valid_file.name == 'whatever.txt'
assert valid_file.size == 456
assert isinstance(valid_file, File)
assert isinstance(valid_file, ValidFile)
with pytest.raises(ValidationError) as e:
ValidFile(hash=[1], name='name', size=3)
assert e.value.errors(include_url=False) == [
{
'type': 'string_type',
'loc': ('hash',),
'msg': 'Input should be a valid string',
'input': [1],
},
]
def test_override_builtin_dataclass_2():
@dataclasses.dataclass
class Meta:
modified_date: Optional[datetime]
seen_count: int
Meta(modified_date='not-validated', seen_count=0)
@pydantic.dataclasses.dataclass
@dataclasses.dataclass
class File(Meta):
filename: str
Meta(modified_date='still-not-validated', seen_count=0)
f = File(filename=b'thefilename', modified_date='2020-01-01T00:00', seen_count='7')
assert f.filename == 'thefilename'
assert f.modified_date == datetime(2020, 1, 1, 0, 0)
assert f.seen_count == 7
def test_override_builtin_dataclass_nested():
@dataclasses.dataclass
class Meta:
modified_date: Optional[datetime]
seen_count: int
__pydantic_config__ = {'revalidate_instances': 'always'}
@dataclasses.dataclass
class File:
filename: str
meta: Meta
FileChecked = pydantic.dataclasses.dataclass(File)
f = FileChecked(filename=b'thefilename', meta=Meta(modified_date='2020-01-01T00:00', seen_count='7'))
assert f.filename == 'thefilename'
assert f.meta.modified_date == datetime(2020, 1, 1, 0, 0)
assert f.meta.seen_count == 7
with pytest.raises(ValidationError) as e:
FileChecked(filename=b'thefilename', meta=Meta(modified_date='2020-01-01T00:00', seen_count=['7']))
# insert_assert(e.value.errors(include_url=False))
assert e.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('meta', 'seen_count'), 'msg': 'Input should be a valid integer', 'input': ['7']}
]
class Foo(
BaseModel,
):
file: File
foo = Foo.model_validate(
{
'file': {
'filename': b'thefilename',
'meta': {'modified_date': '2020-01-01T00:00', 'seen_count': '7'},
},
}
)
assert foo.file.filename == 'thefilename'
assert foo.file.meta.modified_date == datetime(2020, 1, 1, 0, 0)
assert foo.file.meta.seen_count == 7
def test_override_builtin_dataclass_nested_schema():
@dataclasses.dataclass
class Meta:
modified_date: Optional[datetime]
seen_count: int
@dataclasses.dataclass
class File:
filename: str
meta: Meta
FileChecked = pydantic.dataclasses.dataclass(File)
assert model_json_schema(FileChecked) == {
'$defs': {
'Meta': {
'properties': {
'modified_date': {
'anyOf': [{'format': 'date-time', 'type': 'string'}, {'type': 'null'}],
'title': 'Modified Date',
},
'seen_count': {'title': 'Seen Count', 'type': 'integer'},
},
'required': ['modified_date', 'seen_count'],
'title': 'Meta',
'type': 'object',
}
},
'properties': {'filename': {'title': 'Filename', 'type': 'string'}, 'meta': {'$ref': '#/$defs/Meta'}},
'required': ['filename', 'meta'],
'title': 'File',
'type': 'object',
}
def test_inherit_builtin_dataclass():
@dataclasses.dataclass
class Z:
z: int
@dataclasses.dataclass
class Y(Z):
y: int
@pydantic.dataclasses.dataclass
class X(Y):
x: int
pika = X(x='2', y='4', z='3')
assert pika.x == 2
assert pika.y == 4
assert pika.z == 3
def test_forward_stdlib_dataclass_params():
@dataclasses.dataclass(frozen=True)
class Item:
name: str
class Example(BaseModel):
item: Item
other: str
model_config = ConfigDict(arbitrary_types_allowed=True)
e = Example(item=Item(name='pika'), other='bulbi')
e.other = 'bulbi2'
with pytest.raises(dataclasses.FrozenInstanceError):
e.item.name = 'pika2'
def test_pydantic_callable_field():
"""pydantic callable fields behaviour should be the same as stdlib dataclass"""
def foo(arg1, arg2):
return arg1, arg2
def bar(x: int, y: float, z: str) -> bool:
return str(x + y) == z
class PydanticModel(BaseModel):
required_callable: Callable
required_callable_2: Callable[[int, float, str], bool]
default_callable: Callable = foo
default_callable_2: Callable[[int, float, str], bool] = bar
@pydantic.dataclasses.dataclass
class PydanticDataclass:
required_callable: Callable
required_callable_2: Callable[[int, float, str], bool]
default_callable: Callable = foo
default_callable_2: Callable[[int, float, str], bool] = bar
@dataclasses.dataclass
class StdlibDataclass:
required_callable: Callable
required_callable_2: Callable[[int, float, str], bool]
default_callable: Callable = foo
default_callable_2: Callable[[int, float, str], bool] = bar
pyd_m = PydanticModel(required_callable=foo, required_callable_2=bar)
pyd_dc = PydanticDataclass(required_callable=foo, required_callable_2=bar)
std_dc = StdlibDataclass(required_callable=foo, required_callable_2=bar)
assert (
pyd_m.required_callable
is pyd_m.default_callable
is pyd_dc.required_callable
is pyd_dc.default_callable
is std_dc.required_callable
is std_dc.default_callable
)
assert (
pyd_m.required_callable_2
is pyd_m.default_callable_2
is pyd_dc.required_callable_2
is pyd_dc.default_callable_2
is std_dc.required_callable_2
is std_dc.default_callable_2
)
def test_pickle_overridden_builtin_dataclass(create_module: Any):
module = create_module(
# language=Python
"""\
import dataclasses
import pydantic
@pydantic.dataclasses.dataclass(config=pydantic.config.ConfigDict(validate_assignment=True))
class BuiltInDataclassForPickle:
value: int
"""
)
obj = module.BuiltInDataclassForPickle(value=5)
pickled_obj = pickle.dumps(obj)
restored_obj = pickle.loads(pickled_obj)