-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_retry.py
More file actions
745 lines (631 loc) · 28.1 KB
/
test_retry.py
File metadata and controls
745 lines (631 loc) · 28.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
"""Tests for the exponential backoff retry logic in APIDeploymentsClient."""
import io
from unittest.mock import MagicMock, patch
import pytest
from requests.exceptions import ConnectionError, Timeout
from unstract.api_deployments.client import (
APIDeploymentsClient,
_WaitRetryAfterOrExponentialJitter,
)
@pytest.fixture
def client():
"""Create a client with fast retry settings for testing."""
return APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
api_timeout=30,
logging_level="WARNING",
max_retries=3,
initial_delay=0.01,
max_delay=0.1,
backoff_factor=2.0,
)
@pytest.fixture
def client_no_retry():
"""Create a client with retries disabled."""
return APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
max_retries=0,
)
def _mock_response(status_code=200, json_data=None, headers=None, text=""):
"""Helper to create a mock response object."""
resp = MagicMock()
resp.status_code = status_code
resp.headers = headers or {}
resp.text = text
resp.json.return_value = json_data or {}
return resp
# ── Constructor and backward compatibility ──
class TestConstructorDefaults:
def test_default_retry_params(self):
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
)
assert c.max_retries == 4
assert c.initial_delay == 2.0
assert c.max_delay == 60.0
assert c.backoff_factor == 2.0
assert c.jitter == 1.0
def test_custom_retry_params(self):
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
max_retries=5,
initial_delay=0.5,
max_delay=30.0,
backoff_factor=3.0,
)
assert c.max_retries == 5
assert c.initial_delay == 0.5
assert c.max_delay == 30.0
assert c.backoff_factor == 3.0
def test_backward_compat_no_retry_args(self):
"""Existing code that doesn't pass retry params still works."""
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
api_timeout=10,
logging_level="DEBUG",
include_metadata=False,
)
assert c.api_timeout == 10
assert c.max_retries == 4
class TestIsRetryableStatus:
def test_default_retries_429(self, client):
assert client._is_retryable_status(429) is True
def test_default_retries_500(self, client):
assert client._is_retryable_status(500) is True
def test_default_retries_502(self, client):
assert client._is_retryable_status(502) is True
def test_default_retries_503(self, client):
assert client._is_retryable_status(503) is True
def test_default_retries_504(self, client):
assert client._is_retryable_status(504) is True
def test_default_retries_any_5xx(self, client):
"""Any 5xx status code should be retried by default."""
for code in (500, 501, 502, 503, 504, 507, 511, 599):
assert client._is_retryable_status(code) is True, (
f"Expected {code} retryable"
)
def test_default_no_retry_4xx_except_429(self, client):
"""4xx codes (except 429) should not be retried by default."""
for code in (400, 401, 403, 404, 405, 408, 422):
assert client._is_retryable_status(code) is False, (
f"Expected {code} not retryable"
)
def test_default_no_retry_2xx(self, client):
assert client._is_retryable_status(200) is False
assert client._is_retryable_status(201) is False
# ── _WaitRetryAfterOrExponentialJitter ──
class TestWaitStrategy:
"""Tests for the custom tenacity wait strategy."""
def _make_retry_state(self, attempt_number, result=None, exception=None):
"""Create a minimal mock RetryCallState for testing the wait
strategy."""
rs = MagicMock()
rs.attempt_number = attempt_number
outcome = MagicMock()
if exception is not None:
outcome.failed = True
outcome.exception.return_value = exception
else:
outcome.failed = False
outcome.result.return_value = result
rs.outcome = outcome
return rs
def test_delay_within_bounds(self):
"""Additive jitter: delay in [initial, initial + jitter] at attempt 1."""
wait = _WaitRetryAfterOrExponentialJitter(
initial=2.0, max=60.0, exp_base=2.0, jitter=1.0
)
resp = MagicMock(status_code=500, headers={})
for _ in range(50):
rs = self._make_retry_state(attempt_number=1, result=resp)
delay = wait(rs)
# At attempt 1: base = initial * exp_base^0 = 2.0, jitter up to 1.0
assert 2.0 <= delay <= 3.0
def test_delay_exponential_growth(self):
"""Higher attempts produce larger base delays."""
wait = _WaitRetryAfterOrExponentialJitter(
initial=2.0, max=60.0, exp_base=2.0, jitter=0.0
)
resp = MagicMock(status_code=500, headers={})
rs1 = self._make_retry_state(attempt_number=1, result=resp)
rs2 = self._make_retry_state(attempt_number=2, result=resp)
delay1 = wait(rs1)
delay2 = wait(rs2)
assert delay2 > delay1
def test_delay_capped_at_max(self):
wait = _WaitRetryAfterOrExponentialJitter(
initial=10.0, max=5.0, exp_base=10.0, jitter=0.0
)
resp = MagicMock(status_code=500, headers={})
for attempt in range(1, 10):
rs = self._make_retry_state(attempt_number=attempt, result=resp)
delay = wait(rs)
assert delay <= 5.0 + 1e-9 # max + float tolerance
def test_retry_after_header_respected(self):
"""429 with valid Retry-After returns that value."""
wait = _WaitRetryAfterOrExponentialJitter(
initial=2.0, max=60.0, exp_base=2.0, jitter=1.0
)
resp = MagicMock(status_code=429, headers={"Retry-After": "7"})
rs = self._make_retry_state(attempt_number=1, result=resp)
assert wait(rs) == 7.0
def test_retry_after_invalid_falls_back(self):
"""429 with invalid Retry-After falls back to exponential jitter."""
wait = _WaitRetryAfterOrExponentialJitter(
initial=2.0, max=60.0, exp_base=2.0, jitter=1.0
)
resp = MagicMock(status_code=429, headers={"Retry-After": "bad"})
rs = self._make_retry_state(attempt_number=1, result=resp)
delay = wait(rs)
assert 2.0 <= delay <= 3.0
def test_exception_outcome_uses_exponential(self):
"""When the outcome is an exception, exponential jitter is used."""
wait = _WaitRetryAfterOrExponentialJitter(
initial=2.0, max=60.0, exp_base=2.0, jitter=1.0
)
rs = self._make_retry_state(attempt_number=1, exception=ConnectionError("fail"))
delay = wait(rs)
assert 2.0 <= delay <= 3.0
# ── _request_with_retry: successful requests ──
class TestRequestWithRetrySuccess:
@patch("unstract.api_deployments.client.requests.request")
def test_success_on_first_try(self, mock_request, client):
mock_request.return_value = _mock_response(200)
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 1
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_retry_on_503_then_success(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
_mock_response(503),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 2
assert mock_sleep.call_count == 1
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_retry_on_500_then_success(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
_mock_response(500),
_mock_response(500),
_mock_response(200),
]
resp = client._request_with_retry("POST", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 3
assert mock_sleep.call_count == 2
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_retry_on_429_then_success(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
_mock_response(429),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 2
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_retry_on_502_then_success(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
_mock_response(502),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 2
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_retry_on_504_then_success(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
_mock_response(504),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 2
# ── _request_with_retry: connection errors ──
class TestRequestWithRetryConnectionErrors:
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_retry_on_connection_error_then_success(
self, mock_request, mock_sleep, client
):
mock_request.side_effect = [
ConnectionError("Connection refused"),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 2
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_retry_on_timeout_then_success(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
Timeout("Request timed out"),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 2
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_connection_error_exhausted_raises(self, mock_request, mock_sleep, client):
mock_request.side_effect = ConnectionError("Connection refused")
with pytest.raises(ConnectionError):
client._request_with_retry("GET", "https://api.example.com/test")
assert mock_request.call_count == client.max_retries + 1
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_timeout_exhausted_raises(self, mock_request, mock_sleep, client):
mock_request.side_effect = Timeout("Request timed out")
with pytest.raises(Timeout):
client._request_with_retry("GET", "https://api.example.com/test")
assert mock_request.call_count == client.max_retries + 1
# ── _request_with_retry: exhaustion returns last response ──
class TestRequestWithRetryExhaustion:
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_all_retries_exhausted_returns_last_response(
self, mock_request, mock_sleep, client
):
mock_request.return_value = _mock_response(503)
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 503
assert mock_request.call_count == client.max_retries + 1
# ── No retry on non-retryable status codes ──
class TestNoRetryOnNonRetryable:
@patch("unstract.api_deployments.client.requests.request")
def test_no_retry_on_200(self, mock_request, client):
mock_request.return_value = _mock_response(200)
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
assert mock_request.call_count == 1
@patch("unstract.api_deployments.client.requests.request")
def test_no_retry_on_400(self, mock_request, client):
mock_request.return_value = _mock_response(400)
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 400
assert mock_request.call_count == 1
@patch("unstract.api_deployments.client.requests.request")
def test_no_retry_on_401(self, mock_request, client):
mock_request.return_value = _mock_response(401)
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 401
assert mock_request.call_count == 1
@patch("unstract.api_deployments.client.requests.request")
def test_no_retry_on_404(self, mock_request, client):
mock_request.return_value = _mock_response(404)
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 404
assert mock_request.call_count == 1
@patch("unstract.api_deployments.client.requests.request")
def test_no_retry_on_422(self, mock_request, client):
mock_request.return_value = _mock_response(422)
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 422
assert mock_request.call_count == 1
# ── Timeout passed to requests ──
class TestTimeoutPassed:
@patch("unstract.api_deployments.client.requests.request")
def test_no_default_timeout_set(self, mock_request, client):
"""api_timeout is a server-side parameter, not an HTTP socket timeout.
_request_with_retry should NOT inject a default timeout kwarg.
"""
mock_request.return_value = _mock_response(200)
client._request_with_retry("GET", "https://api.example.com/test")
_, kwargs = mock_request.call_args
assert "timeout" not in kwargs
@patch("unstract.api_deployments.client.requests.request")
def test_explicit_timeout_not_overridden(self, mock_request, client):
"""Callers can still pass an explicit HTTP socket timeout."""
mock_request.return_value = _mock_response(200)
client._request_with_retry("GET", "https://api.example.com/test", timeout=99)
_, kwargs = mock_request.call_args
assert kwargs["timeout"] == 99
# ── Retry-After header on 429 ──
class TestRetryAfterHeader:
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_429_respects_retry_after_header(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
_mock_response(429, headers={"Retry-After": "5"}),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
mock_sleep.assert_called_once_with(5.0)
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_429_invalid_retry_after_falls_back(self, mock_request, mock_sleep, client):
mock_request.side_effect = [
_mock_response(429, headers={"Retry-After": "not-a-number"}),
_mock_response(200),
]
resp = client._request_with_retry("GET", "https://api.example.com/test")
assert resp.status_code == 200
# Should have used exponential jitter fallback (additive: >= initial_delay)
assert mock_sleep.call_count == 1
delay_used = mock_sleep.call_args[0][0]
assert delay_used >= client.initial_delay
# ── File seek on retry ──
class TestFileSeekOnRetry:
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_file_objects_rewound_on_retry(self, mock_request, mock_sleep, client):
file_obj = io.BytesIO(b"test data")
files = [("files", ("test.pdf", file_obj, "application/octet-stream"))]
mock_request.side_effect = [
_mock_response(503),
_mock_response(200),
]
resp = client._request_with_retry(
"POST", "https://api.example.com/test", files=files
)
assert resp.status_code == 200
# File should have been rewound before second attempt
assert file_obj.tell() == 0 or mock_request.call_count == 2
# ── max_retries=0 disables retry ──
class TestDisabledRetry:
@patch("unstract.api_deployments.client.requests.request")
def test_no_retry_when_max_retries_zero(self, mock_request, client_no_retry):
mock_request.return_value = _mock_response(503)
resp = client_no_retry._request_with_retry(
"GET", "https://api.example.com/test"
)
assert resp.status_code == 503
assert mock_request.call_count == 1
@patch("unstract.api_deployments.client.requests.request")
def test_connection_error_raises_immediately_when_disabled(
self, mock_request, client_no_retry
):
mock_request.side_effect = ConnectionError("fail")
with pytest.raises(ConnectionError):
client_no_retry._request_with_retry("GET", "https://api.example.com/test")
assert mock_request.call_count == 1
# ── check_execution_status pending bug fix ──
class TestCheckExecutionStatusPendingFix:
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_503_after_exhaustion_sets_pending_true(
self, mock_request, mock_sleep, client
):
mock_request.return_value = _mock_response(
503, json_data={"status": "", "error": "Service Unavailable", "message": ""}
)
result = client.check_execution_status("/api/v1/status/123")
assert result["pending"] is True
assert result["status_code"] == 503
@patch("unstract.api_deployments.client.requests.request")
def test_200_with_pending_status_sets_pending_true(self, mock_request, client):
mock_request.return_value = _mock_response(
200, json_data={"status": "EXECUTING", "error": "", "message": ""}
)
result = client.check_execution_status("/api/v1/status/123")
assert result["pending"] is True
assert result["status_code"] == 200
@patch("unstract.api_deployments.client.requests.request")
def test_200_with_completed_status_sets_pending_false(self, mock_request, client):
mock_request.return_value = _mock_response(
200,
json_data={
"status": "COMPLETED",
"error": "",
"message": '{"result": "data"}',
},
)
result = client.check_execution_status("/api/v1/status/123")
assert result["pending"] is False
@patch("unstract.api_deployments.client.requests.request")
def test_422_with_executing_status_sets_pending_true(self, mock_request, client):
"""HTTP 422 is currently returned by Unstract for in-progress statuses.
Per the Status API migration guide, the server will change from 422 to
200 for EXECUTING/PENDING statuses. We determine pending state solely
from the response body ``status`` field (Option 1 from the docs), making
this client future-proof regardless of the HTTP status code.
"""
mock_request.return_value = _mock_response(
422, json_data={"status": "EXECUTING", "error": "", "message": ""}
)
result = client.check_execution_status("/api/v1/status/123")
assert result["pending"] is True
assert result["status_code"] == 422
@patch("unstract.api_deployments.client.requests.request")
def test_422_with_pending_status_sets_pending_true(self, mock_request, client):
"""HTTP 422 with PENDING body status — still detected via body
check."""
mock_request.return_value = _mock_response(
422, json_data={"status": "PENDING", "error": "", "message": ""}
)
result = client.check_execution_status("/api/v1/status/123")
assert result["pending"] is True
assert result["status_code"] == 422
@patch("unstract.api_deployments.client.requests.request")
def test_400_does_not_set_pending(self, mock_request, client):
mock_request.return_value = _mock_response(
400, json_data={"status": "", "error": "Bad request", "message": ""}
)
result = client.check_execution_status("/api/v1/status/123")
assert result["pending"] is False
# ── structure_file uses retry ──
class TestStructureFileUsesRetry:
@patch("unstract.api_deployments.client.time.sleep")
@patch("unstract.api_deployments.client.requests.request")
def test_structure_file_retries_on_503_async_mode(
self, mock_request, mock_sleep, tmp_path
):
"""In async mode (api_timeout=0), POST is retried on 5xx."""
test_file = tmp_path / "test.pdf"
test_file.write_bytes(b"fake pdf content")
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
api_timeout=0,
max_retries=2,
initial_delay=0.01,
max_delay=0.1,
)
mock_request.side_effect = [
_mock_response(503),
_mock_response(
200,
json_data={
"message": {
"execution_status": "SUCCESS",
"error": "",
"result": '{"key": "value"}',
"status_api": "/api/status/1",
}
},
),
]
result = c.structure_file([str(test_file)])
assert result["status_code"] == 200
assert mock_request.call_count == 2
class TestStructureFileNoRetryInSyncMode:
@patch("unstract.api_deployments.client.requests.post")
def test_structure_file_no_retry_on_503_sync_mode(self, mock_post, tmp_path):
"""In sync mode (api_timeout>0), POST is NOT retried on 5xx."""
test_file = tmp_path / "test.pdf"
test_file.write_bytes(b"fake pdf content")
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
api_timeout=300,
max_retries=3,
initial_delay=0.01,
max_delay=0.1,
)
mock_post.return_value = _mock_response(
503,
json_data={
"message": {
"execution_status": "",
"error": "Service Unavailable",
"result": "",
}
},
)
result = c.structure_file([str(test_file)])
assert result["status_code"] == 503
# Only one call — no retries in sync mode
assert mock_post.call_count == 1
@patch("unstract.api_deployments.client.requests.post")
def test_structure_file_sync_mode_default_timeout(self, mock_post, tmp_path):
"""Default api_timeout=300 means sync mode — no POST retry."""
test_file = tmp_path / "test.pdf"
test_file.write_bytes(b"fake pdf content")
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
max_retries=3,
initial_delay=0.01,
max_delay=0.1,
)
mock_post.return_value = _mock_response(
500,
json_data={
"message": {
"execution_status": "",
"error": "Internal Server Error",
"result": "",
}
},
)
result = c.structure_file([str(test_file)])
assert result["status_code"] == 500
assert mock_post.call_count == 1
# ── structure_file: POST 422 does NOT set pending ──
# The POST endpoint returns 200 for successful queuing (PENDING/EXECUTING)
# and 422 only on setup errors. A 422 should never trigger polling.
class TestStructureFile422DoesNotSetPending:
@patch("unstract.api_deployments.client.requests.post")
def test_422_pending_does_not_set_pending(self, mock_post, tmp_path):
"""POST 422 with PENDING status should NOT set pending=True.
The POST endpoint returns 422 only on setup errors, so the
client must not start polling even if execution_status says
PENDING.
"""
test_file = tmp_path / "test.pdf"
test_file.write_bytes(b"fake pdf content")
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
max_retries=0,
logging_level="WARNING",
)
mock_post.return_value = _mock_response(
422,
json_data={
"message": {
"execution_status": "PENDING",
"error": "",
"result": "",
"status_api": "/api/status/abc",
}
},
)
result = c.structure_file([str(test_file)])
assert result["pending"] is False
assert result["status_code"] == 422
@patch("unstract.api_deployments.client.requests.post")
def test_422_executing_does_not_set_pending(self, mock_post, tmp_path):
"""POST 422 with EXECUTING status should NOT set pending=True.
Same rationale as above — 422 from POST means a setup error, not
a legitimately queued execution.
"""
test_file = tmp_path / "test.pdf"
test_file.write_bytes(b"fake pdf content")
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
max_retries=0,
logging_level="WARNING",
)
mock_post.return_value = _mock_response(
422,
json_data={
"message": {
"execution_status": "EXECUTING",
"error": "",
"result": "",
"status_api": "/api/status/abc",
}
},
)
result = c.structure_file([str(test_file)])
assert result["pending"] is False
assert result["status_code"] == 422
@patch("unstract.api_deployments.client.requests.post")
def test_200_pending_sets_pending_true(self, mock_post, tmp_path):
"""POST 200 + PENDING correctly sets pending=True for polling."""
test_file = tmp_path / "test.pdf"
test_file.write_bytes(b"fake pdf content")
c = APIDeploymentsClient(
api_url="https://api.example.com/v1/deploy",
api_key="test-key",
max_retries=0,
logging_level="WARNING",
)
mock_post.return_value = _mock_response(
200,
json_data={
"message": {
"execution_status": "PENDING",
"error": "",
"result": "",
"status_api": "/api/status/abc",
}
},
)
result = c.structure_file([str(test_file)])
assert result["pending"] is True
assert result["status_code"] == 200