Debian Codegraph @

tests/test_core.py

raw
1 import copy
2 from http import HTTPStatus
3
4 import pytest
5 import yaml
6
7 from apispec import APISpec, BasePlugin
8 from apispec.exceptions import (
9 APISpecError,
10 DuplicateComponentNameError,
11 DuplicateParameterError,
12 InvalidParameterError,
13 )
14
15 from .utils import (
16 build_ref,
17 get_examples,
18 get_headers,
19 get_links,
20 get_parameters,
21 get_paths,
22 get_responses,
23 get_schemas,
24 get_security_schemes,
25 )
26
27 description = "This is a sample Petstore server. You can find out more "
28 'about Swagger at <a href="http://swagger.wordnik.com">http://swagger.wordnik.com</a> '
29 "or on irc.freenode.net, #swagger. For this sample, you can use the api "
30 'key "special-key" to test the authorization filters'
31
32
33 class RefsSchemaTestMixin:
34 REFS_SCHEMA = {
35 "properties": {
36 "nested": "NestedSchema",
37 "deep_nested": {"properties": {"nested": "NestedSchema"}},
38 "nested_list": {"items": "DeepNestedSchema"},
39 "deep_nested_list": {
40 "items": {"properties": {"nested": "DeepNestedSchema"}}
41 },
42 "allof": {
43 "allOf": [
44 "AllOfSchema",
45 {"properties": {"nested": "AllOfSchema"}},
46 ]
47 },
48 "oneof": {
49 "oneOf": [
50 "OneOfSchema",
51 {"properties": {"nested": "OneOfSchema"}},
52 ]
53 },
54 "anyof": {
55 "anyOf": [
56 "AnyOfSchema",
57 {"properties": {"nested": "AnyOfSchema"}},
58 ]
59 },
60 "not": "NotSchema",
61 "deep_not": {"properties": {"nested": "DeepNotSchema"}},
62 }
63 }
64
65 @staticmethod
66 def assert_schema_refs(spec, schema):
67 props = schema["properties"]
68 assert props["nested"] == build_ref(spec, "schema", "NestedSchema")
69 assert props["deep_nested"]["properties"]["nested"] == build_ref(
70 spec, "schema", "NestedSchema"
71 )
72 assert props["nested_list"]["items"] == build_ref(
73 spec, "schema", "DeepNestedSchema"
74 )
75 assert props["deep_nested_list"]["items"]["properties"]["nested"] == build_ref(
76 spec, "schema", "DeepNestedSchema"
77 )
78 assert props["allof"]["allOf"][0] == build_ref(spec, "schema", "AllOfSchema")
79 assert props["allof"]["allOf"][1]["properties"]["nested"] == build_ref(
80 spec, "schema", "AllOfSchema"
81 )
82 assert props["oneof"]["oneOf"][0] == build_ref(spec, "schema", "OneOfSchema")
83 assert props["oneof"]["oneOf"][1]["properties"]["nested"] == build_ref(
84 spec, "schema", "OneOfSchema"
85 )
86 assert props["anyof"]["anyOf"][0] == build_ref(spec, "schema", "AnyOfSchema")
87 assert props["anyof"]["anyOf"][1]["properties"]["nested"] == build_ref(
88 spec, "schema", "AnyOfSchema"
89 )
90 assert props["not"] == build_ref(spec, "schema", "NotSchema")
91 assert props["deep_not"]["properties"]["nested"] == build_ref(
92 spec, "schema", "DeepNotSchema"
93 )
94
95
96 @pytest.fixture(params=("2.0", "3.0.0"))
97 def spec(request):
98 openapi_version = request.param
99 if openapi_version == "2.0":
100 security_kwargs = {"security": [{"apiKey": []}]}
101 else:
102 security_kwargs = {
103 "components": {
104 "securitySchemes": {
105 "bearerAuth": dict(type="http", scheme="bearer", bearerFormat="JWT")
106 },
107 "schemas": {
108 "ErrorResponse": {
109 "type": "object",
110 "properties": {
111 "ok": {
112 "type": "boolean",
113 "description": "status indicator",
114 "example": False,
115 }
116 },
117 "required": ["ok"],
118 }
119 },
120 }
121 }
122 return APISpec(
123 title="Swagger Petstore",
124 version="1.0.0",
125 openapi_version=openapi_version,
126 info={"description": description},
127 **security_kwargs,
128 )
129
130
131 class TestAPISpecInit:
132 def test_raises_wrong_apispec_version(self):
133 message = "Not a valid OpenAPI version number:"
134 with pytest.raises(APISpecError, match=message):
135 APISpec(
136 "Swagger Petstore",
137 version="1.0.0",
138 openapi_version="4.0", # 4.0 is not supported
139 info={"description": description},
140 security=[{"apiKey": []}],
141 )
142
143
144 class TestMetadata:
145 def test_openapi_metadata(self, spec):
146 metadata = spec.to_dict()
147 assert metadata["info"]["title"] == "Swagger Petstore"
148 assert metadata["info"]["version"] == "1.0.0"
149 assert metadata["info"]["description"] == description
150 if spec.openapi_version.major < 3:
151 assert metadata["swagger"] == str(spec.openapi_version)
152 assert metadata["security"] == [{"apiKey": []}]
153 else:
154 assert metadata["openapi"] == str(spec.openapi_version)
155 security_schemes = {
156 "bearerAuth": dict(type="http", scheme="bearer", bearerFormat="JWT")
157 }
158 assert metadata["components"]["securitySchemes"] == security_schemes
159 assert metadata["components"]["schemas"].get("ErrorResponse", False)
160 assert metadata["info"]["title"] == "Swagger Petstore"
161 assert metadata["info"]["version"] == "1.0.0"
162 assert metadata["info"]["description"] == description
163
164 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
165 def test_openapi_metadata_merge_v3(self, spec):
166 properties = {
167 "ok": {
168 "type": "boolean",
169 "description": "property description",
170 "example": True,
171 }
172 }
173 spec.components.schema(
174 "definition", {"properties": properties, "description": "description"}
175 )
176 metadata = spec.to_dict()
177 assert metadata["components"]["schemas"].get("ErrorResponse", False)
178 assert metadata["components"]["schemas"].get("definition", False)
179
180
181 class TestTags:
182 tag = {
183 "name": "MyTag",
184 "description": "This tag gathers all API endpoints which are mine.",
185 }
186
187 def test_tag(self, spec):
188 spec.tag(self.tag)
189 tags_json = spec.to_dict()["tags"]
190 assert self.tag in tags_json
191
192 def test_tag_is_chainable(self, spec):
193 spec.tag({"name": "tag1"}).tag({"name": "tag2"})
194 assert spec.to_dict()["tags"] == [{"name": "tag1"}, {"name": "tag2"}]
195
196
197 class TestComponents(RefsSchemaTestMixin):
198 properties = {
199 "id": {"type": "integer", "format": "int64"},
200 "name": {"type": "string", "example": "doggie"},
201 }
202
203 def test_schema(self, spec):
204 spec.components.schema("Pet", {"properties": self.properties})
205 schemas = get_schemas(spec)
206 assert "Pet" in schemas
207 assert schemas["Pet"]["properties"] == self.properties
208
209 def test_schema_is_chainable(self, spec):
210 spec.components.schema("Pet", {"properties": {}}).schema(
211 "Plant", {"properties": {}}
212 )
213 schemas = get_schemas(spec)
214 assert "Pet" in schemas
215 assert "Plant" in schemas
216
217 def test_schema_description(self, spec):
218 model_description = "An animal which lives with humans."
219 spec.components.schema(
220 "Pet", {"properties": self.properties, "description": model_description}
221 )
222 schemas = get_schemas(spec)
223 assert schemas["Pet"]["description"] == model_description
224
225 def test_schema_stores_enum(self, spec):
226 enum = ["name", "photoUrls"]
227 spec.components.schema("Pet", {"properties": self.properties, "enum": enum})
228 schemas = get_schemas(spec)
229 assert schemas["Pet"]["enum"] == enum
230
231 def test_schema_discriminator(self, spec):
232 spec.components.schema(
233 "Pet", {"properties": self.properties, "discriminator": "name"}
234 )
235 schemas = get_schemas(spec)
236 assert schemas["Pet"]["discriminator"] == "name"
237
238 def test_schema_duplicate_name(self, spec):
239 spec.components.schema("Pet", {"properties": self.properties})
240 with pytest.raises(
241 DuplicateComponentNameError,
242 match='Another schema with name "Pet" is already registered.',
243 ):
244 spec.components.schema("Pet", properties=self.properties)
245
246 def test_response(self, spec):
247 response = {"description": "Pet not found"}
248 spec.components.response("NotFound", response)
249 responses = get_responses(spec)
250 assert responses["NotFound"] == response
251
252 def test_response_is_chainable(self, spec):
253 spec.components.response("resp1").response("resp2")
254 responses = get_responses(spec)
255 assert "resp1" in responses
256 assert "resp2" in responses
257
258 def test_response_duplicate_name(self, spec):
259 spec.components.response("test_response")
260 with pytest.raises(
261 DuplicateComponentNameError,
262 match='Another response with name "test_response" is already registered.',
263 ):
264 spec.components.response("test_response")
265
266 def test_parameter(self, spec):
267 # Note: this is an OpenAPI v2 parameter header
268 # but is does the job for the test even for OpenAPI v3
269 parameter = {"format": "int64", "type": "integer"}
270 spec.components.parameter("PetId", "path", parameter)
271 params = get_parameters(spec)
272 assert params["PetId"] == {
273 "format": "int64",
274 "type": "integer",
275 "in": "path",
276 "name": "PetId",
277 "required": True,
278 }
279
280 def test_parameter_is_chainable(self, spec):
281 spec.components.parameter("param1", "path").parameter("param2", "path")
282 params = get_parameters(spec)
283 assert "param1" in params
284 assert "param2" in params
285
286 def test_parameter_duplicate_name(self, spec):
287 spec.components.parameter("test_parameter", "path")
288 with pytest.raises(
289 DuplicateComponentNameError,
290 match='Another parameter with name "test_parameter" is already registered.',
291 ):
292 spec.components.parameter("test_parameter", "path")
293
294 # Referenced headers are only supported in OAS 3.x
295 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
296 def test_header(self, spec):
297 header = {"schema": {"type": "string"}}
298 spec.components.header("test_header", header.copy())
299 headers = get_headers(spec)
300 assert headers["test_header"] == header
301
302 # Referenced headers are only supported in OAS 3.x
303 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
304 def test_header_is_chainable(self, spec):
305 header = {"schema": {"type": "string"}}
306 spec.components.header("header1", header).header("header2", header)
307 headers = get_headers(spec)
308 assert "header1" in headers
309 assert "header2" in headers
310
311 # Referenced headers are only supported in OAS 3.x
312 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
313 def test_header_duplicate_name(self, spec):
314 spec.components.header("test_header", {"schema": {"type": "string"}})
315 with pytest.raises(
316 DuplicateComponentNameError,
317 match='Another header with name "test_header" is already registered.',
318 ):
319 spec.components.header("test_header", {"schema": {"type": "integer"}})
320
321 # Referenced examples are only supported in OAS 3.x
322 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
323 def test_example(self, spec):
324 spec.components.example("test_example", {"value": {"a": "b"}})
325 examples = get_examples(spec)
326 assert examples["test_example"]["value"] == {"a": "b"}
327
328 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
329 def test_example_is_chainable(self, spec):
330 spec.components.example("test_example_1", {}).example("test_example_2", {})
331 examples = get_examples(spec)
332 assert "test_example_1" in examples
333 assert "test_example_2" in examples
334
335 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
336 def test_example_duplicate_name(self, spec):
337 spec.components.example("test_example", {})
338 with pytest.raises(
339 DuplicateComponentNameError,
340 match='Another example with name "test_example" is already registered.',
341 ):
342 spec.components.example("test_example", {})
343
344 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
345 def test_links(self, spec):
346 link = {
347 "operationRef": "#/paths/~1users~1{user_id}/get",
348 "parameters": {"user_id": "$response.body#/id"},
349 }
350 spec.components.link("GetUser", link)
351 links = get_links(spec)
352 assert "GetUser" in links
353 assert links["GetUser"] == link
354
355 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
356 def test_links_duplicate_name(self, spec):
357 link = {"operationRef": "#/paths/~1users/get"}
358 spec.components.link("GetUser", link)
359 with pytest.raises(APISpecError, match='Another link with name "GetUser"'):
360 spec.components.link("GetUser", link)
361
362 def test_security_scheme(self, spec):
363 sec_scheme = {"type": "apiKey", "in": "header", "name": "X-API-Key"}
364 spec.components.security_scheme("ApiKeyAuth", sec_scheme)
365 assert get_security_schemes(spec)["ApiKeyAuth"] == sec_scheme
366
367 def test_security_scheme_is_chainable(self, spec):
368 spec.components.security_scheme("sec_1", {}).security_scheme("sec_2", {})
369 security_schemes = get_security_schemes(spec)
370 assert "sec_1" in security_schemes
371 assert "sec_2" in security_schemes
372
373 def test_security_scheme_duplicate_name(self, spec):
374 sec_scheme_1 = {"type": "apiKey", "in": "header", "name": "X-API-Key"}
375 sec_scheme_2 = {"type": "apiKey", "in": "header", "name": "X-API-Key-2"}
376 spec.components.security_scheme("ApiKeyAuth", sec_scheme_1)
377 with pytest.raises(
378 DuplicateComponentNameError,
379 match='Another security scheme with name "ApiKeyAuth" is already registered.',
380 ):
381 spec.components.security_scheme("ApiKeyAuth", sec_scheme_2)
382
383 def test_to_yaml(self, spec):
384 enum = ["name", "photoUrls"]
385 spec.components.schema("Pet", properties=self.properties, enum=enum)
386 assert spec.to_dict() == yaml.safe_load(spec.to_yaml())
387
388 def test_components_can_be_accessed_by_plugin_in_init_spec(self):
389 class TestPlugin(BasePlugin):
390 def init_spec(self, spec):
391 spec.components.schema(
392 "TestSchema",
393 {"properties": {"key": {"type": "string"}}, "type": "object"},
394 )
395
396 spec = APISpec(
397 "Test API", version="0.0.1", openapi_version="2.0", plugins=[TestPlugin()]
398 )
399 assert get_schemas(spec) == {
400 "TestSchema": {"properties": {"key": {"type": "string"}}, "type": "object"}
401 }
402
403 def test_components_resolve_refs_in_schema(self, spec):
404 spec.components.schema("refs_schema", copy.deepcopy(self.REFS_SCHEMA))
405 self.assert_schema_refs(spec, get_schemas(spec)["refs_schema"])
406
407 def test_components_resolve_response_schema(self, spec):
408 schema = {"schema": "PetSchema"}
409 if spec.openapi_version.major >= 3:
410 schema = {"content": {"application/json": schema}}
411 spec.components.response("Response", schema)
412 resp = get_responses(spec)["Response"]
413 if spec.openapi_version.major < 3:
414 schema = resp["schema"]
415 else:
416 schema = resp["content"]["application/json"]["schema"]
417 assert schema == build_ref(spec, "schema", "PetSchema")
418
419 # "headers" components section only exists in OAS 3
420 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
421 def test_components_resolve_response_header(self, spec):
422 response = {"headers": {"header_1": "Header_1"}}
423 spec.components.response("Response", response)
424 resp = get_responses(spec)["Response"]
425 header_1 = resp["headers"]["header_1"]
426 assert header_1 == build_ref(spec, "header", "Header_1")
427
428 # "headers" components section only exists in OAS 3
429 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
430 def test_components_resolve_response_header_schema(self, spec):
431 response = {"headers": {"header_1": {"name": "Pet", "schema": "PetSchema"}}}
432 spec.components.response("Response", response)
433 resp = get_responses(spec)["Response"]
434 header_1 = resp["headers"]["header_1"]
435 assert header_1["schema"] == build_ref(spec, "schema", "PetSchema")
436
437 # "headers" components section only exists in OAS 3
438 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
439 def test_components_resolve_response_header_examples(self, spec):
440 response = {
441 "headers": {
442 "header_1": {"name": "Pet", "examples": {"example_1": "Example_1"}}
443 }
444 }
445 spec.components.response("Response", response)
446 resp = get_responses(spec)["Response"]
447 header_1 = resp["headers"]["header_1"]
448 assert header_1["examples"]["example_1"] == build_ref(
449 spec, "example", "Example_1"
450 )
451
452 # "examples" components section only exists in OAS 3
453 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
454 def test_components_resolve_response_examples(self, spec):
455 response = {
456 "content": {"application/json": {"examples": {"example_1": "Example_1"}}}
457 }
458 spec.components.response("Response", response)
459 resp = get_responses(spec)["Response"]
460 example_1 = resp["content"]["application/json"]["examples"]["example_1"]
461 assert example_1 == build_ref(spec, "example", "Example_1")
462
463 def test_components_resolve_refs_in_response_schema(self, spec):
464 schema = copy.deepcopy(self.REFS_SCHEMA)
465 if spec.openapi_version.major >= 3:
466 response = {"content": {"application/json": {"schema": schema}}}
467 else:
468 response = {"schema": schema}
469 spec.components.response("Response", response)
470 resp = get_responses(spec)["Response"]
471 if spec.openapi_version.major < 3:
472 schema = resp["schema"]
473 else:
474 schema = resp["content"]["application/json"]["schema"]
475 self.assert_schema_refs(spec, schema)
476
477 # "headers" components section only exists in OAS 3
478 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
479 def test_components_resolve_refs_in_response_header_schema(self, spec):
480 header = {"schema": copy.deepcopy(self.REFS_SCHEMA)}
481 response = {"headers": {"header": header}}
482 spec.components.response("Response", response)
483 resp = get_responses(spec)["Response"]
484 self.assert_schema_refs(spec, resp["headers"]["header"]["schema"])
485
486 # "examples" components section only exists in OAS 3
487 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
488 def test_components_resolve_parameter_examples(self, spec):
489 parameter = {
490 "examples": {"example_1": "Example_1"},
491 }
492 spec.components.parameter("param", "path", parameter)
493 param = get_parameters(spec)["param"]
494 example_1 = param["examples"]["example_1"]
495 assert example_1 == build_ref(spec, "example", "Example_1")
496
497 def test_components_resolve_parameter_schemas(self, spec):
498 parameter = {"schema": "PetSchema"}
499 spec.components.parameter("param", "path", parameter)
500 param = get_parameters(spec)["param"]
501 assert param["schema"] == build_ref(spec, "schema", "PetSchema")
502
503 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
504 def test_components_resolve_parameter_schemas_v3(self, spec):
505 parameter = {"content": {"application/json": {"schema": "PetSchema"}}}
506 spec.components.parameter("param", "path", parameter)
507 param = get_parameters(spec)["param"]
508 schema = param["content"]["application/json"]["schema"]
509 assert schema == build_ref(spec, "schema", "PetSchema")
510
511 def test_components_resolve_refs_in_parameter_schema(self, spec):
512 parameter = {"schema": copy.deepcopy(self.REFS_SCHEMA)}
513 spec.components.parameter("param", "path", parameter)
514 self.assert_schema_refs(spec, get_parameters(spec)["param"]["schema"])
515
516 # "headers" components section only exists in OAS 3
517 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
518 def test_components_resolve_header_schema(self, spec):
519 header = {"name": "Pet", "schema": "PetSchema"}
520 spec.components.header("header", header)
521 header = get_headers(spec)["header"]
522 assert header["schema"] == build_ref(spec, "schema", "PetSchema")
523
524 # "headers" components section only exists in OAS 3
525 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
526 def test_components_resolve_header_examples(self, spec):
527 header = {"name": "Pet", "examples": {"example_1": "Example_1"}}
528 spec.components.header("header", header)
529 header = get_headers(spec)["header"]
530 assert header["examples"]["example_1"] == build_ref(
531 spec, "example", "Example_1"
532 )
533
534 # "headers" components section only exists in OAS 3
535 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
536 def test_components_resolve_refs_in_header_schema(self, spec):
537 header = {"schema": copy.deepcopy(self.REFS_SCHEMA)}
538 spec.components.header("header", header)
539 self.assert_schema_refs(spec, get_headers(spec)["header"]["schema"])
540
541 def test_schema_lazy(self, spec):
542 spec.components.schema("Pet_1", {"properties": self.properties}, lazy=False)
543 spec.components.schema("Pet_2", {"properties": self.properties}, lazy=True)
544 schemas = get_schemas(spec)
545 assert "Pet_1" in schemas
546 assert "Pet_2" not in schemas
547 spec.components.schema("PetFriend", {"oneOf": ["Pet_1", "Pet_2"]})
548 schemas = get_schemas(spec)
549 assert "Pet_2" in schemas
550 assert schemas["Pet_2"]["properties"] == self.properties
551
552 def test_response_lazy(self, spec):
553 response_1 = {"description": "Response 1"}
554 response_2 = {"description": "Response 2"}
555 spec.components.response("Response_1", response_1, lazy=False)
556 spec.components.response("Response_2", response_2, lazy=True)
557 responses = get_responses(spec)
558 assert "Response_1" in responses
559 assert "Response_2" not in responses
560 spec.path("/path", operations={"get": {"responses": {"200": "Response_2"}}})
561 responses = get_responses(spec)
562 assert "Response_2" in responses
563
564 def test_parameter_lazy(self, spec):
565 parameter = {"format": "int64", "type": "integer"}
566 spec.components.parameter("Param_1", "path", parameter, lazy=False)
567 spec.components.parameter("Param_2", "path", parameter, lazy=True)
568 params = get_parameters(spec)
569 assert "Param_1" in params
570 assert "Param_2" not in params
571 spec.path("/path", operations={"get": {"parameters": ["Param_1", "Param_2"]}})
572 assert "Param_2" in params
573
574 # Referenced headers are only supported in OAS 3.x
575 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
576 def test_header_lazy(self, spec):
577 header = {"schema": {"type": "string"}}
578 spec.components.header("Header_1", header, lazy=False)
579 spec.components.header("Header_2", header, lazy=True)
580 headers = get_headers(spec)
581 assert "Header_1" in headers
582 assert "Header_2" not in headers
583 spec.path(
584 "/path",
585 operations={
586 "get": {"responses": {"200": {"headers": {"header_2": "Header_2"}}}}
587 },
588 )
589 assert "Header_2" in headers
590
591 # Referenced examples are only supported in OAS 3.x
592 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
593 def test_example_lazy(self, spec):
594 spec.components.example("Example_1", {"value": {"a": "b"}}, lazy=False)
595 spec.components.example("Example_2", {"value": {"a": "b"}}, lazy=True)
596 examples = get_examples(spec)
597 assert "Example_1" in examples
598 assert "Example_2" not in examples
599 spec.path(
600 "/path",
601 operations={
602 "get": {
603 "responses": {
604 "200": {
605 "content": {
606 "application/json": {
607 "examples": {"example_2": "Example_2"}
608 }
609 }
610 }
611 }
612 }
613 },
614 )
615 assert "Example_2" in examples
616
617 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
618 def test_links_lazy(self, spec):
619 link = {"operationRef": "#/paths/~1users~1{user_id}/get"}
620 spec.components.link("GetUser", link, lazy=True)
621 # Should not appear until referenced
622 links = get_links(spec)
623 assert "GetUser" not in links
624
625 # Reference the link and verify it appears
626 spec.path(
627 path="/path",
628 operations={
629 "get": {
630 "responses": {
631 "201": {
632 "description": "Created",
633 "links": {
634 "GetUser": "GetUser", # Reference by name
635 },
636 }
637 }
638 }
639 },
640 )
641 links = get_links(spec)
642 assert "GetUser" in links
643 assert links["GetUser"] == link
644
645
646 class TestPath(RefsSchemaTestMixin):
647 paths = {
648 "/pet/{petId}": {
649 "get": {
650 "parameters": [
651 {
652 "required": True,
653 "format": "int64",
654 "name": "petId",
655 "in": "path",
656 "type": "integer",
657 "description": "ID of pet that needs to be fetched",
658 }
659 ],
660 "responses": {
661 "200": {"description": "successful operation"},
662 "400": {"description": "Invalid ID supplied"},
663 "404": {"description": "Pet not found"},
664 },
665 "produces": ["application/json", "application/xml"],
666 "operationId": "getPetById",
667 "summary": "Find pet by ID",
668 "description": (
669 "Returns a pet when ID < 10. "
670 "ID > 10 or nonintegers will simulate API error conditions"
671 ),
672 "tags": ["pet"],
673 }
674 }
675 }
676
677 def test_path(self, spec):
678 route_spec = self.paths["/pet/{petId}"]["get"]
679 spec.path(path="/pet/{petId}", operations=dict(get=route_spec))
680
681 p = get_paths(spec)["/pet/{petId}"]["get"]
682 assert p["parameters"] == route_spec["parameters"]
683 assert p["responses"] == route_spec["responses"]
684 assert p["operationId"] == route_spec["operationId"]
685 assert p["summary"] == route_spec["summary"]
686 assert p["description"] == route_spec["description"]
687 assert p["tags"] == route_spec["tags"]
688
689 def test_paths_maintain_order(self, spec):
690 spec.path(path="/path1")
691 spec.path(path="/path2")
692 spec.path(path="/path3")
693 spec.path(path="/path4")
694 assert list(spec.to_dict()["paths"].keys()) == [
695 "/path1",
696 "/path2",
697 "/path3",
698 "/path4",
699 ]
700
701 def test_path_is_chainable(self, spec):
702 spec.path(path="/path1").path("/path2")
703 assert list(spec.to_dict()["paths"].keys()) == ["/path1", "/path2"]
704
705 def test_path_methods_maintain_order(self, spec):
706 methods = ["get", "post", "put", "patch", "delete", "head", "options"]
707 for method in methods:
708 spec.path(path="/path", operations={method: {}})
709 assert list(spec.to_dict()["paths"]["/path"]) == methods
710
711 def test_path_merges_paths(self, spec):
712 """Test that adding a second HTTP method to an existing path performs
713 a merge operation instead of an overwrite"""
714 path = "/pet/{petId}"
715 route_spec = self.paths[path]["get"]
716 spec.path(path=path, operations=dict(get=route_spec))
717 spec.path(
718 path=path,
719 operations=dict(
720 put=dict(
721 parameters=route_spec["parameters"],
722 responses=route_spec["responses"],
723 produces=route_spec["produces"],
724 operationId="updatePet",
725 summary="Updates an existing Pet",
726 description="Use this method to make changes to Pet `petId`",
727 tags=route_spec["tags"],
728 )
729 ),
730 )
731
732 p = get_paths(spec)[path]
733 assert "get" in p
734 assert "put" in p
735
736 @pytest.mark.parametrize("openapi_version", ("2.0", "3.0.0"))
737 def test_path_called_twice_with_same_operations_parameters(self, openapi_version):
738 """Test calling path twice with same operations or parameters
739
740 operations and parameters being mutated by clean_operations and plugin helpers
741 should not make path fail on second call
742 """
743
744 class TestPlugin(BasePlugin):
745 def path_helper(self, path, operations, parameters, **kwargs):
746 """Mutate operations and parameters"""
747 operations.update({"post": {"responses": {"201": "201ResponseRef"}}})
748 parameters.append("ParamRef_3")
749 return path
750
751 spec = APISpec(
752 title="Swagger Petstore",
753 version="1.0.0",
754 openapi_version=openapi_version,
755 plugins=[TestPlugin()],
756 )
757
758 path = "/pet/{petId}"
759 parameters = ["ParamRef_1"]
760 operation = {
761 "parameters": ["ParamRef_2"],
762 "responses": {"200": "200ResponseRef"},
763 }
764
765 spec.path(path=path, operations={"get": operation}, parameters=parameters)
766 spec.path(path=path, operations={"put": operation}, parameters=parameters)
767 operations = (get_paths(spec))[path]
768 assert (
769 operations["get"]
770 == operations["put"]
771 == {
772 "parameters": [build_ref(spec, "parameter", "ParamRef_2")],
773 "responses": {"200": build_ref(spec, "response", "200ResponseRef")},
774 }
775 )
776 assert operations["parameters"] == [
777 build_ref(spec, "parameter", "ParamRef_1"),
778 build_ref(spec, "parameter", "ParamRef_3"),
779 ]
780
781 def test_path_ensures_path_parameters_required(self, spec):
782 path = "/pet/{petId}"
783 spec.path(
784 path=path,
785 operations=dict(put=dict(parameters=[{"name": "petId", "in": "path"}])),
786 )
787 assert get_paths(spec)[path]["put"]["parameters"][0]["required"] is True
788
789 def test_path_with_no_path_raises_error(self, spec):
790 message = "Path template is not specified"
791 with pytest.raises(APISpecError, match=message):
792 spec.path()
793
794 def test_path_summary_description(self, spec):
795 summary = "Operations on a Pet"
796 description = "Operations on a Pet identified by its ID"
797 spec.path(path="/pet/{petId}", summary=summary, description=description)
798
799 p = get_paths(spec)["/pet/{petId}"]
800 assert p["summary"] == summary
801 assert p["description"] == description
802
803 def test_path_resolves_parameter(self, spec):
804 route_spec = self.paths["/pet/{petId}"]["get"]
805 spec.components.parameter("test_parameter", "path", route_spec["parameters"][0])
806 spec.path(
807 path="/pet/{petId}", operations={"get": {"parameters": ["test_parameter"]}}
808 )
809 p = get_paths(spec)["/pet/{petId}"]["get"]
810 assert p["parameters"][0] == build_ref(spec, "parameter", "test_parameter")
811
812 @pytest.mark.parametrize(
813 "parameters",
814 ([{"name": "petId"}], [{"in": "path"}]), # missing "in" # missing "name"
815 )
816 def test_path_invalid_parameter(self, spec, parameters):
817 path = "/pet/{petId}"
818
819 with pytest.raises(InvalidParameterError):
820 spec.path(path=path, operations=dict(put={}, get={}), parameters=parameters)
821
822 def test_parameter_duplicate(self, spec):
823 spec.path(
824 path="/pet/{petId}",
825 operations={
826 "get": {
827 "parameters": [
828 {"name": "petId", "in": "path"},
829 {"name": "petId", "in": "query"},
830 ]
831 }
832 },
833 )
834
835 with pytest.raises(DuplicateParameterError):
836 spec.path(
837 path="/pet/{petId}",
838 operations={
839 "get": {
840 "parameters": [
841 {"name": "petId", "in": "path"},
842 {"name": "petId", "in": "path"},
843 ]
844 }
845 },
846 )
847
848 def test_global_parameters(self, spec):
849 path = "/pet/{petId}"
850 route_spec = self.paths["/pet/{petId}"]["get"]
851
852 spec.components.parameter("test_parameter", "path", route_spec["parameters"][0])
853 spec.path(
854 path=path,
855 operations=dict(put={}, get={}),
856 parameters=[{"name": "petId", "in": "path"}, "test_parameter"],
857 )
858
859 assert get_paths(spec)[path]["parameters"] == [
860 {"name": "petId", "in": "path", "required": True},
861 build_ref(spec, "parameter", "test_parameter"),
862 ]
863
864 def test_global_parameter_duplicate(self, spec):
865 path = "/pet/{petId}"
866 spec.path(
867 path=path,
868 operations=dict(put={}, get={}),
869 parameters=[
870 {"name": "petId", "in": "path"},
871 {"name": "petId", "in": "query"},
872 ],
873 )
874
875 assert get_paths(spec)[path]["parameters"] == [
876 {"name": "petId", "in": "path", "required": True},
877 {"name": "petId", "in": "query"},
878 ]
879
880 with pytest.raises(DuplicateParameterError):
881 spec.path(
882 path=path,
883 operations=dict(put={}, get={}),
884 parameters=[
885 {"name": "petId", "in": "path"},
886 {"name": "petId", "in": "path"},
887 "test_parameter",
888 ],
889 )
890
891 def test_path_resolves_response(self, spec):
892 route_spec = self.paths["/pet/{petId}"]["get"]
893 spec.components.response("test_response", route_spec["responses"]["200"])
894 spec.path(
895 path="/pet/{petId}",
896 operations={"get": {"responses": {"200": "test_response"}}},
897 )
898 p = get_paths(spec)["/pet/{petId}"]["get"]
899 assert p["responses"]["200"] == build_ref(spec, "response", "test_response")
900
901 def test_path_response_with_HTTPStatus_code(self, spec):
902 code = HTTPStatus(200)
903 spec.path(
904 path="/pet/{petId}",
905 operations={"get": {"responses": {code: "test_response"}}},
906 )
907
908 assert "200" in get_paths(spec)["/pet/{petId}"]["get"]["responses"]
909
910 def test_path_response_with_status_code_range(self, spec, recwarn):
911 status_code = "2XX"
912
913 spec.path(
914 path="/pet/{petId}",
915 operations={"get": {"responses": {status_code: "test_response"}}},
916 )
917
918 if spec.openapi_version.major < 3:
919 assert len(recwarn) == 1
920 assert recwarn.pop(UserWarning)
921
922 assert status_code in get_paths(spec)["/pet/{petId}"]["get"]["responses"]
923
924 def test_path_check_invalid_http_method(self, spec):
925 spec.path("/pet/{petId}", operations={"get": {}})
926 spec.path("/pet/{petId}", operations={"x-dummy": {}})
927 message = "One or more HTTP methods are invalid"
928 with pytest.raises(APISpecError, match=message):
929 spec.path("/pet/{petId}", operations={"dummy": {}})
930
931 def test_path_resolve_response_schema(self, spec):
932 schema = {"schema": "PetSchema"}
933 if spec.openapi_version.major >= 3:
934 schema = {"content": {"application/json": schema}}
935 spec.path("/pet/{petId}", operations={"get": {"responses": {"200": schema}}})
936 resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
937 if spec.openapi_version.major < 3:
938 schema = resp["schema"]
939 else:
940 schema = resp["content"]["application/json"]["schema"]
941 assert schema == build_ref(spec, "schema", "PetSchema")
942
943 # callbacks only exists in OAS 3
944 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
945 def test_path_resolve_callbacks(self, spec):
946 parameter = {"name": "petId", "in": "query", "schema": "PetSchema"}
947 spec.path(
948 "/pet/{petId}",
949 operations={
950 "get": {
951 "callbacks": {
952 "onEvent": {
953 "/callback/{petId}": {
954 "post": {
955 "parameters": [parameter],
956 "requestBody": {
957 "content": {
958 "application/json": {"schema": "PetSchema"}
959 }
960 },
961 "responses": {
962 "200": {
963 "content": {
964 "application/json": {
965 "schema": "PetSchema"
966 }
967 }
968 }
969 },
970 }
971 }
972 }
973 },
974 }
975 },
976 )
977 path = get_paths(spec)["/pet/{petId}"]
978 schema_ref = build_ref(spec, "schema", "PetSchema")
979 callback_op = path["get"]["callbacks"]["onEvent"]["/callback/{petId}"]["post"]
980 assert callback_op["parameters"][0]["schema"] == schema_ref
981 assert (
982 callback_op["requestBody"]["content"]["application/json"]["schema"]
983 == schema_ref
984 )
985 assert (
986 callback_op["responses"]["200"]["content"]["application/json"]["schema"]
987 == schema_ref
988 )
989
990 # requestBody only exists in OAS 3
991 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
992 def test_path_resolve_request_body(self, spec):
993 spec.path(
994 "/pet/{petId}",
995 operations={
996 "get": {
997 "requestBody": {
998 "content": {"application/json": {"schema": "PetSchema"}}
999 }
1000 }
1001 },
1002 )
1003 assert get_paths(spec)["/pet/{petId}"]["get"]["requestBody"]["content"][
1004 "application/json"
1005 ]["schema"] == build_ref(spec, "schema", "PetSchema")
1006
1007 # "headers" components section only exists in OAS 3
1008 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
1009 def test_path_resolve_response_header(self, spec):
1010 response = {"headers": {"header_1": "Header_1"}}
1011 spec.path("/pet/{petId}", operations={"get": {"responses": {"200": response}}})
1012 resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
1013 header_1 = resp["headers"]["header_1"]
1014 assert header_1 == build_ref(spec, "header", "Header_1")
1015
1016 # "headers" components section only exists in OAS 3
1017 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
1018 def test_path_resolve_response_header_schema(self, spec):
1019 response = {"headers": {"header_1": {"name": "Pet", "schema": "PetSchema"}}}
1020 spec.path("/pet/{petId}", operations={"get": {"responses": {"200": response}}})
1021 resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
1022 header_1 = resp["headers"]["header_1"]
1023 assert header_1["schema"] == build_ref(spec, "schema", "PetSchema")
1024
1025 # "headers" components section only exists in OAS 3
1026 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
1027 def test_path_resolve_response_header_examples(self, spec):
1028 response = {
1029 "headers": {
1030 "header_1": {"name": "Pet", "examples": {"example_1": "Example_1"}}
1031 }
1032 }
1033 spec.path("/pet/{petId}", operations={"get": {"responses": {"200": response}}})
1034 resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
1035 header_1 = resp["headers"]["header_1"]
1036 assert header_1["examples"]["example_1"] == build_ref(
1037 spec, "example", "Example_1"
1038 )
1039
1040 # "examples" components section only exists in OAS 3
1041 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
1042 def test_path_resolve_response_examples(self, spec):
1043 response = {
1044 "content": {"application/json": {"examples": {"example_1": "Example_1"}}}
1045 }
1046 spec.path("/pet/{petId}", operations={"get": {"responses": {"200": response}}})
1047 resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
1048 example_1 = resp["content"]["application/json"]["examples"]["example_1"]
1049 assert example_1 == build_ref(spec, "example", "Example_1")
1050
1051 # "examples" components section only exists in OAS 3
1052 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
1053 def test_path_resolve_request_body_examples(self, spec):
1054 request_body = {
1055 "content": {"application/json": {"examples": {"example_1": "Example_1"}}}
1056 }
1057 spec.path("/pet/{petId}", operations={"get": {"requestBody": request_body}})
1058 reqbdy = get_paths(spec)["/pet/{petId}"]["get"]["requestBody"]
1059 example_1 = reqbdy["content"]["application/json"]["examples"]["example_1"]
1060 assert example_1 == build_ref(spec, "example", "Example_1")
1061
1062 # "examples" components section only exists in OAS 3
1063 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
1064 def test_path_resolve_parameter_examples(self, spec):
1065 parameter = {
1066 "name": "test",
1067 "in": "query",
1068 "examples": {"example_1": "Example_1"},
1069 }
1070 spec.path("/pet/{petId}", operations={"get": {"parameters": [parameter]}})
1071 param = get_paths(spec)["/pet/{petId}"]["get"]["parameters"][0]
1072 example_1 = param["examples"]["example_1"]
1073 assert example_1 == build_ref(spec, "example", "Example_1")
1074
1075 def test_path_resolve_parameter_schemas(self, spec):
1076 parameter = {"name": "test", "in": "query", "schema": "PetSchema"}
1077 spec.path("/pet/{petId}", operations={"get": {"parameters": [parameter]}})
1078 param = get_paths(spec)["/pet/{petId}"]["get"]["parameters"][0]
1079 assert param["schema"] == build_ref(spec, "schema", "PetSchema")
1080
1081 def test_path_resolve_refs_in_response_schema(self, spec):
1082 if spec.openapi_version.major >= 3:
1083 schema = {"content": {"application/json": {"schema": self.REFS_SCHEMA}}}
1084 else:
1085 schema = {"schema": self.REFS_SCHEMA}
1086 spec.path("/pet/{petId}", operations={"get": {"responses": {"200": schema}}})
1087 resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
1088 if spec.openapi_version.major < 3:
1089 schema = resp["schema"]
1090 else:
1091 schema = resp["content"]["application/json"]["schema"]
1092 self.assert_schema_refs(spec, schema)
1093
1094 def test_path_resolve_refs_in_parameter_schema(self, spec):
1095 schema = copy.copy({"schema": self.REFS_SCHEMA})
1096 schema["in"] = "query"
1097 schema["name"] = "test"
1098 spec.path("/pet/{petId}", operations={"get": {"parameters": [schema]}})
1099 schema = get_paths(spec)["/pet/{petId}"]["get"]["parameters"][0]["schema"]
1100 self.assert_schema_refs(spec, schema)
1101
1102 # requestBody only exists in OAS 3
1103 @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
1104 def test_path_resolve_refs_in_request_body_schema(self, spec):
1105 schema = {"content": {"application/json": {"schema": self.REFS_SCHEMA}}}
1106 spec.path("/pet/{petId}", operations={"get": {"responses": {"200": schema}}})
1107 resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
1108 schema = resp["content"]["application/json"]["schema"]
1109 self.assert_schema_refs(spec, schema)
1110
1111
1112 class TestPlugins:
1113 @staticmethod
1114 def make_test_plugin(return_none=False):
1115 class TestPlugin(BasePlugin):
1116 """Test Plugin
1117
1118 return_none allows to check plugin helpers returning ``None``
1119 Inputs are mutated to allow testing only a copy is passed.
1120 """
1121
1122 def schema_helper(self, name, definition, **kwargs):
1123 definition.pop("dummy", None)
1124 if not return_none:
1125 return {"properties": {"name": {"type": "string"}}}
1126
1127 def parameter_helper(self, parameter, **kwargs):
1128 parameter.pop("dummy", None)
1129 if not return_none:
1130 return {"description": "some parameter"}
1131
1132 def response_helper(self, response, **kwargs):
1133 response.pop("dummy", None)
1134 if not return_none:
1135 return {"description": "42"}
1136
1137 def header_helper(self, header, **kwargs):
1138 header.pop("dummy", None)
1139 if not return_none:
1140 return {"description": "some header"}
1141
1142 def path_helper(self, path, operations, parameters, **kwargs):
1143 if not return_none:
1144 if path == "/path_1":
1145 operations.update({"get": {"responses": {"200": {}}}})
1146 parameters.append({"name": "page", "in": "query"})
1147 return "/path_1_modified"
1148
1149 def operation_helper(self, path, operations, **kwargs):
1150 if path == "/path_2":
1151 operations["post"] = {"responses": {"201": {}}}
1152
1153 return TestPlugin()
1154
1155 @pytest.mark.parametrize("openapi_version", ("2.0", "3.0.0"))
1156 @pytest.mark.parametrize("return_none", (True, False))
1157 def test_plugin_schema_helper_is_used(self, openapi_version, return_none):
1158 spec = APISpec(
1159 title="Swagger Petstore",
1160 version="1.0.0",
1161 openapi_version=openapi_version,
1162 plugins=(self.make_test_plugin(return_none),),
1163 )
1164 schema = {"dummy": "dummy"}
1165 spec.components.schema("Pet", schema)
1166 definitions = get_schemas(spec)
1167 if return_none:
1168 assert definitions["Pet"] == {}
1169 else:
1170 assert definitions["Pet"] == {"properties": {"name": {"type": "string"}}}
1171 # Check original schema is not modified
1172 assert schema == {"dummy": "dummy"}
1173
1174 @pytest.mark.parametrize("openapi_version", ("2.0", "3.0.0"))
1175 @pytest.mark.parametrize("return_none", (True, False))
1176 def test_plugin_parameter_helper_is_used(self, openapi_version, return_none):
1177 spec = APISpec(
1178 title="Swagger Petstore",
1179 version="1.0.0",
1180 openapi_version=openapi_version,
1181 plugins=(self.make_test_plugin(return_none),),
1182 )
1183 parameter = {"dummy": "dummy"}
1184 spec.components.parameter("Pet", "body", parameter)
1185 parameters = get_parameters(spec)
1186 if return_none:
1187 assert parameters["Pet"] == {"in": "body", "name": "Pet"}
1188 else:
1189 assert parameters["Pet"] == {
1190 "in": "body",
1191 "name": "Pet",
1192 "description": "some parameter",
1193 }
1194 # Check original parameter is not modified
1195 assert parameter == {"dummy": "dummy"}
1196
1197 @pytest.mark.parametrize("openapi_version", ("2.0", "3.0.0"))
1198 @pytest.mark.parametrize("return_none", (True, False))
1199 def test_plugin_response_helper_is_used(self, openapi_version, return_none):
1200 spec = APISpec(
1201 title="Swagger Petstore",
1202 version="1.0.0",
1203 openapi_version=openapi_version,
1204 plugins=(self.make_test_plugin(return_none),),
1205 )
1206 response = {"dummy": "dummy"}
1207 spec.components.response("Pet", response)
1208 responses = get_responses(spec)
1209 if return_none:
1210 assert responses["Pet"] == {}
1211 else:
1212 assert responses["Pet"] == {"description": "42"}
1213 # Check original response is not modified
1214 assert response == {"dummy": "dummy"}
1215
1216 @pytest.mark.parametrize("openapi_version", ("3.0.0",))
1217 @pytest.mark.parametrize("return_none", (True, False))
1218 def test_plugin_header_helper_is_used(self, openapi_version, return_none):
1219 spec = APISpec(
1220 title="Swagger Petstore",
1221 version="1.0.0",
1222 openapi_version=openapi_version,
1223 plugins=(self.make_test_plugin(return_none),),
1224 )
1225 header = {"dummy": "dummy"}
1226 spec.components.header("Pet", header)
1227 headers = get_headers(spec)
1228 if return_none:
1229 assert headers["Pet"] == {}
1230 else:
1231 assert headers["Pet"] == {
1232 "description": "some header",
1233 }
1234 # Check original header is not modified
1235 assert header == {"dummy": "dummy"}
1236
1237 @pytest.mark.parametrize("openapi_version", ("2.0", "3.0.0"))
1238 @pytest.mark.parametrize("return_none", (True, False))
1239 def test_plugin_path_helper_is_used(self, openapi_version, return_none):
1240 spec = APISpec(
1241 title="Swagger Petstore",
1242 version="1.0.0",
1243 openapi_version=openapi_version,
1244 plugins=(self.make_test_plugin(return_none),),
1245 )
1246 spec.path("/path_1")
1247 paths = get_paths(spec)
1248 assert len(paths) == 1
1249 if return_none:
1250 assert paths["/path_1"] == {}
1251 else:
1252 assert paths["/path_1_modified"] == {
1253 "get": {"responses": {"200": {}}},
1254 "parameters": [{"in": "query", "name": "page"}],
1255 }
1256
1257 @pytest.mark.parametrize("openapi_version", ("2.0", "3.0.0"))
1258 def test_plugin_operation_helper_is_used(self, openapi_version):
1259 spec = APISpec(
1260 title="Swagger Petstore",
1261 version="1.0.0",
1262 openapi_version=openapi_version,
1263 plugins=(self.make_test_plugin(),),
1264 )
1265 spec.path("/path_2", operations={"post": {"responses": {"200": {}}}})
1266 paths = get_paths(spec)
1267 assert len(paths) == 1
1268 assert paths["/path_2"] == {"post": {"responses": {"201": {}}}}
1269
1270
1271 class TestPluginsOrder:
1272 class OrderedPlugin(BasePlugin):
1273 def __init__(self, index, output):
1274 super().__init__()
1275 self.index = index
1276 self.output = output
1277
1278 def path_helper(self, path, operations, **kwargs):
1279 self.output.append(f"plugin_{self.index}_path")
1280
1281 def operation_helper(self, path, operations, **kwargs):
1282 self.output.append(f"plugin_{self.index}_operations")
1283
1284 def test_plugins_order(self):
1285 """Test plugins execution order in APISpec.path
1286
1287 - All path helpers are called, then all operation helpers, then all response helpers.
1288 - At each step, helpers are executed in the order the plugins are passed to APISpec.
1289 """
1290 output = []
1291 spec = APISpec(
1292 title="Swagger Petstore",
1293 version="1.0.0",
1294 openapi_version="3.0.0",
1295 plugins=(self.OrderedPlugin(1, output), self.OrderedPlugin(2, output)),
1296 )
1297 spec.path("/path", operations={"get": {"responses": {200: {}}}})
1298 assert output == [
1299 "plugin_1_path",
1300 "plugin_2_path",
1301 "plugin_1_operations",
1302 "plugin_2_operations",
1303 ]