forked from fastapilabs/fastapi-cloud-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api_client.py
More file actions
373 lines (299 loc) · 10.1 KB
/
test_api_client.py
File metadata and controls
373 lines (299 loc) · 10.1 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
from datetime import timedelta
from unittest.mock import patch
import httpx
import pytest
import respx
from httpx import Response
from time_machine import TimeMachineFixture
from fastapi_cloud_cli.config import Settings
from fastapi_cloud_cli.utils.api import (
STREAM_LOGS_MAX_RETRIES,
APIClient,
BuildLogLineMessage,
StreamLogError,
TooManyRetriesError,
)
from tests.utils import build_logs_response
settings = Settings.get()
@pytest.fixture
def client() -> httpx.Client:
"""Create an HTTP client for testing."""
return APIClient()
@pytest.fixture
def deployment_id() -> str:
return "test-deployment-123"
api_mock = respx.mock(base_url=settings.base_api_url)
@pytest.fixture
def logs_route(deployment_id: str) -> respx.Route:
return api_mock.get(f"/deployments/{deployment_id}/build-logs")
@api_mock
def test_stream_build_logs_successful(
logs_route: respx.Route,
client: APIClient,
deployment_id: str,
) -> None:
logs_route.mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "message", "message": "Building...", "id": "1"},
{"type": "message", "message": "Done!", "id": "2"},
{"type": "complete", "id": "3"},
),
)
)
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 3
assert logs[0].type == "message"
assert logs[0].message == "Building..."
assert logs[1].type == "message"
assert logs[1].message == "Done!"
assert logs[2].type == "complete"
@api_mock
def test_stream_build_logs_failed(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
logs_route.mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "message", "message": "Error occurred", "id": "1"},
{"type": "failed", "id": "2"},
),
)
)
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 2
assert logs[0].type == "message"
assert logs[1].type == "failed"
@pytest.mark.parametrize("terminal_type", ["complete", "failed"])
@api_mock
def test_stream_build_logs_stop_after_terminal_state(
logs_route: respx.Route,
client: APIClient,
terminal_type: str,
deployment_id: str,
) -> None:
logs_route.mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "message", "message": "Step 1", "id": "1"},
{"type": terminal_type, "id": "2"},
{"type": "message", "message": "This should not appear", "id": "3"},
),
)
)
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 2
assert logs[0].type == "message"
assert logs[1].type == terminal_type
@api_mock
def test_stream_build_logs_internal_messages_are_skipped(
logs_route: respx.Route,
client: APIClient,
deployment_id: str,
) -> None:
logs_route.mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "heartbeat", "id": "1"},
{"type": "message", "message": "Continuing...", "id": "2"},
{"type": "complete", "id": "3"},
),
)
)
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 2
assert logs[0].type == "message"
assert logs[1].type == "complete"
@api_mock
def test_stream_build_logs_malformed_json_is_skipped(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
content = "\n".join(
[
'{"type": "message", "message": "Valid", "id": "1"}',
"not valid json",
'{"type": "complete", "id": "2"}',
]
)
logs_route.mock(return_value=Response(200, content=content))
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 2
assert logs[0].type == "message"
assert logs[1].type == "complete"
@api_mock
def test_stream_build_logs_unknown_log_type_is_skipped(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
logs_route.mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "unknown_future_type", "id": "1"},
{"type": "message", "message": "Valid", "id": "2"},
{"type": "complete", "id": "3"},
),
)
)
logs = list(client.stream_build_logs(deployment_id))
# Unknown type should be filtered out
assert len(logs) == 2
assert logs[0].type == "message"
assert logs[1].type == "complete"
@pytest.mark.parametrize(
"network_error",
[httpx.NetworkError, httpx.TimeoutException, httpx.RemoteProtocolError],
)
@api_mock
def test_stream_build_logs_network_error_retry(
logs_route: respx.Route,
client: APIClient,
network_error: Exception,
deployment_id: str,
) -> None:
# First call fails, second succeeds
logs_route.side_effect = [
network_error,
network_error,
Response(
200,
content=build_logs_response(
{"type": "message", "message": "Success after retry", "id": "1"},
{"type": "complete", "id": "2"},
),
),
]
with patch("time.sleep"):
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 2
assert logs[0].type == "message"
assert logs[0].message == "Success after retry"
@api_mock
def test_stream_build_logs_server_error_retry(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
logs_route.side_effect = [
Response(500, text="Internal Server Error"),
Response(
200,
content=build_logs_response(
{"type": "complete", "id": "1"},
),
),
]
with patch("time.sleep"):
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 1
assert logs[0].type == "complete"
@api_mock
def test_stream_build_logs_client_error_raises_immediately(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
logs_route.mock(return_value=Response(404, text="Not Found"))
with pytest.raises(StreamLogError, match="HTTP 404"):
list(client.stream_build_logs(deployment_id))
@api_mock
def test_stream_build_logs_max_retries_exceeded(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
logs_route.side_effect = httpx.NetworkError("Connection failed")
with patch("time.sleep"):
with pytest.raises(
TooManyRetriesError,
match=f"Failed after {STREAM_LOGS_MAX_RETRIES} attempts",
):
list(client.stream_build_logs(deployment_id))
@api_mock
def test_stream_build_logs_empty_lines_are_skipped(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
content = "\n".join(
[
"",
'{"type": "message", "message": "Valid", "id": "1"}',
" ",
'{"type": "complete", "id": "2"}',
"",
]
)
logs_route.mock(return_value=Response(200, content=content))
logs = list(client.stream_build_logs(deployment_id))
assert len(logs) == 2
assert logs[0].type == "message"
assert logs[1].type == "complete"
@respx.mock(base_url=settings.base_api_url)
def test_stream_build_logs_continue_after_timeout(
respx_mock: respx.MockRouter,
client: APIClient,
deployment_id: str,
) -> None:
for id, last_id in enumerate([None, "1", "2"], start=1):
params = {"last_id": last_id} if last_id else {}
message = f"message {id}"
respx_mock.get(
f"/deployments/{deployment_id}/build-logs", params__eq=params
).mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "message", "message": message, "id": str(id)},
{"type": "timeout"},
),
)
)
respx_mock.get(
f"/deployments/{deployment_id}/build-logs", params__eq={"last_id": "3"}
).mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "message", "message": "message 4", "id": "4"},
{"type": "complete", "id": "5"},
),
)
)
logs = client.stream_build_logs(deployment_id)
with patch("time.sleep"):
assert next(logs) == BuildLogLineMessage(message="message 1", id="1")
assert next(logs) == BuildLogLineMessage(message="message 2", id="2")
assert next(logs) == BuildLogLineMessage(message="message 3", id="3")
assert next(logs) == BuildLogLineMessage(message="message 4", id="4")
assert next(logs).type == "complete"
@api_mock
def test_stream_build_logs_connection_closed_without_complete_failed_or_timeout(
logs_route: respx.Route, client: APIClient, deployment_id: str
) -> None:
logs_route.mock(
return_value=Response(
200,
content=build_logs_response(
{"type": "message", "message": "hello", "id": "1"},
),
)
)
logs = client.stream_build_logs(deployment_id)
with patch("time.sleep"), pytest.raises(TooManyRetriesError, match="Failed after"):
for _ in range(STREAM_LOGS_MAX_RETRIES + 1):
next(logs)
@api_mock
def test_stream_build_logs_retry_timeout(
logs_route: respx.Route,
client: APIClient,
time_machine: TimeMachineFixture,
deployment_id: str,
) -> None:
time_machine.move_to("2025-11-01 13:00:00", tick=False)
def responses(request: httpx.Request, route: respx.Route) -> Response:
time_machine.shift(timedelta(hours=1))
return Response(
200,
content=build_logs_response(
{"type": "message", "message": "First", "id": "1"},
),
)
logs_route.mock(side_effect=responses)
with patch("time.sleep"), pytest.raises(TimeoutError, match="timed out"):
list(client.stream_build_logs(deployment_id))