-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathtest_graphql.py
457 lines (394 loc) · 15.3 KB
/
test_graphql.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
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
#
# 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 GraphQL source class methods"""
from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, Mock, patch
import aiohttp
import pytest
from aiohttp.client_exceptions import ClientResponseError
from freezegun import freeze_time
from graphql import parse
from connectors.source import ConfigurableFieldValueError
from connectors.sources.graphql import GraphQLDataSource, UnauthorizedException
from tests.commons import AsyncIterator
from tests.sources.support import create_source
class JSONAsyncMock(AsyncMock):
def __init__(self, json, status, *args, **kwargs):
super().__init__(*args, **kwargs)
self._json = json
self.status = status
async def json(self):
return self._json
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
@asynccontextmanager
async def create_graphql_source(
headers=None,
graphql_variables=None,
graphql_query="{users {name {firstName } } }",
graphql_object_to_id_map='{"users": "id"}',
):
async with create_source(
GraphQLDataSource,
http_endpoint="http://127.0.0.1:1234",
authentication_method="none",
graphql_query=graphql_query,
graphql_object_to_id_map=graphql_object_to_id_map,
headers=headers,
graphql_variables=graphql_variables,
) as source:
yield source
@pytest.mark.asyncio
@pytest.mark.parametrize(
"object_list, data, expected_result",
[
(
{"basicInfo": "id"},
{"basicInfo": {"name": "xyz", "id": "abc#123"}},
[{"name": "xyz", "id": "abc#123", "_id": "abc#123"}],
),
(
{"basicInfo": "id"},
{
"basicInfo": [
{"name": "xyz", "id": "abc#123"},
{"name": "pqr", "id": "pqr#456"},
]
},
[
{"name": "xyz", "id": "abc#123", "_id": "abc#123"},
{"name": "pqr", "id": "pqr#456", "_id": "pqr#456"},
],
),
(
{"empData.basicInfo": "id"},
{"empData": {"basicInfo": {"name": "xyz", "id": "abc#123"}}},
[{"id": "abc#123", "name": "xyz", "_id": "abc#123"}],
),
],
)
async def test_extract_graphql_data_items(object_list, data, expected_result):
actual_response = []
async with create_graphql_source() as source:
source.graphql_client.graphql_object_to_id_map = object_list
for doc in source.graphql_client.extract_graphql_data_items(data):
actual_response.append(doc)
assert actual_response == expected_result
@pytest.mark.asyncio
async def test_get():
async with create_graphql_source() as source:
source.graphql_client.session.get = Mock(
return_value=get_json_mock(
mock_response={"data": {"users": "xyz"}}, status=200
)
)
data = await source.graphql_client.get("query")
assert data == {"users": "xyz"}
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_get_with_errors():
async with create_graphql_source() as source:
source.graphql_client.session.get = Mock(
return_value=get_json_mock(
mock_response={
"errors": [{"type": "QUERY", "message": "Invalid query"}]
},
status=200,
)
)
with pytest.raises(Exception):
await source.graphql_client.get("query")
@pytest.mark.asyncio
async def test_post():
async with create_graphql_source() as source:
source.graphql_client.session.post = Mock(
return_value=get_json_mock(
mock_response={"data": {"users": "xyz"}}, status=200
)
)
data = await source.graphql_client.post("query")
assert data == {"users": "xyz"}
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_post_with_errors():
async with create_graphql_source() as source:
source.graphql_client.session.post = Mock(
return_value=get_json_mock(
mock_response={
"errors": [{"type": "QUERY", "message": "Invalid query"}]
},
status=200,
)
)
with pytest.raises(Exception):
await source.graphql_client.post("query")
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_make_request_with_unauthorized():
async with create_graphql_source() as source:
source.graphql_client.session.post = Mock(
side_effect=ClientResponseError(
status=401,
request_info=aiohttp.RequestInfo(
real_url="", method=None, headers=None, url=""
),
history=None,
)
)
with pytest.raises(UnauthorizedException):
await source.graphql_client.make_request("QUERY")
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_make_request_with_429_exception():
async with create_graphql_source() as source:
source.graphql_client.session.post = Mock(
side_effect=ClientResponseError(
status=429,
request_info=aiohttp.RequestInfo(
real_url="", method=None, headers=None, url=""
),
history=None,
)
)
with pytest.raises(Exception):
await source.graphql_client.make_request("query")
@pytest.mark.asyncio
async def test_validate_config_with_invalid_url():
async with create_graphql_source() as source:
source.graphql_client.url = "dummy_url"
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_mutation():
async with create_graphql_source(
graphql_query="""mutation {
addCategory(id: 6, name: "Green Fruits", products: [8, 2, 3]) {
name
products {
name
}
}
}"""
) as source:
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_non_json_headers():
async with create_graphql_source(headers="Invalid Headers") as source:
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_non_json_variables():
async with create_graphql_source(graphql_variables="Invalid Variables") as source:
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_ping():
async with create_graphql_source() as source:
source.graphql_client.post = AsyncMock()
await source.ping()
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_ping_negative():
async with create_graphql_source() as source:
source.graphql_client.post = AsyncMock(side_effect=Exception())
with pytest.raises(Exception):
await source.ping()
@pytest.mark.asyncio
async def test_fetch_data():
expected_response = [{"id": "1", "name": {"firstName": "xyz"}, "_id": "1"}]
actual_response = []
async with create_graphql_source() as source:
source.graphql_client.pagination_model = "no_pagination"
source.graphql_client.graphql_object_to_id_map = {"users": "id"}
source.graphql_client.post = AsyncMock(
return_value={
"users": [{"id": "1", "name": {"firstName": "xyz"}, "_id": "1"}]
}
)
async for doc in source.fetch_data("{users {id name}}"):
actual_response.append(doc)
assert actual_response == expected_response
@pytest.mark.asyncio
async def test_fetch_data_with_pagination():
expected_response = [
{
"id": "1",
"name": {"firstName": "xyz"},
"pageInfo": {"hasNextPage": True, "endCursor": "xyz#123"},
"_id": "1",
},
{
"id": "2",
"name": {"firstName": "abc"},
"pageInfo": {"hasNextPage": False, "endCursor": "pqr#123"},
"_id": "2",
},
]
actual_response = []
async with create_graphql_source() as source:
source.graphql_client.pagination_model = "cursor_pagination"
source.graphql_client.graphql_object_to_id_map = {"users": "id"}
source.graphql_client.pagination_key = "users"
source.graphql_client.post = AsyncMock(
side_effect=[
{
"users": {
"id": "1",
"name": {"firstName": "xyz"},
"pageInfo": {"hasNextPage": True, "endCursor": "xyz#123"},
"_id": "1",
}
},
{
"users": {
"id": "2",
"name": {"firstName": "abc"},
"pageInfo": {"hasNextPage": False, "endCursor": "pqr#123"},
"_id": "2",
}
},
]
)
async for doc in source.fetch_data(
"query($afterCursor: String!) {users(first:5, after:$afterCursor) {name pageInfo}}"
):
actual_response.append(doc)
assert actual_response == expected_response
@pytest.mark.asyncio
async def test_fetch_data_without_pageinfo():
async with create_graphql_source() as source:
source.graphql_client.pagination_model = "cursor_pagination"
source.graphql_client.graphql_object_to_id_map = {"users": id}
source.graphql_client.post = AsyncMock(
side_effect=[{"users": {"id": "123", "name": {"firstName": "xyz"}}}]
)
with pytest.raises(ConfigurableFieldValueError):
async for _doc in source.fetch_data("{users {id name pageInfo}}"):
pass
@pytest.mark.asyncio
@freeze_time("2024-01-24T04:07:19")
async def test_get_docs():
expected_response = [
{
"name": "xyz",
"id": "id1",
"_id": "id1",
"_timestamp": "2024-01-24T04:07:19+00:00",
},
{
"name": "pqr",
"id": "id2",
"_id": "id2",
"_timestamp": "2024-01-24T04:07:19+00:00",
},
{
"name": "abc",
"id": "id3",
"_id": "id3",
"_timestamp": "2024-01-24T04:07:19+00:00",
},
]
actual_response = []
async with create_graphql_source() as source:
source.graphql_client.graphql_field_id = "id"
source.fetch_data = AsyncIterator(
[
{"name": "xyz", "id": "id1", "_id": "id1"},
{"name": "pqr", "id": "id2", "_id": "id2"},
{"name": "abc", "id": "id3", "_id": "id3"},
]
)
async for doc, _ in source.get_docs():
actual_response.append(doc)
assert actual_response == expected_response
@pytest.mark.asyncio
@freeze_time("2024-01-24T04:07:19")
async def test_get_docs_with_dict_id():
async with create_graphql_source() as source:
source.fetch_data = AsyncIterator(
[
{"name": "xyz", "_id": {"sys_id": 1}},
]
)
with pytest.raises(ConfigurableFieldValueError):
async for _, _ in source.get_docs():
pass
@pytest.mark.asyncio
async def test_extract_graphql_data_items_with_invalid_key():
async with create_graphql_source() as source:
source.graphql_client.graphql_object_to_id_map = {"user": "id"}
data = {"users": {"namexyzid": "123"}}
with pytest.raises(ConfigurableFieldValueError):
for _ in source.graphql_client.extract_graphql_data_items(data):
pass
@pytest.mark.asyncio
async def test_extract_pagination_info_with_invalid_key():
async with create_graphql_source() as source:
source.pagination_key = ["users_data.user"]
data = {"users_data": {"users": {"namexyzid": "123"}}}
with pytest.raises(ConfigurableFieldValueError):
for _ in source.graphql_client.extract_pagination_info(data):
pass
@pytest.mark.asyncio
async def test_is_query_with_mutation_query():
async with create_graphql_source() as source:
ast = parse("mutation Login($email: String!){login(email: $email) { token }}")
response = source.is_query(ast)
assert response is False
@pytest.mark.asyncio
async def test_is_query_with_invalid_query():
async with create_graphql_source() as source:
source.graphql_client.graphql_query = "invalid_query {user {}}"
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_invalid_objects():
async with create_graphql_source() as source:
source.graphql_client.graphql_query = (
"query {organization {repository { issues {name}}}}"
)
source.graphql_client.graphql_object_to_id_map = {
"organization.repository.pullRequest": "id"
}
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_invalid_pagination_key():
async with create_graphql_source(
graphql_object_to_id_map='{"organization.repository.issues": "id"}'
) as source:
source.graphql_client.graphql_query = (
"query {organization {repository { issues {id name}}}}"
)
source.graphql_client.pagination_model = "cursor_pagination"
source.graphql_client.pagination_key = "organization.repository.pullRequest"
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_missing_config_field():
async with create_graphql_source(
graphql_object_to_id_map='{"organization.repository.issues": "id"}'
) as source:
source.graphql_client.graphql_query = (
"query {organization {repository { issues {name}}}}"
)
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_invalid_json():
async with create_graphql_source(
graphql_object_to_id_map='{"organization.repository.issues": "id"'
) as source:
source.graphql_client.graphql_query = (
"query {organization {repository { issues {name}}}}"
)
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()