| 1 |
import sys |
| 2 |
from sys import version_info |
| 3 |
from typing import Any, List, Union |
| 4 |
from unittest.mock import Mock |
| 5 |
from uuid import uuid4 |
| 6 |
|
| 7 |
import pydantic |
| 8 |
import pytest |
| 9 |
from django.contrib.admin.views.decorators import staff_member_required |
| 10 |
from django.db import models |
| 11 |
from django.test import Client, override_settings |
| 12 |
from typing_extensions import Annotated |
| 13 |
|
| 14 |
from ninja import ( |
| 15 |
Body, |
| 16 |
Field, |
| 17 |
File, |
| 18 |
Form, |
| 19 |
ModelSchema, |
| 20 |
NinjaAPI, |
| 21 |
P, |
| 22 |
PathEx, |
| 23 |
Query, |
| 24 |
Schema, |
| 25 |
UploadedFile, |
| 26 |
) |
| 27 |
from ninja.openapi.urls import get_openapi_urls |
| 28 |
from ninja.pagination import PaginationBase, paginate |
| 29 |
from ninja.renderers import JSONRenderer |
| 30 |
|
| 31 |
api = NinjaAPI() |
| 32 |
|
| 33 |
|
| 34 |
class Payload(Schema): |
| 35 |
i: int |
| 36 |
f: float |
| 37 |
|
| 38 |
|
| 39 |
class TypeA(Schema): |
| 40 |
a: str |
| 41 |
|
| 42 |
|
| 43 |
class TypeB(Schema): |
| 44 |
b: str |
| 45 |
|
| 46 |
|
| 47 |
AnnotatedStr = Annotated[ |
| 48 |
str, |
| 49 |
pydantic.WithJsonSchema({ |
| 50 |
"type": "string", |
| 51 |
"format": "custom-format", |
| 52 |
"example": "example_string", |
| 53 |
}), |
| 54 |
] |
| 55 |
|
| 56 |
|
| 57 |
def to_camel(string: str) -> str: |
| 58 |
words = string.split("_") |
| 59 |
return words[0].lower() + "".join(word.capitalize() for word in words[1:]) |
| 60 |
|
| 61 |
|
| 62 |
class Response(Schema): |
| 63 |
model_config = pydantic.ConfigDict(alias_generator=to_camel, populate_by_name=True) |
| 64 |
i: int |
| 65 |
f: float = Field(..., title="f title", description="f desc") |
| 66 |
|
| 67 |
|
| 68 |
@api.post("/test", response=Response) |
| 69 |
def method(request, data: Payload): |
| 70 |
return data.dict() |
| 71 |
|
| 72 |
|
| 73 |
@api.post("/test-alias", response=Response, by_alias=True) |
| 74 |
def method_alias(request, data: Payload): |
| 75 |
return data.dict() |
| 76 |
|
| 77 |
|
| 78 |
@api.post("/test_list", response=List[Response]) |
| 79 |
def method_list_response(request, data: List[Payload]): |
| 80 |
return [] |
| 81 |
|
| 82 |
|
| 83 |
@api.post("/test-body", response=Response) |
| 84 |
def method_body(request, i: int = Body(...), f: float = Body(...)): |
| 85 |
return dict(i=i, f=f) |
| 86 |
|
| 87 |
|
| 88 |
@api.post("/test-body-schema", response=Response) |
| 89 |
def method_body_schema(request, data: Payload): |
| 90 |
return dict(i=data.i, f=data.f) |
| 91 |
|
| 92 |
|
| 93 |
@api.get("/test-path/{int:i}/{f}", response=Response) |
| 94 |
def method_path( |
| 95 |
request, |
| 96 |
i: int, |
| 97 |
f: float, |
| 98 |
): |
| 99 |
return dict(i=i, f=f) |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
if version_info >= (3, 9): |
| 105 |
|
| 106 |
@api.get("/test-pathex/{path_ex}", response=AnnotatedStr) |
| 107 |
def method_pathex( |
| 108 |
request, |
| 109 |
path_ex: PathEx[ |
| 110 |
AnnotatedStr, |
| 111 |
P(description="path_ex description"), |
| 112 |
], |
| 113 |
): |
| 114 |
return path_ex |
| 115 |
|
| 116 |
else: |
| 117 |
with pytest.raises(NotImplementedError, match="3.9+"): |
| 118 |
|
| 119 |
@api.get("/test-pathex/{path_ex}", response=AnnotatedStr) |
| 120 |
def method_pathex( |
| 121 |
request, |
| 122 |
path_ex: PathEx[ |
| 123 |
AnnotatedStr, |
| 124 |
P(description="path_ex description"), |
| 125 |
], |
| 126 |
): |
| 127 |
return path_ex |
| 128 |
|
| 129 |
|
| 130 |
@api.post("/test-form", response=Response) |
| 131 |
def method_form(request, data: Payload = Form(...)): |
| 132 |
return dict(i=data.i, f=data.f) |
| 133 |
|
| 134 |
|
| 135 |
@api.post("/test-form-single", response=Response) |
| 136 |
def method_form_single(request, data: float = Form(...)): |
| 137 |
return dict(i=int(data), f=data) |
| 138 |
|
| 139 |
|
| 140 |
@api.post("/test-form-body", response=Response) |
| 141 |
def method_form_body(request, i: int = Form(10), s: str = Body("10")): |
| 142 |
return dict(i=i, s=s) |
| 143 |
|
| 144 |
|
| 145 |
@api.post("/test-form-file", response=Response) |
| 146 |
def method_form_file(request, files: List[UploadedFile], data: Payload = Form(...)): |
| 147 |
return dict(i=data.i, f=data.f) |
| 148 |
|
| 149 |
|
| 150 |
@api.post("/test-body-file", response=Response) |
| 151 |
def method_body_file( |
| 152 |
request, |
| 153 |
files: List[UploadedFile], |
| 154 |
body: Payload = Body(...), |
| 155 |
): |
| 156 |
return dict(i=body.i, f=body.f) |
| 157 |
|
| 158 |
|
| 159 |
@api.post("/test-union-type", response=Response) |
| 160 |
def method_union_payload(request, data: Union[TypeA, TypeB]): |
| 161 |
return dict(i=data.i, f=data.f) |
| 162 |
|
| 163 |
|
| 164 |
@api.post("/test-union-type-with-simple", response=Response) |
| 165 |
def method_union_payload_and_simple(request, data: Union[int, TypeB]): |
| 166 |
return data.dict() |
| 167 |
|
| 168 |
|
| 169 |
if sys.version_info >= (3, 10): |
| 170 |
|
| 171 |
|
| 172 |
@api.post("/test-new-union-type", response=Response) |
| 173 |
def method_new_union_payload(request, data: "TypeA | TypeB"): |
| 174 |
return dict(i=data.i, f=data.f) |
| 175 |
|
| 176 |
|
| 177 |
@api.post( |
| 178 |
"/test-title-description/", |
| 179 |
tags=["a-tag"], |
| 180 |
summary="Best API Ever", |
| 181 |
response=Response, |
| 182 |
) |
| 183 |
def method_test_title_description( |
| 184 |
request, |
| 185 |
param1: int = Query(..., title="param 1 title"), |
| 186 |
param2: str = Query("A Default", description="param 2 desc"), |
| 187 |
file: UploadedFile = File(..., description="file param desc"), |
| 188 |
): |
| 189 |
return dict(i=param1, f=param2) |
| 190 |
|
| 191 |
|
| 192 |
@api.post("/test-deprecated-example-examples/") |
| 193 |
def method_test_deprecated_example_examples( |
| 194 |
request, |
| 195 |
param1: int = Query(None, deprecated=True), |
| 196 |
param2: str = Query(..., example="Example Value"), |
| 197 |
param3: str = Query( |
| 198 |
..., |
| 199 |
max_length=5, |
| 200 |
examples={ |
| 201 |
"normal": { |
| 202 |
"summary": "A normal example", |
| 203 |
"description": "A **normal** string works correctly.", |
| 204 |
"value": "Foo", |
| 205 |
}, |
| 206 |
"invalid": { |
| 207 |
"summary": "Invalid data is rejected with an error", |
| 208 |
"value": "MoreThan5Length", |
| 209 |
}, |
| 210 |
}, |
| 211 |
), |
| 212 |
param4: int = Query(None, deprecated=True, include_in_schema=False), |
| 213 |
): |
| 214 |
return dict(i=param2, f=param3) |
| 215 |
|
| 216 |
|
| 217 |
def test_schema_views(client: Client): |
| 218 |
assert client.get("/api/").status_code == 404 |
| 219 |
assert client.get("/api/docs").status_code == 200 |
| 220 |
assert client.get("/api/openapi.json").status_code == 200 |
| 221 |
|
| 222 |
|
| 223 |
def test_schema_views_no_INSTALLED_APPS(client: Client): |
| 224 |
"Making sure that cdn and included js works fine" |
| 225 |
from django.conf import settings |
| 226 |
|
| 227 |
|
| 228 |
INSTALLED_APPS = [i for i in settings.INSTALLED_APPS if i != "ninja"] |
| 229 |
|
| 230 |
@override_settings(INSTALLED_APPS=INSTALLED_APPS) |
| 231 |
def call_docs(): |
| 232 |
assert client.get("/api/docs").status_code == 200 |
| 233 |
|
| 234 |
call_docs() |
| 235 |
|
| 236 |
|
| 237 |
@pytest.fixture(scope="session") |
| 238 |
def schema(): |
| 239 |
return api.get_openapi_schema() |
| 240 |
|
| 241 |
|
| 242 |
def test_schema(schema): |
| 243 |
method = schema["paths"]["/api/test"]["post"] |
| 244 |
|
| 245 |
assert method["requestBody"] == { |
| 246 |
"content": { |
| 247 |
"application/json": {"schema": {"$ref": "#/components/schemas/Payload"}} |
| 248 |
}, |
| 249 |
"required": True, |
| 250 |
} |
| 251 |
assert method["responses"] == { |
| 252 |
200: { |
| 253 |
"content": { |
| 254 |
"application/json": { |
| 255 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 256 |
} |
| 257 |
}, |
| 258 |
"description": "OK", |
| 259 |
} |
| 260 |
} |
| 261 |
assert schema.schemas == { |
| 262 |
"Response": { |
| 263 |
"title": "Response", |
| 264 |
"type": "object", |
| 265 |
"properties": { |
| 266 |
"i": {"title": "I", "type": "integer"}, |
| 267 |
"f": {"description": "f desc", "title": "f title", "type": "number"}, |
| 268 |
}, |
| 269 |
"required": ["i", "f"], |
| 270 |
}, |
| 271 |
"Payload": { |
| 272 |
"title": "Payload", |
| 273 |
"type": "object", |
| 274 |
"properties": { |
| 275 |
"i": {"title": "I", "type": "integer"}, |
| 276 |
"f": {"title": "F", "type": "number"}, |
| 277 |
}, |
| 278 |
"required": ["i", "f"], |
| 279 |
}, |
| 280 |
"TypeA": { |
| 281 |
"properties": { |
| 282 |
"a": {"title": "A", "type": "string"}, |
| 283 |
}, |
| 284 |
"required": ["a"], |
| 285 |
"title": "TypeA", |
| 286 |
"type": "object", |
| 287 |
}, |
| 288 |
"TypeB": { |
| 289 |
"properties": { |
| 290 |
"b": {"title": "B", "type": "string"}, |
| 291 |
}, |
| 292 |
"required": ["b"], |
| 293 |
"title": "TypeB", |
| 294 |
"type": "object", |
| 295 |
}, |
| 296 |
} |
| 297 |
|
| 298 |
|
| 299 |
def test_schema_alias(schema): |
| 300 |
method = schema["paths"]["/api/test-alias"]["post"] |
| 301 |
|
| 302 |
assert method["requestBody"] == { |
| 303 |
"content": { |
| 304 |
"application/json": {"schema": {"$ref": "#/components/schemas/Payload"}} |
| 305 |
}, |
| 306 |
"required": True, |
| 307 |
} |
| 308 |
assert method["responses"] == { |
| 309 |
200: { |
| 310 |
"content": { |
| 311 |
"application/json": { |
| 312 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 313 |
} |
| 314 |
}, |
| 315 |
"description": "OK", |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
""" |
| 320 |
assert schema.schemas == { |
| 321 |
"Response": { |
| 322 |
"title": "Response", |
| 323 |
"type": "object", |
| 324 |
"properties": { |
| 325 |
"I": {"title": "I", "type": "integer"}, |
| 326 |
"F": {"title": "F", "type": "number"}, |
| 327 |
}, |
| 328 |
"required": ["i", "f"], |
| 329 |
}, |
| 330 |
"Payload": { |
| 331 |
"title": "Payload", |
| 332 |
"type": "object", |
| 333 |
"properties": { |
| 334 |
"i": {"title": "I", "type": "integer"}, |
| 335 |
"f": {"title": "F", "type": "number"}, |
| 336 |
}, |
| 337 |
"required": ["i", "f"], |
| 338 |
}, |
| 339 |
} |
| 340 |
""" |
| 341 |
|
| 342 |
|
| 343 |
def test_schema_list(schema): |
| 344 |
method_list = schema["paths"]["/api/test_list"]["post"] |
| 345 |
|
| 346 |
assert method_list["requestBody"] == { |
| 347 |
"content": { |
| 348 |
"application/json": { |
| 349 |
"schema": { |
| 350 |
"items": {"$ref": "#/components/schemas/Payload"}, |
| 351 |
"title": "Data", |
| 352 |
"type": "array", |
| 353 |
} |
| 354 |
} |
| 355 |
}, |
| 356 |
"required": True, |
| 357 |
} |
| 358 |
assert method_list["responses"] == { |
| 359 |
200: { |
| 360 |
"content": { |
| 361 |
"application/json": { |
| 362 |
"schema": { |
| 363 |
"items": {"$ref": "#/components/schemas/Response"}, |
| 364 |
"title": "Response", |
| 365 |
"type": "array", |
| 366 |
} |
| 367 |
} |
| 368 |
}, |
| 369 |
"description": "OK", |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
assert schema["components"]["schemas"] == { |
| 374 |
"Payload": { |
| 375 |
"properties": { |
| 376 |
"f": {"title": "F", "type": "number"}, |
| 377 |
"i": {"title": "I", "type": "integer"}, |
| 378 |
}, |
| 379 |
"required": ["i", "f"], |
| 380 |
"title": "Payload", |
| 381 |
"type": "object", |
| 382 |
}, |
| 383 |
"TypeA": { |
| 384 |
"properties": { |
| 385 |
"a": {"title": "A", "type": "string"}, |
| 386 |
}, |
| 387 |
"required": ["a"], |
| 388 |
"title": "TypeA", |
| 389 |
"type": "object", |
| 390 |
}, |
| 391 |
"TypeB": { |
| 392 |
"properties": { |
| 393 |
"b": {"title": "B", "type": "string"}, |
| 394 |
}, |
| 395 |
"required": ["b"], |
| 396 |
"title": "TypeB", |
| 397 |
"type": "object", |
| 398 |
}, |
| 399 |
"Response": { |
| 400 |
"properties": { |
| 401 |
"f": {"description": "f desc", "title": "f title", "type": "number"}, |
| 402 |
"i": {"title": "I", "type": "integer"}, |
| 403 |
}, |
| 404 |
"required": ["i", "f"], |
| 405 |
"title": "Response", |
| 406 |
"type": "object", |
| 407 |
}, |
| 408 |
} |
| 409 |
|
| 410 |
|
| 411 |
def test_schema_body(schema): |
| 412 |
method_list = schema["paths"]["/api/test-body"]["post"] |
| 413 |
|
| 414 |
assert method_list["requestBody"] == { |
| 415 |
"content": { |
| 416 |
"application/json": { |
| 417 |
"schema": { |
| 418 |
"properties": { |
| 419 |
"f": {"title": "F", "type": "number"}, |
| 420 |
"i": {"title": "I", "type": "integer"}, |
| 421 |
}, |
| 422 |
"required": ["i", "f"], |
| 423 |
"title": "BodyParams", |
| 424 |
"type": "object", |
| 425 |
} |
| 426 |
} |
| 427 |
}, |
| 428 |
"required": True, |
| 429 |
} |
| 430 |
assert method_list["responses"] == { |
| 431 |
200: { |
| 432 |
"content": { |
| 433 |
"application/json": { |
| 434 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 435 |
} |
| 436 |
}, |
| 437 |
"description": "OK", |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
|
| 442 |
def test_schema_body_schema(schema): |
| 443 |
method_list = schema["paths"]["/api/test-body-schema"]["post"] |
| 444 |
|
| 445 |
assert method_list["requestBody"] == { |
| 446 |
"content": { |
| 447 |
"application/json": {"schema": {"$ref": "#/components/schemas/Payload"}}, |
| 448 |
}, |
| 449 |
"required": True, |
| 450 |
} |
| 451 |
assert method_list["responses"] == { |
| 452 |
200: { |
| 453 |
"content": { |
| 454 |
"application/json": { |
| 455 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 456 |
} |
| 457 |
}, |
| 458 |
"description": "OK", |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
|
| 463 |
def test_schema_path(schema): |
| 464 |
method_list = schema["paths"]["/api/test-path/{i}/{f}"]["get"] |
| 465 |
|
| 466 |
assert "requestBody" not in method_list |
| 467 |
|
| 468 |
assert method_list["parameters"] == [ |
| 469 |
{ |
| 470 |
"in": "path", |
| 471 |
"name": "i", |
| 472 |
"schema": {"title": "I", "type": "integer"}, |
| 473 |
"required": True, |
| 474 |
}, |
| 475 |
{ |
| 476 |
"in": "path", |
| 477 |
"name": "f", |
| 478 |
"schema": {"title": "F", "type": "number"}, |
| 479 |
"required": True, |
| 480 |
}, |
| 481 |
] |
| 482 |
|
| 483 |
assert method_list["responses"] == { |
| 484 |
200: { |
| 485 |
"content": { |
| 486 |
"application/json": { |
| 487 |
"schema": {"$ref": "#/components/schemas/Response"}, |
| 488 |
}, |
| 489 |
}, |
| 490 |
"description": "OK", |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
|
| 495 |
@pytest.mark.skipif( |
| 496 |
version_info < (3, 9), |
| 497 |
reason="requires py3.9+ for Annotated[] at the route definition site", |
| 498 |
) |
| 499 |
def test_schema_pathex(schema): |
| 500 |
method_list = schema["paths"]["/api/test-pathex/{path_ex}"]["get"] |
| 501 |
|
| 502 |
assert "requestBody" not in method_list |
| 503 |
|
| 504 |
assert method_list["parameters"] == [ |
| 505 |
{ |
| 506 |
"in": "path", |
| 507 |
"name": "path_ex", |
| 508 |
"schema": { |
| 509 |
"title": "Path Ex", |
| 510 |
"type": "string", |
| 511 |
"format": "custom-format", |
| 512 |
"description": "path_ex description", |
| 513 |
"example": "example_string", |
| 514 |
}, |
| 515 |
"required": True, |
| 516 |
"example": "example_string", |
| 517 |
"description": "path_ex description", |
| 518 |
}, |
| 519 |
] |
| 520 |
|
| 521 |
assert method_list["responses"] == { |
| 522 |
200: { |
| 523 |
"content": { |
| 524 |
"application/json": { |
| 525 |
"schema": { |
| 526 |
"example": "example_string", |
| 527 |
"format": "custom-format", |
| 528 |
"title": "Response", |
| 529 |
"type": "string", |
| 530 |
}, |
| 531 |
}, |
| 532 |
}, |
| 533 |
"description": "OK", |
| 534 |
} |
| 535 |
} |
| 536 |
|
| 537 |
|
| 538 |
def test_schema_form(schema): |
| 539 |
method_list = schema["paths"]["/api/test-form"]["post"] |
| 540 |
|
| 541 |
assert method_list["requestBody"] == { |
| 542 |
"content": { |
| 543 |
"application/x-www-form-urlencoded": { |
| 544 |
"schema": { |
| 545 |
"title": "FormParams", |
| 546 |
"type": "object", |
| 547 |
"properties": { |
| 548 |
"i": {"title": "I", "type": "integer"}, |
| 549 |
"f": {"title": "F", "type": "number"}, |
| 550 |
}, |
| 551 |
"required": ["i", "f"], |
| 552 |
} |
| 553 |
} |
| 554 |
}, |
| 555 |
"required": True, |
| 556 |
} |
| 557 |
assert method_list["responses"] == { |
| 558 |
200: { |
| 559 |
"description": "OK", |
| 560 |
"content": { |
| 561 |
"application/json": { |
| 562 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 563 |
} |
| 564 |
}, |
| 565 |
} |
| 566 |
} |
| 567 |
|
| 568 |
|
| 569 |
def test_schema_single(schema): |
| 570 |
method_list = schema["paths"]["/api/test-form-single"]["post"] |
| 571 |
|
| 572 |
assert method_list["requestBody"] == { |
| 573 |
"content": { |
| 574 |
"application/x-www-form-urlencoded": { |
| 575 |
"schema": { |
| 576 |
"properties": {"data": {"title": "Data", "type": "number"}}, |
| 577 |
"required": ["data"], |
| 578 |
"title": "FormParams", |
| 579 |
"type": "object", |
| 580 |
} |
| 581 |
} |
| 582 |
}, |
| 583 |
"required": True, |
| 584 |
} |
| 585 |
assert method_list["responses"] == { |
| 586 |
200: { |
| 587 |
"description": "OK", |
| 588 |
"content": { |
| 589 |
"application/json": { |
| 590 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 591 |
} |
| 592 |
}, |
| 593 |
} |
| 594 |
} |
| 595 |
|
| 596 |
|
| 597 |
def test_schema_form_body(schema): |
| 598 |
method_list = schema["paths"]["/api/test-form-body"]["post"] |
| 599 |
|
| 600 |
assert method_list["requestBody"] == { |
| 601 |
"content": { |
| 602 |
"multipart/form-data": { |
| 603 |
"schema": { |
| 604 |
"properties": { |
| 605 |
"i": {"default": 10, "title": "I", "type": "integer"}, |
| 606 |
"s": {"default": "10", "title": "S", "type": "string"}, |
| 607 |
}, |
| 608 |
"title": "MultiPartBodyParams", |
| 609 |
"type": "object", |
| 610 |
} |
| 611 |
} |
| 612 |
}, |
| 613 |
"required": True, |
| 614 |
} |
| 615 |
assert method_list["responses"] == { |
| 616 |
200: { |
| 617 |
"description": "OK", |
| 618 |
"content": { |
| 619 |
"application/json": { |
| 620 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 621 |
} |
| 622 |
}, |
| 623 |
} |
| 624 |
} |
| 625 |
|
| 626 |
|
| 627 |
def test_schema_form_file(schema): |
| 628 |
method_list = schema["paths"]["/api/test-form-file"]["post"] |
| 629 |
|
| 630 |
assert method_list["requestBody"] == { |
| 631 |
"content": { |
| 632 |
"multipart/form-data": { |
| 633 |
"schema": { |
| 634 |
"properties": { |
| 635 |
"files": { |
| 636 |
"items": {"format": "binary", "type": "string"}, |
| 637 |
"title": "Files", |
| 638 |
"type": "array", |
| 639 |
}, |
| 640 |
"i": {"title": "I", "type": "integer"}, |
| 641 |
"f": {"title": "F", "type": "number"}, |
| 642 |
}, |
| 643 |
"required": ["files", "i", "f"], |
| 644 |
"title": "MultiPartBodyParams", |
| 645 |
"type": "object", |
| 646 |
} |
| 647 |
} |
| 648 |
}, |
| 649 |
"required": True, |
| 650 |
} |
| 651 |
assert method_list["responses"] == { |
| 652 |
200: { |
| 653 |
"description": "OK", |
| 654 |
"content": { |
| 655 |
"application/json": { |
| 656 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 657 |
} |
| 658 |
}, |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
|
| 663 |
def test_schema_body_file(schema): |
| 664 |
method_list = schema["paths"]["/api/test-body-file"]["post"] |
| 665 |
|
| 666 |
assert method_list["requestBody"] == { |
| 667 |
"content": { |
| 668 |
"multipart/form-data": { |
| 669 |
"schema": { |
| 670 |
"properties": { |
| 671 |
"body": {"$ref": "#/components/schemas/Payload"}, |
| 672 |
"files": { |
| 673 |
"items": {"format": "binary", "type": "string"}, |
| 674 |
"title": "Files", |
| 675 |
"type": "array", |
| 676 |
}, |
| 677 |
}, |
| 678 |
"required": ["files", "body"], |
| 679 |
"title": "MultiPartBodyParams", |
| 680 |
"type": "object", |
| 681 |
} |
| 682 |
} |
| 683 |
}, |
| 684 |
"required": True, |
| 685 |
} |
| 686 |
assert method_list["responses"] == { |
| 687 |
200: { |
| 688 |
"description": "OK", |
| 689 |
"content": { |
| 690 |
"application/json": { |
| 691 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 692 |
} |
| 693 |
}, |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
|
| 698 |
def test_schema_title_description(schema): |
| 699 |
method_list = schema["paths"]["/api/test-title-description/"]["post"] |
| 700 |
|
| 701 |
assert method_list["summary"] == "Best API Ever" |
| 702 |
assert method_list["tags"] == ["a-tag"] |
| 703 |
|
| 704 |
assert method_list["requestBody"] == { |
| 705 |
"content": { |
| 706 |
"multipart/form-data": { |
| 707 |
"schema": { |
| 708 |
"properties": { |
| 709 |
"file": { |
| 710 |
"description": "file param desc", |
| 711 |
"format": "binary", |
| 712 |
"title": "File", |
| 713 |
"type": "string", |
| 714 |
} |
| 715 |
}, |
| 716 |
"required": ["file"], |
| 717 |
"title": "FileParams", |
| 718 |
"type": "object", |
| 719 |
} |
| 720 |
} |
| 721 |
}, |
| 722 |
"required": True, |
| 723 |
} |
| 724 |
|
| 725 |
assert method_list["parameters"] == [ |
| 726 |
{ |
| 727 |
"in": "query", |
| 728 |
"name": "param1", |
| 729 |
"required": True, |
| 730 |
"schema": {"title": "param 1 title", "type": "integer"}, |
| 731 |
}, |
| 732 |
{ |
| 733 |
"in": "query", |
| 734 |
"name": "param2", |
| 735 |
"description": "param 2 desc", |
| 736 |
"required": False, |
| 737 |
"schema": { |
| 738 |
"default": "A Default", |
| 739 |
"description": "param 2 desc", |
| 740 |
"title": "Param2", |
| 741 |
"type": "string", |
| 742 |
}, |
| 743 |
}, |
| 744 |
] |
| 745 |
|
| 746 |
assert method_list["responses"] == { |
| 747 |
200: { |
| 748 |
"content": { |
| 749 |
"application/json": { |
| 750 |
"schema": {"$ref": "#/components/schemas/Response"} |
| 751 |
} |
| 752 |
}, |
| 753 |
"description": "OK", |
| 754 |
} |
| 755 |
} |
| 756 |
|
| 757 |
|
| 758 |
def test_schema_deprecated_example_examples(schema): |
| 759 |
method_list = schema["paths"]["/api/test-deprecated-example-examples/"]["post"] |
| 760 |
|
| 761 |
assert method_list["parameters"] == [ |
| 762 |
{ |
| 763 |
"deprecated": True, |
| 764 |
"in": "query", |
| 765 |
"name": "param1", |
| 766 |
"required": False, |
| 767 |
"schema": {"title": "Param1", "type": "integer", "deprecated": True}, |
| 768 |
}, |
| 769 |
{ |
| 770 |
"in": "query", |
| 771 |
"name": "param2", |
| 772 |
"required": True, |
| 773 |
"schema": {"title": "Param2", "type": "string", "example": "Example Value"}, |
| 774 |
"example": "Example Value", |
| 775 |
}, |
| 776 |
{ |
| 777 |
"in": "query", |
| 778 |
"name": "param3", |
| 779 |
"required": True, |
| 780 |
"schema": { |
| 781 |
"maxLength": 5, |
| 782 |
"title": "Param3", |
| 783 |
"type": "string", |
| 784 |
"examples": { |
| 785 |
"invalid": { |
| 786 |
"summary": "Invalid data is rejected with an error", |
| 787 |
"value": "MoreThan5Length", |
| 788 |
}, |
| 789 |
"normal": { |
| 790 |
"description": "A **normal** string works correctly.", |
| 791 |
"summary": "A normal example", |
| 792 |
"value": "Foo", |
| 793 |
}, |
| 794 |
}, |
| 795 |
}, |
| 796 |
"examples": { |
| 797 |
"invalid": { |
| 798 |
"summary": "Invalid data is rejected with an error", |
| 799 |
"value": "MoreThan5Length", |
| 800 |
}, |
| 801 |
"normal": { |
| 802 |
"description": "A **normal** string works correctly.", |
| 803 |
"summary": "A normal example", |
| 804 |
"value": "Foo", |
| 805 |
}, |
| 806 |
}, |
| 807 |
}, |
| 808 |
] |
| 809 |
|
| 810 |
assert method_list["responses"] == { |
| 811 |
200: { |
| 812 |
"description": "OK", |
| 813 |
} |
| 814 |
} |
| 815 |
|
| 816 |
|
| 817 |
def test_union_payload_type(schema): |
| 818 |
method = schema["paths"]["/api/test-union-type"]["post"] |
| 819 |
|
| 820 |
assert method["requestBody"] == { |
| 821 |
"content": { |
| 822 |
"application/json": { |
| 823 |
"schema": { |
| 824 |
"anyOf": [ |
| 825 |
{"$ref": "#/components/schemas/TypeA"}, |
| 826 |
{"$ref": "#/components/schemas/TypeB"}, |
| 827 |
], |
| 828 |
"title": "Data", |
| 829 |
} |
| 830 |
} |
| 831 |
}, |
| 832 |
"required": True, |
| 833 |
} |
| 834 |
|
| 835 |
|
| 836 |
def test_union_payload_simple(schema): |
| 837 |
method = schema["paths"]["/api/test-union-type-with-simple"]["post"] |
| 838 |
|
| 839 |
print(method["requestBody"]) |
| 840 |
assert method["requestBody"] == { |
| 841 |
"content": { |
| 842 |
"application/json": { |
| 843 |
"schema": { |
| 844 |
"title": "Data", |
| 845 |
"anyOf": [ |
| 846 |
{"type": "integer"}, |
| 847 |
{"$ref": "#/components/schemas/TypeB"}, |
| 848 |
], |
| 849 |
} |
| 850 |
} |
| 851 |
}, |
| 852 |
"required": True, |
| 853 |
} |
| 854 |
|
| 855 |
|
| 856 |
@pytest.mark.skipif( |
| 857 |
sys.version_info < (3, 10), |
| 858 |
reason="requires Python 3.10 or higher (PEP 604)", |
| 859 |
) |
| 860 |
def test_new_union_payload_type(schema): |
| 861 |
method = schema["paths"]["/api/test-new-union-type"]["post"] |
| 862 |
|
| 863 |
assert method["requestBody"] == { |
| 864 |
"content": { |
| 865 |
"application/json": { |
| 866 |
"schema": { |
| 867 |
"anyOf": [ |
| 868 |
{"$ref": "#/components/schemas/TypeA"}, |
| 869 |
{"$ref": "#/components/schemas/TypeB"}, |
| 870 |
], |
| 871 |
"title": "Data", |
| 872 |
} |
| 873 |
} |
| 874 |
}, |
| 875 |
"required": True, |
| 876 |
} |
| 877 |
|
| 878 |
|
| 879 |
def test_get_openapi_urls(): |
| 880 |
api = NinjaAPI(openapi_url=None) |
| 881 |
paths = get_openapi_urls(api) |
| 882 |
assert len(paths) == 0 |
| 883 |
|
| 884 |
api = NinjaAPI(docs_url=None) |
| 885 |
paths = get_openapi_urls(api) |
| 886 |
assert len(paths) == 1 |
| 887 |
|
| 888 |
api = NinjaAPI(openapi_url="/path", docs_url="/path") |
| 889 |
with pytest.raises( |
| 890 |
AssertionError, match="Please use different urls for openapi_url and docs_url" |
| 891 |
): |
| 892 |
get_openapi_urls(api) |
| 893 |
|
| 894 |
|
| 895 |
def test_unique_operation_ids(capsys): |
| 896 |
api = NinjaAPI() |
| 897 |
|
| 898 |
@api.get("/1") |
| 899 |
def same_name(request): |
| 900 |
pass |
| 901 |
|
| 902 |
@api.get("/2") |
| 903 |
def same_name(request): |
| 904 |
pass |
| 905 |
|
| 906 |
api.get_openapi_schema() |
| 907 |
captured = capsys.readouterr() |
| 908 |
assert '"test_openapi_schema_same_name" is already used ' in captured.out |
| 909 |
|
| 910 |
|
| 911 |
def test_docs_decorator(): |
| 912 |
api = NinjaAPI(docs_decorator=staff_member_required) |
| 913 |
|
| 914 |
paths = get_openapi_urls(api) |
| 915 |
assert len(paths) == 2 |
| 916 |
for ptrn in paths: |
| 917 |
request = Mock(user=Mock(is_staff=True)) |
| 918 |
result = ptrn.callback(request) |
| 919 |
assert result.status_code == 200 |
| 920 |
|
| 921 |
request = Mock(user=Mock(is_staff=False)) |
| 922 |
request.build_absolute_uri = lambda: "http://example.com" |
| 923 |
result = ptrn.callback(request) |
| 924 |
assert result.status_code == 302 |
| 925 |
|
| 926 |
|
| 927 |
class TestRenderer(JSONRenderer): |
| 928 |
media_type = "custom/type" |
| 929 |
|
| 930 |
|
| 931 |
def test_renderer_media_type(): |
| 932 |
api = NinjaAPI(renderer=TestRenderer) |
| 933 |
|
| 934 |
@api.get("/1", response=TypeA) |
| 935 |
def same_name( |
| 936 |
request, |
| 937 |
): |
| 938 |
pass |
| 939 |
|
| 940 |
schema = api.get_openapi_schema() |
| 941 |
method = schema["paths"]["/api/1"]["get"] |
| 942 |
assert method["responses"] == { |
| 943 |
200: { |
| 944 |
"content": { |
| 945 |
"custom/type": {"schema": {"$ref": "#/components/schemas/TypeA"}} |
| 946 |
}, |
| 947 |
"description": "OK", |
| 948 |
} |
| 949 |
} |
| 950 |
|
| 951 |
|
| 952 |
def test_all_paths_rendered(): |
| 953 |
api = NinjaAPI(renderer=TestRenderer) |
| 954 |
|
| 955 |
@api.post("/1") |
| 956 |
def some_name_create( |
| 957 |
request, |
| 958 |
): |
| 959 |
pass |
| 960 |
|
| 961 |
@api.get("/1") |
| 962 |
def some_name_list( |
| 963 |
request, |
| 964 |
): |
| 965 |
pass |
| 966 |
|
| 967 |
@api.get("/1/{param}") |
| 968 |
def some_name_get_one(request, param: int): |
| 969 |
pass |
| 970 |
|
| 971 |
@api.delete("/1/{param}") |
| 972 |
def some_name_delete(request, param: int): |
| 973 |
pass |
| 974 |
|
| 975 |
schema = api.get_openapi_schema() |
| 976 |
|
| 977 |
expected_result = {"/api/1": ["post", "get"], "/api/1/{param}": ["get", "delete"]} |
| 978 |
result = {p: list(schema["paths"][p].keys()) for p in schema["paths"].keys()} |
| 979 |
assert expected_result == result |
| 980 |
|
| 981 |
|
| 982 |
def test_all_paths_typed_params_rendered(): |
| 983 |
api = NinjaAPI(renderer=TestRenderer) |
| 984 |
|
| 985 |
@api.post("/1") |
| 986 |
def some_name_create( |
| 987 |
request, |
| 988 |
): |
| 989 |
pass |
| 990 |
|
| 991 |
@api.get("/1") |
| 992 |
def some_name_list( |
| 993 |
request, |
| 994 |
): |
| 995 |
pass |
| 996 |
|
| 997 |
@api.get("/1/{int:param}") |
| 998 |
def some_name_get_one(request, param: int): |
| 999 |
pass |
| 1000 |
|
| 1001 |
@api.delete("/1/{str:param}") |
| 1002 |
def some_name_delete(request, param: str): |
| 1003 |
pass |
| 1004 |
|
| 1005 |
schema = api.get_openapi_schema() |
| 1006 |
|
| 1007 |
expected_result = {"/api/1": ["post", "get"], "/api/1/{param}": ["get", "delete"]} |
| 1008 |
result = {p: list(schema["paths"][p].keys()) for p in schema["paths"].keys()} |
| 1009 |
assert expected_result == result |
| 1010 |
|
| 1011 |
|
| 1012 |
def test_no_default_for_custom_items_attribute(): |
| 1013 |
api = NinjaAPI(renderer=TestRenderer) |
| 1014 |
|
| 1015 |
class EmployeeOut(Schema): |
| 1016 |
id: int |
| 1017 |
first_name: str |
| 1018 |
last_name: str |
| 1019 |
|
| 1020 |
class CustomPagination(PaginationBase): |
| 1021 |
class Output(Schema): |
| 1022 |
data: List[Any] |
| 1023 |
detail: str |
| 1024 |
total: int |
| 1025 |
|
| 1026 |
items_attribute: str = "data" |
| 1027 |
|
| 1028 |
def paginate_queryset(self, queryset, pagination, **params): |
| 1029 |
pass |
| 1030 |
|
| 1031 |
@api.get( |
| 1032 |
"/employees", |
| 1033 |
auth=["OAuth"], |
| 1034 |
response=List[EmployeeOut], |
| 1035 |
) |
| 1036 |
@paginate(CustomPagination) |
| 1037 |
def get_employees(request): |
| 1038 |
pass |
| 1039 |
|
| 1040 |
schema = api.get_openapi_schema() |
| 1041 |
|
| 1042 |
paged_employee_out = schema["components"]["schemas"]["PagedEmployeeOut"] |
| 1043 |
|
| 1044 |
assert "default" not in paged_employee_out["properties"]["data"] |
| 1045 |
|
| 1046 |
|
| 1047 |
def test_by_alias_uses_serialization_alias_simple(): |
| 1048 |
"""Test the serialization_alias on the Field is used when by_alias=True is set on the route""" |
| 1049 |
api = NinjaAPI() |
| 1050 |
|
| 1051 |
class PersonOut(Schema): |
| 1052 |
uuid: str = Field(..., serialization_alias="id") |
| 1053 |
name: str = Field(..., serialization_alias="fullName") |
| 1054 |
|
| 1055 |
@api.get("/person", response={200: PersonOut}, by_alias=True) |
| 1056 |
def get_user(request): |
| 1057 |
return {"uuid": uuid4(), "fullname": "John Snow"} |
| 1058 |
|
| 1059 |
schema = api.get_openapi_schema() |
| 1060 |
user_alias_schema = schema["components"]["schemas"]["PersonOut"] |
| 1061 |
assert user_alias_schema == { |
| 1062 |
"title": "PersonOut", |
| 1063 |
"type": "object", |
| 1064 |
"properties": { |
| 1065 |
"id": {"title": "Id", "type": "string"}, |
| 1066 |
"fullName": {"type": "string", "title": "Fullname"}, |
| 1067 |
}, |
| 1068 |
"required": ["id", "fullName"], |
| 1069 |
} |
| 1070 |
|
| 1071 |
|
| 1072 |
def test_by_alias_uses_validation_alias_simple(): |
| 1073 |
"""Test the serialization_alias on the Field is used when by_alias=True is set on the route""" |
| 1074 |
api = NinjaAPI() |
| 1075 |
|
| 1076 |
class PersonIn(Schema): |
| 1077 |
uuid: str = Field(..., validation_alias="id") |
| 1078 |
name: str = Field(..., validation_alias="fullName") |
| 1079 |
|
| 1080 |
@api.get("/person", by_alias=True) |
| 1081 |
def get_user(request, param: PersonIn): |
| 1082 |
return {"uuid": uuid4(), "fullname": "John Snow"} |
| 1083 |
|
| 1084 |
schema = api.get_openapi_schema() |
| 1085 |
user_alias_schema = schema["components"]["schemas"]["PersonIn"] |
| 1086 |
assert user_alias_schema == { |
| 1087 |
"title": "PersonIn", |
| 1088 |
"type": "object", |
| 1089 |
"properties": { |
| 1090 |
"id": {"title": "Id", "type": "string"}, |
| 1091 |
"fullName": {"type": "string", "title": "Fullname"}, |
| 1092 |
}, |
| 1093 |
"required": ["id", "fullName"], |
| 1094 |
} |
| 1095 |
|
| 1096 |
|
| 1097 |
@pytest.mark.django_db |
| 1098 |
def test_by_alias_uses_serialization_alias_model(): |
| 1099 |
"""Test the serialization_alias on the Field is used when by_alias=True is set on the route""" |
| 1100 |
api = NinjaAPI() |
| 1101 |
|
| 1102 |
class Person(models.Model): |
| 1103 |
uuid = models.CharField( |
| 1104 |
max_length=36, unique=True, default=lambda: str(uuid4()), editable=False |
| 1105 |
) |
| 1106 |
created = models.DateTimeField(auto_now_add=True) |
| 1107 |
|
| 1108 |
class Meta: |
| 1109 |
app_label = "tests" |
| 1110 |
|
| 1111 |
class PersonModelOut(ModelSchema): |
| 1112 |
uuid: str = Field(..., serialization_alias="id") |
| 1113 |
|
| 1114 |
class Meta: |
| 1115 |
model = Person |
| 1116 |
fields = ["created"] |
| 1117 |
|
| 1118 |
@api.get("/person", response={200: PersonModelOut}, by_alias=True) |
| 1119 |
def get_user(request): |
| 1120 |
return Person(fullname="John Snow") |
| 1121 |
|
| 1122 |
schema = api.get_openapi_schema() |
| 1123 |
user_alias_schema = schema["components"]["schemas"]["PersonModelOut"] |
| 1124 |
assert user_alias_schema == { |
| 1125 |
"title": "PersonModelOut", |
| 1126 |
"type": "object", |
| 1127 |
"properties": { |
| 1128 |
"id": {"title": "Id", "type": "string"}, |
| 1129 |
"created": {"type": "string", "format": "date-time", "title": "Created"}, |
| 1130 |
}, |
| 1131 |
"required": ["id", "created"], |
| 1132 |
} |