/
test-endpoint-requests.py
647 lines (499 loc) · 19 KB
/
test-endpoint-requests.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
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
import io
import json
import requests
import urllib
from nose.tools import eq_
from unittest.mock import patch
from sgqlc.endpoint.requests import RequestsEndpoint, add_query_to_url
from sgqlc.types import Schema, Type
from sgqlc.operation import Operation
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
self.text = json_data
def __enter__(self):
return self
def raise_for_status(self):
pass
def __exit__(self, exception_type, exception_value, traceback):
pass
def json(self):
return json.loads(self.json_data)
test_url = 'http://some-server.com/graphql'
extra_accept_header = ', '.join([
'application/json; charset=utf-8',
'application/vnd.xyz.feature-flag+json',
])
graphql_query = '''
query GitHubRepoIssues($repoOwner: String!, $repoName: String!) {
repository(owner: $repoOwner, name: $repoName) {
issues(first: 100) {
nodes {
number
title
}
}
}
}
'''
graphql_response_ok = '''
{
"data": {
"repository": {
"issues": {
"nodes": [
{
"number": 1,
"title": "unit tests: sgqlc.types"
}
]
}
}
}
}'''
graphql_response_error = '''
{
"errors": [{
"message": "Server Reported Error",
"locations": [{"line": 1, "column": 1}]
}, {
"message": "Other Message",
"path": ["repository", "issues"]
}]
}
'''
graphql_response_json_error = '''
{
"data": {
'''
# -- Test Helpers --
def get_json_exception(s):
try:
json.loads(s)
return None
except json.JSONDecodeError as e:
return e
def configure_mock_requests_send(mock_requests_send, payload):
if isinstance(payload, Exception):
mock_requests_send.side_effect = payload
else:
mock_requests_send.return_value = MockResponse(payload, 200)
def check_request_url(req, expected):
split = urllib.parse.urlsplit(req.url)
received = urllib.parse.SplitResult(
split.scheme,
split.netloc,
split.path,
None,
split.fragment,
).geturl()
eq_(received, expected)
def check_request_headers_(req, headers, name):
if not headers:
return
if isinstance(headers, dict):
headers = headers.items()
for k, v in headers:
g = req.headers.get(k)
eq_(g, v, 'Failed {} header {}: {!r} != {!r}'.format(name, k, v, g))
def check_request_headers(req, base_headers, extra_headers):
if extra_headers and 'Accept' in extra_headers:
accept_header = extra_accept_header
else:
accept_header = 'application/json; charset=utf-8'
eq_(req.headers.get('Accept'), accept_header)
if req.method == 'POST':
eq_(req.headers.get('Content-type'), 'application/json; charset=utf-8')
check_request_headers_(req, base_headers, 'base')
check_request_headers_(req, extra_headers, 'extra')
def get_request_url_query(req):
split = urllib.parse.urlsplit(req.url)
query = urllib.parse.parse_qsl(split.query)
if isinstance(query, list):
query = dict(query)
return query
def check_request_variables(req, variables):
if req.method == 'POST':
post_data = json.loads(req.body)
received = post_data.get('variables')
else:
query = get_request_url_query(req)
received = json.loads(query.get('variables', 'null'))
eq_(received, variables)
def check_request_operation_name(req, operation_name):
if req.method == 'POST':
post_data = json.loads(req.body)
received = post_data.get('operationName')
else:
query = get_request_url_query(req)
received = query.get('operationName')
eq_(received, operation_name)
def check_request_query(req, query):
if req.method == 'POST':
post_data = json.loads(req.body)
received = post_data.get('query')
else:
query_data = get_request_url_query(req)
received = query_data.get('query')
if isinstance(query, bytes):
query = query.decode('utf-8')
eq_(received, query)
def check_mock_requests_send(mock_requests_send,
method='POST',
timeout=None,
base_headers=None,
extra_headers=None,
variables=None,
operation_name=None,
query=None, # defaults to `graphql_query`
):
assert mock_requests_send.called
args = mock_requests_send.call_args
req = args[0][0]
eq_(req.method, method)
check_request_url(req, test_url)
check_request_headers(req, base_headers, extra_headers)
check_request_variables(req, variables)
check_request_operation_name(req, operation_name)
check_request_query(req, query or graphql_query)
eq_(args[1]['timeout'], timeout)
# -- Actual Tests --
@patch('requests.sessions.Session.send')
def test_basic(mock_requests_send):
'[Requests] - Test if basic usage with only essential parameters works'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send)
eq_(str(endpoint),
'RequestsEndpoint('
+ 'url={}, '.format(test_url)
+ 'base_headers={}, timeout=None, method=POST, auth=None)')
@patch('requests.sessions.Session.send')
def test_basic_auth(mock_requests_send):
'[Requests] - Test if basic usage with only auth works'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
endpoint = RequestsEndpoint(test_url,
auth=requests.auth.HTTPBasicAuth("user",
"password"))
data = endpoint(graphql_query)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send)
eq_(str(endpoint),
'RequestsEndpoint('
+ 'url={}, '.format(test_url)
+ 'base_headers={}, timeout=None, method=POST, '
+ 'auth=<class \'requests.auth.HTTPBasicAuth\'>)')
@patch('requests.sessions.Session.send')
def test_basic_bytes_query(mock_requests_send):
'[Requests] - Test if query with type bytes works'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query.encode('utf-8'))
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_basic_operation_query(mock_requests_send):
'[Requests] - Test if query with type sgqlc.operation.Operation() works'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
schema = Schema()
# MyType and Query may be declared if doctests were processed by nose
if 'MyType' in schema:
schema -= schema.MyType
if 'Query' in schema:
schema -= schema.Query
class MyType(Type):
__schema__ = schema
i = int
class Query(Type):
__schema__ = schema
my_type = MyType
op = Operation(Query)
op.my_type.i()
endpoint = RequestsEndpoint(test_url)
data = endpoint(op)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send, query=bytes(op))
@patch('requests.sessions.Session.send')
def test_headers(mock_requests_send):
'[Requests] - Test if all headers are passed'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
base_headers = {
'Xpto': 'abc',
}
extra_headers = {
'Extra': '123',
'Accept': extra_accept_header,
}
endpoint = RequestsEndpoint(test_url, base_headers=base_headers)
data = endpoint(graphql_query, extra_headers=extra_headers)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send,
base_headers=base_headers,
extra_headers=extra_headers)
@patch('requests.sessions.Session.send')
def test_default_timeout(mock_requests_send):
'[Requests] - Test if default timeout is respected'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
timeout = 123
endpoint = RequestsEndpoint(test_url, timeout=timeout)
data = endpoint(graphql_query)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send, timeout=timeout)
@patch('requests.sessions.Session.send')
def test_call_timeout(mock_requests_send):
'[Requests] - Test if call timeout takes precedence over default'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
timeout = 123
endpoint = RequestsEndpoint(test_url, timeout=1)
data = endpoint(graphql_query, timeout=timeout)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send, timeout=timeout)
@patch('requests.sessions.Session.send')
def test_variables(mock_requests_send):
'[Requests] - Test if variables are passed to server'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
variables = {'repoOwner': 'owner', 'repoName': 'name'}
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query, variables)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send, variables=variables)
@patch('requests.sessions.Session.send')
def test_operation_name(mock_requests_send):
'[Requests] - Test if operation name is passed to server'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
operation_name = 'xpto'
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query, operation_name=operation_name)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send, operation_name=operation_name)
@patch('requests.sessions.Session.send')
def test_json_error(mock_requests_send):
'[Requests] - Test if broken server responses (invalid JSON) is handled'
configure_mock_requests_send(mock_requests_send,
graphql_response_json_error)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
exc = get_json_exception(graphql_response_json_error)
got_exc = data['errors'][0].pop('exception')
assert isinstance(got_exc, json.JSONDecodeError), \
'{} is not json.JSONDecodeError'.format(type(got_exc))
eq_(data, {
'errors': [{
'message': str(exc),
'body': graphql_response_json_error,
}],
'data': None,
})
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_get(mock_requests_send):
'[Requests] - Test if HTTP method GET request works'
configure_mock_requests_send(mock_requests_send, graphql_response_ok)
base_headers = {
'Xpto': 'abc',
}
extra_headers = {
'Extra': '123',
'Accept': extra_accept_header,
}
variables = {'repoOwner': 'owner', 'repoName': 'name'}
operation_name = 'xpto'
endpoint = RequestsEndpoint(test_url,
base_headers=base_headers,
method='GET')
data = endpoint(graphql_query,
extra_headers=extra_headers,
variables=variables,
operation_name=operation_name,
)
eq_(data, json.loads(graphql_response_ok))
check_mock_requests_send(mock_requests_send,
method='GET',
base_headers=base_headers,
extra_headers=extra_headers,
variables=variables,
operation_name=operation_name,
)
eq_(str(endpoint),
'RequestsEndpoint('
+ 'url={}, '.format(test_url)
+ 'base_headers={}, '.format(base_headers)
+ 'timeout=None, method=GET, auth=None)',
)
@patch('requests.sessions.Session.send')
def test_server_reported_error(mock_requests_send):
'[Requests] - Test if GraphQL errors reported with HTTP 200 is handled'
configure_mock_requests_send(mock_requests_send, graphql_response_error)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
eq_(data, json.loads(graphql_response_error))
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_server_http_error(mock_requests_send):
'[Requests] - Test if HTTP error without JSON payload is handled'
res = requests.Response()
res.status_code = 500
res.url = test_url
res.reason = 'Some Error'
res.headers = {'Xpto': 'abc'}
res.raw = io.BytesIO(b'xpto')
err = requests.exceptions.HTTPError(response=res)
configure_mock_requests_send(mock_requests_send, err)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
eq_(data, {
'errors': [{
'message': str(err),
'exception': err,
'status': 500,
'headers': {'Xpto': 'abc'},
'body': 'xpto',
}],
'data': None,
})
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_server_http_non_conforming_json(mock_requests_send):
'[Requests] - Test HTTP error that is NOT conforming to GraphQL payload'
res = requests.Response()
res.status_code = 500
res.url = test_url
res.reason = 'Some Error'
res.headers = {'Content-Type': 'application/json'}
res.raw = io.BytesIO(b'{"message": "xpto"}')
err = requests.exceptions.HTTPError(response=res)
configure_mock_requests_send(mock_requests_send, err)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
eq_(data, {
'errors': [{
'message': str(err),
'exception': err,
'status': 500,
'headers': {'Content-Type': 'application/json'},
'body': '{"message": "xpto"}',
}],
'data': None,
})
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_server_error_broken_json(mock_requests_send):
'[Requests] - Test if HTTP error with broken JSON payload is handled'
res = requests.Response()
res.status_code = 500
res.url = test_url
res.reason = 'Some Error'
res.headers = {'Content-Type': 'application/json'}
res.raw = io.BytesIO(b'xpto')
err = requests.exceptions.HTTPError(response=res)
configure_mock_requests_send(mock_requests_send, err)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
got_exc = data['errors'][0].pop('exception')
assert isinstance(got_exc, json.JSONDecodeError), \
'{} is not json.JSONDecodeError'.format(type(got_exc))
eq_(data, {
'errors': [{
'message': str(got_exc),
'body': 'xpto',
}],
'data': None,
})
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_server_http_graphql_error(mock_requests_send):
'[Requests] - Test HTTP error that IS conforming to GraphQL payload'
res = requests.Response()
res.status_code = 500
res.url = test_url
res.reason = 'Some Error'
res.headers = {'Content-Type': 'application/json'}
res.raw = io.BytesIO(graphql_response_error.encode())
err = requests.exceptions.HTTPError(response=res)
configure_mock_requests_send(mock_requests_send, err)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
expected_data = json.loads(graphql_response_error)
expected_data.update({
'exception': err,
'status': 500,
'headers': {'Content-Type': 'application/json'},
})
eq_(data, expected_data)
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_server_http_single_error(mock_requests_send):
'[Requests] - Test HTTP error that a single JSON error string'
res = requests.Response()
res.status_code = 500
res.url = test_url
res.reason = 'Some Error'
res.headers = {'Content-Type': 'application/json'}
res.raw = io.BytesIO(b'{"errors": "a string"}')
err = requests.exceptions.HTTPError(response=res)
configure_mock_requests_send(mock_requests_send, err)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
expected_data = {'errors': [{'message': 'a string'}]}
expected_data.update({
'exception': err,
'status': 500,
'headers': {'Content-Type': 'application/json'},
})
eq_(data, expected_data)
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_server_http_error_string_list(mock_requests_send):
'[Requests] - Test if HTTP error that a JSON error string list is handled'
res = requests.Response()
res.status_code = 500
res.url = test_url
res.reason = 'Some Error'
res.headers = {'Content-Type': 'application/json'}
res.raw = io.BytesIO(b'{"errors": ["a", "b"]}')
err = requests.exceptions.HTTPError(response=res)
configure_mock_requests_send(mock_requests_send, err)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
expected_data = {'errors': [{'message': 'a'}, {'message': 'b'}]}
expected_data.update({
'exception': err,
'status': 500,
'headers': {'Content-Type': 'application/json'},
})
eq_(data, expected_data)
check_mock_requests_send(mock_requests_send)
@patch('requests.sessions.Session.send')
def test_server_http_error_list_message(mock_requests_send):
'[Requests] - Test HTTP JSON error with messages being a list'
res = requests.Response()
res.status_code = 500
res.url = test_url
res.reason = 'Some Error'
res.headers = {'Content-Type': 'application/json'}
res.raw = io.BytesIO(b'{"errors": [{"message": [1, 2]}]}')
err = requests.exceptions.HTTPError(response=res)
configure_mock_requests_send(mock_requests_send, err)
endpoint = RequestsEndpoint(test_url)
data = endpoint(graphql_query)
expected_data = {'errors': [{'message': '[1, 2]'}]}
expected_data.update({
'exception': err,
'status': 500,
'headers': {'Content-Type': 'application/json'},
})
eq_(data, expected_data)
check_mock_requests_send(mock_requests_send)
# add_query_to_url():
# test paths not already tested, here just the repeated query
def test_add_query_to_url_dict_of_list():
'[Requests] - Test add_query_to_url() with extra_query as a dict-of-list'
url = add_query_to_url('http://domain.com?a=1&a=2', {'a': ['3', '4']})
eq_(url, 'http://domain.com?a=1&a=2&a=3&a=4')
def test_add_query_to_url_sequence():
'[Requests] - Test add_query_to_url() with extra_query as pairs'
u = add_query_to_url('http://domain.com?a=1&a=2', (('a', '3'), ('a', '4')))
eq_(u, 'http://domain.com?a=1&a=2&a=3&a=4')