Skip to content

Commit

Permalink
Merge pull request #144 from foarsitter/async_typeadapter_coverage
Browse files Browse the repository at this point in the history
Add coverage TypeAdapter in asend
  • Loading branch information
foarsitter authored Nov 18, 2024
2 parents 285bb11 + cabb2aa commit 177f89f
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/requestmodel/adapters/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ def send(self, client: Session) -> ResponseType:
r = self.as_request()
self.response = client.send(r.prepare())
self.handle_error(self.response)
return self.response_model.model_validate(self.response.json())
return self.adapt_type(self.response)
25 changes: 19 additions & 6 deletions src/requestmodel/model.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from typing import Any
from typing import ClassVar
from typing import Generic
from typing import Iterator
from typing import Optional
from typing import Protocol
from typing import Set
from typing import Type

Expand All @@ -13,6 +15,7 @@
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import TypeAdapter
from pydantic._internal._model_construction import ModelMetaclass
from typing_extensions import get_type_hints
from typing_extensions import override

Expand All @@ -26,6 +29,10 @@
from .utils import unify_body


class JSONResponse(Protocol): # pragma: no cover
def json(self) -> Any: ... # noqa: E704


class BaseRequestModel(BaseModel, Generic[ResponseType]):
"""Declarative way to define a model"""

Expand Down Expand Up @@ -86,6 +93,15 @@ def request_args_for_values(self) -> RequestArgs:

return request_args

def adapt_type(self, response: JSONResponse) -> ResponseType:
if isinstance(self.response_model, TypeAdapter):
return self.response_model.validate_python(response.json())

if isinstance(self.response_model, (BaseModel, ModelMetaclass)):
return self.response_model.model_validate(response.json())

raise ValueError("response_model must be a TypeAdapter or a BaseModel")


class RequestModel(BaseRequestModel[ResponseType]):
raw_response: Optional[Response] = None
Expand All @@ -98,18 +114,15 @@ def send(self, client: Client) -> ResponseType:
r = self.as_request(client)
self.raw_response = client.send(r)
self.handle_error(self.raw_response)
if isinstance(self.response_model, TypeAdapter):
return self.response_model.validate_python(self.raw_response.json())
return self.response_model.model_validate(self.raw_response.json())

return self.adapt_type(self.raw_response)

async def asend(self, client: AsyncClient) -> ResponseType:
"""Send the request asynchronously"""
r = self.as_request(client)
self.raw_response = await client.send(r)
self.handle_error(self.raw_response)
if isinstance(self.response_model, TypeAdapter):
return self.response_model.validate_python(self.raw_response.json())
return self.response_model.model_validate(self.raw_response.json())
return self.adapt_type(self.raw_response)

def as_request(self, client: BaseClient) -> Request:
"""Transform the properties of the object into a request"""
Expand Down
8 changes: 7 additions & 1 deletion src/requestmodel/typing.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
from typing import Any
from typing import Dict
from typing import List
from typing import Type
from typing import TypeVar
from typing import Union

from pydantic import BaseModel
from pydantic import TypeAdapter
from pydantic.fields import FieldInfo


ResponseType = TypeVar("ResponseType", bound=BaseModel)
ResponseType = TypeVar(
"ResponseType",
bound=Union[BaseModel, TypeAdapter[List[BaseModel]], List[BaseModel]],
)
RequestArgs = Dict[Type[FieldInfo], Dict[str, Any]]
9 changes: 9 additions & 0 deletions tests/test_request_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,12 @@ def test_type_adapter() -> None:
response = request.send(client)

assert response == [NameModel(name="test")]


def test_type_adapter_exception() -> None:
request = TypeAdapterRequest()
TypeAdapterRequest.response_model = int # type: ignore
with pytest.raises(
ValueError, match="response_model must be a TypeAdapter or a BaseModel"
):
request.adapt_type(SimpleResponse(data="test"))

0 comments on commit 177f89f

Please sign in to comment.