Skip to content

Commit

Permalink
Type checking against TypeAdapter and BaseModel
Browse files Browse the repository at this point in the history
  • Loading branch information
foarsitter committed Nov 18, 2024
1 parent 55071a0 commit c336641
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 10 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):
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]]
4 changes: 2 additions & 2 deletions tests/test_request_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,8 @@ def test_type_adapter() -> None:
async def test_type_adapter_async() -> None:
request = TypeAdapterRequest()

async with AsyncClient(app=app, base_url="http://test") as client:
async with AsyncClient(app=app, base_url="http://test", timeout=30) as aclient:

response = await request.asend(client)
response = await request.asend(aclient)

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

0 comments on commit c336641

Please sign in to comment.