openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
custom-code-from-generated-20260521

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

tests/lib/snapshots.py

100lines · modeblame

3fc6b983Alex Chang1 months ago1from __future__ import annotations
2
3import os
4import json
5from typing import Any, Callable, Awaitable
6from typing_extensions import TypeVar
7
8import httpx
9from respx import MockRouter
10from inline_snapshot import get_snapshot_value
11
12from openai import OpenAI, AsyncOpenAI
13
14_T = TypeVar("_T")
15
16
17def make_snapshot_request(
18func: Callable[[OpenAI], _T],
19*,
20content_snapshot: Any,
21respx_mock: MockRouter,
22mock_client: OpenAI,
23path: str,
24) -> _T:
25live = os.environ.get("OPENAI_LIVE") == "1"
26if live:
27
28def _on_response(response: httpx.Response) -> None:
29# update the content snapshot
30assert json.dumps(json.loads(response.read())) == content_snapshot
31
32respx_mock.stop()
33
34client = OpenAI(
35http_client=httpx.Client(
36event_hooks={
37"response": [_on_response],
38}
39)
40)
41else:
42respx_mock.post(path).mock(
43return_value=httpx.Response(
44200,
45content=get_snapshot_value(content_snapshot),
46headers={"content-type": "application/json"},
47)
48)
49
50client = mock_client
51
52result = func(client)
53
54if live:
55client.close()
56
57return result
58
59
60async def make_async_snapshot_request(
61func: Callable[[AsyncOpenAI], Awaitable[_T]],
62*,
63content_snapshot: Any,
64respx_mock: MockRouter,
65mock_client: AsyncOpenAI,
66path: str,
67) -> _T:
68live = os.environ.get("OPENAI_LIVE") == "1"
69if live:
70
71async def _on_response(response: httpx.Response) -> None:
72# update the content snapshot
73assert json.dumps(json.loads(await response.aread())) == content_snapshot
74
75respx_mock.stop()
76
77client = AsyncOpenAI(
78http_client=httpx.AsyncClient(
79event_hooks={
80"response": [_on_response],
81}
82)
83)
84else:
85respx_mock.post(path).mock(
86return_value=httpx.Response(
87200,
88content=get_snapshot_value(content_snapshot),
89headers={"content-type": "application/json"},
90)
91)
92
93client = mock_client
94
95result = await func(client)
96
97if live:
98await client.close()
99
100return result