| 1 | from ninja import NinjaAPI, Router |
| 2 | |
| 3 | |
| 4 | def test_openapi_info_defined(): |
| 5 | "Test appending schema.info" |
| 6 | extra_info = { |
| 7 | "termsOfService": "https://example.com/terms/", |
| 8 | "title": "Test API", |
| 9 | } |
| 10 | api = NinjaAPI(openapi_extra={"info": extra_info}, version="1.0.0") |
| 11 | schema = api.get_openapi_schema() |
| 12 | |
| 13 | assert schema["info"]["termsOfService"] == "https://example.com/terms/" |
| 14 | assert schema["info"]["title"] == "Test API" |
| 15 | assert schema["info"]["version"] == "1.0.0" |
| 16 | |
| 17 | |
| 18 | def test_openapi_no_additional_info(): |
| 19 | api = NinjaAPI(title="Test API") |
| 20 | schema = api.get_openapi_schema() |
| 21 | |
| 22 | assert schema["info"]["title"] == "Test API" |
| 23 | assert "termsOfService" not in schema["info"] |
| 24 | |
| 25 | |
| 26 | def test_openapi_extra(): |
| 27 | "Test adding extra attribute to the schema" |
| 28 | api = NinjaAPI( |
| 29 | openapi_extra={ |
| 30 | "externalDocs": { |
| 31 | "description": "Find more info here", |
| 32 | "url": "https://example.com", |
| 33 | } |
| 34 | }, |
| 35 | version="1.0.0", |
| 36 | ) |
| 37 | schema = api.get_openapi_schema() |
| 38 | |
| 39 | assert schema == { |
| 40 | "openapi": "3.1.0", |
| 41 | "info": {"title": "NinjaAPI", "version": "1.0.0", "description": ""}, |
| 42 | "paths": {}, |
| 43 | "components": {"schemas": {}}, |
| 44 | "servers": [], |
| 45 | "externalDocs": { |
| 46 | "description": "Find more info here", |
| 47 | "url": "https://example.com", |
| 48 | }, |
| 49 | } |
| 50 | |
| 51 | |
| 52 | def test_router_openapi_extra_extends(): |
| 53 | """ |
| 54 | Test for #1505. |
| 55 | When adding an extra parameter to a route via openapi_extra, this should be combined with the route's own parameters. |
| 56 | """ |
| 57 | api = NinjaAPI() |
| 58 | test_router = Router() |
| 59 | api.add_router("", test_router) |
| 60 | |
| 61 | extra_param = { |
| 62 | "in": "header", |
| 63 | "name": "X-HelloWorld", |
| 64 | "required": False, |
| 65 | "schema": { |
| 66 | "type": "string", |
| 67 | "format": "uuid", |
| 68 | }, |
| 69 | } |
| 70 | |
| 71 | @test_router.get("/path/{item_id}", openapi_extra={"parameters": [extra_param]}) |
| 72 | def get_path_item_id(request, item_id: int): |
| 73 | pass |
| 74 | |
| 75 | schema = api.get_openapi_schema() |
| 76 | |
| 77 | assert len(schema["paths"]["/api/path/{item_id}"]["get"]["parameters"]) == 2 |
| 78 | assert schema["paths"]["/api/path/{item_id}"]["get"]["parameters"] == [ |
| 79 | { |
| 80 | "in": "path", |
| 81 | "name": "item_id", |
| 82 | "required": True, |
| 83 | "schema": { |
| 84 | "title": "Item Id", |
| 85 | "type": "integer", |
| 86 | }, |
| 87 | }, |
| 88 | extra_param, |
| 89 | ] |