-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathrest_test.py
More file actions
745 lines (618 loc) · 22.3 KB
/
rest_test.py
File metadata and controls
745 lines (618 loc) · 22.3 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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
"""
Python SDK for OpenFGA
API version: 1.x
Website: https://openfga.dev
Documentation: https://openfga.dev/docs
Support: https://openfga.dev/community
License: [Apache-2.0](https://github.com/openfga/python-sdk/blob/main/LICENSE)
NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT.
"""
import json
import ssl
from unittest.mock import MagicMock, patch
import pytest
from openfga_sdk.exceptions import (
ApiException,
ForbiddenException,
NotFoundException,
RateLimitExceededError,
ServiceException,
UnauthorizedException,
ValidationException,
)
from openfga_sdk.sync.rest import RESTClientObject, RESTResponse
def test_restresponse_init():
mock_resp = MagicMock()
mock_resp.status = 200
mock_resp.reason = "OK"
resp_data = b'{"test":"data"}'
rest_resp = RESTResponse(mock_resp, resp_data)
assert rest_resp.status == 200
assert rest_resp.reason == "OK"
assert rest_resp.data == resp_data
assert rest_resp.response == mock_resp
def test_restresponse_getheaders():
mock_resp = MagicMock()
mock_resp.headers = {"Content-Type": "application/json", "X-Testing": "true"}
rest_resp = RESTResponse(mock_resp, b"")
headers = rest_resp.getheaders()
assert headers["Content-Type"] == "application/json"
assert headers["X-Testing"] == "true"
def test_restresponse_getheader():
mock_resp = MagicMock()
mock_resp.headers = {"Content-Type": "application/json"}
rest_resp = RESTResponse(mock_resp, b"")
val = rest_resp.getheader("Content-Type")
missing = rest_resp.getheader("X-Not-Here", default="fallback")
assert val == "application/json"
assert missing == "fallback"
def test_build_request_json_body():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
req_args = client.build_request(
method="POST",
url="http://example.com/test",
body={"foo": "bar"},
headers={"Content-Type": "application/json"},
)
assert req_args["method"] == "POST"
assert req_args["url"] == "http://example.com/test"
assert req_args["headers"]["Content-Type"] == "application/json"
assert json.loads(req_args["body"]) == {"foo": "bar"}
def test_build_request_multipart():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
req_args = client.build_request(
method="POST",
url="http://example.com/upload",
post_params={"file": ("filename.txt", b"contents", "text/plain")},
headers={"Content-Type": "multipart/form-data"},
)
assert req_args["method"] == "POST"
assert req_args["url"] == "http://example.com/upload"
assert "Content-Type" not in req_args["headers"]
assert req_args["encode_multipart"] is True
assert req_args["fields"] == {"file": ("filename.txt", b"contents", "text/plain")}
def test_build_request_timeout():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
req_args = client.build_request(
method="GET",
url="http://example.com",
_request_timeout=10.0,
)
# We'll just confirm that the "timeout" object was set to 10.0
# A deeper check might be verifying urllib3.Timeout, but this suffices.
assert req_args["timeout"].total == 10.0
def test_handle_response_exception_success():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_response = MagicMock()
mock_response.status = 200
client.handle_response_exception(mock_response) # no exception
@pytest.mark.parametrize(
"status,exc",
[
(400, ValidationException),
(401, UnauthorizedException),
(403, ForbiddenException),
(404, NotFoundException),
(429, RateLimitExceededError),
(500, ServiceException),
(418, ApiException),
],
)
def test_handle_response_exception_error(status, exc):
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_response = MagicMock()
mock_response.status = status
with pytest.raises(exc):
client.handle_response_exception(mock_response)
def test_close():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_pool_manager = MagicMock()
client.pool_manager = mock_pool_manager
client.close()
mock_pool_manager.clear.assert_called_once()
def test_request_preload_content():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_pool_manager = MagicMock()
client.pool_manager = mock_pool_manager
mock_raw_response = MagicMock()
mock_raw_response.status = 200
mock_raw_response.reason = "OK"
mock_raw_response.data = b'{"some":"data"}'
mock_pool_manager.request.return_value = mock_raw_response
resp = client.request(method="GET", url="http://example.com", _preload_content=True)
mock_pool_manager.request.assert_called_once()
assert isinstance(resp, RESTResponse)
assert resp.status == 200
assert resp.data == b'{"some":"data"}'
def test_request_no_preload_content():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_pool_manager = MagicMock()
client.pool_manager = mock_pool_manager
mock_raw_response = MagicMock()
mock_raw_response.status = 200
mock_raw_response.reason = "OK"
mock_raw_response.data = b"unused"
mock_pool_manager.request.return_value = mock_raw_response
resp = client.request(
method="GET", url="http://example.com", _preload_content=False
)
mock_pool_manager.request.assert_called_once()
# We expect the raw HTTPResponse
assert resp == mock_raw_response
assert resp.status == 200
def test_stream_happy_path():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_pool_manager = MagicMock()
client.pool_manager = mock_pool_manager
class FakeHTTPResponse:
def __init__(self):
self.status = 200
self.reason = "OK"
def stream(self, chunk_size):
# Single chunk with two JSON lines
yield b'{"foo":"bar"}\n{"hello":"world"}'
def release_conn(self):
pass
mock_response = FakeHTTPResponse()
mock_pool_manager.request.return_value = mock_response
results = list(client.stream("GET", "http://example.com"))
assert results == [{"foo": "bar"}, {"hello": "world"}]
mock_pool_manager.request.assert_called_once()
def test_stream_partial_chunks():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_pool_manager = MagicMock()
client.pool_manager = mock_pool_manager
class FakeHTTPResponse:
def __init__(self):
self.status = 200
self.reason = "OK"
def stream(self, chunk_size):
# Two partial chunks that form "foo":"bar" plus a second object
yield b'{"foo":"b'
yield b'ar"}\n{"hello":"world"}'
def release_conn(self):
pass
mock_response = FakeHTTPResponse()
mock_pool_manager.request.return_value = mock_response
results = list(client.stream("GET", "http://example.com"))
assert results == [{"foo": "bar"}, {"hello": "world"}]
mock_pool_manager.request.assert_called_once()
def test_stream_exception_in_chunks():
mock_config = MagicMock(
spec=[
"verify_ssl",
"ssl_ca_cert",
"cert_file",
"key_file",
"assert_hostname",
"retries",
"socket_options",
"connection_pool_maxsize",
"timeout_millisec",
"proxy",
"proxy_headers",
]
)
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
mock_config.proxy_headers = None
client = RESTClientObject(configuration=mock_config)
mock_pool_manager = MagicMock()
client.pool_manager = mock_pool_manager
class FakeHTTPResponse:
def __init__(self):
self.status = 200
self.reason = "OK"
def stream(self, chunk_size):
# Raise an exception while streaming
raise ValueError("Boom!")
def release_conn(self):
pass
mock_response = FakeHTTPResponse()
mock_pool_manager.request.return_value = mock_response
results = list(client.stream("GET", "http://example.com"))
# Exception is logged, we yield nothing
assert results == []
mock_pool_manager.request.assert_called_once()
# Tests for SSL Context Reuse (fix for OpenSSL 3.0+ performance issues)
@patch("ssl.create_default_context")
@patch("urllib3.PoolManager")
def test_ssl_context_created_with_ca_cert(mock_pool_manager, mock_create_context):
"""Test that SSL context is created with CA certificate file."""
mock_ssl_context = MagicMock()
mock_create_context.return_value = mock_ssl_context
mock_config = MagicMock()
mock_config.ssl_ca_cert = "/path/to/ca.pem"
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
RESTClientObject(configuration=mock_config)
# Verify SSL context was created with CA file
mock_create_context.assert_called_once_with(cafile="/path/to/ca.pem")
# Verify SSL context was passed to PoolManager
mock_pool_manager.assert_called_once()
call_kwargs = mock_pool_manager.call_args[1]
assert call_kwargs["ssl_context"] == mock_ssl_context
@patch("ssl.create_default_context")
@patch("urllib3.PoolManager")
def test_ssl_context_loads_client_certificate(mock_pool_manager, mock_create_context):
"""Test that SSL context loads client certificate and key when provided."""
mock_ssl_context = MagicMock()
mock_create_context.return_value = mock_ssl_context
mock_config = MagicMock()
mock_config.ssl_ca_cert = None
mock_config.cert_file = "/path/to/client.pem"
mock_config.key_file = "/path/to/client.key"
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
RESTClientObject(configuration=mock_config)
# Verify SSL context was created
mock_create_context.assert_called_once_with(cafile=None)
# Verify client certificate was loaded
mock_ssl_context.load_cert_chain.assert_called_once_with(
"/path/to/client.pem", keyfile="/path/to/client.key"
)
# Verify SSL context was passed to PoolManager
mock_pool_manager.assert_called_once()
call_kwargs = mock_pool_manager.call_args[1]
assert call_kwargs["ssl_context"] == mock_ssl_context
@patch("ssl.create_default_context")
@patch("urllib3.PoolManager")
def test_ssl_context_disables_verification_when_verify_ssl_false(
mock_pool_manager, mock_create_context
):
"""Test that SSL context disables verification when verify_ssl=False."""
mock_ssl_context = MagicMock()
mock_create_context.return_value = mock_ssl_context
mock_config = MagicMock()
mock_config.ssl_ca_cert = None
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = False
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
RESTClientObject(configuration=mock_config)
# Verify SSL context was created
mock_create_context.assert_called_once_with(cafile=None)
# Verify SSL verification was disabled
assert mock_ssl_context.check_hostname is False
assert mock_ssl_context.verify_mode == ssl.CERT_NONE
# Verify SSL context was passed to PoolManager
mock_pool_manager.assert_called_once()
call_kwargs = mock_pool_manager.call_args[1]
assert call_kwargs["ssl_context"] == mock_ssl_context
@patch("ssl.create_default_context")
@patch("urllib3.ProxyManager")
def test_ssl_context_used_with_proxy_manager(mock_proxy_manager, mock_create_context):
"""Test that SSL context is passed to ProxyManager when proxy is configured."""
mock_ssl_context = MagicMock()
mock_create_context.return_value = mock_ssl_context
mock_config = MagicMock()
mock_config.ssl_ca_cert = "/path/to/ca.pem"
mock_config.cert_file = "/path/to/client.pem"
mock_config.key_file = "/path/to/client.key"
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = "http://proxy:8080"
mock_config.proxy_headers = {"Proxy-Auth": "token"}
RESTClientObject(configuration=mock_config)
# Verify SSL context was created with CA file
mock_create_context.assert_called_once_with(cafile="/path/to/ca.pem")
# Verify client certificate was loaded
mock_ssl_context.load_cert_chain.assert_called_once_with(
"/path/to/client.pem", keyfile="/path/to/client.key"
)
# Verify SSL context was passed to ProxyManager
mock_proxy_manager.assert_called_once()
call_kwargs = mock_proxy_manager.call_args[1]
assert call_kwargs["ssl_context"] == mock_ssl_context
assert call_kwargs["proxy_url"] == "http://proxy:8080"
assert call_kwargs["proxy_headers"] == {"Proxy-Auth": "token"}
@patch("ssl.create_default_context")
@patch("urllib3.PoolManager")
def test_ssl_context_reuse_performance_optimization(
mock_pool_manager, mock_create_context
):
"""Test that SSL context creation is called only once per client instance."""
mock_ssl_context = MagicMock()
mock_create_context.return_value = mock_ssl_context
mock_config = MagicMock()
mock_config.ssl_ca_cert = "/path/to/ca.pem"
mock_config.cert_file = None
mock_config.key_file = None
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 4
mock_config.timeout_millisec = 5000
mock_config.proxy = None
# Create client instance
client = RESTClientObject(configuration=mock_config)
# Verify SSL context was created exactly once
mock_create_context.assert_called_once_with(cafile="/path/to/ca.pem")
# Verify the same SSL context instance is reused
mock_pool_manager.assert_called_once()
call_kwargs = mock_pool_manager.call_args[1]
assert call_kwargs["ssl_context"] is mock_ssl_context
# Verify context was not created again during subsequent operations
mock_create_context.reset_mock()
# Build a request (this should not trigger SSL context creation)
client.build_request("GET", "https://example.com")
# SSL context should not be created again
mock_create_context.assert_not_called()
@patch("ssl.create_default_context")
@patch("urllib3.PoolManager")
def test_ssl_context_with_all_ssl_options(mock_pool_manager, mock_create_context):
"""Test SSL context creation with all SSL configuration options set."""
mock_ssl_context = MagicMock()
mock_create_context.return_value = mock_ssl_context
mock_config = MagicMock()
mock_config.ssl_ca_cert = "/path/to/ca.pem"
mock_config.cert_file = "/path/to/client.pem"
mock_config.key_file = "/path/to/client.key"
mock_config.verify_ssl = True
mock_config.connection_pool_maxsize = 8
mock_config.timeout_millisec = 10000
mock_config.proxy = None
RESTClientObject(configuration=mock_config)
# Verify SSL context was created with CA file
mock_create_context.assert_called_once_with(cafile="/path/to/ca.pem")
# Verify client certificate was loaded
mock_ssl_context.load_cert_chain.assert_called_once_with(
"/path/to/client.pem", keyfile="/path/to/client.key"
)
# Verify SSL verification settings were NOT modified (verify_ssl=True)
# check_hostname and verify_mode should remain at their default secure values
assert (
not hasattr(mock_ssl_context, "check_hostname")
or mock_ssl_context.check_hostname
)
assert (
not hasattr(mock_ssl_context, "verify_mode")
or mock_ssl_context.verify_mode != ssl.CERT_NONE
)
# Verify SSL context was passed to PoolManager
mock_pool_manager.assert_called_once()
call_kwargs = mock_pool_manager.call_args[1]
assert call_kwargs["ssl_context"] == mock_ssl_context
assert call_kwargs["maxsize"] == 8