Debian Codegraph @

tests/test_ext_marshmallow_openapi.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import importlib.metadata
2 from datetime import datetime
3
4 import pytest
5 from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate
6 from packaging.version import Version
7
8 from apispec import APISpec, exceptions
9 from apispec.ext.marshmallow import MarshmallowPlugin, OpenAPIConverter
10
11 from .schemas import CustomList, CustomStringField
12 from .utils import build_ref, get_schemas, validate_spec
13
14 MA_VERSION = Version(importlib.metadata.version("marshmallow"))
15
16
17 class TestMarshmallowFieldToOpenAPI:
18 def test_fields_with_load_default_load(self, openapi):
19 class MySchema(Schema):
20 field = fields.Str(dump_default="foo", load_default="bar")
21
22 res = openapi.schema2parameters(MySchema, location="query")
23 if openapi.openapi_version.major < 3:
24 assert res[0]["default"] == "bar"
25 else:
26 assert res[0]["schema"]["default"] == "bar"
27
28 # json/body is invalid for OpenAPI 3
29 @pytest.mark.parametrize("openapi", ("2.0",), indirect=True)
30 def test_fields_default_location_mapping_if_schema_many(self, openapi):
31 class ExampleSchema(Schema):
32 id = fields.Int()
33
34 schema = ExampleSchema(many=True)
35 res = openapi.schema2parameters(schema=schema, location="json")
36 assert res[0]["in"] == "body"
37
38 def test_fields_with_dump_only(self, openapi):
39 class UserSchema(Schema):
40 name = fields.Str(dump_only=True)
41
42 res = openapi.schema2parameters(schema=UserSchema(), location="query")
43 assert len(res) == 0
44
45 class UserSchema2(Schema):
46 name = fields.Str()
47
48 class Meta:
49 dump_only = ("name",)
50
51 res = openapi.schema2parameters(schema=UserSchema2(), location="query")
52 assert len(res) == 0
53
54
55 class TestMarshmallowSchemaToModelDefinition:
56 def test_schema2jsonschema_with_explicit_fields(self, openapi):
57 class UserSchema(Schema):
58 _id = fields.Int()
59 email = fields.Email(metadata={"description": "email address of the user"})
60 name = fields.Str()
61
62 class Meta:
63 title = "User"
64
65 res = openapi.schema2jsonschema(UserSchema)
66 assert res["title"] == "User"
67 assert res["type"] == "object"
68 props = res["properties"]
69 assert props["_id"]["type"] == "integer"
70 assert props["email"]["type"] == "string"
71 assert props["email"]["format"] == "email"
72 assert props["email"]["description"] == "email address of the user"
73
74 def test_schema2jsonschema_override_name(self, openapi):
75 class ExampleSchema(Schema):
76 _id = fields.Int(data_key="id")
77 _global = fields.Int(data_key="global")
78
79 class Meta:
80 exclude = ("_global",)
81
82 res = openapi.schema2jsonschema(ExampleSchema)
83 assert res["type"] == "object"
84 props = res["properties"]
85 # `_id` renamed to `id`
86 assert "_id" not in props and props["id"]["type"] == "integer"
87 # `_global` excluded correctly
88 assert "_global" not in props and "global" not in props
89
90 def test_required_fields(self, openapi):
91 class BandSchema(Schema):
92 drummer = fields.Str(required=True)
93 bassist = fields.Str()
94
95 res = openapi.schema2jsonschema(BandSchema)
96 assert res["required"] == ["drummer"]
97
98 def test_partial(self, openapi):
99 class BandSchema(Schema):
100 drummer = fields.Str(required=True)
101 bassist = fields.Str(required=True)
102
103 res = openapi.schema2jsonschema(BandSchema(partial=True))
104 assert "required" not in res
105
106 res = openapi.schema2jsonschema(BandSchema(partial=("drummer",)))
107 assert res["required"] == ["bassist"]
108
109 def test_no_required_fields(self, openapi):
110 class BandSchema(Schema):
111 drummer = fields.Str()
112 bassist = fields.Str()
113
114 res = openapi.schema2jsonschema(BandSchema)
115 assert "required" not in res
116
117 def test_title_and_description_may_be_added(self, openapi):
118 class UserSchema(Schema):
119 class Meta:
120 title = "User"
121 description = "A registered user"
122
123 res = openapi.schema2jsonschema(UserSchema)
124 assert res["description"] == "A registered user"
125 assert res["title"] == "User"
126
127 def test_excluded_fields(self, openapi):
128 class WhiteStripesSchema(Schema):
129 class Meta:
130 exclude = ("bassist",)
131
132 guitarist = fields.Str()
133 drummer = fields.Str()
134 bassist = fields.Str()
135
136 res = openapi.schema2jsonschema(WhiteStripesSchema)
137 assert set(res["properties"].keys()) == {"guitarist", "drummer"}
138
139 def test_unknown_values_default_disallow(self, openapi):
140 class UnknownDefaultSchema(Schema):
141 first = fields.Str()
142
143 res = openapi.schema2jsonschema(UnknownDefaultSchema)
144 assert res["additionalProperties"] is False
145
146 def test_unknown_values_disallow(self, openapi):
147 class UnknownRaiseSchema(Schema):
148 class Meta:
149 unknown = RAISE
150
151 first = fields.Str()
152
153 res = openapi.schema2jsonschema(UnknownRaiseSchema)
154 assert res["additionalProperties"] is False
155
156 def test_unknown_values_allow(self, openapi):
157 class UnknownIncludeSchema(Schema):
158 class Meta:
159 unknown = INCLUDE
160
161 first = fields.Str()
162
163 res = openapi.schema2jsonschema(UnknownIncludeSchema)
164 assert res["additionalProperties"] is True
165
166 def test_unknown_values_ignore(self, openapi):
167 class UnknownExcludeSchema(Schema):
168 class Meta:
169 unknown = EXCLUDE
170
171 first = fields.Str()
172
173 res = openapi.schema2jsonschema(UnknownExcludeSchema)
174 assert "additionalProperties" not in res
175
176 @pytest.mark.parametrize("meta_unknown", (RAISE, INCLUDE, EXCLUDE, None))
177 @pytest.mark.parametrize(
178 "instance_unknown,expected", ((RAISE, False), (INCLUDE, True), (EXCLUDE, None))
179 )
180 def test_unknown_values_instance_override_meta(
181 self, openapi, instance_unknown, expected, meta_unknown
182 ):
183 class UnknownSchema(Schema):
184 if meta_unknown is not None:
185
186 class Meta:
187 unknown = meta_unknown
188
189 first = fields.Str()
190
191 res = openapi.schema2jsonschema(UnknownSchema(unknown=instance_unknown))
192 if expected is None:
193 assert "additionalProperties" not in res
194 else:
195 assert res["additionalProperties"] is expected
196
197 @pytest.mark.skipif(
198 MA_VERSION.major >= 4, reason="marshmallow 4 drop inferred fields"
199 )
200 def test_only_explicitly_declared_fields_are_translated(self, openapi):
201 class UserSchema(Schema):
202 _id = fields.Int()
203
204 class Meta:
205 title = "User"
206 fields = ("_id", "email")
207
208 with pytest.warns(
209 UserWarning,
210 match="Only explicitly-declared fields will be included in the Schema Object.",
211 ):
212 res = openapi.schema2jsonschema(UserSchema)
213 assert res["type"] == "object"
214 props = res["properties"]
215 assert "_id" in props
216 assert "email" not in props
217
218 def test_observed_field_name_for_required_field(self, openapi):
219 fields_dict = {"user_id": fields.Int(data_key="id", required=True)}
220 res = openapi.fields2jsonschema(fields_dict)
221 assert res["required"] == ["id"]
222
223 @pytest.mark.parametrize("many", (True, False))
224 def test_schema_instance_inspection(self, openapi, many):
225 class UserSchema(Schema):
226 _id = fields.Int()
227
228 res = openapi.schema2jsonschema(UserSchema(many=many))
229 assert res["type"] == "object"
230 props = res["properties"]
231 assert "_id" in props
232
233 def test_raises_error_if_no_declared_fields(self, openapi):
234 class NotASchema:
235 pass
236
237 expected_error = (
238 f"{NotASchema!r} is neither a Schema class nor a Schema instance."
239 )
240 with pytest.raises(ValueError, match=expected_error):
241 openapi.schema2jsonschema(NotASchema)
242
243
244 class TestMarshmallowSchemaToParameters:
245 def test_custom_properties_for_custom_fields(self, spec_fixture):
246 class DelimitedList(fields.List):
247 """Delimited list field"""
248
249 def delimited_list2param(self, field: fields.Field, **kwargs) -> dict:
250 ret: dict = {}
251 if isinstance(field, DelimitedList):
252 if self.openapi_version.major < 3:
253 ret["collectionFormat"] = "csv"
254 else:
255 ret["explode"] = False
256 ret["style"] = "form"
257 return ret
258
259 spec_fixture.marshmallow_plugin.converter.add_parameter_attribute_function(
260 delimited_list2param
261 )
262
263 class MySchema(Schema):
264 delimited_list = DelimitedList(fields.Int)
265
266 param = spec_fixture.marshmallow_plugin.converter.schema2parameters(
267 MySchema(), location="query"
268 )[0]
269
270 if spec_fixture.openapi.openapi_version.major < 3:
271 assert param["collectionFormat"] == "csv"
272 else:
273 assert param["explode"] is False
274 assert param["style"] == "form"
275
276 def test_field_required(self, openapi):
277 field = fields.Str(required=True)
278 res = openapi._field2parameter(field, name="field", location="query")
279 assert res["required"] is True
280
281 def test_field_deprecated(self, openapi):
282 field = fields.Str(metadata={"deprecated": True})
283 res = openapi._field2parameter(field, name="field", location="query")
284 assert res["deprecated"] is True
285
286 def test_schema_partial(self, openapi):
287 class UserSchema(Schema):
288 field = fields.Str(required=True)
289
290 res_nodump = openapi.schema2parameters(
291 UserSchema(partial=True), location="query"
292 )
293
294 param = res_nodump[0]
295 assert param["required"] is False
296
297 def test_schema_partial_list(self, openapi):
298 class UserSchema(Schema):
299 field = fields.Str(required=True)
300 partial_field = fields.Str(required=True)
301
302 res_nodump = openapi.schema2parameters(
303 UserSchema(partial=("partial_field",)), location="query"
304 )
305
306 param = next(p for p in res_nodump if p["name"] == "field")
307 assert param["required"] is True
308 param = next(p for p in res_nodump if p["name"] == "partial_field")
309 assert param["required"] is False
310
311 @pytest.mark.parametrize("ListClass", [fields.List, CustomList])
312 def test_field_list(self, ListClass, openapi):
313 field = ListClass(fields.Str)
314 res = openapi._field2parameter(field, name="field", location="query")
315 assert res["in"] == "query"
316 if openapi.openapi_version.major < 3:
317 assert res["type"] == "array"
318 assert res["items"]["type"] == "string"
319 assert res["collectionFormat"] == "multi"
320 else:
321 assert res["schema"]["type"] == "array"
322 assert res["schema"]["items"]["type"] == "string"
323 assert res["style"] == "form"
324 assert res["explode"] is True
325
326 # json/body is invalid for OpenAPI 3
327 @pytest.mark.parametrize("openapi", ("2.0",), indirect=True)
328 def test_schema_body(self, openapi):
329 class UserSchema(Schema):
330 name = fields.Str()
331 email = fields.Email()
332
333 res = openapi.schema2parameters(UserSchema, location="body")
334 assert len(res) == 1
335 param = res[0]
336 assert param["in"] == "body"
337 assert param["schema"] == {"$ref": "#/definitions/User"}
338
339 # json/body is invalid for OpenAPI 3
340 @pytest.mark.parametrize("openapi", ("2.0",), indirect=True)
341 def test_schema_body_with_dump_only(self, openapi):
342 class UserSchema(Schema):
343 name = fields.Str()
344 email = fields.Email(dump_only=True)
345
346 res_nodump = openapi.schema2parameters(UserSchema, location="body")
347 assert len(res_nodump) == 1
348 param = res_nodump[0]
349 assert param["in"] == "body"
350 assert param["schema"] == build_ref(openapi.spec, "schema", "User")
351
352 # json/body is invalid for OpenAPI 3
353 @pytest.mark.parametrize("openapi", ("2.0",), indirect=True)
354 def test_schema_body_many(self, openapi):
355 class UserSchema(Schema):
356 name = fields.Str()
357 email = fields.Email()
358
359 res = openapi.schema2parameters(UserSchema(many=True), location="body")
360 assert len(res) == 1
361 param = res[0]
362 assert param["in"] == "body"
363 assert param["schema"]["type"] == "array"
364 assert param["schema"]["items"] == {"$ref": "#/definitions/User"}
365
366 def test_schema_query(self, openapi):
367 class UserSchema(Schema):
368 name = fields.Str()
369 email = fields.Email()
370
371 res = openapi.schema2parameters(UserSchema, location="query")
372 assert len(res) == 2
373 res.sort(key=lambda param: param["name"])
374 assert res[0]["name"] == "email"
375 assert res[0]["in"] == "query"
376 assert res[1]["name"] == "name"
377 assert res[1]["in"] == "query"
378
379 def test_schema_query_instance(self, openapi):
380 class UserSchema(Schema):
381 name = fields.Str()
382 email = fields.Email()
383
384 res = openapi.schema2parameters(UserSchema(), location="query")
385 assert len(res) == 2
386 res.sort(key=lambda param: param["name"])
387 assert res[0]["name"] == "email"
388 assert res[0]["in"] == "query"
389 assert res[1]["name"] == "name"
390 assert res[1]["in"] == "query"
391
392 def test_schema_query_instance_many_should_raise_exception(self, openapi):
393 class UserSchema(Schema):
394 name = fields.Str()
395 email = fields.Email()
396
397 with pytest.raises(AssertionError):
398 openapi.schema2parameters(UserSchema(many=True), location="query")
399
400 def test_fields_query(self, openapi):
401 class MySchema(Schema):
402 name = fields.Str()
403 email = fields.Email()
404
405 res = openapi.schema2parameters(MySchema, location="query")
406 assert len(res) == 2
407 res.sort(key=lambda param: param["name"])
408 assert res[0]["name"] == "email"
409 assert res[0]["in"] == "query"
410 assert res[1]["name"] == "name"
411 assert res[1]["in"] == "query"
412
413 def test_raises_error_if_not_a_schema(self, openapi):
414 class NotASchema:
415 pass
416
417 expected_error = (
418 f"{NotASchema!r} is neither a Schema class nor a Schema instance."
419 )
420 with pytest.raises(ValueError, match=expected_error):
421 openapi.schema2jsonschema(NotASchema)
422
423
424 class CategorySchema(Schema):
425 id = fields.Int()
426 name = fields.Str(required=True)
427 breed = fields.Str(dump_only=True)
428
429
430 class PageSchema(Schema):
431 offset = fields.Int()
432 limit = fields.Int()
433
434
435 class PetSchema(Schema):
436 category = fields.Nested(CategorySchema, many=True)
437 name = fields.Str()
438
439
440 class TestNesting:
441 def test_schema2jsonschema_with_nested_fields(self, spec_fixture):
442 res = spec_fixture.openapi.schema2jsonschema(PetSchema)
443 props = res["properties"]
444
445 assert props["category"]["items"] == build_ref(
446 spec_fixture.spec, "schema", "Category"
447 )
448
449 @pytest.mark.parametrize("modifier", ("only", "exclude"))
450 def test_schema2jsonschema_with_nested_fields_only_exclude(
451 self, spec_fixture, modifier
452 ):
453 class Child(Schema):
454 i = fields.Int()
455 j = fields.Int()
456
457 class Parent(Schema):
458 child = fields.Nested(Child, **{modifier: ("i",)})
459
460 spec_fixture.openapi.schema2jsonschema(Parent)
461 props = get_schemas(spec_fixture.spec)["Child"]["properties"]
462 assert ("i" in props) == (modifier == "only")
463 assert ("j" not in props) == (modifier == "only")
464
465 def test_schema2jsonschema_with_plucked_field(self, spec_fixture):
466 class PetSchema(Schema):
467 breed = fields.Pluck(CategorySchema, "breed")
468
469 category_schema = spec_fixture.openapi.schema2jsonschema(CategorySchema)
470 pet_schema = spec_fixture.openapi.schema2jsonschema(PetSchema)
471 assert (
472 pet_schema["properties"]["breed"] == category_schema["properties"]["breed"]
473 )
474
475 def test_schema2jsonschema_with_nested_fields_with_adhoc_changes(
476 self, spec_fixture
477 ):
478 category_schema = CategorySchema()
479 category_schema.fields["id"].required = True
480
481 class PetSchema(Schema):
482 category = fields.Nested(category_schema, many=True)
483 name = fields.Str()
484
485 spec_fixture.spec.components.schema("Pet", schema=PetSchema)
486 props = get_schemas(spec_fixture.spec)
487
488 assert props["Category"] == spec_fixture.openapi.schema2jsonschema(
489 category_schema
490 )
491 assert set(props["Category"]["required"]) == {"id", "name"}
492
493 props["Category"]["required"] = ["name"]
494 assert props["Category"] == spec_fixture.openapi.schema2jsonschema(
495 CategorySchema
496 )
497
498 def test_schema2jsonschema_with_plucked_fields_with_adhoc_changes(
499 self, spec_fixture
500 ):
501 category_schema = CategorySchema()
502 category_schema.fields["breed"].dump_only = True
503
504 class PetSchema(Schema):
505 breed = fields.Pluck(category_schema, "breed", many=True)
506
507 spec_fixture.spec.components.schema("Pet", schema=PetSchema)
508 props = get_schemas(spec_fixture.spec)["Pet"]["properties"]
509
510 assert props["breed"]["items"]["readOnly"] is True
511
512 def test_schema2jsonschema_with_nested_excluded_fields(self, spec):
513 category_schema = CategorySchema(exclude=("breed",))
514
515 class PetSchema(Schema):
516 category = fields.Nested(category_schema)
517
518 spec.components.schema("Pet", schema=PetSchema)
519
520 category_props = get_schemas(spec)["Category"]["properties"]
521 assert "breed" not in category_props
522
523
524 def test_openapi_tools_validate_v2():
525 ma_plugin = MarshmallowPlugin()
526 spec = APISpec(
527 title="Pets", version="0.1", plugins=(ma_plugin,), openapi_version="2.0"
528 )
529 openapi = ma_plugin.converter
530 assert openapi is not None
531
532 spec.components.schema("Category", schema=CategorySchema)
533 spec.components.schema("Pet", {"discriminator": "name"}, schema=PetSchema)
534
535 spec.path(
536 view=None,
537 path="/category/{category_id}",
538 operations={
539 "get": {
540 "parameters": [
541 {"name": "q", "in": "query", "type": "string"},
542 {
543 "name": "category_id",
544 "in": "path",
545 "required": True,
546 "type": "string",
547 },
548 openapi._field2parameter(
549 field=fields.List(
550 fields.Str(),
551 validate=validate.OneOf(["freddie", "roger"]),
552 ),
553 location="query",
554 name="body",
555 ),
556 ]
557 + openapi.schema2parameters(PageSchema, location="query"),
558 "responses": {200: {"schema": PetSchema, "description": "A pet"}},
559 },
560 "post": {
561 "parameters": (
562 [
563 {
564 "name": "category_id",
565 "in": "path",
566 "required": True,
567 "type": "string",
568 }
569 ]
570 + openapi.schema2parameters(CategorySchema, location="body")
571 ),
572 "responses": {201: {"schema": PetSchema, "description": "A pet"}},
573 },
574 },
575 )
576 try:
577 validate_spec(spec)
578 except exceptions.OpenAPIError as error:
579 pytest.fail(str(error))
580
581
582 def test_openapi_tools_validate_v3():
583 ma_plugin = MarshmallowPlugin()
584 spec = APISpec(
585 title="Pets", version="0.1", plugins=(ma_plugin,), openapi_version="3.0.0"
586 )
587 openapi = ma_plugin.converter
588 assert openapi is not None
589
590 spec.components.schema("Category", schema=CategorySchema)
591 spec.components.schema("Pet", schema=PetSchema)
592
593 spec.path(
594 view=None,
595 path="/category/{category_id}",
596 operations={
597 "get": {
598 "parameters": [
599 {"name": "q", "in": "query", "schema": {"type": "string"}},
600 {
601 "name": "category_id",
602 "in": "path",
603 "required": True,
604 "schema": {"type": "string"},
605 },
606 openapi._field2parameter(
607 field=fields.List(
608 fields.Str(),
609 validate=validate.OneOf(["freddie", "roger"]),
610 ),
611 location="query",
612 name="body",
613 ),
614 ]
615 + openapi.schema2parameters(PageSchema, location="query"),
616 "responses": {
617 200: {
618 "description": "success",
619 "content": {"application/json": {"schema": PetSchema}},
620 }
621 },
622 },
623 "post": {
624 "parameters": (
625 [
626 {
627 "name": "category_id",
628 "in": "path",
629 "required": True,
630 "schema": {"type": "string"},
631 }
632 ]
633 ),
634 "requestBody": {
635 "content": {"application/json": {"schema": CategorySchema}}
636 },
637 "responses": {
638 201: {
639 "description": "created",
640 "content": {"application/json": {"schema": PetSchema}},
641 }
642 },
643 },
644 },
645 )
646 try:
647 validate_spec(spec)
648 except exceptions.OpenAPIError as error:
649 pytest.fail(str(error))
650
651
652 def test_openapi_converter_openapi_version_types():
653 spec = APISpec(title="Pets", version="0.1", openapi_version="2.0")
654 converter_with_version = OpenAPIConverter(Version("3.1"), None, spec)
655 converter_with_str_version = OpenAPIConverter("3.1", None, spec)
656 assert (
657 converter_with_version.openapi_version
658 == converter_with_str_version.openapi_version
659 )
660
661
662 class TestFieldValidation:
663 class ValidationSchema(Schema):
664 id = fields.Int(dump_only=True)
665 range = fields.Int(validate=validate.Range(min=1, max=10))
666 range_no_upper = fields.Float(validate=validate.Range(min=1))
667 multiple_ranges = fields.Int(
668 validate=[
669 validate.Range(min=1),
670 validate.Range(min=3),
671 validate.Range(max=10),
672 validate.Range(max=7),
673 ]
674 )
675 list_length = fields.List(fields.Str, validate=validate.Length(min=1, max=10))
676 custom_list_length = CustomList(
677 fields.Str, validate=validate.Length(min=1, max=10)
678 )
679 string_length = fields.Str(validate=validate.Length(min=1, max=10))
680 custom_field_length = CustomStringField(validate=validate.Length(min=1, max=10))
681 multiple_lengths = fields.Str(
682 validate=[
683 validate.Length(min=1),
684 validate.Length(min=3),
685 validate.Length(max=10),
686 validate.Length(max=7),
687 ]
688 )
689 equal_length = fields.Str(
690 validate=[validate.Length(equal=5), validate.Length(min=1, max=10)]
691 )
692 date_range = fields.DateTime(
693 validate=validate.Range(
694 min=datetime(1900, 1, 1),
695 )
696 )
697
698 @pytest.mark.parametrize(
699 ("field", "properties"),
700 [
701 ("range", {"minimum": 1, "maximum": 10}),
702 ("range_no_upper", {"minimum": 1}),
703 ("multiple_ranges", {"minimum": 3, "maximum": 7}),
704 ("list_length", {"minItems": 1, "maxItems": 10}),
705 ("custom_list_length", {"minItems": 1, "maxItems": 10}),
706 ("string_length", {"minLength": 1, "maxLength": 10}),
707 ("custom_field_length", {"minLength": 1, "maxLength": 10}),
708 ("multiple_lengths", {"minLength": 3, "maxLength": 7}),
709 ("equal_length", {"minLength": 5, "maxLength": 5}),
710 ("date_range", {"x-minimum": "1900-01-01T00:00:00"}),
711 ],
712 )
713 def test_properties(self, field, properties, spec):
714 spec.components.schema("Validation", schema=self.ValidationSchema)
715 result = get_schemas(spec)["Validation"]["properties"][field]
716
717 for attr, expected_value in properties.items():
718 assert attr in result
719 assert result[attr] == expected_value