Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support both new and old style Union/Optional #687

Merged
merged 3 commits into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion ninja/signature/details.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@
"FuncParam", ["name", "alias", "source", "annotation", "is_collection"]
)

try:
from types import UnionType

UNION_TYPES = (Union, UnionType)
except ImportError:
UNION_TYPES = (Union,)


class ViewSignature:
FLATTEN_PATH_SEP = (
Expand Down Expand Up @@ -247,7 +254,7 @@ def _get_param_type(self, name: str, arg: inspect.Parameter) -> FuncParam:

def is_pydantic_model(cls: Any) -> bool:
try:
if get_collection_origin(cls) == Union:
if get_collection_origin(cls) in UNION_TYPES:
return any(issubclass(arg, pydantic.BaseModel) for arg in get_args(cls))
return issubclass(cls, pydantic.BaseModel)
except TypeError:
Expand Down
32 changes: 32 additions & 0 deletions tests/test_openapi_schema.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
from typing import List, Union
from unittest.mock import Mock

Expand Down Expand Up @@ -107,6 +108,14 @@ 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"],
Expand Down Expand Up @@ -659,6 +668,29 @@ def test_union_payload_simple(schema):
}


@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)
Expand Down