-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathtest_api.py
More file actions
659 lines (566 loc) · 27.9 KB
/
test_api.py
File metadata and controls
659 lines (566 loc) · 27.9 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
import io
import json
import sys
from unittest import TestCase
from unittest.mock import Mock, call, patch
import httpretty
import pytest
from rsconnect.api import (
CloudServer,
CloudService,
PositClient,
RSConnectClient,
RSConnectExecutor,
RSConnectServer,
ShinyappsServer,
ShinyappsService,
SPCSConnectServer,
)
from rsconnect.exception import DeploymentFailedException, RSConnectException
from rsconnect.models import AppModes
from .utils import require_api_key, require_connect
class TestAPI(TestCase):
def test_executor_init(self):
connect_server = require_connect()
api_key = require_api_key()
ce = RSConnectExecutor(None, None, connect_server, api_key, True, None)
self.assertEqual(ce.remote_server.url, connect_server)
def test_output_task_log(self):
first_task = {
"output": ["line 1", "line 2", "line 3"],
"last": 3,
"finished": False,
"code": 0,
}
output = []
RSConnectClient.output_task_log(first_task, output.append)
self.assertEqual(["line 1", "line 2", "line 3"], output)
second_task = {
"output": ["line 4"],
"last": 4,
"finished": True,
"code": 0,
}
RSConnectClient.output_task_log(second_task, output.append)
self.assertEqual(["line 1", "line 2", "line 3", "line 4"], output)
def test_make_deployment_name(self):
connect_server = require_connect()
api_key = require_api_key()
ce = RSConnectExecutor(None, None, connect_server, api_key, True, None)
self.assertEqual(ce.make_deployment_name("title", False), "title")
self.assertEqual(ce.make_deployment_name("Title", False), "title")
self.assertEqual(ce.make_deployment_name("My Title", False), "my_title")
self.assertEqual(ce.make_deployment_name("My Title", False), "my_title")
self.assertEqual(ce.make_deployment_name("My _ Title", False), "my_title")
self.assertEqual(ce.make_deployment_name("My-Title", False), "my-title")
# noinspection SpellCheckingInspection
self.assertEqual(ce.make_deployment_name("M\ry\n \tT\u2103itle", False), "my_title")
self.assertEqual(ce.make_deployment_name("\r\n\t\u2103", False), "___")
self.assertEqual(ce.make_deployment_name("\r\n\tR\u2103", False), "__r")
def test_connect_authorization_header(self):
jwt_connect_server = RSConnectServer("http://test-server", None, bootstrap_jwt="123.456.789")
jwt_connect_client = RSConnectClient(jwt_connect_server)
self.assertEqual(jwt_connect_client.get_authorization(), "Connect-Bootstrap 123.456.789")
api_key_connect_server = RSConnectServer("http://test-server", "api_key")
api_key_connect_client = RSConnectClient(api_key_connect_server)
self.assertEqual(api_key_connect_client.get_authorization(), "Key api_key")
none_connect_server = RSConnectServer("http://test-server", None)
none_connect_client = RSConnectClient(none_connect_server)
self.assertEqual(none_connect_client.get_authorization(), None)
class TestSystemRuntimeCachesAPI(TestCase):
# RSConnectExecutor.runtime_caches returns the resulting JSON from the server.
@httpretty.activate(verbose=True, allow_net_connect=False)
def test_client_system_caches_runtime_list(self):
ce = RSConnectExecutor(None, None, "http://test-server/", "api_key")
mocked_response = {
"caches": [
{"language": "R", "version": "3.6.3", "image_name": "Local"},
{"language": "Python", "version": "5.6.7", "image_name": "teapot.bak"},
]
}
httpretty.register_uri(
httpretty.GET,
"http://test-server/__api__/v1/system/caches/runtime",
body=json.dumps(mocked_response),
status=200,
forcing_headers={"Content-Type": "application/json"},
)
result = ce.runtime_caches
self.assertDictEqual(result, mocked_response)
# RSConnectExecutor.delete_runtime_cache() dry run returns expected request
# RSConnectExecutor.delete_runtime_cache() dry run prints expected messages
@httpretty.activate(verbose=True, allow_net_connect=False)
def test_executor_delete_runtime_cache_dry_run(self):
ce = RSConnectExecutor(None, None, "http://test-server/", "api_key")
mocked_output = {"language": "Python", "version": "1.2.3", "image_name": "teapot", "task_id": None}
httpretty.register_uri(
httpretty.DELETE,
"http://test-server/__api__/v1/system/caches/runtime",
body=json.dumps(mocked_output),
status=200,
forcing_headers={"Content-Type": "application/json"},
)
captured_output = io.StringIO()
sys.stdout = captured_output
result, task = ce.delete_runtime_cache(language="Python", version="1.2.3", image_name="teapot", dry_run=True)
sys.stdout = sys.__stdout__
# Print expectations
output_lines = captured_output.getvalue().splitlines()
self.assertEqual(output_lines[0], "Dry run finished")
# Result expectations
self.assertDictEqual(mocked_output, result)
self.assertEqual(task, None)
# RSConnectExecutor.delete_runtime_cache() wet run returns expected request
# RSConnectExecutor.delete_runtime_cache() wet run prints expected messages
@httpretty.activate(verbose=True, allow_net_connect=False)
def test_executor_delete_runtime_cache_wet_run(self):
ce = RSConnectExecutor(None, None, "http://test-server/", "api_key")
mocked_delete_output = {
"language": "Python",
"version": "1.2.3",
"image_name": "teapot",
"task_id": "this_is_a_task_id",
}
httpretty.register_uri(
httpretty.DELETE,
"http://test-server/__api__/v1/system/caches/runtime",
body=json.dumps(mocked_delete_output),
status=200,
forcing_headers={"Content-Type": "application/json"},
)
mocked_task = {
"id": "this_is_a_task_id",
"user_id": 1,
"output": ["Removing runtime cache"],
"result": {"type": "", "data": None},
"finished": True,
"code": 0,
"error": "",
"last": 1,
}
expected_task = {
"id": "this_is_a_task_id",
"user_id": 1,
"output": ["Removing runtime cache"],
"status": ["Removing runtime cache"],
"result": {"type": "", "data": None},
"finished": True,
"code": 0,
"error": "",
"last": 1,
"last_status": 1,
}
httpretty.register_uri(
httpretty.GET,
"http://test-server/__api__/v1/tasks/this_is_a_task_id",
body=json.dumps(mocked_task),
status=200,
forcing_headers={"Content-Type": "application/json"},
)
captured_output = io.StringIO()
sys.stdout = captured_output
result, task = ce.delete_runtime_cache(language="Python", version="1.2.3", image_name="teapot", dry_run=False)
sys.stdout = sys.__stdout__
# Print expectations
# TODO: *We* don't print anything here anymore. Unsure how to capture log messages from Connect.
# output_lines = captured_output.getvalue().splitlines()
# self.assertEqual(output_lines[0], "Cache deletion finished")
# Result expectations
self.assertDictEqual(mocked_delete_output, result)
# mocked task plus backwards-compatible fields for rsconnect-jupyter
self.assertDictEqual(expected_task, task)
# RSConnectExecutor.delete_runtime_cache() raises the correct error
@httpretty.activate(verbose=True, allow_net_connect=False)
def test_executor_delete_runtime_cache_error(self):
ce = RSConnectExecutor(None, None, "http://test-server/", "api_key")
mocked_delete_output = {"code": 4, "error": "Cache does not exist", "payload": None}
httpretty.register_uri(
httpretty.DELETE,
"http://test-server/__api__/v1/system/caches/runtime",
body=json.dumps(mocked_delete_output),
status=404,
forcing_headers={"Content-Type": "application/json"},
)
with self.assertRaisesRegex(RSConnectException, "Cache does not exist"):
ce.delete_runtime_cache(language="Python", version="1.2.3", image_name="teapot", dry_run=False)
class RSConnectClientTestCase(TestCase):
def test_deploy_existing_application_with_failure(self):
with patch.object(RSConnectClient, "__init__", lambda _, server, cookies, timeout: None):
client = RSConnectClient(Mock(), Mock(), Mock())
client.app_get = Mock(side_effect=RSConnectException(""))
client._server = Mock(spec=RSConnectServer)
app_id = Mock()
with self.assertRaises(RSConnectException):
client.deploy(app_id, app_name=None, app_title=None, title_is_default=None, tarball=None)
class ShinyappsServiceTestCase(TestCase):
def setUp(self) -> None:
super().setUp()
self.cloud_client = Mock(spec=PositClient)
server = ShinyappsServer("https://api.posit.cloud", "the_account", "the_token", "the_secret")
self.service = ShinyappsService(self.cloud_client, server)
def test_do_deploy(self):
bundle_id = 1
app_id = 2
task_id = 3
self.cloud_client.deploy_application.return_value = {"id": task_id}
self.service.do_deploy(bundle_id, app_id)
self.cloud_client.set_bundle_status.assert_called_with(bundle_id, "ready")
self.cloud_client.deploy_application.assert_called_with(bundle_id, app_id)
self.cloud_client.wait_until_task_is_successful.assert_called_with(task_id)
def test_do_deploy_failure(self):
bundle_id = 1
app_id = 2
task_id = 3
build_task_id = 4
self.cloud_client.deploy_application.return_value = {"id": task_id}
self.cloud_client.wait_until_task_is_successful.side_effect = DeploymentFailedException("uh oh")
self.cloud_client.get_shinyapps_build_task.return_value = {"tasks": [{"id": build_task_id}]}
task_logs_response = Mock()
task_logs_response.response_body = "here's why it failed"
self.cloud_client.get_task_logs.return_value = task_logs_response
with pytest.raises(DeploymentFailedException):
self.service.do_deploy(bundle_id, app_id)
self.cloud_client.set_bundle_status.assert_called_with(bundle_id, "ready")
self.cloud_client.deploy_application.assert_called_with(bundle_id, app_id)
self.cloud_client.wait_until_task_is_successful.assert_called_with(task_id)
self.cloud_client.get_shinyapps_build_task.assert_called_with(task_id)
self.cloud_client.get_task_logs.assert_called_with(build_task_id)
class CloudServiceTestCase(TestCase):
def setUp(self):
self.cloud_client = Mock(spec=PositClient)
self.server = CloudServer("https://api.posit.cloud", "the_account", "the_token", "the_secret")
self.project_application_id = "20"
self.cloud_service = CloudService(
cloud_client=self.cloud_client, server=self.server, project_application_id=self.project_application_id
)
def test_prepare_new_deploy_python_shiny(self):
app_id = None
app_name = "my app"
bundle_size = 5000
bundle_hash = "the_hash"
app_mode = AppModes.PYTHON_SHINY
self.cloud_client.get_application.return_value = {
"content_id": 2,
}
self.cloud_client.get_content.return_value = {
"space_id": 1000,
}
self.cloud_client.create_output.return_value = {
"id": 1,
"source_id": 10,
"url": "https://posit.cloud/content/1",
}
self.cloud_client.create_bundle.return_value = {
"id": 100,
"presigned_url": "https://presigned.url",
"presigned_checksum": "the_checksum",
}
prepare_deploy_result = self.cloud_service.prepare_deploy(
app_id=app_id,
app_name=app_name,
bundle_size=bundle_size,
bundle_hash=bundle_hash,
app_mode=app_mode,
app_store_version=1,
)
self.cloud_client.get_application.assert_called_with(self.project_application_id)
self.cloud_client.get_content.assert_called_with(2)
self.cloud_client.create_output.assert_called_with(
name=app_name, application_type="connect", project_id=2, space_id=1000, render_by=None
)
self.cloud_client.create_bundle.assert_called_with(10, "application/x-tar", bundle_size, bundle_hash)
assert prepare_deploy_result.app_id == 1
assert prepare_deploy_result.application_id == 10
assert prepare_deploy_result.app_url == "https://posit.cloud/content/1"
assert prepare_deploy_result.bundle_id == 100
assert prepare_deploy_result.presigned_url == "https://presigned.url"
assert prepare_deploy_result.presigned_checksum == "the_checksum"
def test_prepare_new_deploy_static_quarto(self):
cloud_client = Mock(spec=PositClient)
server = CloudServer("https://api.posit.cloud", "the_account", "the_token", "the_secret")
project_application_id = "20"
cloud_service = CloudService(
cloud_client=cloud_client, server=server, project_application_id=project_application_id
)
app_id = None
app_name = "my app"
bundle_size = 5000
bundle_hash = "the_hash"
app_mode = AppModes.STATIC_QUARTO
cloud_client.get_application.return_value = {
"content_id": 2,
}
cloud_client.get_content.return_value = {
"space_id": 1000,
}
cloud_client.create_output.return_value = {
"id": 1,
"source_id": 10,
"url": "https://posit.cloud/content/1",
}
cloud_client.create_bundle.return_value = {
"id": 100,
"presigned_url": "https://presigned.url",
"presigned_checksum": "the_checksum",
}
cloud_service.prepare_deploy(
app_id=app_id,
app_name=app_name,
bundle_size=bundle_size,
bundle_hash=bundle_hash,
app_mode=app_mode,
app_store_version=1,
)
cloud_client.get_application.assert_called_with(project_application_id)
cloud_client.get_content.assert_called_with(2)
cloud_client.create_output.assert_called_with(
name=app_name, application_type="static", project_id=2, space_id=1000, render_by="server"
)
def test_prepare_redeploy(self):
app_id = 1
app_name = "my app"
bundle_size = 5000
bundle_hash = "the_hash"
app_mode = AppModes.PYTHON_SHINY
self.cloud_client.get_content.return_value = {"id": 1, "source_id": 10, "url": "https://posit.cloud/content/1"}
self.cloud_client.get_application.return_value = {"id": 10, "content_id": 200}
self.cloud_client.create_bundle.return_value = {
"id": 100,
"presigned_url": "https://presigned.url",
"presigned_checksum": "the_checksum",
}
prepare_deploy_result = self.cloud_service.prepare_deploy(
app_id=app_id,
app_name=app_name,
bundle_size=bundle_size,
bundle_hash=bundle_hash,
app_mode=app_mode,
app_store_version=1,
)
self.cloud_client.get_content.assert_called_with(1)
self.cloud_client.create_bundle.assert_called_with(10, "application/x-tar", bundle_size, bundle_hash)
self.cloud_client.update_output.assert_called_with(1, {"project": 200})
assert prepare_deploy_result.app_id == 1
assert prepare_deploy_result.application_id == 10
assert prepare_deploy_result.app_url == "https://posit.cloud/content/1"
assert prepare_deploy_result.bundle_id == 100
assert prepare_deploy_result.presigned_url == "https://presigned.url"
assert prepare_deploy_result.presigned_checksum == "the_checksum"
def test_prepare_redeploy_static(self):
app_id = 1
app_name = "my app"
bundle_size = 5000
bundle_hash = "the_hash"
app_mode = AppModes.STATIC
self.cloud_client.get_content.return_value = {"id": 1, "source_id": 10, "url": "https://posit.cloud/content/1"}
self.cloud_client.get_application.return_value = {"id": 10, "content_id": 200}
self.cloud_client.create_revision.return_value = {
"application_id": 11,
}
self.cloud_client.create_bundle.return_value = {
"id": 100,
"presigned_url": "https://presigned.url",
"presigned_checksum": "the_checksum",
}
prepare_deploy_result = self.cloud_service.prepare_deploy(
app_id=app_id,
app_name=app_name,
bundle_size=bundle_size,
bundle_hash=bundle_hash,
app_mode=app_mode,
app_store_version=1,
)
self.cloud_client.get_content.assert_called_with(1)
self.cloud_client.create_revision.assert_called_with(1)
self.cloud_client.create_bundle.assert_called_with(11, "application/x-tar", bundle_size, bundle_hash)
self.cloud_client.update_output.assert_called_with(1, {"project": 200})
assert prepare_deploy_result.app_id == 1
assert prepare_deploy_result.application_id == 11
assert prepare_deploy_result.app_url == "https://posit.cloud/content/1"
assert prepare_deploy_result.bundle_id == 100
assert prepare_deploy_result.presigned_url == "https://presigned.url"
assert prepare_deploy_result.presigned_checksum == "the_checksum"
def test_prepare_redeploy_preversioned_app_store(self):
app_id = 10
app_name = "my app"
bundle_size = 5000
bundle_hash = "the_hash"
app_mode = AppModes.PYTHON_SHINY
self.cloud_client.get_application.return_value = {
"id": 10,
"content_id": 1,
}
self.cloud_client.get_content.return_value = {"id": 1, "source_id": 10, "url": "https://posit.cloud/content/1"}
self.cloud_client.create_bundle.return_value = {
"id": 100,
"presigned_url": "https://presigned.url",
"presigned_checksum": "the_checksum",
}
prepare_deploy_result = self.cloud_service.prepare_deploy(
app_id=app_id,
app_name=app_name,
bundle_size=bundle_size,
bundle_hash=bundle_hash,
app_mode=app_mode,
app_store_version=None,
)
# first call is to get the current project id, second call is to get the application
self.cloud_client.get_application.assert_has_calls([call(self.project_application_id), call(app_id)])
self.cloud_client.get_content.assert_called_with(1)
self.cloud_client.create_bundle.assert_called_with(10, "application/x-tar", bundle_size, bundle_hash)
self.cloud_client.update_output.assert_called_with(1, {"project": 1})
assert prepare_deploy_result.app_id == 1
assert prepare_deploy_result.application_id == 10
assert prepare_deploy_result.app_url == "https://posit.cloud/content/1"
assert prepare_deploy_result.bundle_id == 100
assert prepare_deploy_result.presigned_url == "https://presigned.url"
assert prepare_deploy_result.presigned_checksum == "the_checksum"
def test_do_deploy(self):
bundle_id = 1
app_id = 2
task_id = 3
self.cloud_client.deploy_application.return_value = {"id": task_id}
self.cloud_service.do_deploy(bundle_id, app_id)
self.cloud_client.set_bundle_status.assert_called_with(bundle_id, "ready")
self.cloud_client.deploy_application.assert_called_with(bundle_id, app_id)
self.cloud_client.wait_until_task_is_successful.assert_called_with(task_id)
def test_do_deploy_failure(self):
bundle_id = 1
app_id = 2
task_id = 3
self.cloud_client.deploy_application.return_value = {"id": task_id}
self.cloud_client.wait_until_task_is_successful.side_effect = DeploymentFailedException("uh oh")
task_logs_response = Mock()
task_logs_response.response_body = "here's why it failed"
self.cloud_client.get_task_logs.return_value = task_logs_response
with pytest.raises(DeploymentFailedException):
self.cloud_service.do_deploy(bundle_id, app_id)
self.cloud_client.set_bundle_status.assert_called_with(bundle_id, "ready")
self.cloud_client.deploy_application.assert_called_with(bundle_id, app_id)
self.cloud_client.wait_until_task_is_successful.assert_called_with(task_id)
self.cloud_client.get_task_logs.assert_called_with(task_id)
class SPCSConnectServerTestCase(TestCase):
def test_init(self):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
assert server.url == "https://spcs.example.com"
assert server.remote_name == "Posit Connect (SPCS)"
assert server.snowflake_connection_name == "example_connection"
assert server.api_key == "test-api-key"
@patch("rsconnect.api.SPCSConnectServer.token_endpoint")
def test_token_endpoint(self, mock_token_endpoint):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
mock_token_endpoint.return_value = "https://example.snowflakecomputing.com/"
endpoint = server.token_endpoint()
assert endpoint == "https://example.snowflakecomputing.com/"
@patch("rsconnect.api.get_parameters")
def test_token_endpoint_with_account(self, mock_get_parameters):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
mock_get_parameters.return_value = {"account": "test_account"}
endpoint = server.token_endpoint()
assert endpoint == "https://test_account.snowflakecomputing.com/"
mock_get_parameters.assert_called_once_with("example_connection")
@patch("rsconnect.api.get_parameters")
def test_token_endpoint_with_none_params(self, mock_get_parameters):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
mock_get_parameters.return_value = None
with pytest.raises(RSConnectException, match="No Snowflake connection found."):
server.token_endpoint()
@patch("rsconnect.api.get_parameters")
def test_fmt_payload(self, mock_get_parameters):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
mock_get_parameters.return_value = {
"account": "test_account",
"role": "test_role",
"authenticator": "SNOWFLAKE_JWT",
}
with patch("rsconnect.api.generate_jwt") as mock_generate_jwt:
mock_generate_jwt.return_value = "mocked_jwt"
payload = server.fmt_payload()
assert (
payload["body"]
== "scope=session%3Arole%3Atest_role+spcs.example.com&assertion=mocked_jwt&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer" # noqa
)
assert payload["headers"] == {"Content-Type": "application/x-www-form-urlencoded"}
assert payload["path"] == "/oauth/token"
mock_get_parameters.assert_called_once_with("example_connection")
mock_generate_jwt.assert_called_once_with("example_connection")
@patch("rsconnect.api.get_parameters")
def test_fmt_payload_with_none_params(self, mock_get_parameters):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
mock_get_parameters.return_value = None
with pytest.raises(RSConnectException, match="No Snowflake connection found."):
server.fmt_payload()
@patch("rsconnect.api.HTTPServer")
@patch("rsconnect.api.SPCSConnectServer.token_endpoint")
@patch("rsconnect.api.SPCSConnectServer.fmt_payload")
def test_exchange_token_success(self, mock_fmt_payload, mock_token_endpoint, mock_http_server):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
# Mock the HTTP request
mock_server_instance = mock_http_server.return_value
mock_response = Mock()
mock_response.status = 200
mock_response.response_body = "token_data"
mock_server_instance.request.return_value = mock_response
# Mock the token endpoint and payload
mock_token_endpoint.return_value = "https://example.snowflakecomputing.com/"
mock_fmt_payload.return_value = {
"body": "mocked_payload_body",
"headers": {"Content-Type": "application/x-www-form-urlencoded"},
"path": "/oauth/token",
}
# Call the method
result = server.exchange_token()
# Verify the results
assert result == "token_data"
mock_http_server.assert_called_once_with(url="https://example.snowflakecomputing.com/")
mock_server_instance.request.assert_called_once_with(
method="POST",
body="mocked_payload_body",
headers={"Content-Type": "application/x-www-form-urlencoded"},
path="/oauth/token",
)
@patch("rsconnect.api.HTTPServer")
@patch("rsconnect.api.SPCSConnectServer.token_endpoint")
@patch("rsconnect.api.SPCSConnectServer.fmt_payload")
def test_exchange_token_error_status(self, mock_fmt_payload, mock_token_endpoint, mock_http_server):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
# Mock the HTTP request with error status
mock_server_instance = mock_http_server.return_value
mock_response = Mock()
mock_response.status = 401
mock_response.full_uri = "https://example.snowflakecomputing.com/oauth/token"
mock_response.reason = "Unauthorized"
mock_server_instance.request.return_value = mock_response
# Mock the token endpoint and payload
mock_token_endpoint.return_value = "https://example.snowflakecomputing.com/"
mock_fmt_payload.return_value = {
"body": "mocked_payload_body",
"headers": {"Content-Type": "application/x-www-form-urlencoded"},
"path": "/oauth/token",
}
# Call the method and verify it raises the expected exception
with pytest.raises(RSConnectException, match="Failed to exchange Snowflake token"):
server.exchange_token()
@patch("rsconnect.api.HTTPServer")
@patch("rsconnect.api.SPCSConnectServer.token_endpoint")
@patch("rsconnect.api.SPCSConnectServer.fmt_payload")
def test_exchange_token_empty_response(self, mock_fmt_payload, mock_token_endpoint, mock_http_server):
server = SPCSConnectServer("https://spcs.example.com", "test-api-key", "example_connection")
# Mock the HTTP request with empty response body
mock_server_instance = mock_http_server.return_value
mock_response = Mock()
mock_response.status = 200
mock_response.response_body = None
mock_server_instance.request.return_value = mock_response
# Mock the token endpoint and payload
mock_token_endpoint.return_value = "https://example.snowflakecomputing.com/"
mock_fmt_payload.return_value = {
"body": "mocked_payload_body",
"headers": {"Content-Type": "application/x-www-form-urlencoded"},
"path": "/oauth/token",
}
# Call the method and verify it raises the expected exception
with pytest.raises(
RSConnectException, match="Failed to exchange Snowflake token: Token exchange returned empty response"
):
server.exchange_token()