-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathtest_box.py
428 lines (383 loc) · 13 KB
/
test_box.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
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
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
"""Tests the Box source class methods"""
from unittest.mock import AsyncMock, Mock, patch
import aiohttp
import pytest
from aiohttp import StreamReader
from aiohttp.client_exceptions import ClientResponseError
from connectors.source import ConfigurableFieldValueError
from connectors.sources.box import FINISHED, BoxDataSource, NotFound, TokenError
from tests.commons import AsyncIterator
from tests.sources.support import create_source
MOCK_RESPONSE = {
"total_count": 2,
"entries": [
{
"type": "file",
"id": "1273609717220",
"etag": "0",
"name": "dummy.pdf",
"modified_at": "2023-08-04T03:17:55-07:00",
"size": 1875887,
},
{
"type": "folder",
"id": "220376481442",
"etag": "0",
"name": "My Box Notes",
"modified_at": "2023-08-18T00:59:46-07:00",
"size": 1501,
},
],
"offset": 0,
"limit": 100,
"order": [{"by": "type", "direction": "ASC"}, {"by": "name", "direction": "ASC"}],
}
EMPTY_RESPONSE = {
"total_count": 1,
"entries": [],
"offset": 100,
"limit": 100,
"order": [{"by": "type", "direction": "ASC"}, {"by": "name", "direction": "ASC"}],
}
FOLDER_ITEMS = {
"total_count": 1,
"entries": [
{
"type": "file",
"id": "1273609717123",
"etag": "0",
"name": "dummy.txt",
"modified_at": "2023-08-04T03:17:55-07:00",
"size": 1875887,
},
],
"offset": 0,
"limit": 100,
"order": [{"by": "type", "direction": "ASC"}, {"by": "name", "direction": "ASC"}],
}
MOCK_ATTACHMENT = {
"type": "file",
"id": "1273609717220",
"etag": "0",
"name": "dummy.pdf",
"modified_at": "2023-08-04T03:17:55-07:00",
"size": 1875887,
}
MOCK_ATTACHMENT_WITH_UNSUPPORTED_EXTENSION = {
"type": "file",
"id": "1273609717220",
"etag": "0",
"name": "Get Started with Box.jpg",
"modified_at": "2023-08-04T03:17:55-07:00",
"size": 1875887,
}
MOCK_ATTACHMENT_WITH_LARGE_DATA = {
"type": "file",
"id": "1273609717220",
"etag": "0",
"name": "dummy.pdf",
"modified_at": "2023-08-04T03:17:55-07:00",
"size": 10485762,
}
MOCK_ATTACHMENT_WITHOUT_EXTENSION = {
"type": "file",
"id": "1273609717220",
"etag": "0",
"name": "Get Started with Box",
"modified_at": "2023-08-04T03:17:55-07:00",
"size": 1875887,
}
MOCK_RESPONSE_FETCH = [
(
{
"type": "file",
"etag": "0",
"name": "dummy.pdf",
"size": 1875887,
"_id": "1273609717220",
"_timestamp": "2023-08-04T03:17:55-07:00",
},
{
"type": "file",
"etag": "0",
"name": "dummy.pdf",
"size": 1875887,
"id": "1273609717220",
"modified_at": "2023-08-04T03:17:55-07:00",
},
),
(
{
"type": "folder",
"etag": "0",
"name": "My Box Notes",
"size": 1501,
"_id": "220376481442",
"_timestamp": "2023-08-18T00:59:46-07:00",
},
None,
),
]
EXPECTED_CONTENT = {
"_id": "1273609717220",
"_timestamp": "2023-08-04T03:17:55-07:00",
"_attachment": "SGVsbG8gV29ybGQuLi4=",
}
class JSONAsyncMock:
def __init__(self, json, status, *args, **kwargs):
super().__init__(*args, **kwargs)
self._json = json
self.status = status
async def json(self):
return self._json
class StreamReaderAsyncMock(AsyncMock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.content = StreamReader
def get_json_mock(mock_response, status):
async_mock = AsyncMock()
async_mock.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(json=mock_response, status=status)
)
return async_mock
def client_get_mock_func(url, headers, params):
if params is not None:
if params.get("offset") == 0 and "/2.0/folders/220376481442/items" in url:
return JSONAsyncMock(json=FOLDER_ITEMS, status=200)
if params.get("offset") == 0:
return JSONAsyncMock(json=MOCK_RESPONSE, status=200)
elif params.get("offset") == 1000:
return JSONAsyncMock(json=EMPTY_RESPONSE, status=200)
return StreamReaderAsyncMock()
@pytest.mark.asyncio
@pytest.mark.parametrize("field", ["client_id", "client_secret", "refresh_token"])
async def test_validate_config_raise_on_missing_fields(field):
async with create_source(BoxDataSource) as source:
source.configuration.set_field(name=field, value="")
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_get():
async with create_source(BoxDataSource) as source:
source.client.token._set_access_token = AsyncMock()
source.client.token.access_token = "abcd#123"
access_token = await source.client.token.get()
assert access_token == source.client.token.access_token
@pytest.mark.asyncio
@pytest.mark.parametrize("box_account", ["box_free", "box_enterprise"])
async def test_set_access_token(box_account):
async with create_source(BoxDataSource) as source:
source.client.token.is_enterprise = box_account
mock_token = {
"access_token": "abc#123",
"expires_in": "1234555",
"refresh_token": "xyz#123",
}
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(mock_token, 200)
)
with patch("aiohttp.ClientSession.post", return_value=async_response):
await source.client.token._set_access_token()
assert source.client.token.access_token == "abc#123"
@pytest.mark.asyncio
async def test_set_access_token_raise_token_error_on_exception():
async with create_source(BoxDataSource) as source:
with patch("aiohttp.ClientSession.post", side_effect=Exception):
with pytest.raises(TokenError):
await source.client.token._set_access_token()
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries")
@pytest.mark.parametrize(
"status_code, exception",
[
(409, ClientResponseError),
(401, ClientResponseError),
(404, NotFound),
(429, Exception),
],
)
async def test_client_get_raise_exception_on_response_error(
mock_time_to_sleep_between_retries, status_code, exception
):
async with create_source(BoxDataSource) as source:
mock_time_to_sleep_between_retries.return_value = 0
source.client.token.get = AsyncMock()
source.client.token._set_access_token = AsyncMock()
source.client._http_session.get = AsyncMock(
side_effect=ClientResponseError(
status=status_code,
request_info=aiohttp.RequestInfo(
real_url="", method=None, headers=None, url=""
),
history=None,
headers={"retry-after": 0},
)
)
with pytest.raises(exception):
await source.client.get("/me", {})
@pytest.mark.asyncio
async def test_ping_with_successful_connection():
async with create_source(BoxDataSource) as source:
source.client.token.get = AsyncMock()
source.client._http_session.get = AsyncMock(
return_value=JSONAsyncMock(json={"username": "demo"}, status=200)
)
try:
await source.ping()
except Exception as exception:
msg = "Ping should've been successful"
raise AssertionError(msg) from exception
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries")
async def test_ping_raises_on_unsuccessful_connection(
mock_time_to_sleep_between_retries,
):
async with create_source(BoxDataSource) as source:
mock_time_to_sleep_between_retries.return_value = 0
source.client.token.get = AsyncMock(side_effect=Exception())
with pytest.raises(Exception):
await source.ping()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"attachment, doit, expected_content",
[
(MOCK_ATTACHMENT, True, EXPECTED_CONTENT),
(MOCK_ATTACHMENT_WITHOUT_EXTENSION, True, None),
(MOCK_ATTACHMENT_WITH_LARGE_DATA, True, None),
(MOCK_ATTACHMENT_WITH_UNSUPPORTED_EXTENSION, True, None),
(MOCK_ATTACHMENT, False, None),
],
)
async def test_get_content(attachment, doit, expected_content):
async with create_source(BoxDataSource) as source:
source.client.token.get = AsyncMock()
source.client._http_session.get = AsyncMock(
return_value=StreamReaderAsyncMock()
)
with patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes("Hello World...", "utf-8")]),
):
response = await source.get_content(
attachment=attachment,
doit=doit,
)
assert response == expected_content
@pytest.mark.asyncio
async def test_consumer_processes_queue_items():
mock_folder = {
"type": "folder",
"etag": "0",
"name": "My Box Notes",
"size": 1501,
"_id": "220376481442",
"_timestamp": "2023-08-18T00:59:46-07:00",
}
mock_file = {
"type": "file",
"etag": "0",
"name": "dummy.pdf",
"size": 1875887,
"_id": "1273609717220",
"_timestamp": "2023-08-04T03:17:55-07:00",
}
async with create_source(BoxDataSource) as source:
source.tasks = 2
await source.queue.put((mock_file, None))
await source.queue.put(FINISHED)
await source.queue.put((mock_folder, None))
await source.queue.put(FINISHED)
items = []
async for item, _ in source._consumer():
items.append(item)
assert items == [mock_file, mock_folder]
@pytest.mark.asyncio
async def test_fetch():
actual_response = []
expected_response = [
{
"type": "file",
"etag": "0",
"name": "dummy.pdf",
"size": 1875887,
"_id": "1273609717220",
"_timestamp": "2023-08-04T03:17:55-07:00",
},
{
"type": "folder",
"etag": "0",
"name": "My Box Notes",
"size": 1501,
"_id": "220376481442",
"_timestamp": "2023-08-18T00:59:46-07:00",
},
"FINISHED",
]
async with create_source(BoxDataSource) as source:
source.client.token.get = AsyncMock()
source.client._http_session.get = AsyncMock(side_effect=client_get_mock_func)
await source._fetch("0")
while not source.queue.empty():
_, doc = await source.queue.get()
if isinstance(doc, tuple):
actual_response.append(doc[0])
else:
actual_response.append(doc)
assert actual_response == expected_response
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries")
async def test_fetch_returns_none_on_client_exception(
mock_time_to_sleep_between_retries,
):
async with create_source(BoxDataSource) as source:
mock_time_to_sleep_between_retries.return_value = Mock()
source.client.token.get = AsyncMock(side_effect=Exception())
with pytest.raises(Exception):
await source._fetch("0")
@pytest.mark.asyncio
async def test_get_docs():
actual_response = []
expected_response = [
{
"type": "file",
"etag": "0",
"name": "dummy.pdf",
"size": 1875887,
"_id": "1273609717220",
"_timestamp": "2023-08-04T03:17:55-07:00",
},
{
"type": "folder",
"etag": "0",
"name": "My Box Notes",
"size": 1501,
"_id": "220376481442",
"_timestamp": "2023-08-18T00:59:46-07:00",
},
]
async with create_source(BoxDataSource) as source:
source._fetch = AsyncMock()
await source.queue.put((expected_response[0], None))
await source.queue.put((expected_response[1], None))
await source.queue.put(FINISHED)
async for doc, _ in source.get_docs():
actual_response.append(doc)
assert actual_response == expected_response
@pytest.mark.asyncio
async def test_end_signal_is_added_to_queue_in_case_of_exception():
END_SIGNAL = "FINISHED"
async with create_source(BoxDataSource) as source:
with patch.object(
source.client,
"paginated_call",
side_effect=Exception("Error while fetching documents"),
):
with pytest.raises(Exception):
await source._fetch(doc_id=0)
assert source.queue.get_nowait()[1] == END_SIGNAL