Repository navigation
Expand file tree
/
Copy pathtest_split_pdf_hook.py
More file actions
2224 lines (1798 loc) · 80.5 KB
/
Copy pathtest_split_pdf_hook.py
File metadata and controls
2224 lines (1798 loc) · 80.5 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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import io
import logging
import threading
from collections import Counter
from concurrent import futures
from functools import partial
from pathlib import Path
from typing import Any, Coroutine
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
import requests # type: ignore[import-untyped]
from requests_toolbelt import MultipartDecoder # type: ignore[import-untyped]
from unstructured_client._hooks.custom import form_utils, pdf_utils, request_utils
from unstructured_client._hooks.custom.form_utils import (
FormData,
PARTITION_FORM_CONCURRENCY_LEVEL_KEY,
PARTITION_FORM_STARTING_PAGE_NUMBER_KEY,
PARTITION_FORM_PAGE_RANGE_KEY,
)
from unstructured_client._hooks.custom.split_pdf_hook import (
DEFAULT_CACHE_TMP_DATA_DIR,
DEFAULT_CONCURRENCY_LEVEL,
DEFAULT_STARTING_PAGE_NUMBER,
MAX_CONCURRENCY_LEVEL,
MAX_PAGES_PER_SPLIT,
MIN_PAGES_PER_SPLIT,
SPLIT_PDF_HEADER_PREFIX,
SplitPdfHook,
_get_request_timeout_seconds,
get_optimal_split_size,
run_tasks,
)
from unstructured_client._hooks.sdkhooks import SDKHooks
from unstructured_client._hooks.types import AfterErrorContext, AfterSuccessContext, BeforeRequestContext
from unstructured_client.basesdk import BaseSDK
from unstructured_client.models import shared
from unstructured_client.sdkconfiguration import SDKConfiguration
from unstructured_client.types import UNSET
from unstructured_client.utils import BackoffStrategy, RetryConfig
def test_unit_clear_operation():
"""Test clear operation method properly clears request/response data."""
hook = SplitPdfHook()
operation_id = "some_id"
hook.coroutines_to_execute[operation_id] = [MagicMock(), MagicMock()]
hook.api_successful_responses[operation_id] = [
requests.Response(),
requests.Response(),
]
hook.api_failed_responses[operation_id] = [requests.Response()]
hook.operation_timeouts[operation_id] = 30.0
assert len(hook.coroutines_to_execute[operation_id]) == 2
assert len(hook.api_successful_responses[operation_id]) == 2
hook._clear_operation(operation_id)
assert hook.coroutines_to_execute.get(operation_id) is None
assert hook.api_successful_responses.get(operation_id) is None
assert hook.api_failed_responses.get(operation_id) is None
assert hook.operation_timeouts.get(operation_id) is None
def test_unit_clear_operation_closes_unconsumed_chunk_files(tmp_path: Path):
hook = SplitPdfHook()
operation_id = "cache-mode-clear"
chunk_path = tmp_path / "chunk.pdf"
chunk_path.write_bytes(b"%PDF")
chunk_file = open(chunk_path, mode="rb") # pylint: disable=consider-using-with
tempdir = MagicMock()
hook.coroutines_to_execute[operation_id] = [
partial(hook.call_api_partial, pdf_chunk_file=chunk_file),
]
hook.tempdirs[operation_id] = tempdir
hook._clear_operation(operation_id)
assert chunk_file.closed
tempdir.cleanup.assert_called_once()
def test_unit_get_request_timeout_seconds_uses_request_timeout_extension():
request = httpx.Request(
"POST",
"http://localhost",
extensions={"timeout": {"connect": 10.0, "read": 30.0, "write": 20.0, "pool": 5.0}},
)
assert _get_request_timeout_seconds(request) == 30.0
def test_unit_prepare_request_headers():
"""Test prepare request headers method properly removes Content-Type and Content-Length headers."""
test_headers = {
"Content-Type": "application/json",
"Content-Length": "100",
"Authorization": "Bearer token",
}
expected_headers = {
"Authorization": "Bearer token",
}
headers = request_utils.prepare_request_headers(test_headers)
assert headers != test_headers
assert dict(headers) == expected_headers
def test_unit_create_response():
"""Test create response method properly overrides body elements and Content-Length header."""
test_elements = [{"key": "value"}, {"key_2": "value"}]
expected_status_code = 200
expected_content = b'[{"key": "value"}, {"key_2": "value"}]'
expected_content_length = "38"
response = request_utils.create_response(test_elements)
assert response.status_code == expected_status_code
assert response._content == expected_content
assert response.headers.get("Content-Length") == expected_content_length
def test_unit_decode_content_disposition():
"""Test decode content disposition method properly decodes Content-Disposition header."""
# Test case 1: Single parameter
content_disposition = b'attachment; filename="test_file.pdf"'
expected_result = {"filename": "test_file.pdf"}
result = form_utils.decode_content_disposition(content_disposition)
assert result == expected_result
# Test case 2: Multiple parameters
content_disposition = b'attachment; filename="test_file.pdf"; size=100; version="1.0"'
expected_result = {"filename": "test_file.pdf", "size": "100", "version": "1.0"}
result = form_utils.decode_content_disposition(content_disposition)
assert result == expected_result
# Test case 3: No parameters
content_disposition = b"attachment"
expected_result = {}
result = form_utils.decode_content_disposition(content_disposition)
assert result == expected_result
def test_unit_parse_form_data():
"""Test parse form data method properly parses the form data and returns dictionary.
Parameters with the same key should be consolidated to a list."""
# Prepare test data
test_form_data = (
b"--boundary\r\n"
b"Content-Disposition: form-data; name=\"files\"; filename=\"test_file.pdf\"\r\n"
b"\r\n"
b"file_content\r\n"
b"--boundary\r\n"
b"Content-Disposition: form-data; name=\"parameter_1\"\r\n"
b"\r\n"
b"value_1\r\n"
b"--boundary\r\n"
b"Content-Disposition: form-data; name=\"parameter_2\"\r\n"
b"\r\n"
b"value_2\r\n"
b"--boundary\r\n"
b"Content-Disposition: form-data; name=\"list_parameter\"\r\n"
b"\r\n"
b"value_1\r\n"
b"--boundary\r\n"
b"Content-Disposition: form-data; name=\"list_parameter\"\r\n"
b"\r\n"
b"value_2\r\n"
b"--boundary--\r\n"
)
decoded_data = MultipartDecoder(
test_form_data,
"multipart/form-data; boundary=boundary",
)
# Expected results
expected_form_data = {
"files": shared.Files(content=b"file_content", file_name="test_file.pdf"),
"parameter_1": "value_1",
"parameter_2": "value_2",
"list_parameter": ["value_1", "value_2"],
}
# Parse form data
form_data = form_utils.parse_form_data(decoded_data)
# Assert the parsed form data
assert form_data.get("parameter_1") == expected_form_data.get("parameter_1")
assert form_data.get("parameter_2") == expected_form_data.get("parameter_2")
assert form_data.get("list_parameter") == expected_form_data.get("list_parameter")
assert form_data.get("files").file_name == expected_form_data.get("files").file_name
assert form_data.get("files").content == expected_form_data.get("files").content
def test_unit_parse_form_data_error():
"""Test parse form data method raises RuntimeError when the form data is invalid (no Content-Disposition header)."""
# Prepare test data
decoded_data = MultipartDecoder(
b'--boundary\r\nContent: form-data; name="files"; filename="test_file.pdf"\r\n\r\nfile_content\r\n--boundary--\r\n',
"multipart/form-data; boundary=boundary",
)
# Assert RuntimeError
with pytest.raises(RuntimeError):
form_utils.parse_form_data(decoded_data)
def test_unit_parse_form_data_empty_filename_error():
"""Test parse form data method raises ValueError when the form data has empty filename."""
# Prepare test data
decoded_data = MultipartDecoder(
b'--boundary\r\nContent-Disposition: form-data; name="files"; filename=""\r\n\r\nfile_content\r\n--boundary--\r\n',
"multipart/form-data; boundary=boundary",
)
with pytest.raises(ValueError):
form_utils.parse_form_data(decoded_data)
def test_unit_parse_form_data_none_filename_error():
"""Test parse form data method raises ValueError when the form data has no filename (None)."""
# Prepare test data
decoded_data = MultipartDecoder(
b'--boundary\r\nContent-Disposition: form-data; name="files"\r\n\r\nfile_content\r\n--boundary--\r\n',
"multipart/form-data; boundary=boundary",
)
with pytest.raises(ValueError):
form_utils.parse_form_data(decoded_data)
def test_unit_is_pdf_valid_pdf_when_passing_file_object():
"""Test is pdf method returns pdf object for valid pdf file with filename."""
filename = "_sample_docs/layout-parser-paper-fast.pdf"
with open(filename, "rb") as f:
result = pdf_utils.read_pdf(f)
assert result is not None
def test_unit_is_pdf_valid_pdf_when_passing_binary_content():
"""Test is pdf method returns pdf object for file with valid pdf content"""
filename = "_sample_docs/layout-parser-paper-fast.pdf"
with open(filename, "rb") as f:
result = pdf_utils.read_pdf(f.read())
assert result is not None
def test_unit_is_pdf_invalid_pdf():
"""Test is pdf method returns False for file with invalid extension."""
result = pdf_utils.read_pdf(b"txt_content")
assert result is None
def test_unit_get_starting_page_number_missing_key():
"""Test _get_starting_page_number method with missing key."""
form_data = {}
result = form_utils.get_starting_page_number(
form_data,
key=PARTITION_FORM_STARTING_PAGE_NUMBER_KEY,
fallback_value=DEFAULT_STARTING_PAGE_NUMBER,
)
assert result == 1
@pytest.mark.parametrize(
("num_pages", "concurrency_level", "expected_split_size"),
[
(5, 3, 2), # "1st worker gets 2 pages, 2nd worker gets 2 pages, 3rd worker gets 1 page"
(100, 3, MAX_PAGES_PER_SPLIT), # large PDF, each worker gets 20 pages
(1, 5, MIN_PAGES_PER_SPLIT), # small PDF, one worker with MIN_PAGES_PER_WORKER size
(60, 4, 15), # exact multiple of no. workers
(3, 10, MIN_PAGES_PER_SPLIT), # more workers than pages
],
)
def test_get_optimal_split_size(num_pages, concurrency_level, expected_split_size):
split_size = get_optimal_split_size(num_pages, concurrency_level)
assert split_size == expected_split_size
@pytest.mark.parametrize(
("form_data", "expected_result"),
[
({}, DEFAULT_CONCURRENCY_LEVEL), # no value
({"split_pdf_concurrency_level": "10"}, 10), # valid number
(
# exceeds max value
{"split_pdf_concurrency_level": f"{MAX_CONCURRENCY_LEVEL + 1}"},
MAX_CONCURRENCY_LEVEL,
),
({"split_pdf_concurrency_level": "-3"}, DEFAULT_CONCURRENCY_LEVEL), # negative value
],
)
def test_unit_get_split_pdf_concurrency_level_returns_valid_number(form_data, expected_result):
assert (
form_utils.get_split_pdf_concurrency_level_param(
form_data,
key=PARTITION_FORM_CONCURRENCY_LEVEL_KEY,
fallback_value=DEFAULT_CONCURRENCY_LEVEL,
max_allowed=MAX_CONCURRENCY_LEVEL,
)
== expected_result
)
@pytest.mark.parametrize(
"starting_page_number, expected_result",
[
("5", 5), # Valid integer
("abc", 1), # Invalid integer
("0", 1), # Value less than 1
("", 1), # Empty string
(None, 1), # None value
],
)
def test_unit_get_starting_page_number(starting_page_number, expected_result):
"""Test _get_starting_page_number method with different inputs."""
form_data = {"starting_page_number": starting_page_number}
result = form_utils.get_starting_page_number(
form_data,
key=PARTITION_FORM_STARTING_PAGE_NUMBER_KEY,
fallback_value=DEFAULT_STARTING_PAGE_NUMBER,
)
assert result == expected_result
@pytest.mark.parametrize(
"page_range, expected_result",
[
(["1", "14"], (1, 14)), # Valid range, start on boundary
(["4", "16"], (4, 16)), # Valid range, end on boundary
(None, (1, 20)), # Range not specified, defaults to full range
(["2", "5"], (2, 5)), # Valid range within boundary
(["2", "100"], None), # End page too high
(["50", "100"], None), # Range too high
(["-50", "5"], None), # Start page too low
(["-50", "-2"], None), # Range too low
(["10", "2"], None), # Backwards range
(["foo", "foo"], None), # Parse error
],
)
def test_unit_get_page_range_returns_valid_range(page_range, expected_result):
"""Test get_page_range method with different inputs.
Ranges that are out of bounds for a 20 page doc will throw a ValueError."""
form_data = {"split_pdf_page_range[]": page_range}
try:
result = form_utils.get_page_range(
form_data,
key=PARTITION_FORM_PAGE_RANGE_KEY,
max_pages=20,
)
except ValueError as exc:
assert not expected_result
assert "is out of bounds." in str(exc) or "is not a valid page range." in str(exc)
return
assert result == expected_result
async def _request_mock(
async_client: httpx.AsyncClient, # not used by mock
limiter: asyncio.Semaphore, # not used by mock
fails: bool,
content: str) -> requests.Response:
response = requests.Response()
response.status_code = 500 if fails else 200
response._content = content.encode()
return response
@pytest.mark.parametrize(
("allow_failed", "tasks", "expected_responses"), [
pytest.param(
True, [
partial(_request_mock, fails=False, content="1"),
partial(_request_mock, fails=False, content="2"),
partial(_request_mock, fails=False, content="3"),
partial(_request_mock, fails=False, content="4"),
],
["1", "2", "3", "4"],
id="no failures, fails allower"
),
pytest.param(
True, [
partial(_request_mock, fails=False, content="1"),
partial(_request_mock, fails=True, content="2"),
partial(_request_mock, fails=False, content="3"),
partial(_request_mock, fails=True, content="4"),
],
["1", "2", "3", "4"],
id="failures, fails allowed"
),
pytest.param(
False, [
partial(_request_mock, fails=True, content="failure"),
partial(_request_mock, fails=False, content="2"),
partial(_request_mock, fails=True, content="failure"),
partial(_request_mock, fails=False, content="4"),
],
["failure"],
id="failures, fails disallowed"
),
pytest.param(
False, [
partial(_request_mock, fails=False, content="1"),
partial(_request_mock, fails=False, content="2"),
partial(_request_mock, fails=False, content="3"),
partial(_request_mock, fails=False, content="4"),
],
["1", "2", "3", "4"],
id="no failures, fails disallowed"
),
]
)
@pytest.mark.asyncio
async def test_unit_disallow_failed_coroutines(
allow_failed: bool,
tasks: list[partial[Coroutine[Any, Any, httpx.Response]]],
expected_responses: list[str],
):
"""Test disallow failed coroutines method properly sets the flag to False."""
responses = await run_tasks(tasks, allow_failed=allow_failed)
response_contents = [response[1].content.decode() for response in responses]
assert response_contents == expected_responses
async def _fetch_canceller_error(
async_client: httpx.AsyncClient, # not used by mock
limiter: asyncio.Semaphore, # not used by mock
fails: bool,
content: str,
cancelled_counter: Counter):
try:
if not fails:
await asyncio.sleep(0.01)
print("Doesn't fail")
else:
print("Fails")
return await _request_mock(async_client=async_client, limiter=limiter, fails=fails, content=content)
except asyncio.CancelledError:
cancelled_counter.update(["cancelled"])
print(cancelled_counter["cancelled"])
print("Cancelled")
@pytest.mark.asyncio
async def test_remaining_tasks_cancelled_when_fails_disallowed():
cancelled_counter = Counter()
tasks = [
partial(_fetch_canceller_error, fails=True, content="1", cancelled_counter=cancelled_counter),
*[partial(_fetch_canceller_error, fails=False, content=f"{i}", cancelled_counter=cancelled_counter)
for i in range(2, 200)],
]
await run_tasks(tasks, allow_failed=False)
# give some time to actually cancel the tasks in background
await asyncio.sleep(1)
print("Cancelled amount: ", cancelled_counter["cancelled"])
assert len(tasks) > cancelled_counter["cancelled"] > 0
@pytest.mark.asyncio
async def test_unit_run_tasks_pool_limits_configurable_via_env(
monkeypatch: pytest.MonkeyPatch,
):
"""Env vars override the httpx.AsyncClient connection-pool limits.
Operators running the SDK in a Kubernetes Deployment with
connect-time-only load balancing (kube-proxy ClusterIP, meshless)
need to be able to shrink the keepalive pool so connections recycle
frequently and redistribute across backend pods.
"""
monkeypatch.setenv("UNSTRUCTURED_CLIENT_MAX_CONNECTIONS", "7")
monkeypatch.setenv("UNSTRUCTURED_CLIENT_MAX_KEEPALIVE_CONNECTIONS", "1")
monkeypatch.setenv("UNSTRUCTURED_CLIENT_KEEPALIVE_EXPIRY", "30.0")
captured: dict[str, httpx.Limits] = {}
real_async_client = httpx.AsyncClient
def _capturing_async_client(*args, **kwargs):
captured["limits"] = kwargs.get("limits")
return real_async_client(*args, **kwargs)
with patch(
"unstructured_client._hooks.custom.split_pdf_hook.httpx.AsyncClient",
side_effect=_capturing_async_client,
):
await run_tasks(
[partial(_request_mock, fails=False, content="ok")],
allow_failed=True,
)
limits = captured["limits"]
assert isinstance(limits, httpx.Limits)
assert limits.max_connections == 7
assert limits.max_keepalive_connections == 1
assert limits.keepalive_expiry == 30.0
_TLS_ENV_VARS = (
"SSL_CERT_FILE",
"REQUESTS_CA_BUNDLE",
"UNSTRUCTURED_CLIENT_TLS_CLIENT_CERT",
"UNSTRUCTURED_CLIENT_TLS_CLIENT_KEY",
)
def test_unit_resolve_tls_config_defaults_unchanged_without_env(
monkeypatch: pytest.MonkeyPatch,
):
"""No env vars set → verify=True, cert=None (httpx defaults). Backward
compatibility check — callers that don't opt into TLS config see no
behavior change."""
from unstructured_client._hooks.custom.split_pdf_hook import _resolve_tls_config
for var in _TLS_ENV_VARS:
monkeypatch.delenv(var, raising=False)
verify, cert = _resolve_tls_config()
assert verify is True
assert cert is None
def test_unit_resolve_tls_config_ssl_cert_file_from_env(
monkeypatch: pytest.MonkeyPatch, tmp_path
):
"""SSL_CERT_FILE (stdlib ssl convention) → verify=<path>. Use case:
internal CA bundle shared with other Python tooling."""
from unstructured_client._hooks.custom.split_pdf_hook import _resolve_tls_config
for var in _TLS_ENV_VARS:
monkeypatch.delenv(var, raising=False)
ca_bundle = tmp_path / "custom-ca.pem"
ca_bundle.write_text("-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n")
monkeypatch.setenv("SSL_CERT_FILE", str(ca_bundle))
verify, cert = _resolve_tls_config()
assert verify == str(ca_bundle)
assert cert is None
def test_unit_resolve_tls_config_requests_ca_bundle_from_env(
monkeypatch: pytest.MonkeyPatch, tmp_path
):
"""REQUESTS_CA_BUNDLE (requests/httpx-ecosystem convention) → verify=<path>."""
from unstructured_client._hooks.custom.split_pdf_hook import _resolve_tls_config
for var in _TLS_ENV_VARS:
monkeypatch.delenv(var, raising=False)
ca_bundle = tmp_path / "custom-ca.pem"
ca_bundle.write_text("-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n")
monkeypatch.setenv("REQUESTS_CA_BUNDLE", str(ca_bundle))
verify, cert = _resolve_tls_config()
assert verify == str(ca_bundle)
assert cert is None
def test_unit_resolve_tls_config_ssl_cert_file_wins_over_requests_ca_bundle(
monkeypatch: pytest.MonkeyPatch,
):
"""If both standard env vars are set, SSL_CERT_FILE takes precedence —
it's the lower-level stdlib convention."""
from unstructured_client._hooks.custom.split_pdf_hook import _resolve_tls_config
monkeypatch.setenv("SSL_CERT_FILE", "/etc/ssl/stdlib-ca.pem")
monkeypatch.setenv("REQUESTS_CA_BUNDLE", "/etc/ssl/requests-ca.pem")
verify, _ = _resolve_tls_config()
assert verify == "/etc/ssl/stdlib-ca.pem"
def test_unit_resolve_tls_config_client_cert_only(monkeypatch: pytest.MonkeyPatch):
"""UNSTRUCTURED_CLIENT_TLS_CLIENT_CERT alone → cert=<path>. httpx will
read the private key from the same PEM file."""
from unstructured_client._hooks.custom.split_pdf_hook import _resolve_tls_config
monkeypatch.setenv("UNSTRUCTURED_CLIENT_TLS_CLIENT_CERT", "/etc/ssl/client.pem")
monkeypatch.delenv("UNSTRUCTURED_CLIENT_TLS_CLIENT_KEY", raising=False)
verify, cert = _resolve_tls_config()
assert cert == "/etc/ssl/client.pem"
def test_unit_resolve_tls_config_client_cert_and_key_split(
monkeypatch: pytest.MonkeyPatch,
):
"""Both _CLIENT_CERT and _CLIENT_KEY → cert=(cert_path, key_path). For
PKI setups where cert and key live in separate files."""
from unstructured_client._hooks.custom.split_pdf_hook import _resolve_tls_config
monkeypatch.setenv("UNSTRUCTURED_CLIENT_TLS_CLIENT_CERT", "/etc/ssl/client.crt")
monkeypatch.setenv("UNSTRUCTURED_CLIENT_TLS_CLIENT_KEY", "/etc/ssl/client.key")
verify, cert = _resolve_tls_config()
assert cert == ("/etc/ssl/client.crt", "/etc/ssl/client.key")
@pytest.mark.asyncio
async def test_unit_run_tasks_forwards_tls_config_to_httpx_async_client(
monkeypatch: pytest.MonkeyPatch, tmp_path
):
"""run_tasks() actually wires verify+cert into httpx.AsyncClient(). End-to-
end check that _resolve_tls_config is called and its result reaches the
client construction. AsyncClient is fully mocked so we don't have to feed
httpx a real cert chain."""
ca_bundle = tmp_path / "ca.pem"
ca_bundle.write_text("-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n")
monkeypatch.setenv("SSL_CERT_FILE", str(ca_bundle))
monkeypatch.setenv("UNSTRUCTURED_CLIENT_TLS_CLIENT_CERT", "/etc/ssl/client.pem")
captured: dict = {}
class _MockAsyncClient:
def __init__(self, *args, **kwargs):
captured["verify"] = kwargs.get("verify")
captured["cert"] = kwargs.get("cert")
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
with patch(
"unstructured_client._hooks.custom.split_pdf_hook.httpx.AsyncClient",
new=_MockAsyncClient,
):
await run_tasks(
[partial(_request_mock, fails=False, content="ok")],
allow_failed=True,
)
assert captured["verify"] == str(ca_bundle)
assert captured["cert"] == "/etc/ssl/client.pem"
@patch("unstructured_client._hooks.custom.form_utils.Path")
def test_unit_get_split_pdf_cache_tmp_data_dir_uses_dir_from_form_data(mock_path: MagicMock):
"""Test get_split_pdf_cache_tmp_data_dir uses the directory from the form data."""
# -- Create the form_data
dir_key = form_utils.PARTITION_FORM_SPLIT_CACHE_TMP_DATA_DIR_KEY # -- "split_pdf_cache_tmp_data_dir"
mock_dir = "/mock/dir"
form_data: FormData = {dir_key: mock_dir}
# -- Mock the Path object in form_utils
mock_path_instance = MagicMock()
mock_path.return_value = mock_path_instance
mock_path_instance.exists.return_value = True
mock_path_instance.resolve.return_value = Path(mock_dir)
result = form_utils.get_split_pdf_cache_tmp_data_dir(
form_data = form_data,
key=dir_key,
fallback_value=DEFAULT_CACHE_TMP_DATA_DIR # -- tempfile.gettempdir()
)
assert dir_key == "split_pdf_cache_tmp_data_dir"
assert form_data.get(dir_key) == "/mock/dir"
mock_path.assert_called_once_with(mock_dir)
mock_path_instance.exists.assert_called_once()
assert result == str(Path(mock_dir).resolve())
def test_before_request_raises_pdf_validation_error_when_pdf_check_fails():
"""Test that before_request raises PDFValidationError when pdf_utils.check_pdf throws PDFValidationError."""
hook = SplitPdfHook()
# Initialize the hook with a mock client
mock_client = MagicMock()
hook.sdk_init(base_url="http://localhost:8888", client=mock_client)
# Create a mock request context
mock_hook_ctx = MagicMock()
mock_hook_ctx.operation_id = "partition"
# Create a mock request with proper headers and content
mock_request = MagicMock()
mock_request.headers = {"Content-Type": "multipart/form-data"}
mock_request.url.host = "localhost"
# Mock the form data to include the necessary fields for PDF splitting
mock_pdf_file = MagicMock()
mock_pdf_file.read.return_value = b"mock_pdf_content"
mock_form_data = {
"split_pdf_page": "true",
"files": {
"filename": "test.pdf",
"content_type": "application/pdf",
"file": mock_pdf_file
}
}
# Mock the PDF reader object
mock_pdf_reader = MagicMock()
# Define the error message that will be raised
error_message = "File does not appear to be a valid PDF."
with patch("unstructured_client._hooks.custom.request_utils.get_multipart_stream_fields") as mock_get_fields, \
patch("unstructured_client._hooks.custom.pdf_utils.read_pdf") as mock_read_pdf, \
patch("unstructured_client._hooks.custom.pdf_utils.check_pdf") as mock_check_pdf:
# Set up the mocks
mock_get_fields.return_value = mock_form_data
mock_read_pdf.return_value = mock_pdf_reader
mock_check_pdf.side_effect = pdf_utils.PDFValidationError(error_message)
# Call the method under test and verify it raises PDFValidationError
with pytest.raises(pdf_utils.PDFValidationError) as exc_info:
hook.before_request(mock_hook_ctx, mock_request)
# Verify the exception has the correct message
assert str(exc_info.value) == error_message
# Verify that the mocked functions were called as expected
mock_get_fields.assert_called_once_with(mock_request)
mock_read_pdf.assert_called_once_with(mock_pdf_file)
mock_check_pdf.assert_called_once_with(mock_pdf_reader)
_MISSING = object()
def _httpx_response(content: str, status_code: int = 200) -> httpx.Response:
return httpx.Response(
status_code=status_code,
content=content.encode(),
request=httpx.Request("POST", "http://localhost:8888/general/v0/general"),
)
def _httpx_json_response(payload: list[dict], status_code: int = 200) -> httpx.Response:
return httpx.Response(
status_code=status_code,
json=payload,
request=httpx.Request("POST", "http://localhost:8888/general/v0/general"),
)
async def _transport_error_request(
async_client: httpx.AsyncClient, # pragma: no cover - signature compatibility
limiter: asyncio.Semaphore, # pragma: no cover - signature compatibility
error_cls: type[httpx.TransportError],
request_id: str,
):
raise error_cls(
f"transport failure for {request_id}",
request=httpx.Request("POST", f"http://localhost:8888/chunk/{request_id}"),
)
async def _slow_success_request(
async_client: httpx.AsyncClient, # pragma: no cover - signature compatibility
limiter: asyncio.Semaphore, # pragma: no cover - signature compatibility
content: str,
) -> httpx.Response:
await asyncio.sleep(0.05)
return _httpx_response(content)
async def _cancelled_request(
async_client: httpx.AsyncClient, # pragma: no cover - signature compatibility
limiter: asyncio.Semaphore, # pragma: no cover - signature compatibility
) -> httpx.Response:
raise asyncio.CancelledError()
def _make_hook_with_split_request(
hook: SplitPdfHook | None = None,
*,
timeout_extension: object = _MISSING,
config_timeout_ms: int | None = 12_000,
retry_config: RetryConfig | object = UNSET,
allow_failed: str | None = None,
cache_tmp_data: str | None = None,
pdf_chunks: list[tuple[io.BytesIO, int]] | None = None,
):
"""Helper: run before_request with mocked PDF parsing so it returns a dummy request."""
hook = hook or SplitPdfHook()
if hook.client is None:
hook.sdk_init(base_url="http://localhost:8888", client=httpx.Client())
hook_ctx = MagicMock(spec=BeforeRequestContext)
hook_ctx.operation_id = "partition"
hook_ctx.config = MagicMock()
hook_ctx.config.timeout_ms = config_timeout_ms
hook_ctx.config.retry_config = retry_config
request_extensions: dict[str, object] = {}
if timeout_extension is not _MISSING and timeout_extension is not None:
request_extensions["timeout"] = timeout_extension
elif config_timeout_ms is not None:
timeout_seconds = config_timeout_ms / 1000
request_extensions["timeout"] = {
"connect": timeout_seconds,
"read": timeout_seconds,
"write": timeout_seconds,
"pool": timeout_seconds,
}
request = httpx.Request(
"POST",
"http://localhost:8888/general/v0/general",
headers={"Content-Type": "multipart/form-data"},
extensions=request_extensions,
)
mock_pdf_file = MagicMock()
form_data = {
"split_pdf_page": "true",
"strategy": "fast",
"files": {
"filename": "test.pdf",
"content_type": "application/pdf",
"file": mock_pdf_file,
},
}
if allow_failed is not None:
form_data["split_pdf_allow_failed"] = allow_failed
if cache_tmp_data is not None:
form_data["split_pdf_cache_tmp_data"] = cache_tmp_data
mock_pdf_reader = MagicMock()
mock_pdf_reader.get_num_pages.return_value = 100
mock_pdf_reader.pages = [MagicMock()] * 100
mock_pdf_reader.stream = io.BytesIO(b"fake-pdf-bytes")
with patch("unstructured_client._hooks.custom.request_utils.get_multipart_stream_fields") as mock_get_fields, \
patch("unstructured_client._hooks.custom.pdf_utils.read_pdf") as mock_read_pdf, \
patch("unstructured_client._hooks.custom.pdf_utils.check_pdf") as mock_check_pdf, \
patch.object(hook, "_trim_large_pages", side_effect=lambda pdf, fd: pdf), \
patch.object(hook, "_get_pdf_chunk_paths", return_value=[]), \
patch.object(hook, "_get_pdf_chunks_in_memory", return_value=pdf_chunks or []):
mock_get_fields.return_value = form_data
mock_read_pdf.return_value = mock_pdf_reader
mock_check_pdf.return_value = mock_pdf_reader
result = hook.before_request(hook_ctx, request)
return hook, hook_ctx, result
def _make_sdk_hook_context():
hook_ctx = MagicMock()
hook_ctx.config = MagicMock()
hook_ctx.base_url = "http://localhost:8888"
hook_ctx.operation_id = "partition"
hook_ctx.oauth2_scopes = None
hook_ctx.security_source = None
return hook_ctx
class _BlockingAsyncClient:
def __init__(self) -> None:
self.started = asyncio.Event()
async def send(self, request: httpx.Request, stream=False) -> httpx.Response:
del stream
self.started.set()
await asyncio.Event().wait()
return httpx.Response(status_code=200, request=request)
@pytest.mark.asyncio
async def test_unit_do_request_async_cancellation_after_before_request_cleans_split_state():
operation_id = "cancelled-operation"
split_hook = SplitPdfHook()
split_hook.coroutines_to_execute[operation_id] = [MagicMock()]
split_hook.pending_operation_ids[operation_id] = operation_id
tempdir = MagicMock()
split_hook.tempdirs[operation_id] = tempdir
def _prepared_split_request(hook_ctx, request):
del hook_ctx, request
return httpx.Request(
"GET",
"http://localhost:8888/general/docs",
headers={"operation_id": operation_id},
extensions={"split_pdf_operation_id": operation_id},
)
split_hook.before_request = _prepared_split_request # type: ignore[method-assign]
hooks = SDKHooks()
hooks.before_request_hooks = [split_hook]
hooks.after_error_hooks = [split_hook]
hooks.after_success_hooks = [split_hook]
client = _BlockingAsyncClient()
config = SDKConfiguration(
client=None,
client_supplied=False,
async_client=client, # type: ignore[arg-type]
async_client_supplied=True,
debug_logger=logging.getLogger("test"),
)
config.__dict__["_hooks"] = hooks
sdk = BaseSDK(config)
task = asyncio.create_task(
sdk.do_request_async(
_make_sdk_hook_context(),
httpx.Request("POST", "http://localhost:8888/general/v0/general"),
error_status_codes=[],
)
)
await client.started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert operation_id not in split_hook.coroutines_to_execute
assert operation_id not in split_hook.pending_operation_ids
assert operation_id not in split_hook.tempdirs
tempdir.cleanup.assert_called_once()
@pytest.mark.asyncio
async def test_unit_do_request_async_cancellation_logs_cancelled_cleanup(
caplog: pytest.LogCaptureFixture,
):
caplog.set_level(logging.DEBUG, logger="test")
operation_id = "cancelled-cleanup"
class PreparedRequestHook:
def before_request(self, hook_ctx, request):
del hook_ctx, request
return httpx.Request(
"GET",
"http://localhost:8888/general/docs",
headers={"operation_id": operation_id},
extensions={"split_pdf_operation_id": operation_id},
)
class CancelledCleanupHook:
async def after_error_async(self, hook_ctx, response, error):
del hook_ctx, response, error
raise asyncio.CancelledError()
def after_error(self, hook_ctx, response, error): # pragma: no cover - dispatch guard
raise AssertionError("async hook should be awaited")
hooks = SDKHooks()
hooks.before_request_hooks = [PreparedRequestHook()] # type: ignore[list-item]
hooks.after_error_hooks = [CancelledCleanupHook()] # type: ignore[list-item]
client = _BlockingAsyncClient()
config = SDKConfiguration(
client=None,
client_supplied=False,
async_client=client, # type: ignore[arg-type]
async_client_supplied=True,
debug_logger=logging.getLogger("test"),
)
config.__dict__["_hooks"] = hooks
sdk = BaseSDK(config)
task = asyncio.create_task(
sdk.do_request_async(
_make_sdk_hook_context(),
httpx.Request("POST", "http://localhost:8888/general/v0/general"),
error_status_codes=[],
)
)
await client.started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert "Cancellation cleanup cancelled" in caplog.text