-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathtest_http_client.py
More file actions
687 lines (596 loc) · 25.2 KB
/
test_http_client.py
File metadata and controls
687 lines (596 loc) · 25.2 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
from unittest.mock import Mock
import pytest
from nylas.handler.http_client import (
HttpClient,
_build_query_params,
_validate_response,
)
from nylas.models.errors import NylasApiError, NylasOAuthError
class TestData:
def __init__(self, content_type=None):
self.content_type = content_type
class TestHttpClient:
def test_http_client_init(self):
http_client = HttpClient(
api_server="https://test.nylas.com",
api_key="test-key",
timeout=60,
)
assert http_client.api_server == "https://test.nylas.com"
assert http_client.api_key == "test-key"
assert http_client.timeout == 60
def test_build_headers_default(self, http_client, patched_version_and_sys):
headers = http_client._build_headers()
assert headers == {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
}
def test_build_headers_extra_headers(self, http_client, patched_version_and_sys):
headers = http_client._build_headers(
extra_headers={
"foo": "bar",
"X-Test": "test",
}
)
assert headers == {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"foo": "bar",
"X-Test": "test",
}
def test_build_headers_json_body(self, http_client, patched_version_and_sys):
headers = http_client._build_headers(
response_body={
"foo": "bar",
}
)
assert headers == {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"Content-type": "application/json; charset=utf-8",
}
def test_build_headers_form_body(self, http_client, patched_version_and_sys):
headers = http_client._build_headers(
response_body={
"foo": "bar",
},
data=TestData(content_type="application/x-www-form-urlencoded"),
)
assert headers == {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"Content-type": "application/x-www-form-urlencoded",
}
def test_build_headers_override_headers(self, http_client, patched_version_and_sys):
headers = http_client._build_headers(
overrides={
"headers": {
"foo": "bar",
"X-Test": "test",
}
}
)
assert headers == {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"foo": "bar",
"X-Test": "test",
}
def test_build_headers_override_api_key(self, http_client, patched_version_and_sys):
headers = http_client._build_headers(
overrides={
"api_key": "test-key-override",
}
)
assert headers == {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key-override",
}
def test_build_request_default(self, http_client, patched_version_and_sys):
request = http_client._build_request(
method="GET",
path="/foo",
)
assert request == {
"method": "GET",
"url": "https://test.nylas.com/foo",
"headers": {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
},
}
def test_build_request_override_api_uri(self, http_client, patched_version_and_sys):
request = http_client._build_request(
method="GET",
path="/foo",
overrides={
"api_uri": "https://override.nylas.com",
},
)
assert request == {
"method": "GET",
"url": "https://override.nylas.com/foo",
"headers": {
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
},
}
def test_build_query_params(self, patched_version_and_sys):
url = _build_query_params(
base_url="https://test.nylas.com/foo",
query_params={
"foo": "bar",
"list": ["a", "b", "c"],
"map": {"key1": "value1", "key2": "value2"},
},
)
assert (
url
== "https://test.nylas.com/foo?foo=bar&list=a&list=b&list=c&map=key1:value1&map=key2:value2"
)
def test_execute_download_request(self, http_client, patched_request):
response = http_client._execute_download_request(
path="/foo",
)
assert response == b"mock data"
def test_execute_download_request_with_stream(self, http_client, patched_request):
response = http_client._execute_download_request(
path="/foo",
stream=True,
)
assert isinstance(response, Mock) is True
assert response.content == b"mock data"
def test_execute_download_request_timeout(self, http_client, mock_session_timeout):
with pytest.raises(Exception) as e:
http_client._execute_download_request(
path="/foo",
)
assert (
str(e.value)
== "Nylas SDK timed out before receiving a response from the server."
)
def test_execute_download_request_override_timeout(
self, http_client, patched_version_and_sys, patched_request
):
response = http_client._execute_download_request(
path="/foo",
overrides={"timeout": 60},
)
patched_request.assert_called_once_with(
"GET",
"https://test.nylas.com/foo",
headers={
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"Content-type": "application/json; charset=utf-8",
},
timeout=60,
stream=False,
)
def test_validate_response(self):
response = Mock()
response.status_code = 200
response.json.return_value = {"foo": "bar"}
response.url = "https://test.nylas.com/foo"
response.headers = {"X-Test-Header": "test"}
response_json, response_headers = _validate_response(response)
assert response_json == {"foo": "bar"}
assert response_headers == {"X-Test-Header": "test"}
def test_validate_response_400_error(self):
response = Mock()
response.status_code = 400
response.json.return_value = {
"request_id": "123",
"error": {
"type": "api_error",
"message": "The request is invalid.",
"provider_error": {"foo": "bar"},
},
}
response.url = "https://test.nylas.com/foo"
with pytest.raises(Exception) as e:
_validate_response(response)
assert e.type == NylasApiError
assert str(e.value) == "The request is invalid."
assert e.value.type == "api_error"
assert e.value.request_id == "123"
assert e.value.status_code == 400
assert e.value.provider_error == {"foo": "bar"}
def test_validate_response_auth_error(self):
response = Mock()
response.status_code = 401
response.json.return_value = {
"error": "invalid_request",
"error_description": "The request is invalid.",
"error_uri": "https://docs.nylas.com/reference#authentication-errors",
"error_code": 100241,
}
response.url = "https://test.nylas.com/connect/token"
with pytest.raises(Exception) as e:
_validate_response(response)
assert e.type == NylasOAuthError
assert str(e.value) == "The request is invalid."
assert e.value.error == "invalid_request"
assert e.value.error_code == 100241
assert e.value.error_description == "The request is invalid."
def test_validate_response_400_keyerror(self):
response = Mock()
response.status_code = 400
response.json.return_value = {
"request_id": "123",
"foo": "bar",
}
response.url = "https://test.nylas.com/foo"
with pytest.raises(Exception) as e:
_validate_response(response)
assert e.type == NylasApiError
assert str(e.value) == "{'request_id': '123', 'foo': 'bar'}"
assert e.value.type == "unknown"
assert e.value.request_id == "123"
assert e.value.status_code == 400
def test_execute(self, http_client, patched_version_and_sys, patched_request):
mock_response = Mock()
mock_response.json.return_value = {"foo": "bar"}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
response_json, response_headers = http_client._execute(
method="GET",
path="/foo",
headers={"test": "header"},
query_params={"query": "param"},
request_body={"foo": "bar"},
)
assert response_json == {"foo": "bar"}
assert response_headers == {"X-Test-Header": "test"}
patched_request.assert_called_once_with(
"GET",
"https://test.nylas.com/foo?query=param",
headers={
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"Content-type": "application/json; charset=utf-8",
"test": "header",
},
data=b'{"foo": "bar"}',
timeout=30,
)
def test_execute_override_timeout(
self, http_client, patched_version_and_sys, patched_request
):
mock_response = Mock()
mock_response.json.return_value = {"foo": "bar"}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
response_json, response_headers = http_client._execute(
method="GET",
path="/foo",
headers={"test": "header"},
query_params={"query": "param"},
request_body={"foo": "bar"},
overrides={"timeout": 60},
)
assert response_json == {"foo": "bar"}
assert response_headers == {"X-Test-Header": "test"}
patched_request.assert_called_once_with(
"GET",
"https://test.nylas.com/foo?query=param",
headers={
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"Content-type": "application/json; charset=utf-8",
"test": "header",
},
data=b'{"foo": "bar"}',
timeout=60,
)
def test_execute_timeout(self, http_client, mock_session_timeout):
with pytest.raises(Exception) as e:
http_client._execute(
method="GET",
path="/foo",
headers={"test": "header"},
query_params={"query": "param"},
request_body={"foo": "bar"},
)
assert (
str(e.value)
== "Nylas SDK timed out before receiving a response from the server."
)
def test_validate_response_with_headers(self):
response = Mock()
response.status_code = 200
response.json.return_value = {"foo": "bar"}
response.url = "https://test.nylas.com/foo"
response.headers = {"X-Test-Header": "test"}
json_response, headers = _validate_response(response)
assert json_response == {"foo": "bar"}
assert headers == {"X-Test-Header": "test"}
def test_validate_response_400_error_with_headers(self):
response = Mock()
response.status_code = 400
response.json.return_value = {
"request_id": "123",
"error": {
"type": "api_error",
"message": "The request is invalid.",
"provider_error": {"foo": "bar"},
},
}
response.url = "https://test.nylas.com/foo"
response.headers = {"X-Test-Header": "test"}
with pytest.raises(NylasApiError) as e:
_validate_response(response)
assert e.value.headers == {"X-Test-Header": "test"}
def test_validate_response_auth_error_with_headers(self):
response = Mock()
response.status_code = 401
response.json.return_value = {
"error": "invalid_request",
"error_description": "The request is invalid.",
"error_uri": "https://docs.nylas.com/reference#authentication-errors",
"error_code": 100241,
}
response.url = "https://test.nylas.com/connect/token"
response.headers = {"X-Test-Header": "test"}
with pytest.raises(NylasOAuthError) as e:
_validate_response(response)
assert e.value.headers == {"X-Test-Header": "test"}
def test_execute_with_headers(self, http_client, patched_version_and_sys, patched_request):
mock_response = Mock()
mock_response.json.return_value = {"foo": "bar"}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
response_json, response_headers = http_client._execute(
method="GET",
path="/foo",
headers={"test": "header"},
query_params={"query": "param"},
request_body={"foo": "bar"},
)
assert response_json == {"foo": "bar"}
assert response_headers == {"X-Test-Header": "test"}
patched_request.assert_called_once_with(
"GET",
"https://test.nylas.com/foo?query=param",
headers={
"X-Nylas-API-Wrapper": "python",
"User-Agent": "Nylas Python SDK 2.0.0 - 1.2.3",
"Authorization": "Bearer test-key",
"Content-type": "application/json; charset=utf-8",
"test": "header",
},
data=b'{"foo": "bar"}',
timeout=30,
)
def test_execute_with_utf8_characters(self, http_client, patched_version_and_sys, patched_request):
"""Test that UTF-8 characters are preserved in JSON requests (not escaped)."""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
# Request with special characters
request_body = {
"title": "Réunion d'équipe",
"description": "De l'idée à la post-prod, sans friction",
"location": "café",
}
response_json, response_headers = http_client._execute(
method="POST",
path="/events",
request_body=request_body,
)
assert response_json == {"success": True}
# Verify that the data is sent as UTF-8 encoded bytes
call_kwargs = patched_request.call_args[1]
assert "data" in call_kwargs
sent_data = call_kwargs["data"]
# The data should be bytes with actual UTF-8 characters (not escape sequences)
assert isinstance(sent_data, bytes)
decoded_data = sent_data.decode("utf-8")
assert "Réunion d'équipe" in decoded_data
assert "De l'idée à la post-prod, sans friction" in decoded_data
assert "café" in decoded_data
# Should NOT contain unicode escape sequences
assert "\\u" not in decoded_data
def test_execute_with_none_request_body(self, http_client, patched_version_and_sys, patched_request):
"""Test that None request_body is handled correctly."""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
response_json, response_headers = http_client._execute(
method="GET",
path="/events",
request_body=None,
)
assert response_json == {"success": True}
# Verify that data branch is used when request_body is None
call_kwargs = patched_request.call_args[1]
# Should use data= parameter, not json= parameter
assert "data" in call_kwargs
assert "json" not in call_kwargs
assert call_kwargs["data"] is None
def test_execute_with_none_request_body_and_none_data(self, http_client, patched_version_and_sys, patched_request):
"""Test that both None request_body and None data are handled correctly."""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
response_json, response_headers = http_client._execute(
method="DELETE",
path="/events/123",
request_body=None,
data=None,
)
assert response_json == {"success": True}
call_kwargs = patched_request.call_args[1]
# Should use data= parameter with None value
assert "data" in call_kwargs
assert "json" not in call_kwargs
assert call_kwargs["data"] is None
def test_execute_with_emoji_and_international_characters(self, http_client, patched_version_and_sys, patched_request):
"""Test that emoji and various international characters are preserved."""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
request_body = {
"emoji": "🎉 Party time! 🥳",
"japanese": "こんにちは",
"chinese": "你好",
"russian": "Привет",
"german": "Größe",
"spanish": "¿Cómo estás?",
}
response_json, response_headers = http_client._execute(
method="POST",
path="/messages",
request_body=request_body,
)
assert response_json == {"success": True}
call_kwargs = patched_request.call_args[1]
sent_data = call_kwargs["data"]
# All characters should be preserved as UTF-8 encoded bytes
assert isinstance(sent_data, bytes)
decoded_data = sent_data.decode("utf-8")
assert "🎉 Party time! 🥳" in decoded_data
assert "こんにちは" in decoded_data
assert "你好" in decoded_data
assert "Привет" in decoded_data
assert "Größe" in decoded_data
assert "¿Cómo estás?" in decoded_data
def test_execute_with_right_single_quotation_mark(self, http_client, patched_version_and_sys, patched_request):
"""Test that right single quotation mark (\\u2019) is handled correctly.
This character caused UnicodeEncodeError: 'latin-1' codec can't encode character '\\u2019'.
"""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
# The \u2019 character is the right single quotation mark (')
# This was the exact character that caused the original encoding error
request_body = {
"subject": "It's a test", # Contains \u2019 (right single quotation mark)
"body": "Here's another example with curly apostrophe",
}
response_json, response_headers = http_client._execute(
method="POST",
path="/messages/send",
request_body=request_body,
)
assert response_json == {"success": True}
call_kwargs = patched_request.call_args[1]
sent_data = call_kwargs["data"]
# The data should be UTF-8 encoded bytes with the \u2019 character preserved
assert isinstance(sent_data, bytes)
decoded_data = sent_data.decode("utf-8")
assert "'" in decoded_data # \u2019 right single quotation mark
assert "It's a test" in decoded_data
assert "Here's another" in decoded_data
def test_execute_with_emojis(self, http_client, patched_version_and_sys, patched_request):
"""Test that emojis are handled correctly in request bodies.
Emojis are multi-byte UTF-8 characters that could cause encoding issues
if not handled properly.
"""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
request_body = {
"subject": "Hello 👋 World 🌍",
"body": "Great job! 🎉 Keep up the good work 💪 See you soon 😊",
"emoji_only": "🔥🚀✨💯",
"mixed": "Meeting at 3pm 📅 Don't forget! ⏰",
}
response_json, response_headers = http_client._execute(
method="POST",
path="/messages/send",
request_body=request_body,
)
assert response_json == {"success": True}
call_kwargs = patched_request.call_args[1]
sent_data = call_kwargs["data"]
# All emojis should be preserved in UTF-8 encoded bytes
assert isinstance(sent_data, bytes)
decoded_data = sent_data.decode("utf-8")
assert "Hello 👋 World 🌍" in decoded_data
assert "🎉" in decoded_data
assert "💪" in decoded_data
assert "😊" in decoded_data
assert "🔥🚀✨💯" in decoded_data
assert "📅" in decoded_data
assert "⏰" in decoded_data
def test_execute_with_nan_and_infinity(self, http_client, patched_version_and_sys, patched_request):
"""Test that NaN and Infinity float values are handled correctly.
The requests library's json= parameter uses allow_nan=False which raises
ValueError for NaN/Infinity. Our implementation uses json.dumps with
allow_nan=True to maintain backward compatibility.
"""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
request_body = {
"nan_value": float("nan"),
"infinity": float("inf"),
"neg_infinity": float("-inf"),
"normal": 42.5,
}
# This should NOT raise ValueError
response_json, response_headers = http_client._execute(
method="POST",
path="/data",
request_body=request_body,
)
assert response_json == {"success": True}
call_kwargs = patched_request.call_args[1]
sent_data = call_kwargs["data"]
# The data should be UTF-8 encoded bytes with NaN/Infinity serialized
assert isinstance(sent_data, bytes)
decoded_data = sent_data.decode("utf-8")
# json.dumps with allow_nan=True produces NaN, Infinity, -Infinity (JS-style)
assert "NaN" in decoded_data
assert "Infinity" in decoded_data
assert "-Infinity" in decoded_data
assert "42.5" in decoded_data
def test_execute_with_multipart_data_not_affected(self, http_client, patched_version_and_sys, patched_request):
"""Test that multipart/form-data is not affected by the change."""
mock_response = Mock()
mock_response.json.return_value = {"success": True}
mock_response.headers = {"X-Test-Header": "test"}
mock_response.status_code = 200
patched_request.return_value = mock_response
# When data is provided (multipart), request_body should be ignored
mock_data = Mock()
mock_data.content_type = "multipart/form-data"
response_json, response_headers = http_client._execute(
method="POST",
path="/messages/send",
request_body={"foo": "bar"}, # This should be ignored
data=mock_data,
)
assert response_json == {"success": True}
call_kwargs = patched_request.call_args[1]
# Should use the multipart data, not JSON
assert call_kwargs["data"] == mock_data