Skip to content

Commit 1b18e64

Browse files
stainless-app[bot]stainless-bot
authored andcommitted
chore(client): fix parsing union responses when non-json is returned (#318)
1 parent eddc160 commit 1b18e64

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/openlayer/_models.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,8 @@ def is_basemodel(type_: type) -> bool:
380380

381381
def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
382382
origin = get_origin(type_) or type_
383+
if not inspect.isclass(origin):
384+
return False
383385
return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
384386

385387

tests/test_response.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import json
2-
from typing import List, cast
2+
from typing import Any, List, Union, cast
33
from typing_extensions import Annotated
44

55
import httpx
@@ -188,3 +188,40 @@ async def test_async_response_parse_annotated_type(async_client: AsyncOpenlayer)
188188
)
189189
assert obj.foo == "hello!"
190190
assert obj.bar == 2
191+
192+
193+
class OtherModel(BaseModel):
194+
a: str
195+
196+
197+
@pytest.mark.parametrize("client", [False], indirect=True) # loose validation
198+
def test_response_parse_expect_model_union_non_json_content(client: Openlayer) -> None:
199+
response = APIResponse(
200+
raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/text"}),
201+
client=client,
202+
stream=False,
203+
stream_cls=None,
204+
cast_to=str,
205+
options=FinalRequestOptions.construct(method="get", url="/foo"),
206+
)
207+
208+
obj = response.parse(to=cast(Any, Union[CustomModel, OtherModel]))
209+
assert isinstance(obj, str)
210+
assert obj == "foo"
211+
212+
213+
@pytest.mark.asyncio
214+
@pytest.mark.parametrize("async_client", [False], indirect=True) # loose validation
215+
async def test_async_response_parse_expect_model_union_non_json_content(async_client: AsyncOpenlayer) -> None:
216+
response = AsyncAPIResponse(
217+
raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/text"}),
218+
client=async_client,
219+
stream=False,
220+
stream_cls=None,
221+
cast_to=str,
222+
options=FinalRequestOptions.construct(method="get", url="/foo"),
223+
)
224+
225+
obj = await response.parse(to=cast(Any, Union[CustomModel, OtherModel]))
226+
assert isinstance(obj, str)
227+
assert obj == "foo"

0 commit comments

Comments
 (0)