openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
tests/test_legacy_response.py
84lines · modecode
| 1 | import json |
| 2 | from typing import cast |
| 3 | from typing_extensions import Annotated |
| 4 | |
| 5 | import httpx |
| 6 | import pytest |
| 7 | import pydantic |
| 8 | |
| 9 | from openai import OpenAI, BaseModel |
| 10 | from openai._streaming import Stream |
| 11 | from openai._base_client import FinalRequestOptions |
| 12 | from openai._legacy_response import LegacyAPIResponse |
| 13 | |
| 14 | |
| 15 | class PydanticModel(pydantic.BaseModel): |
| 16 | ... |
| 17 | |
| 18 | |
| 19 | def test_response_parse_mismatched_basemodel(client: OpenAI) -> None: |
| 20 | response = LegacyAPIResponse( |
| 21 | raw=httpx.Response(200, content=b"foo"), |
| 22 | client=client, |
| 23 | stream=False, |
| 24 | stream_cls=None, |
| 25 | cast_to=str, |
| 26 | options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 27 | ) |
| 28 | |
| 29 | with pytest.raises( |
| 30 | TypeError, |
| 31 | match="Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`", |
| 32 | ): |
| 33 | response.parse(to=PydanticModel) |
| 34 | |
| 35 | |
| 36 | def test_response_parse_custom_stream(client: OpenAI) -> None: |
| 37 | response = LegacyAPIResponse( |
| 38 | raw=httpx.Response(200, content=b"foo"), |
| 39 | client=client, |
| 40 | stream=True, |
| 41 | stream_cls=None, |
| 42 | cast_to=str, |
| 43 | options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 44 | ) |
| 45 | |
| 46 | stream = response.parse(to=Stream[int]) |
| 47 | assert stream._cast_to == int |
| 48 | |
| 49 | |
| 50 | class CustomModel(BaseModel): |
| 51 | foo: str |
| 52 | bar: int |
| 53 | |
| 54 | |
| 55 | def test_response_parse_custom_model(client: OpenAI) -> None: |
| 56 | response = LegacyAPIResponse( |
| 57 | raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), |
| 58 | client=client, |
| 59 | stream=False, |
| 60 | stream_cls=None, |
| 61 | cast_to=str, |
| 62 | options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 63 | ) |
| 64 | |
| 65 | obj = response.parse(to=CustomModel) |
| 66 | assert obj.foo == "hello!" |
| 67 | assert obj.bar == 2 |
| 68 | |
| 69 | |
| 70 | def test_response_parse_annotated_type(client: OpenAI) -> None: |
| 71 | response = LegacyAPIResponse( |
| 72 | raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), |
| 73 | client=client, |
| 74 | stream=False, |
| 75 | stream_cls=None, |
| 76 | cast_to=str, |
| 77 | options=FinalRequestOptions.construct(method="get", url="/foo"), |
| 78 | ) |
| 79 | |
| 80 | obj = response.parse( |
| 81 | to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), |
| 82 | ) |
| 83 | assert obj.foo == "hello!" |
| 84 | assert obj.bar == 2 |
| 85 | |