Debian Codegraph @

tests/conftest.py

raw
1 from __future__ import annotations
2
3 import os
4 import logging
5 from typing import TYPE_CHECKING, Any, Iterator, AsyncIterator
6
7 import httpx2
8 import pytest
9 import inline_snapshot
10 from http_snapshot import SnapshotSerializerOptions
11 from pytest_asyncio import is_async_test
12 from http_snapshot.httpx import HttpxSyncSnapshotClient, HttpxAsyncSnapshotClient
13
14 from anthropic import Anthropic, AsyncAnthropic, DefaultAioHttpClient
15 from anthropic._utils import is_dict
16
17 if TYPE_CHECKING:
18 from _pytest.fixtures import FixtureRequest # pyright: ignore[reportPrivateImportUsage]
19
20 pytest.register_assert_rewrite("tests.utils")
21
22 logging.getLogger("anthropic").setLevel(logging.DEBUG)
23
24 SNAPSHOT_RESPONSE_HEADERS_EXCLUDE = [
25 "date",
26 "request-id",
27 "anthropic-organization-id",
28 "x-envoy-upstream-service-time",
29 "cf-ray",
30 ]
31
32 SNAPSHOT_REQUEST_HEADERS_EXCLUDE = [
33 "x-api-key",
34 ]
35
36
37 # automatically add `pytest.mark.asyncio()` to all of our async tests
38 # so we don't have to add that boilerplate everywhere
39 def pytest_collection_modifyitems(items: list[pytest.Function]) -> None:
40 pytest_asyncio_tests = (item for item in items if is_async_test(item))
41 session_scope_marker = pytest.mark.asyncio(loop_scope="session")
42 for async_test in pytest_asyncio_tests:
43 async_test.add_marker(session_scope_marker, append=False)
44
45 # We skip tests that use both the aiohttp client and respx_mock as respx_mock
46 # doesn't support custom transports.
47 for item in items:
48 if "async_client" not in item.fixturenames or "respx_mock" not in item.fixturenames:
49 continue
50
51 if not hasattr(item, "callspec"):
52 continue
53
54 async_client_param = item.callspec.params.get("async_client")
55 if is_dict(async_client_param) and async_client_param.get("http_client") == "aiohttp":
56 item.add_marker(pytest.mark.skip(reason="aiohttp client is not compatible with respx_mock"))
57
58
59 base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
60
61 api_key = "my-anthropic-api-key"
62
63
64 @pytest.fixture(scope="session")
65 def client(request: FixtureRequest) -> Iterator[Anthropic]:
66 strict = getattr(request, "param", True)
67 if not isinstance(strict, bool):
68 raise TypeError(f"Unexpected fixture parameter type {type(strict)}, expected {bool}")
69
70 with Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=strict) as client:
71 yield client
72
73
74 @pytest.fixture
75 def http_snapshot_serializer_options() -> SnapshotSerializerOptions:
76 return SnapshotSerializerOptions(
77 exclude_response_headers=SNAPSHOT_RESPONSE_HEADERS_EXCLUDE,
78 exclude_request_headers=SNAPSHOT_REQUEST_HEADERS_EXCLUDE,
79 include_request=True,
80 )
81
82
83 @pytest.fixture(scope="function")
84 def snapshot_client(
85 is_recording: bool,
86 http_snapshot_serializer_options: SnapshotSerializerOptions,
87 http_snapshot: inline_snapshot.Snapshot[Any],
88 ) -> Iterator[Anthropic]:
89 with HttpxSyncSnapshotClient(
90 http_snapshot, is_recording, serializer_options=http_snapshot_serializer_options
91 ) as snapshot_client:
92 with Anthropic(http_client=snapshot_client, api_key=None if is_recording else api_key) as client:
93 yield client
94
95
96 @pytest.fixture(scope="function")
97 async def async_snapshot_client(
98 is_recording: bool,
99 http_snapshot_serializer_options: SnapshotSerializerOptions,
100 http_snapshot: inline_snapshot.Snapshot[Any],
101 ) -> AsyncIterator[AsyncAnthropic]:
102 async with HttpxAsyncSnapshotClient(
103 http_snapshot, is_recording, serializer_options=http_snapshot_serializer_options
104 ) as snapshot_client:
105 client = AsyncAnthropic(http_client=snapshot_client, api_key=None if is_recording else api_key)
106 yield client
107
108
109 @pytest.fixture(scope="session")
110 async def async_client(request: FixtureRequest) -> AsyncIterator[AsyncAnthropic]:
111 param = getattr(request, "param", True)
112
113 # defaults
114 strict = True
115 http_client: None | httpx2.AsyncClient = None
116
117 if isinstance(param, bool):
118 strict = param
119 elif is_dict(param):
120 strict = param.get("strict", True)
121 assert isinstance(strict, bool)
122
123 http_client_type = param.get("http_client", "httpx")
124 if http_client_type == "aiohttp":
125 http_client = DefaultAioHttpClient()
126 else:
127 raise TypeError(f"Unexpected fixture parameter type {type(param)}, expected bool or dict")
128
129 async with AsyncAnthropic(
130 base_url=base_url, api_key=api_key, _strict_response_validation=strict, http_client=http_client
131 ) as client:
132 yield client