summaryrefslogtreecommitdiff
path: root/tests/brain/test_dataclasses.py
blob: cd3fcb4cfb8c5146a8b8e1eb8283d9c49a1023dc (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt

import pytest

import astroid
from astroid import bases, nodes
from astroid.const import PY310_PLUS
from astroid.exceptions import InferenceError
from astroid.util import Uninferable

parametrize_module = pytest.mark.parametrize(
    ("module",), (["dataclasses"], ["pydantic.dataclasses"], ["marshmallow_dataclass"])
)


@parametrize_module
def test_inference_attribute_no_default(module: str):
    """Test inference of dataclass attribute with no default.

    Note that the argument to the constructor is ignored by the inference.
    """
    klass, instance = astroid.extract_node(
        f"""
    from {module} import dataclass

    @dataclass
    class A:
        name: str

    A.name  #@
    A('hi').name  #@
    """
    )
    with pytest.raises(InferenceError):
        klass.inferred()

    inferred = instance.inferred()
    assert len(inferred) == 1
    assert isinstance(inferred[0], bases.Instance)
    assert inferred[0].name == "str"


@parametrize_module
def test_inference_non_field_default(module: str):
    """Test inference of dataclass attribute with a non-field default."""
    klass, instance = astroid.extract_node(
        f"""
    from {module} import dataclass

    @dataclass
    class A:
        name: str = 'hi'

    A.name  #@
    A().name  #@
    """
    )
    inferred = klass.inferred()
    assert len(inferred) == 1
    assert isinstance(inferred[0], nodes.Const)
    assert inferred[0].value == "hi"

    inferred = instance.inferred()
    assert len(inferred) == 2
    assert isinstance(inferred[0], nodes.Const)
    assert inferred[0].value == "hi"

    assert isinstance(inferred[1], bases.Instance)
    assert inferred[1].name == "str"


@parametrize_module
def test_inference_field_default(module: str):
    """Test inference of dataclass attribute with a field call default
    (default keyword argument given).
    """
    klass, instance = astroid.extract_node(
        f"""
    from {module} import dataclass
    from dataclasses import field

    @dataclass
    class A:
        name: str = field(default='hi')

    A.name  #@
    A().name  #@
    """
    )
    inferred = klass.inferred()
    assert len(inferred) == 1
    assert isinstance(inferred[0], nodes.Const)
    assert inferred[0].value == "hi"

    inferred = instance.inferred()
    assert len(inferred) == 2
    assert isinstance(inferred[0], nodes.Const)
    assert inferred[0].value == "hi"

    assert isinstance(inferred[1], bases.Instance)
    assert inferred[1].name == "str"


@parametrize_module
def test_inference_field_default_factory(module: str):
    """Test inference of dataclass attribute with a field call default
    (default_factory keyword argument given).
    """
    klass, instance = astroid.extract_node(
        f"""
    from {module} import dataclass
    from dataclasses import field

    @dataclass
    class A:
        name: list = field(default_factory=list)

    A.name  #@
    A().name  #@
    """
    )
    inferred = klass.inferred()
    assert len(inferred) == 1
    assert isinstance(inferred[0], nodes.List)
    assert inferred[0].elts == []

    inferred = instance.inferred()
    assert len(inferred) == 2
    assert isinstance(inferred[0], nodes.List)
    assert inferred[0].elts == []

    assert isinstance(inferred[1], bases.Instance)
    assert inferred[1].name == "list"


@parametrize_module
def test_inference_method(module: str):
    """Test inference of dataclass attribute within a method,
    with a default_factory field.

    Based on https://github.com/pylint-dev/pylint/issues/2600
    """
    node = astroid.extract_node(
        f"""
    from typing import Dict
    from {module} import dataclass
    from dataclasses import field

    @dataclass
    class TestClass:
        foo: str
        bar: str
        baz_dict: Dict[str, str] = field(default_factory=dict)

        def some_func(self) -> None:
            f = self.baz_dict.items  #@
            for key, value in f():
                print(key)
                print(value)
    """
    )
    inferred = next(node.value.infer())
    assert isinstance(inferred, bases.BoundMethod)


@parametrize_module
def test_inference_no_annotation(module: str):
    """Test that class variables without type annotations are not
    turned into instance attributes.
    """
    class_def, klass, instance = astroid.extract_node(
        f"""
    from {module} import dataclass

    @dataclass
    class A:
        name = 'hi'

    A  #@
    A.name  #@
    A().name #@
    """
    )
    inferred = next(class_def.infer())
    assert isinstance(inferred, nodes.ClassDef)
    assert inferred.instance_attrs == {}
    assert inferred.is_dataclass

    # Both the class and instance can still access the attribute
    for node in (klass, instance):
        assert isinstance(node, nodes.NodeNG)
        inferred = node.inferred()
        assert len(inferred) == 1
        assert isinstance(inferred[0], nodes.Const)
        assert inferred[0].value == "hi"


@parametrize_module
def test_inference_class_var(module: str):
    """Test that class variables with a ClassVar type annotations are not
    turned into instance attributes.
    """
    class_def, klass, instance = astroid.extract_node(
        f"""
    from {module} import dataclass
    from typing import ClassVar

    @dataclass
    class A:
        name: ClassVar[str] = 'hi'

    A #@
    A.name  #@
    A().name #@
    """
    )
    inferred = next(class_def.infer())
    assert isinstance(inferred, nodes.ClassDef)
    assert inferred.instance_attrs == {}
    assert inferred.is_dataclass

    # Both the class and instance can still access the attribute
    for node in (klass, instance):
        assert isinstance(node, nodes.NodeNG)
        inferred = node.inferred()
        assert len(inferred) == 1
        assert isinstance(inferred[0], nodes.Const)
        assert inferred[0].value == "hi"


@parametrize_module
def test_inference_init_var(module: str):
    """Test that class variables with InitVar type annotations are not
    turned into instance attributes.
    """
    class_def, klass, instance = astroid.extract_node(
        f"""
    from {module} import dataclass
    from dataclasses import InitVar

    @dataclass
    class A:
        name: InitVar[str] = 'hi'

    A  #@
    A.name  #@
    A().name #@
    """
    )
    inferred = next(class_def.infer())
    assert isinstance(inferred, nodes.ClassDef)
    assert inferred.instance_attrs == {}
    assert inferred.is_dataclass

    # Both the class and instance can still access the attribute
    for node in (klass, instance):
        assert isinstance(node, nodes.NodeNG)
        inferred = node.inferred()
        assert len(inferred) == 1
        assert isinstance(inferred[0], nodes.Const)
        assert inferred[0].value == "hi"


@parametrize_module
def test_inference_generic_collection_attribute(module: str):
    """Test that an attribute with a generic collection type from the
    typing module is inferred correctly.
    """
    attr_nodes = astroid.extract_node(
        f"""
    from {module} import dataclass
    from dataclasses import field
    import typing

    @dataclass
    class A:
        dict_prop: typing.Dict[str, str]
        frozenset_prop: typing.FrozenSet[str]
        list_prop: typing.List[str]
        set_prop: typing.Set[str]
        tuple_prop: typing.Tuple[int, str]

    a = A({{}}, frozenset(), [], set(), (1, 'hi'))
    a.dict_prop       #@
    a.frozenset_prop  #@
    a.list_prop       #@
    a.set_prop        #@
    a.tuple_prop      #@
    """
    )
    names = (
        "Dict",
        "FrozenSet",
        "List",
        "Set",
        "Tuple",
    )
    for node, name in zip(attr_nodes, names):
        inferred = next(node.infer())
        assert isinstance(inferred, bases.Instance)
        assert inferred.name == name


@pytest.mark.parametrize(
    ("module", "typing_module"),
    [
        ("dataclasses", "typing"),
        ("pydantic.dataclasses", "typing"),
        ("pydantic.dataclasses", "collections.abc"),
        ("marshmallow_dataclass", "typing"),
        ("marshmallow_dataclass", "collections.abc"),
    ],
)
def test_inference_callable_attribute(module: str, typing_module: str):
    """Test that an attribute with a Callable annotation is inferred as Uninferable.

    See issue #1129 and pylint-dev/pylint#4895
    """
    instance = astroid.extract_node(
        f"""
    from {module} import dataclass
    from {typing_module} import Any, Callable

    @dataclass
    class A:
        enabled: Callable[[Any], bool]

    A(lambda x: x == 42).enabled  #@
    """
    )
    inferred = next(instance.infer())
    assert inferred is Uninferable


@parametrize_module
def test_inference_inherited(module: str):
    """Test that an attribute is inherited from a superclass dataclass."""
    klass1, instance1, klass2, instance2 = astroid.extract_node(
        f"""
    from {module} import dataclass

    @dataclass
    class A:
        value: int
        name: str = "hi"

    @dataclass
    class B(A):
        new_attr: bool = True

    B.value  #@
    B(1).value  #@
    B.name  #@
    B(1).name  #@
    """
    )
    with pytest.raises(InferenceError):  # B.value is not defined
        klass1.inferred()

    inferred = instance1.inferred()
    assert isinstance(inferred[0], bases.Instance)
    assert inferred[0].name == "int"

    inferred = klass2.inferred()
    assert len(inferred) == 1
    assert isinstance(inferred[0], nodes.Const)
    assert inferred[0].value == "hi"

    inferred = instance2.inferred()
    assert len(inferred) == 2
    assert isinstance(inferred[0], nodes.Const)
    assert inferred[0].value == "hi"
    assert isinstance(inferred[1], bases.Instance)
    assert inferred[1].name == "str"


def test_dataclass_order_of_inherited_attributes():
    """Test that an attribute in a child does not get put at the end of the init."""
    child, normal, keyword_only = astroid.extract_node(
        """
    from dataclass import dataclass


    @dataclass
    class Parent:
        a: str
        b: str


    @dataclass
    class Child(Parent):
        c: str
        a: str


    @dataclass(kw_only=True)
    class KeywordOnlyParent:
        a: int
        b: str


    @dataclass
    class NormalChild(KeywordOnlyParent):
        c: str
        a: str


    @dataclass(kw_only=True)
    class KeywordOnlyChild(KeywordOnlyParent):
        c: str
        a: str


    Child.__init__  #@
    NormalChild.__init__  #@
    KeywordOnlyChild.__init__  #@
    """
    )
    child_init: bases.UnboundMethod = next(child.infer())
    assert [a.name for a in child_init.args.args] == ["self", "a", "b", "c"]

    normal_init: bases.UnboundMethod = next(normal.infer())
    if PY310_PLUS:
        assert [a.name for a in normal_init.args.args] == ["self", "a", "c"]
        assert [a.name for a in normal_init.args.kwonlyargs] == ["b"]
    else:
        assert [a.name for a in normal_init.args.args] == ["self", "a", "b", "c"]
        assert [a.name for a in normal_init.args.kwonlyargs] == []

    keyword_only_init: bases.UnboundMethod = next(keyword_only.infer())
    if PY310_PLUS:
        assert [a.name for a in keyword_only_init.args.args] == ["self"]
        assert [a.name for a in keyword_only_init.args.kwonlyargs] == ["a", "b", "c"]
    else:
        assert [a.name for a in keyword_only_init.args.args] == ["self", "a", "b", "c"]


def test_pydantic_field() -> None:
    """Test that pydantic.Field attributes are currently Uninferable.

    (Eventually, we can extend the brain to support pydantic.Field)
    """
    klass, instance = astroid.extract_node(
        """
    from pydantic import Field
    from pydantic.dataclasses import dataclass

    @dataclass
    class A:
        name: str = Field("hi")

    A.name  #@
    A().name #@
    """
    )

    inferred = klass.inferred()
    assert len(inferred) == 1
    assert inferred[0] is Uninferable

    inferred = instance.inferred()
    assert len(inferred) == 2
    assert inferred[0] is Uninferable
    assert isinstance(inferred[1], bases.Instance)
    assert inferred[1].name == "str"


@parametrize_module
def test_init_empty(module: str):
    """Test init for a dataclass with no attributes."""
    node = astroid.extract_node(
        f"""
    from {module} import dataclass

    @dataclass
    class A:
        pass

    A.__init__  #@
    """
    )
    init = next(node.infer())
    assert [a.name for a in init.args.args] == ["self"]


@parametrize_module
def test_init_no_defaults(module: str):
    """Test init for a dataclass with attributes and no defaults."""
    node = astroid.extract_node(
        f"""
    from {module} import dataclass
    from typing import List

    @dataclass
    class A:
        x: int
        y: str
        z: List[bool]

    A.__init__  #@
    """
    )
    init = next(node.infer())
    assert [a.name for a in init.args.args] == ["self", "x", "y", "z"]
    assert [a.as_string() if a else None for a in init.args.annotations] == [
        None,
        "int",
        "str",
        "List[bool]",
    ]


@parametrize_module
def test_init_defaults(module: str):
    """Test init for a dataclass with attributes and some defaults."""
    node = astroid.extract_node(
        f"""
    from {module} import dataclass
    from dataclasses import field
    from typing import List

    @dataclass
    class A:
        w: int
        x: int = 10
        y: str = field(default="hi")
        z: List[bool] = field(default_factory=list)

    A.__init__  #@
    """
    )
    init = next(node.infer())
    assert [a.name for a in init.args.args] == ["self", "w", "x", "y", "z"]
    assert [a.as_string() if a else None for a in init.args.annotations] == [
        None,
        "int",
        "int",
        "str",
        "List[bool]",
    ]
    assert [a.as_string() if a else None for a in init.args.defaults] == [
        "10",
        "'hi'",
        "_HAS_DEFAULT_FACTORY",
    ]


@parametrize_module
def test_init_initvar(module: str):
    """Test init for a dataclass with attributes and an InitVar."""
    node = astroid.extract_node(
        f"""
    from {module} import dataclass
    from dataclasses import InitVar
    from typing import List

    @dataclass
    class A:
        x: int
        y: str
        init_var: InitVar[int]
        z: List[bool]

    A.__init__  #@
    """
    )
    init = next(node.infer())
    assert [a.name for a in init.args.args] == ["self", "x", "y", "init_var", "z"]
    assert [a.as_string() if a else None for a in init.args.annotations] == [
        None,
        "int",
        "str",
        "int",
        "List[bool]",
    ]


@parametrize_module
def test_init_decorator_init_false(module: str):
    """Test that no init is generated when init=False is passed to
    dataclass decorator.
    """
    node = astroid.extract_node(
        f"""
    from {module} import dataclass
    from typing import List

    @dataclass(init=False)
    class A:
        x: int
        y: str
        z: List[bool]

    A.__init__ #@
    """
    )
    init = next(node.infer())
    assert init._proxied.parent.name == "object"


@parametrize_module
def test_init_field_init_false(module: str):
    """Test init for a dataclass with attributes with a field value where init=False
    (these attributes should not be included in the initializer).
    """
    node = astroid.extract_node(
        f"""
    from {module} import dataclass
    from dataclasses import field
    from typing import List

    @dataclass
    class A:
        x: int
        y: str
        z: List[bool] = field(init=False)

    A.__init__  #@
    """
    )
    init = next(node.infer())
    assert [a.name for a in init.args.args] == ["self", "x", "y"]
    assert [a.as_string() if a else None for a in init.args.annotations] == [
        None,
        "int",
        "str",
    ]


@parametrize_module
def test_init_override(module: str):
    """Test init for a dataclass overrides a superclass initializer.

    Based on https://github.com/pylint-dev/pylint/issues/3201
    """
    node = astroid.extract_node(
        f"""
    from {module} import dataclass
    from typing import List

    class A:
        arg0: str = None

        def __init__(self, arg0):
            raise NotImplementedError

    @dataclass
    class B(A):
        arg1: int = None
        arg2: str = None

    B.__init__  #@
    """
    )
    init = next(node.infer())
    assert [a.name for a in init.args.args] == ["self", "arg1", "arg2"]
    assert [a.as_string() if a else None for a in init.args.annotations] == [
        None,
        "int",
        "str",
    ]


@parametrize_module
def test_init_attributes_from_superclasses(module: str):
    """Test init for a dataclass that inherits and overrides attributes from
    superclasses.

    Based on https://github.com/pylint-dev/pylint/issues/3201
    """
    node = astroid.extract_node(
        f"""
    from {module} import dataclass
    from typing import List

    @dataclass
    class A:
        arg0: float
        arg2: str

    @dataclass
    class B(A):
        arg1: int
        arg2: list  # Overrides arg2 from A

    B.__init__  #@
    """
    )
    init = next(node.infer())
    assert [a.name for a in init.args.args] == ["self", "arg0", "arg2", "arg1"]
    assert [a.as_string() if a else None for a in init.args.annotations] == [
        None,
        "float",
        "list",  # not str
        "int",
    ]


@parametrize_module
def test_invalid_init(module: str):
    """Test that astroid doesn't generate an initializer when attribute order is
    invalid.
    """
    node = astroid.extract_node(
        f"""
    from {module} import dataclass

    @dataclass
    class A:
        arg1: float = 0.0
        arg2: str

    A.__init__  #@
    """
    )
    init = next(node.infer())
    assert init._proxied.parent.name == "object"


@parametrize_module
def test_annotated_enclosed_field_call(module: str):
    """Test inference of dataclass attribute with a field call in another function
    call.
    """
    node = astroid.extract_node(
        f"""
    from {module} import dataclass, field
    from typing import cast

    @dataclass
    class A:
        attribute: int = cast(int, field(default_factory=dict))
    """
    )
    inferred = node.inferred()
    assert len(inferred) == 1 and isinstance(inferred[0], nodes.ClassDef)
    assert "attribute" in inferred[0].instance_attrs
    assert inferred[0].is_dataclass


@parametrize_module
def test_invalid_field_call(module: str) -> None:
    """Test inference of invalid field call doesn't crash."""
    code = astroid.extract_node(
        f"""
    from {module} import dataclass, field

    @dataclass
    class A:
        val: field()
    """
    )
    inferred = code.inferred()
    assert len(inferred) == 1
    assert isinstance(inferred[0], nodes.ClassDef)
    assert inferred[0].is_dataclass


def test_non_dataclass_is_not_dataclass() -> None:
    """Test that something that isn't a dataclass has the correct attribute."""
    module = astroid.parse(
        """
    class A:
        val: field()

    def dataclass():
        return

    @dataclass
    class B:
        val: field()
    """
    )
    class_a = module.body[0].inferred()
    assert len(class_a) == 1
    assert isinstance(class_a[0], nodes.ClassDef)
    assert not class_a[0].is_dataclass

    class_b = module.body[2].inferred()
    assert len(class_b) == 1
    assert isinstance(class_b[0], nodes.ClassDef)
    assert not class_b[0].is_dataclass


def test_kw_only_sentinel() -> None:
    """Test that the KW_ONLY sentinel doesn't get added to the fields."""
    node_one, node_two = astroid.extract_node(
        """
    from dataclasses import dataclass, KW_ONLY
    from dataclasses import KW_ONLY as keyword_only

    @dataclass
    class A:
        _: KW_ONLY
        y: str

    A.__init__  #@

    @dataclass
    class B:
        _: keyword_only
        y: str

    B.__init__  #@
    """
    )
    if PY310_PLUS:
        expected = ["self", "y"]
    else:
        expected = ["self", "_", "y"]
    init = next(node_one.infer())
    assert [a.name for a in init.args.args] == expected

    init = next(node_two.infer())
    assert [a.name for a in init.args.args] == expected


def test_kw_only_decorator() -> None:
    """Test that we update the signature correctly based on the keyword.

    kw_only was introduced in PY310.
    """
    foodef, bardef, cee, dee = astroid.extract_node(
        """
    from dataclasses import dataclass

    @dataclass(kw_only=True)
    class Foo:
        a: int
        e: str


    @dataclass(kw_only=False)
    class Bar(Foo):
        c: int


    @dataclass(kw_only=False)
    class Cee(Bar):
        d: int


    @dataclass(kw_only=True)
    class Dee(Cee):
        ee: int


    Foo.__init__  #@
    Bar.__init__  #@
    Cee.__init__  #@
    Dee.__init__  #@
    """
    )

    foo_init: bases.UnboundMethod = next(foodef.infer())
    if PY310_PLUS:
        assert [a.name for a in foo_init.args.args] == ["self"]
        assert [a.name for a in foo_init.args.kwonlyargs] == ["a", "e"]
    else:
        assert [a.name for a in foo_init.args.args] == ["self", "a", "e"]
        assert [a.name for a in foo_init.args.kwonlyargs] == []

    bar_init: bases.UnboundMethod = next(bardef.infer())
    if PY310_PLUS:
        assert [a.name for a in bar_init.args.args] == ["self", "c"]
        assert [a.name for a in bar_init.args.kwonlyargs] == ["a", "e"]
    else:
        assert [a.name for a in bar_init.args.args] == ["self", "a", "e", "c"]
        assert [a.name for a in bar_init.args.kwonlyargs] == []

    cee_init: bases.UnboundMethod = next(cee.infer())
    if PY310_PLUS:
        assert [a.name for a in cee_init.args.args] == ["self", "c", "d"]
        assert [a.name for a in cee_init.args.kwonlyargs] == ["a", "e"]
    else:
        assert [a.name for a in cee_init.args.args] == ["self", "a", "e", "c", "d"]
        assert [a.name for a in cee_init.args.kwonlyargs] == []

    dee_init: bases.UnboundMethod = next(dee.infer())
    if PY310_PLUS:
        assert [a.name for a in dee_init.args.args] == ["self", "c", "d"]
        assert [a.name for a in dee_init.args.kwonlyargs] == ["a", "e", "ee"]
    else:
        assert [a.name for a in dee_init.args.args] == [
            "self",
            "a",
            "e",
            "c",
            "d",
            "ee",
        ]
        assert [a.name for a in dee_init.args.kwonlyargs] == []


def test_kw_only_in_field_call() -> None:
    """Test that keyword only fields get correctly put at the end of the __init__."""

    first, second, third = astroid.extract_node(
        """
    from dataclasses import dataclass, field

    @dataclass
    class Parent:
        p1: int = field(kw_only=True, default=0)

    @dataclass
    class Child(Parent):
        c1: str

    @dataclass(kw_only=True)
    class GrandChild(Child):
        p2: int = field(kw_only=False, default=1)
        p3: int = field(kw_only=True, default=2)

    Parent.__init__  #@
    Child.__init__ #@
    GrandChild.__init__ #@
    """
    )

    first_init: bases.UnboundMethod = next(first.infer())
    assert [a.name for a in first_init.args.args] == ["self"]
    assert [a.name for a in first_init.args.kwonlyargs] == ["p1"]
    assert [d.value for d in first_init.args.kw_defaults] == [0]

    second_init: bases.UnboundMethod = next(second.infer())
    assert [a.name for a in second_init.args.args] == ["self", "c1"]
    assert [a.name for a in second_init.args.kwonlyargs] == ["p1"]
    assert [d.value for d in second_init.args.kw_defaults] == [0]

    third_init: bases.UnboundMethod = next(third.infer())
    assert [a.name for a in third_init.args.args] == ["self", "c1", "p2"]
    assert [a.name for a in third_init.args.kwonlyargs] == ["p1", "p3"]
    assert [d.value for d in third_init.args.defaults] == [1]
    assert [d.value for d in third_init.args.kw_defaults] == [0, 2]


def test_dataclass_with_unknown_base() -> None:
    """Regression test for dataclasses with unknown base classes.

    Reported in https://github.com/pylint-dev/pylint/issues/7418
    """
    node = astroid.extract_node(
        """
    import dataclasses

    from unknown import Unknown


    @dataclasses.dataclass
    class MyDataclass(Unknown):
        pass

    MyDataclass()
    """
    )

    assert next(node.infer())


def test_dataclass_with_unknown_typing() -> None:
    """Regression test for dataclasses with unknown base classes.

    Reported in https://github.com/pylint-dev/pylint/issues/7422
    """
    node = astroid.extract_node(
        """
    from dataclasses import dataclass, InitVar


    @dataclass
    class TestClass:
        '''Test Class'''

        config: InitVar = None

    TestClass.__init__  #@
    """
    )

    init_def: bases.UnboundMethod = next(node.infer())
    assert [a.name for a in init_def.args.args] == ["self", "config"]


def test_dataclass_with_default_factory() -> None:
    """Regression test for dataclasses with default values.

    Reported in https://github.com/pylint-dev/pylint/issues/7425
    """
    bad_node, good_node = astroid.extract_node(
        """
    from dataclasses import dataclass
    from typing import Union

    @dataclass
    class BadExampleParentClass:
        xyz: Union[str, int]

    @dataclass
    class BadExampleClass(BadExampleParentClass):
        xyz: str = ""

    BadExampleClass.__init__  #@

    @dataclass
    class GoodExampleParentClass:
        xyz: str

    @dataclass
    class GoodExampleClass(GoodExampleParentClass):
        xyz: str = ""

    GoodExampleClass.__init__  #@
    """
    )

    bad_init: bases.UnboundMethod = next(bad_node.infer())
    assert bad_init.args.defaults
    assert [a.name for a in bad_init.args.args] == ["self", "xyz"]

    good_init: bases.UnboundMethod = next(good_node.infer())
    assert bad_init.args.defaults
    assert [a.name for a in good_init.args.args] == ["self", "xyz"]


def test_dataclass_with_multiple_inheritance() -> None:
    """Regression test for dataclasses with multiple inheritance.

    Reported in https://github.com/pylint-dev/pylint/issues/7427
    Reported in https://github.com/pylint-dev/pylint/issues/7434
    """
    first, second, overwritten, overwriting, mixed = astroid.extract_node(
        """
    from dataclasses import dataclass

    @dataclass
    class BaseParent:
        _abc: int = 1

    @dataclass
    class AnotherParent:
        ef: int = 2

    @dataclass
    class FirstChild(BaseParent, AnotherParent):
        ghi: int = 3

    @dataclass
    class ConvolutedParent(AnotherParent):
        '''Convoluted Parent'''

    @dataclass
    class SecondChild(BaseParent, ConvolutedParent):
        jkl: int = 4

    @dataclass
    class OverwritingParent:
        ef: str = "2"

    @dataclass
    class OverwrittenChild(OverwritingParent, AnotherParent):
        '''Overwritten Child'''

    @dataclass
    class OverwritingChild(BaseParent, AnotherParent):
        _abc: float = 1.0
        ef: float = 2.0

    class NotADataclassParent:
        ef: int = 2

    @dataclass
    class ChildWithMixedParents(BaseParent, NotADataclassParent):
        ghi: int = 3

    FirstChild.__init__  #@
    SecondChild.__init__  #@
    OverwrittenChild.__init__  #@
    OverwritingChild.__init__  #@
    ChildWithMixedParents.__init__  #@
    """
    )

    first_init: bases.UnboundMethod = next(first.infer())
    assert [a.name for a in first_init.args.args] == ["self", "ef", "_abc", "ghi"]
    assert [a.value for a in first_init.args.defaults] == [2, 1, 3]

    second_init: bases.UnboundMethod = next(second.infer())
    assert [a.name for a in second_init.args.args] == ["self", "ef", "_abc", "jkl"]
    assert [a.value for a in second_init.args.defaults] == [2, 1, 4]

    overwritten_init: bases.UnboundMethod = next(overwritten.infer())
    assert [a.name for a in overwritten_init.args.args] == ["self", "ef"]
    assert [a.value for a in overwritten_init.args.defaults] == ["2"]

    overwriting_init: bases.UnboundMethod = next(overwriting.infer())
    assert [a.name for a in overwriting_init.args.args] == ["self", "ef", "_abc"]
    assert [a.value for a in overwriting_init.args.defaults] == [2.0, 1.0]

    mixed_init: bases.UnboundMethod = next(mixed.infer())
    assert [a.name for a in mixed_init.args.args] == ["self", "_abc", "ghi"]
    assert [a.value for a in mixed_init.args.defaults] == [1, 3]

    first = astroid.extract_node(
        """
    from dataclasses import dataclass

    @dataclass
    class BaseParent:
        required: bool

    @dataclass
    class FirstChild(BaseParent):
        ...

    @dataclass
    class SecondChild(BaseParent):
        optional: bool = False

    @dataclass
    class GrandChild(FirstChild, SecondChild):
        ...

    GrandChild.__init__  #@
    """
    )

    first_init: bases.UnboundMethod = next(first.infer())
    assert [a.name for a in first_init.args.args] == ["self", "required", "optional"]
    assert [a.value for a in first_init.args.defaults] == [False]


@pytest.mark.xfail(reason="Transforms returning Uninferable isn't supported.")
def test_dataclass_non_default_argument_after_default() -> None:
    """Test that a non-default argument after a default argument is not allowed.

    This should succeed, but the dataclass brain is a transform
    which currently can't return an Uninferable correctly. Therefore, we can't
    set the dataclass ClassDef node to be Uninferable currently.
    Eventually it can be merged into test_dataclass_with_multiple_inheritance.
    """

    impossible = astroid.extract_node(
        """
    from dataclasses import dataclass

    @dataclass
    class BaseParent:
        required: bool

    @dataclass
    class FirstChild(BaseParent):
        ...

    @dataclass
    class SecondChild(BaseParent):
        optional: bool = False

    @dataclass
    class ThirdChild:
        other: bool = False

    @dataclass
    class ImpossibleGrandChild(FirstChild, SecondChild, ThirdChild):
        ...

    ImpossibleGrandChild() #@
    """
    )

    assert next(impossible.infer()) is Uninferable


def test_dataclass_with_field_init_is_false() -> None:
    """When init=False it shouldn't end up in the __init__."""
    first, second, second_child, third_child, third = astroid.extract_node(
        """
    from dataclasses import dataclass, field


    @dataclass
    class First:
        a: int

    @dataclass
    class Second(First):
        a: int = field(init=False, default=1)

    @dataclass
    class SecondChild(Second):
        a: float

    @dataclass
    class ThirdChild(SecondChild):
        a: str

    @dataclass
    class Third(First):
        a: str

    First.__init__  #@
    Second.__init__  #@
    SecondChild.__init__  #@
    ThirdChild.__init__  #@
    Third.__init__  #@
    """
    )

    first_init: bases.UnboundMethod = next(first.infer())
    assert [a.name for a in first_init.args.args] == ["self", "a"]
    assert [a.value for a in first_init.args.defaults] == []

    second_init: bases.UnboundMethod = next(second.infer())
    assert [a.name for a in second_init.args.args] == ["self"]
    assert [a.value for a in second_init.args.defaults] == []

    second_child_init: bases.UnboundMethod = next(second_child.infer())
    assert [a.name for a in second_child_init.args.args] == ["self", "a"]
    assert [a.value for a in second_child_init.args.defaults] == [1]

    third_child_init: bases.UnboundMethod = next(third_child.infer())
    assert [a.name for a in third_child_init.args.args] == ["self", "a"]
    assert [a.value for a in third_child_init.args.defaults] == [1]

    third_init: bases.UnboundMethod = next(third.infer())
    assert [a.name for a in third_init.args.args] == ["self", "a"]
    assert [a.value for a in third_init.args.defaults] == []


def test_dataclass_inits_of_non_dataclasses() -> None:
    """Regression test for __init__ mangling for non dataclasses.

    Regression test against changes tested in test_dataclass_with_multiple_inheritance
    """
    first, second, third = astroid.extract_node(
        """
    from dataclasses import dataclass

    @dataclass
    class DataclassParent:
        _abc: int = 1


    class NotADataclassParent:
        ef: int = 2


    class FirstChild(DataclassParent, NotADataclassParent):
        ghi: int = 3


    class SecondChild(DataclassParent, NotADataclassParent):
        ghi: int = 3

        def __init__(self, ef: int = 3):
            self.ef = ef


    class ThirdChild(NotADataclassParent, DataclassParent):
        ghi: int = 3

        def __init__(self, ef: int = 3):
            self.ef = ef

    FirstChild.__init__  #@
    SecondChild.__init__  #@
    ThirdChild.__init__  #@
    """
    )

    first_init: bases.UnboundMethod = next(first.infer())
    assert [a.name for a in first_init.args.args] == ["self", "_abc"]
    assert [a.value for a in first_init.args.defaults] == [1]

    second_init: bases.UnboundMethod = next(second.infer())
    assert [a.name for a in second_init.args.args] == ["self", "ef"]
    assert [a.value for a in second_init.args.defaults] == [3]

    third_init: bases.UnboundMethod = next(third.infer())
    assert [a.name for a in third_init.args.args] == ["self", "ef"]
    assert [a.value for a in third_init.args.defaults] == [3]


def test_dataclass_with_properties() -> None:
    """Tests for __init__ creation for dataclasses that use properties."""
    first, second, third = astroid.extract_node(
        """
    from dataclasses import dataclass

    @dataclass
    class Dataclass:
        attr: int

        @property
        def attr(self) -> int:
            return 1

        @attr.setter
        def attr(self, value: int) -> None:
            pass

    class ParentOne(Dataclass):
        '''Docstring'''

    @dataclass
    class ParentTwo(Dataclass):
        '''Docstring'''

    Dataclass.__init__  #@
    ParentOne.__init__  #@
    ParentTwo.__init__  #@
    """
    )

    first_init: bases.UnboundMethod = next(first.infer())
    assert [a.name for a in first_init.args.args] == ["self", "attr"]
    assert [a.value for a in first_init.args.defaults] == [1]

    second_init: bases.UnboundMethod = next(second.infer())
    assert [a.name for a in second_init.args.args] == ["self", "attr"]
    assert [a.value for a in second_init.args.defaults] == [1]

    third_init: bases.UnboundMethod = next(third.infer())
    assert [a.name for a in third_init.args.args] == ["self", "attr"]
    assert [a.value for a in third_init.args.defaults] == [1]

    fourth = astroid.extract_node(
        """
    from dataclasses import dataclass

    @dataclass
    class Dataclass:
        other_attr: str
        attr: str

        @property
        def attr(self) -> str:
            return self.other_attr[-1]

        @attr.setter
        def attr(self, value: int) -> None:
            pass

    Dataclass.__init__  #@
    """
    )

    fourth_init: bases.UnboundMethod = next(fourth.infer())
    assert [a.name for a in fourth_init.args.args] == ["self", "other_attr", "attr"]
    assert [a.name for a in fourth_init.args.defaults] == ["Uninferable"]