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