-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathtest_client.py
More file actions
275 lines (217 loc) · 10.6 KB
/
test_client.py
File metadata and controls
275 lines (217 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import os
import sys
from unittest import mock
import httpx
import pytest
import respx
from replicate.client import _get_api_token_from_environment
@pytest.mark.asyncio
async def test_authorization_when_setting_environ_after_import():
import replicate
router = respx.Router()
router.route(
method="GET",
url="https://api.replicate.com/",
headers={"Authorization": "Bearer test-set-after-import"},
).mock(
return_value=httpx.Response(
200,
json={},
)
)
token = "test-set-after-import" # noqa: S105
with mock.patch.dict(
os.environ,
{"REPLICATE_API_TOKEN": token},
):
client = replicate.Client(transport=httpx.MockTransport(router.handler))
resp = client._request("GET", "/")
assert resp.status_code == 200
@pytest.mark.asyncio
async def test_client_error_handling():
import replicate
from replicate.exceptions import ReplicateError
router = respx.Router()
router.route(
method="GET",
url="https://api.replicate.com/",
headers={"Authorization": "Bearer test-client-error"},
).mock(
return_value=httpx.Response(
400,
json={"detail": "Client error occurred"},
)
)
token = "test-client-error" # noqa: S105
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": token}):
client = replicate.Client(transport=httpx.MockTransport(router.handler))
with pytest.raises(ReplicateError) as exc_info:
client._request("GET", "/")
assert "status: 400" in str(exc_info.value)
assert "detail: Client error occurred" in str(exc_info.value)
@pytest.mark.asyncio
async def test_server_error_handling():
import replicate
from replicate.exceptions import ReplicateError
router = respx.Router()
router.route(
method="GET",
url="https://api.replicate.com/",
headers={"Authorization": "Bearer test-server-error"},
).mock(
return_value=httpx.Response(
500,
json={"detail": "Server error occurred"},
)
)
token = "test-server-error" # noqa: S105
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": token}):
client = replicate.Client(transport=httpx.MockTransport(router.handler))
with pytest.raises(ReplicateError) as exc_info:
client._request("GET", "/")
assert "status: 500" in str(exc_info.value)
assert "detail: Server error occurred" in str(exc_info.value)
def test_custom_headers_are_applied():
import replicate
from replicate.exceptions import ReplicateError
custom_headers = {"User-Agent": "my-custom-user-agent/1.0"}
def mock_send(request):
assert "User-Agent" in request.headers, "Custom header not found in request"
assert request.headers["User-Agent"] == "my-custom-user-agent/1.0", (
"Custom header value is incorrect"
)
return httpx.Response(401, json={})
mock_send_wrapper = mock.Mock(side_effect=mock_send)
client = replicate.Client(
api_token="dummy_token",
headers=custom_headers,
transport=httpx.MockTransport(mock_send_wrapper),
)
try:
client.accounts.current()
except ReplicateError:
pass
mock_send_wrapper.assert_called_once()
class TestGetApiToken:
"""Test cases for _get_api_token_from_environment function covering all import paths."""
def test_cog_not_available_falls_back_to_env(self):
"""Test fallback to environment when cog package is not available."""
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": None}):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_cog_import_error_falls_back_to_env(self):
"""Test fallback to environment when cog import raises exception."""
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch(
"builtins.__import__",
side_effect=ModuleNotFoundError("No module named 'cog'"),
):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_cog_no_current_scope_method_falls_back_to_env(self):
"""Test fallback when cog exists but has no current_scope method."""
mock_cog = mock.MagicMock()
del mock_cog.current_scope # Remove the method
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_cog_current_scope_returns_none_falls_back_to_env(self):
"""Test fallback when current_scope() returns None."""
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = None
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_cog_scope_no_context_attr_falls_back_to_env(self):
"""Test fallback when scope has no context attribute."""
mock_scope = mock.MagicMock()
del mock_scope.context # Remove the context attribute
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = mock_scope
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_cog_scope_context_not_dict_falls_back_to_env(self):
"""Test fallback when scope.context is not a dictionary."""
mock_scope = mock.MagicMock()
mock_scope.context = "not a dict"
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = mock_scope
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_cog_scope_no_replicate_api_token_key_falls_back_to_env(self):
"""Test fallback when replicate_api_token key is missing from context."""
mock_scope = mock.MagicMock()
mock_scope.context = {"other_key": "other_value"} # Missing replicate_api_token
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = mock_scope
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_cog_scope_replicate_api_token_valid_string(self):
"""Test successful retrieval of non-empty token from cog."""
mock_scope = mock.MagicMock()
mock_scope.context = {"REPLICATE_API_TOKEN": "cog-token"}
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = mock_scope
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "cog-token" # noqa: S105
def test_cog_scope_replicate_api_token_case_insensitive(self):
"""Test successful retrieval of non-empty token from cog ignoring case."""
mock_scope = mock.MagicMock()
mock_scope.context = {"replicate_api_token": "cog-token"}
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = mock_scope
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "cog-token" # noqa: S105
def test_cog_scope_replicate_api_token_empty_string(self):
"""Test that empty string from cog is returned (not falling back to env)."""
mock_scope = mock.MagicMock()
mock_scope.context = {"replicate_api_token": ""} # Empty string
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = mock_scope
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "" # Should return empty string, not env token
def test_cog_scope_replicate_api_token_none(self):
"""Test that None from cog is returned (not falling back to env)."""
mock_scope = mock.MagicMock()
mock_scope.context = {"replicate_api_token": None}
mock_cog = mock.MagicMock()
mock_cog.current_scope.return_value = mock_scope
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token is None # Should return None, not env token
def test_cog_current_scope_raises_exception_falls_back_to_env(self):
"""Test fallback when current_scope() raises an exception."""
mock_cog = mock.MagicMock()
mock_cog.current_scope.side_effect = RuntimeError("Scope error")
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": "env-token"}):
with mock.patch.dict(sys.modules, {"cog": mock_cog}):
token = _get_api_token_from_environment()
assert token == "env-token" # noqa: S105
def test_no_env_token_returns_none(self):
"""Test that None is returned when no environment token is set and cog unavailable."""
with mock.patch.dict(os.environ, {}, clear=True): # Clear all env vars
with mock.patch.dict(sys.modules, {"cog": None}):
token = _get_api_token_from_environment()
assert token is None
def test_env_token_empty_string(self):
"""Test that empty string from environment is returned."""
with mock.patch.dict(os.environ, {"REPLICATE_API_TOKEN": ""}):
with mock.patch.dict(sys.modules, {"cog": None}):
token = _get_api_token_from_environment()
assert token == ""