File: test_json_schema.py

package info (click to toggle)
python-itemadapter 0.12.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 304 kB
  • sloc: python: 3,381; makefile: 4
file content (740 lines) | stat: -rw-r--r-- 22,169 bytes parent folder | download
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
from __future__ import annotations

import sys
import typing
import unittest
from collections.abc import Mapping, Sequence  # noqa: TC003
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional, Union

import pytest

from itemadapter._imports import pydantic
from itemadapter.adapter import AttrsAdapter, ItemAdapter, PydanticAdapter, ScrapyItemAdapter
from tests import (
    AttrsItem,
    AttrsItemJsonSchemaNested,
    DataClassItemJsonSchemaNested,
    PydanticModel,
    PydanticModelJsonSchemaNested,
    PydanticV1Model,
    PydanticV1ModelJsonSchemaNested,
    ScrapySubclassedItem,
    ScrapySubclassedItemJsonSchemaNested,
    SetList,
)

PYTHON_VERSION = sys.version_info[:2]


if ScrapySubclassedItem and AttrsItem:
    from scrapy import Field as ScrapyField
    from scrapy import Item as ScrapyItem

    class ScrapySubclassedItemCrossNested(ScrapyItem):
        nested: AttrsItemJsonSchemaNested = ScrapyField()


@dataclass
class Brand:
    name: str


@dataclass
class OptionalItemListNestedItem:
    is_nested: bool = True


@dataclass
class OptionalItemListItem:
    foo: Optional[list[OptionalItemListNestedItem]] = None


@dataclass
class RecursionItem:
    child: RecursionNestedItem
    sibling: RecursionItem


@dataclass
class RecursionNestedItem:
    parent: RecursionItem
    sibling: RecursionNestedItem


@dataclass
class SimpleItem:
    foo: str


class CustomMapping:  # noqa: PLW1641
    def __init__(self, data):
        self._data = dict(data)

    def __getitem__(self, key):
        return self._data[key]

    def __iter__(self):
        return iter(self._data)

    def __len__(self):
        return len(self._data)

    def __contains__(self, key):
        return key in self._data

    def keys(self):
        return self._data.keys()

    def items(self):
        return self._data.items()

    def values(self):
        return self._data.values()

    def get(self, key, default=None):
        return self._data.get(key, default)

    def __eq__(self, other):
        if isinstance(other, CustomMapping):
            return self._data == other._data
        if isinstance(other, dict):
            return self._data == other
        return NotImplemented

    def __ne__(self, other):
        eq = self.__eq__(other)
        if eq is NotImplemented:
            return NotImplemented
        return not eq


class SimpleEnum(Enum):
    foo = "foo"


if PydanticModel:

    class PydanticEnumModel(pydantic.BaseModel):
        enum: SimpleEnum


