-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtest_integration_freemium.py
212 lines (174 loc) · 6.2 KB
/
test_integration_freemium.py
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
from __future__ import annotations
import asyncio
import json
import os
import pytest
from deepdiff import DeepDiff
from unstructured_client import UnstructuredClient
from unstructured_client.models import shared, operations
from unstructured_client.models.errors import SDKError, ServerError, HTTPValidationError
from unstructured_client.utils.retries import BackoffStrategy, RetryConfig
@pytest.mark.parametrize("split_pdf", [True, False])
@pytest.mark.parametrize("strategy", ["fast", "ocr_only", "hi_res"])
def test_partition_strategies(split_pdf, strategy, client, doc_path):
filename = "layout-parser-paper-fast.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy=strategy,
languages=["eng"],
split_pdf_page=split_pdf,
)
)
response = client.general.partition(request=req)
assert response.status_code == 200
assert len(response.elements)
@pytest.fixture(scope="session")
def event_loop():
"""Make the loop session scope to use session async fixtures."""
policy = asyncio.get_event_loop_policy()
loop = policy.new_event_loop()
yield loop
loop.close()
@pytest.mark.parametrize("split_pdf", [True, False])
@pytest.mark.parametrize("error", [(500, ServerError), (403, SDKError), (422, HTTPValidationError)])
def test_partition_handling_server_error(error, split_pdf, monkeypatch, doc_path, event_loop):
"""
Mock different error responses, assert that the client throws the correct error
"""
filename = "layout-parser-paper-fast.pdf"
import httpx
error_code, sdk_raises = error
# Create the mock response
json_data = {"detail": "An error occurred"}
response = httpx.Response(
status_code=error_code,
headers={'Content-Type': 'application/json'},
content=json.dumps(json_data),
request=httpx.Request("POST", "http://mock-request"),
)
monkeypatch.setattr(httpx.AsyncClient, "send", lambda *args, **kwargs: response)
monkeypatch.setattr(httpx.Client, "send", lambda *args, **kwargs: response)
# initialize client after patching
client = UnstructuredClient(
api_key_auth=os.getenv("UNSTRUCTURED_API_KEY"),
retry_config=RetryConfig("backoff", BackoffStrategy(1, 10, 1.5, 30), False),
)
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=split_pdf,
)
)
with pytest.raises(sdk_raises):
response = client.general.partition(request=req)
@pytest.mark.asyncio
async def test_partition_async_returns_elements(client, doc_path):
filename = "layout-parser-paper.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
)
)
response = await client.general.partition_async(request=req)
assert response.status_code == 200
assert len(response.elements)
@pytest.mark.asyncio
async def test_partition_async_processes_concurrent_files(client, doc_path):
"""
Assert that partition_async can be used to send multiple files concurrently.
Send two separate portions of the test doc, serially and then using asyncio.gather.
The results for both runs should match.
"""
filename = "layout-parser-paper.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
# Set up two SDK requests
# For different page ranges
requests = [
operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
split_pdf_page_range=[1, 3],
)
),
operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
split_pdf_page_range=[10, 12],
)
)
]
serial_responses = []
for req in requests:
res = await client.general.partition_async(request=req)
assert res.status_code == 200
serial_responses.append(res.elements)
concurrent_responses = []
results = await asyncio.gather(
client.general.partition_async(request=requests[0]),
client.general.partition_async(request=requests[1])
)
for res in results:
assert res.status_code == 200
concurrent_responses.append(res.elements)
diff = DeepDiff(
t1=serial_responses,
t2=concurrent_responses,
ignore_order=True,
)
assert len(diff) == 0
def test_uvloop_partitions_without_errors(client, doc_path):
async def call_api():
filename = "layout-parser-paper-fast.pdf"
with open(doc_path / filename, "rb") as f:
files = shared.Files(
content=f.read(),
file_name=filename,
)
req = operations.PartitionRequest(
partition_parameters=shared.PartitionParameters(
files=files,
strategy="fast",
languages=["eng"],
split_pdf_page=True,
)
)
resp = client.general.partition(request=req)
if resp is not None:
return resp.elements
else:
return []
import uvloop
uvloop.install()
elements = asyncio.run(call_api())
assert len(elements) > 0