Debian Codegraph @

tests/test_ext_marshmallow_common.py

raw
1 import pytest
2 from marshmallow import Schema, fields
3
4 from apispec.ext.marshmallow.common import (
5 get_fields,
6 get_unique_schema_name,
7 make_schema_key,
8 )
9
10 from .schemas import PetSchema, SampleSchema
11
12
13 class TestMakeSchemaKey:
14 def test_raise_if_schema_class_passed(self):
15 with pytest.raises(TypeError, match="based on a Schema instance"):
16 make_schema_key(PetSchema)
17
18 def test_same_schemas_instances_equal(self):
19 assert make_schema_key(PetSchema()) == make_schema_key(PetSchema())
20
21 @pytest.mark.parametrize("structure", (list, set))
22 def test_same_schemas_instances_unhashable_modifiers_equal(self, structure):
23 modifier = [str(i) for i in range(1000)]
24 assert make_schema_key(
25 PetSchema(load_only=structure(modifier))
26 ) == make_schema_key(PetSchema(load_only=structure(modifier[::-1])))
27
28 def test_different_schemas_not_equal(self):
29 assert make_schema_key(PetSchema()) != make_schema_key(SampleSchema())
30
31 def test_instances_with_different_modifiers_not_equal(self):
32 assert make_schema_key(PetSchema()) != make_schema_key(PetSchema(partial=True))
33
34
35 class TestUniqueName:
36 def test_unique_name(self, spec):
37 properties = {
38 "id": {"type": "integer", "format": "int64"},
39 "name": {"type": "string", "example": "doggie"},
40 }
41
42 name = get_unique_schema_name(spec.components, "Pet")
43 assert name == "Pet"
44
45 spec.components.schema("Pet", properties=properties)
46 with pytest.warns(
47 UserWarning, match="Multiple schemas resolved to the name Pet"
48 ):
49 name_1 = get_unique_schema_name(spec.components, "Pet")
50 assert name_1 == "Pet1"
51
52 spec.components.schema("Pet1", properties=properties)
53 with pytest.warns(
54 UserWarning, match="Multiple schemas resolved to the name Pet"
55 ):
56 name_2 = get_unique_schema_name(spec.components, "Pet")
57 assert name_2 == "Pet2"
58
59
60 class TestGetFields:
61 @pytest.mark.parametrize("exclude_type", (tuple, list))
62 @pytest.mark.parametrize("dump_only_type", (tuple, list))
63 def test_get_fields_meta_exclude_dump_only_as_list_and_tuple(
64 self, exclude_type, dump_only_type
65 ):
66 class ExcludeSchema(Schema):
67 field1 = fields.Int()
68 field2 = fields.Int()
69 field3 = fields.Int()
70 field4 = fields.Int()
71 field5 = fields.Int()
72
73 class Meta:
74 exclude = exclude_type(("field1", "field2"))
75 dump_only = dump_only_type(("field3", "field4"))
76
77 assert list(get_fields(ExcludeSchema).keys()) == ["field3", "field4", "field5"]
78 assert list(get_fields(ExcludeSchema, exclude_dump_only=True).keys()) == [
79 "field5"
80 ]
81
82 # regression test for https://github.com/marshmallow-code/apispec/issues/673
83 def test_schema_with_field_named_fields(self):
84 class TestSchema(Schema):
85 fields = fields.Int()
86
87 schema_fields = get_fields(TestSchema)
88 assert list(schema_fields.keys()) == ["fields"]
89 assert isinstance(schema_fields["fields"], fields.Int)