class JsonSchemaTestCase(unittest.TestCase):
    maxDiff = None

    @unittest.skipIf(not AttrsItem, "attrs module is not available")
    @unittest.skipIf(not PydanticModel, "pydantic module is not available")
    def test_attrs_pydantic_enum(self):
        """This test exists to ensure that we do not let the JSON Schema
        generation of Pydantic item classes generate nested $defs (which we
        don’t since we do not run Pydantic’s JSON Schema generation but our
        own)."""
        import attrs

        @attrs.define
        class TestAttrsItem:
            pydantic: PydanticEnumModel

        actual = ItemAdapter.get_json_schema(TestAttrsItem)
        expected = {
            "type": "object",
            "properties": {
                "pydantic": {
                    "type": "object",
                    "properties": {
                        "enum": {"enum": ["foo"], "type": "string"},
                    },
                    "required": ["enum"],
                }
            },
            "required": ["pydantic"],
            "additionalProperties": False,
        }
        self.assertEqual(actual, expected)

    @unittest.skipIf(not ScrapySubclassedItem, "scrapy module is not available")
    @unittest.skipIf(
        PYTHON_VERSION >= (3, 13), "It seems inspect can get the class code in Python 3.13+"
    )
    def test_unreachable_source(self):
        """Using inspect to get the item class source and find attribute
        docstrings is not always a possibility, e.g. when the item class is
        defined within a (test) method. In those cases, only the extraction of
        those docstrings should fail."""

        class ScrapySubclassedItemUnreachable(ScrapyItem):
            name: str = ScrapyField(json_schema_extra={"example": "Foo"})
            """Display name"""

        actual = ItemAdapter.get_json_schema(ScrapySubclassedItemUnreachable)
        expected = {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "example": "Foo",
                }
            },
            "required": ["name"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_recursion(self):
        actual = ItemAdapter.get_json_schema(RecursionItem)
        expected = {
            "type": "object",
            "properties": {
                "child": {
                    "type": "object",
                    "properties": {
                        "parent": {
                            "type": "object",
                        },
                        "sibling": {
                            "type": "object",
                        },
                    },
                    "required": ["parent", "sibling"],
                    "additionalProperties": False,
                },
                "sibling": {
                    "type": "object",
                },
            },
            "required": ["child", "sibling"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_nested_dict(self):
        @dataclass
        class TestItem:
            foo: dict

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {
                    "type": "object",
                },
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_optional_item_list(self):
        actual = ItemAdapter.get_json_schema(OptionalItemListItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {
                    "anyOf": [
                        {
                            "type": "null",
                        },
                        {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "is_nested": {
                                        "type": "boolean",
                                        "default": True,
                                    },
                                },
                                "additionalProperties": False,
                            },
                        },
                    ],
                    "default": None,
                },
            },
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_sequence_untyped(self):
        @dataclass
        class TestItem:
            foo: Sequence

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {
                    "type": "array",
                },
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_tuple_ellipsis(self):
        @dataclass
        class TestItem:
            foo: tuple[Any, ...]

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {
                    "type": "array",
                },
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_tuple_multiple_types(self):
        @dataclass
        class TestItem:
            foo: tuple[str, int, int]

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {
                    "type": "array",
                    "items": {"type": SetList(["string", "integer"])},
                },
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_union_single(self):
        @dataclass
        class TestItem:
            foo: Union[str]

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {"type": "string"},
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_custom_any_of(self):
        @dataclass
        class TestItem:
            foo: Union[str, SimpleItem] = field(
                metadata={"json_schema_extra": {"anyOf": []}},
            )

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {"anyOf": []},
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_set_untyped(self):
        @dataclass
        class TestItem:
            foo: set

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {"type": "array", "uniqueItems": True},
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_mapping_untyped(self):
        @dataclass
        class TestItem:
            foo: Mapping

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {"type": "object"},
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_custom_mapping(self):
        @dataclass
        class TestItem:
            foo: CustomMapping

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {"type": "object"},
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_item_without_attributes(self):
        @dataclass
        class TestItem:
            pass

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    def test_typing_sequence_untyped(self):
        @dataclass
        class TestItem:
            foo: typing.Sequence

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {
                    "type": "array",
                },
            },
            "additionalProperties": False,
            "required": ["foo"],
        }
        self.assertEqual(expected, actual)

    def test_custom_items(self):
        @dataclass
        class TestItem:
            foo: typing.Sequence = field(metadata={"json_schema_extra": {"items": {}}})

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {
                    "type": "array",
                    "items": {},
                },
            },
            "additionalProperties": False,
            "required": ["foo"],
        }
        self.assertEqual(expected, actual)

    @unittest.skipIf(not AttrsItem, "attrs module is not available")
    @unittest.skipIf(PYTHON_VERSION < (3, 10), "Modern optional annotations require Python 3.10+")
    def test_modern_optional_annotations(self):
        import attr

        @attr.define
        class Product:
            name: str
            """Product name"""

            brand: Brand | None
            in_stock: bool = True

        actual = ItemAdapter.get_json_schema(Product)
        expected = {
            "type": "object",
            "additionalProperties": False,
            "properties": {
                "name": {"type": "string", "description": "Product name"},
                "brand": {
                    "anyOf": [
                        {"type": "null"},
                        {
                            "type": "object",
                            "additionalProperties": False,
                            "properties": {"name": {"type": "string"}},
                            "required": ["name"],
                        },
                    ]
                },
                "in_stock": {"default": True, "type": "boolean"},
            },
            "required": ["name", "brand"],
        }
        self.assertEqual(expected, actual)

    def test_field_docstring_inheritance(self):
        """Test that field docstrings are inherited from parent classes."""

        @dataclass
        class ParentItem:
            foo: str
            """Parent item foo"""

        @dataclass
        class ChildItem(ParentItem):
            pass

        actual = ItemAdapter.get_json_schema(ChildItem)
        expected = {
            "type": "object",
            "properties": {
                "foo": {"type": "string", "description": "Parent item foo"},
            },
            "required": ["foo"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)


class CrossNestingTestCase(unittest.TestCase):
    """Test item nesting across different item types, with all supported types
    acting as parent or child in one test."""

    maxDiff = None

    @unittest.skipIf(not PydanticV1Model, "pydantic module is not available")
    def test_dataclass_pydantic1(self):
        @dataclass
        class TestItem:
            nested: PydanticV1ModelJsonSchemaNested

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                }
            },
            "required": ["nested"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    @unittest.skipIf(not PydanticModel, "pydantic module is not available")
    @unittest.skipIf(not AttrsItem, "attrs module is not available")
    def test_attrs_pydantic2(self):
        import attrs

        @attrs.define
        class TestItem:
            nested: PydanticModelJsonSchemaNested

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                }
            },
            "required": ["nested"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

        actual = AttrsAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {"nested": {}},
            "required": ["nested"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    @unittest.skipIf(not ScrapySubclassedItem, "scrapy module is not available")
    @unittest.skipIf(not AttrsItem, "attrs module is not available")
    def test_scrapy_attrs(self):
        actual = ItemAdapter.get_json_schema(ScrapySubclassedItemCrossNested)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                    "additionalProperties": False,
                }
            },
            "required": ["nested"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

        actual = ScrapyItemAdapter.get_json_schema(ScrapySubclassedItemCrossNested)
        expected = {
            "type": "object",
            "properties": {"nested": {}},
            "required": ["nested"],
            "additionalProperties": False,
        }
        self.assertEqual(expected, actual)

    @unittest.skipIf(not PydanticV1Model, "pydantic module is not available")
    @unittest.skipIf(not ScrapySubclassedItem, "scrapy module is not available")
    def test_pydantic1_scrapy(self):
        from . import pydantic_v1

        class TestItem(pydantic_v1.BaseModel):
            nested: ScrapySubclassedItemJsonSchemaNested

            class Config:
                arbitrary_types_allowed = True

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                    "additionalProperties": False,
                }
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)

        actual = PydanticAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                # Scrapy item classes implement the Mapping interface, so
                # they are correctly recognized as objects even when there is
                # no access to ScrapyItemAdapter.
                "nested": {"type": "object"}
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)

    @unittest.skipIf(not PydanticModel, "pydantic module is not available")
    def test_pydantic_dataclass(self):
        class TestItem(pydantic.BaseModel):
            nested: DataClassItemJsonSchemaNested

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                    "additionalProperties": False,
                },
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)

        actual = PydanticAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {},
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)

    @unittest.skipIf(not PydanticModel, "pydantic module is not available")
    @unittest.skipIf(not ScrapySubclassedItem, "scrapy module is not available")
    def test_pydantic_scrapy(self):
        class TestItem(pydantic.BaseModel):
            nested: ScrapySubclassedItemJsonSchemaNested

            model_config = {
                "arbitrary_types_allowed": True,
            }

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                    "additionalProperties": False,
                },
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)

        actual = PydanticAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {"type": "object"},
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)

    @unittest.skipIf(not PydanticModel, "pydantic module is not available")
    @pytest.mark.filterwarnings("ignore:Mixing V1 models and V2 models")
    def test_pydantics(self):
        class TestItem(pydantic.BaseModel):
            nested: PydanticV1ModelJsonSchemaNested

        actual = ItemAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                },
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)

        # Since PydanticAdapter is not version-specific, it works with both
        # Pydantic V1 and V2+ models.
        actual = PydanticAdapter.get_json_schema(TestItem)
        expected = {
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "is_nested": {"type": "boolean", "default": True},
                    },
                },
            },
            "required": ["nested"],
        }
        self.assertEqual(expected, actual)