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

v3x/parameter - encoding … #215

Merged
merged 1 commit into from
Feb 15, 2024
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
42 changes: 32 additions & 10 deletions aiopenapi3/v30/parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import decimal
import typing
import uuid
import json
from typing import Union, Optional, Dict, Any
from collections.abc import MutableMapping

Expand Down Expand Up @@ -54,12 +55,19 @@
value = schema.model(value)
if isinstance(value, BaseModel):
type_ = "object"
elif (t := type(value)) == bool:
type_ = "boolean"
elif t in (bytes, datetime.datetime, datetime.date, datetime.time, datetime.timedelta, uuid.UUID):
elif (t := type(value)) in (
bytes,
datetime.datetime,
datetime.date,
datetime.time,
datetime.timedelta,
uuid.UUID,
):
type_ = "string"
elif t in TYPES_SCHEMA_MAP:
type_ = TYPES_SCHEMA_MAP[t]
else:
type_ = TYPES_SCHEMA_MAP[type(value)]
raise TypeError(f"Unsupported type {t}")

Check warning on line 70 in aiopenapi3/v30/parameter.py

View check run for this annotation

Codecov / codecov/patch

aiopenapi3/v30/parameter.py#L70

Added line #L70 was not covered by tests

return self._encode_value(name, type_, value, schema, explode, style)

Expand All @@ -74,9 +82,11 @@
https://www.rfc-editor.org/rfc/rfc6570#section-3.2.8
:param type_:
"""
if type_ in frozenset(["string", "number", "boolean", "integer"]):
if type_ in frozenset(["string", "number", "integer"]):
# ;color=blue
value = f";{name}={value}"
elif type_ == "boolean":
value = f";{name}={json.dumps(value)}"
elif type_ == "null":
value = f";{name}"
elif type_ == "array":
Expand All @@ -101,11 +111,15 @@
"""
3.2.5. Label Expansion with Dot-Prefix: {.var}

https://www.rfc-editor.org/rfc/rfc6570#section-3.2.8
https://www.rfc-editor.org/rfc/rfc6570#section-3.2.5
"""
if type_ in frozenset(["string", "number", "boolean", "integer"]):
if type_ == "string":
# .blue
value = f".{value}"
elif type_ in frozenset(["number", "integer"]):
value = f".{str(value)}"
elif type_ == "boolean":
value = f".{json.dumps(value)}"
elif type_ == "null":
value = "."
elif type_ == "array":
Expand Down Expand Up @@ -134,11 +148,15 @@
https://www.rfc-editor.org/rfc/rfc6570#section-3.2.8
"""

if type_ in frozenset(["string", "number", "boolean", "integer"]):
if type_ == "string":
# color=blue
return {name: value}
elif type_ in frozenset(["number", "integer"]):
return {name: str(value)}
elif type_ == "boolean":
return {name: json.dumps(value)}
elif type_ == "null":
return {name: None}
return {name: ""}
elif type_ == "array":
assert isinstance(value, (list, tuple))
if explode is False:
Expand Down Expand Up @@ -168,8 +186,12 @@
https://www.rfc-editor.org/rfc/rfc6570#section-3.2.2
"""

if type_ in frozenset(["string", "number", "boolean", "integer"]):
if type_ == "string":
return {name: value}
elif type_ in frozenset(["number", "integer"]):
return {name: str(value)}
elif type_ == "boolean":
return {name: json.dumps(value)}
elif type_ == "null":
return dict()
elif type_ == "array":
Expand Down
11 changes: 8 additions & 3 deletions tests/api/v2/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import errno
import uuid
from typing import Optional
from typing import Optional, Union
from typing_extensions import Annotated

import starlette.status
from fastapi import Body, Response, APIRouter, Path
from fastapi import Body, Response, Header, APIRouter, Path
from fastapi.responses import JSONResponse
from fastapi_versioning import version

Expand Down Expand Up @@ -70,7 +71,11 @@ def getPet(pet_id: str = Path(..., alias="petId")) -> schema.Pets:
@router.delete(
"/pets/{petId}", operation_id="deletePet", responses={204: {"model": None}, 404: {"model": schema.Error}}
)
def deletePet(response: Response, pet_id: uuid.UUID = Path(..., alias="petId")) -> None:
def deletePet(
response: Response,
x_raise_nonexist: Annotated[Union[bool, None], Header()],
pet_id: uuid.UUID = Path(..., alias="petId"),
) -> None:
for k, v in ZOO.items():
if pet_id == v.identifier:
del ZOO[k]
Expand Down
11 changes: 7 additions & 4 deletions tests/apiv2_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,12 @@ async def test_createPet(event_loop, server, client):
@pytest.mark.asyncio
async def test_listPet(event_loop, server, client):
r = await client._.createPet(data=randomPet(client, str(uuid.uuid4())))
l = await client._.listPet()
l = await client._.listPet(parameters={"limit": 1})
assert len(l) > 0

l = await client._.listPet(parameters={"limit": None})
assert isinstance(l, client.components.schemas["HTTPValidationError"].get_type())


@pytest.mark.asyncio
async def test_getPet(event_loop, server, client):
Expand All @@ -210,15 +213,15 @@ async def test_getPet(event_loop, server, client):

@pytest.mark.asyncio
async def test_deletePet(event_loop, server, client):
r = await client._.deletePet(parameters={"petId": uuid.uuid4()})
r = await client._.deletePet(parameters={"petId": uuid.uuid4(), "x-raise-nonexist": False})
assert type(r).model_json_schema() == client.components.schemas["Error"].get_type().model_json_schema()

await client._.createPet(data=randomPet(client, str(uuid.uuid4())))
zoo = await client._.listPet()
zoo = await client._.listPet(parameters={"limit": 1})
for pet in zoo:
while hasattr(pet, "root"):
pet = pet.root
await client._.deletePet(parameters={"petId": pet.identifier})
await client._.deletePet(parameters={"petId": pet.identifier, "x-raise-nonexist": None})


@pytest.mark.asyncio
Expand Down
Loading
Loading