-
Notifications
You must be signed in to change notification settings - Fork 537
Expand file tree
/
Copy pathtest_connection.py
More file actions
1625 lines (1410 loc) · 57 KB
/
test_connection.py
File metadata and controls
1625 lines (1410 loc) · 57 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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import annotations
import gc
import logging
import os
import pathlib
import queue
import stat
import tempfile
import threading
import warnings
import weakref
from unittest import mock
from uuid import uuid4
import pytest
import snowflake.connector
from snowflake.connector import DatabaseError, OperationalError, ProgrammingError
from snowflake.connector.connection import (
DEFAULT_CLIENT_PREFETCH_THREADS,
SnowflakeConnection,
)
from snowflake.connector.description import CLIENT_NAME
from snowflake.connector.errorcode import (
ER_CONNECTION_IS_CLOSED,
ER_FAILED_PROCESSING_PYFORMAT,
ER_INVALID_VALUE,
ER_NO_ACCOUNT_NAME,
ER_NOT_IMPLICITY_SNOWFLAKE_DATATYPE,
)
from snowflake.connector.errors import Error, InterfaceError
from snowflake.connector.network import APPLICATION_SNOWSQL, ReauthenticationRequest
from snowflake.connector.sqlstate import SQLSTATE_FEATURE_NOT_SUPPORTED
from snowflake.connector.telemetry import TelemetryField
from ..randomize import random_string
from .conftest import RUNNING_ON_GH, create_connection
try: # pragma: no cover
from ..parameters import CONNECTION_PARAMETERS_ADMIN
except ImportError:
CONNECTION_PARAMETERS_ADMIN = {}
try: # pragma: no cover
from snowflake.connector.auth import AuthByOkta, AuthByPlugin
except ImportError:
from snowflake.connector.auth_by_plugin import AuthByPlugin
from snowflake.connector.auth_okta import AuthByOkta
try:
from snowflake.connector.errorcode import ER_FAILED_PROCESSING_QMARK
except ImportError: # Keep olddrivertest from breaking
ER_FAILED_PROCESSING_QMARK = 252012
def test_basic(conn_testaccount):
"""Basic Connection test."""
assert conn_testaccount, "invalid cnx"
# Test default values
assert conn_testaccount.session_id
def test_connection_without_schema(db_parameters):
"""Basic Connection test without schema."""
cnx = snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
database=db_parameters["database"],
protocol=db_parameters["protocol"],
timezone="UTC",
)
assert cnx, "invalid cnx"
cnx.close()
def test_connection_without_database_schema(db_parameters):
"""Basic Connection test without database and schema."""
cnx = snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
protocol=db_parameters["protocol"],
timezone="UTC",
)
assert cnx, "invalid cnx"
cnx.close()
def test_connection_without_database2(db_parameters):
"""Basic Connection test without database."""
cnx = snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
schema=db_parameters["schema"],
protocol=db_parameters["protocol"],
timezone="UTC",
)
assert cnx, "invalid cnx"
cnx.close()
def test_with_config(db_parameters):
"""Creates a connection with the config parameter."""
config = {
"user": db_parameters["user"],
"password": db_parameters["password"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"account": db_parameters["account"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"timezone": "UTC",
}
cnx = snowflake.connector.connect(**config)
try:
assert cnx, "invalid cnx"
assert not cnx.client_session_keep_alive # default is False
finally:
cnx.close()
@pytest.mark.skipolddriver
def test_with_tokens(conn_cnx, db_parameters):
"""Creates a connection using session and master token."""
try:
with conn_cnx(
timezone="UTC",
) as initial_cnx:
assert initial_cnx, "invalid initial cnx"
master_token = initial_cnx.rest._master_token
session_token = initial_cnx.rest._token
with snowflake.connector.connect(
account=db_parameters["account"],
host=db_parameters["host"],
port=db_parameters["port"],
protocol=db_parameters["protocol"],
session_token=session_token,
master_token=master_token,
) as token_cnx:
assert token_cnx, "invalid second cnx"
except Exception:
# This is my way of guaranteeing that we'll not expose the
# sensitive information that this test needs to handle.
# db_parameter contains passwords.
pytest.fail("something failed", pytrace=False)
@pytest.mark.skipolddriver
def test_with_tokens_expired(conn_cnx, db_parameters):
"""Creates a connection using session and master token."""
try:
with conn_cnx(
timezone="UTC",
) as initial_cnx:
assert initial_cnx, "invalid initial cnx"
master_token = initial_cnx._rest._master_token
session_token = initial_cnx._rest._token
with pytest.raises(ProgrammingError):
token_cnx = snowflake.connector.connect(
account=db_parameters["account"],
host=db_parameters["host"],
port=db_parameters["port"],
protocol=db_parameters["protocol"],
session_token=session_token,
master_token=master_token,
)
token_cnx.close()
except Exception:
# This is my way of guaranteeing that we'll not expose the
# sensitive information that this test needs to handle.
# db_parameter contains passwords.
pytest.fail("something failed", pytrace=False)
def test_keep_alive_true(db_parameters):
"""Creates a connection with client_session_keep_alive parameter."""
config = {
"user": db_parameters["user"],
"password": db_parameters["password"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"account": db_parameters["account"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"timezone": "UTC",
"client_session_keep_alive": True,
}
cnx = snowflake.connector.connect(**config)
try:
assert cnx.client_session_keep_alive
finally:
cnx.close()
def test_keep_alive_heartbeat_frequency(db_parameters):
"""Tests heartbeat setting.
Creates a connection with client_session_keep_alive_heartbeat_frequency
parameter.
"""
config = {
"user": db_parameters["user"],
"password": db_parameters["password"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"account": db_parameters["account"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"timezone": "UTC",
"client_session_keep_alive": True,
"client_session_keep_alive_heartbeat_frequency": 1000,
}
cnx = snowflake.connector.connect(**config)
try:
assert cnx.client_session_keep_alive_heartbeat_frequency == 1000
finally:
cnx.close()
@pytest.mark.skipolddriver
def test_keep_alive_heartbeat_frequency_min(db_parameters):
"""Tests heartbeat setting with custom frequency.
Creates a connection with client_session_keep_alive_heartbeat_frequency parameter and set the minimum frequency.
Also if a value comes as string, should be properly converted to int and not fail assertion.
"""
config = {
"user": db_parameters["user"],
"password": db_parameters["password"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"account": db_parameters["account"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"timezone": "UTC",
"client_session_keep_alive": True,
"client_session_keep_alive_heartbeat_frequency": "10",
}
cnx = snowflake.connector.connect(**config)
try:
# The min value of client_session_keep_alive_heartbeat_frequency
# is 1/16 of master token validity, so 14400 / 4 /4 => 900
assert cnx.client_session_keep_alive_heartbeat_frequency == 900
finally:
cnx.close()
def test_bad_db(db_parameters):
"""Attempts to use a bad DB."""
cnx = snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
protocol=db_parameters["protocol"],
database="baddb",
)
assert cnx, "invald cnx"
cnx.close()
def test_with_string_login_timeout(db_parameters):
"""Test that login_timeout when passed as string does not raise TypeError.
In this test, we pass bad login credentials to raise error and trigger login
timeout calculation. We expect to see DatabaseError instead of TypeError that
comes from str - int arithmetic.
"""
with pytest.raises(DatabaseError):
snowflake.connector.connect(
protocol="http",
user="bogus",
password="bogus",
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
login_timeout="5",
)
@pytest.mark.skip(reason="the test is affected by CI breaking change")
def test_bogus(db_parameters):
"""Attempts to login with invalid user name and password.
Notes:
This takes a long time.
"""
with pytest.raises(DatabaseError):
snowflake.connector.connect(
protocol="http",
user="bogus",
password="bogus",
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
login_timeout=5,
)
with pytest.raises(DatabaseError):
snowflake.connector.connect(
protocol="http",
user="bogus",
password="bogus",
account="testaccount123",
host=db_parameters["host"],
port=db_parameters["port"],
login_timeout=5,
disable_ocsp_checks=True,
)
with pytest.raises(DatabaseError):
snowflake.connector.connect(
protocol="http",
user="snowman",
password="",
account="testaccount123",
host=db_parameters["host"],
port=db_parameters["port"],
login_timeout=5,
)
with pytest.raises(ProgrammingError):
snowflake.connector.connect(
protocol="http",
user="",
password="password",
account="testaccount123",
host=db_parameters["host"],
port=db_parameters["port"],
login_timeout=5,
)
def test_invalid_application(db_parameters):
"""Invalid application name."""
with pytest.raises(snowflake.connector.Error):
snowflake.connector.connect(
protocol=db_parameters["protocol"],
user=db_parameters["user"],
password=db_parameters["password"],
application="%%%",
)
def test_valid_application(db_parameters):
"""Valid application name."""
application = "Special_Client"
cnx = snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
application=application,
protocol=db_parameters["protocol"],
)
assert cnx.application == application, "Must be valid application"
cnx.close()
def test_invalid_default_parameters(db_parameters):
"""Invalid database, schema, warehouse and role name."""
cnx = snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
protocol=db_parameters["protocol"],
database="neverexists",
schema="neverexists",
warehouse="neverexits",
)
assert cnx, "Must be success"
with pytest.raises(snowflake.connector.DatabaseError):
# must not success
snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
protocol=db_parameters["protocol"],
database="neverexists",
schema="neverexists",
validate_default_parameters=True,
)
with pytest.raises(snowflake.connector.DatabaseError):
# must not success
snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
protocol=db_parameters["protocol"],
database=db_parameters["database"],
schema="neverexists",
validate_default_parameters=True,
)
with pytest.raises(snowflake.connector.DatabaseError):
# must not success
snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
protocol=db_parameters["protocol"],
database=db_parameters["database"],
schema=db_parameters["schema"],
warehouse="neverexists",
validate_default_parameters=True,
)
# Invalid role name is already validated
with pytest.raises(snowflake.connector.DatabaseError):
# must not success
snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
protocol=db_parameters["protocol"],
database=db_parameters["database"],
schema=db_parameters["schema"],
role="neverexists",
)
@pytest.mark.skipif(
not CONNECTION_PARAMETERS_ADMIN,
reason="The user needs a privilege of create warehouse.",
)
def test_drop_create_user(conn_cnx, db_parameters):
"""Drops and creates user."""
with conn_cnx() as cnx:
def exe(sql):
return cnx.cursor().execute(sql)
exe("use role accountadmin")
exe("drop user if exists snowdog")
exe("create user if not exists snowdog identified by 'testdoc'")
exe("use {}".format(db_parameters["database"]))
exe("create or replace role snowdog_role")
exe("grant role snowdog_role to user snowdog")
try:
# This statement will be partially executed because REFERENCE_USAGE
# will not be granted.
exe(
"grant all on database {} to role snowdog_role".format(
db_parameters["database"]
)
)
except ProgrammingError as error:
err_str = (
"Grant partially executed: privileges [REFERENCE_USAGE] not granted."
)
assert 3011 == error.errno
assert error.msg.find(err_str) != -1
exe(
"grant all on schema {} to role snowdog_role".format(
db_parameters["schema"]
)
)
with conn_cnx(user="snowdog", password="testdoc") as cnx2:
def exe(sql):
return cnx2.cursor().execute(sql)
exe("use role snowdog_role")
exe("use {}".format(db_parameters["database"]))
exe("use schema {}".format(db_parameters["schema"]))
exe("create or replace table friends(name varchar(100))")
exe("drop table friends")
with conn_cnx() as cnx:
def exe(sql):
return cnx.cursor().execute(sql)
exe("use role accountadmin")
exe(
"revoke all on database {} from role snowdog_role".format(
db_parameters["database"]
)
)
exe("drop role snowdog_role")
exe("drop user if exists snowdog")
@pytest.mark.timeout(15)
@pytest.mark.skipolddriver
def test_invalid_account_timeout():
with pytest.raises(InterfaceError):
snowflake.connector.connect(
account="bogus", user="test", password="test", login_timeout=5
)
@pytest.mark.timeout(15)
def test_invalid_proxy(db_parameters):
http_proxy = os.environ.get("HTTP_PROXY")
https_proxy = os.environ.get("HTTPS_PROXY")
with pytest.raises(OperationalError):
snowflake.connector.connect(
protocol="http",
account="testaccount",
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
login_timeout=0,
proxy_host="localhost",
proxy_port="3333",
)
# Proxy environment variables should not change
assert os.environ.get("HTTP_PROXY") == http_proxy
assert os.environ.get("HTTPS_PROXY") == https_proxy
@pytest.mark.timeout(15)
@pytest.mark.skipolddriver
def test_eu_connection(tmpdir):
"""Tests setting custom region.
If region is specified to eu-central-1, the URL should become
https://testaccount1234.eu-central-1.snowflakecomputing.com/ .
Notes:
Region is deprecated.
"""
import os
os.environ["SF_OCSP_RESPONSE_CACHE_SERVER_ENABLED"] = "true"
with pytest.raises(InterfaceError):
# must reach Snowflake
snowflake.connector.connect(
account="testaccount1234",
user="testuser",
password="testpassword",
region="eu-central-1",
login_timeout=5,
ocsp_response_cache_filename=os.path.join(
str(tmpdir), "test_ocsp_cache.txt"
),
)
@pytest.mark.skipolddriver
def test_us_west_connection(tmpdir):
"""Tests default region setting.
Region='us-west-2' indicates no region is included in the hostname, i.e.,
https://testaccount1234.snowflakecomputing.com.
Notes:
Region is deprecated.
"""
with pytest.raises(InterfaceError):
# must reach Snowflake
snowflake.connector.connect(
account="testaccount1234",
user="testuser",
password="testpassword",
region="us-west-2",
login_timeout=5,
)
@pytest.mark.timeout(60)
def test_privatelink(db_parameters):
"""Ensure the OCSP cache server URL is overridden if privatelink connection is used."""
try:
os.environ["SF_OCSP_FAIL_OPEN"] = "false"
os.environ["SF_OCSP_DO_RETRY"] = "false"
snowflake.connector.connect(
account="testaccount",
user="testuser",
password="testpassword",
region="eu-central-1.privatelink",
login_timeout=5,
)
pytest.fail("should not make connection")
except OperationalError:
ocsp_url = os.getenv("SF_OCSP_RESPONSE_CACHE_SERVER_URL")
assert ocsp_url is not None, "OCSP URL should not be None"
assert (
ocsp_url == "http://ocsp.testaccount.eu-central-1."
"privatelink.snowflakecomputing.com/"
"ocsp_response_cache.json"
)
cnx = snowflake.connector.connect(
user=db_parameters["user"],
password=db_parameters["password"],
host=db_parameters["host"],
port=db_parameters["port"],
account=db_parameters["account"],
database=db_parameters["database"],
protocol=db_parameters["protocol"],
timezone="UTC",
)
assert cnx, "invalid cnx"
ocsp_url = os.getenv("SF_OCSP_RESPONSE_CACHE_SERVER_URL")
assert ocsp_url is None, f"OCSP URL should be None: {ocsp_url}"
del os.environ["SF_OCSP_DO_RETRY"]
del os.environ["SF_OCSP_FAIL_OPEN"]
def test_disable_request_pooling(db_parameters):
"""Creates a connection with client_session_keep_alive parameter."""
config = {
"user": db_parameters["user"],
"password": db_parameters["password"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"account": db_parameters["account"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"timezone": "UTC",
"disable_request_pooling": True,
}
cnx = snowflake.connector.connect(**config)
try:
assert cnx.disable_request_pooling
finally:
cnx.close()
def test_privatelink_ocsp_url_creation():
hostname = "testaccount.us-east-1.privatelink.snowflakecomputing.com"
SnowflakeConnection.setup_ocsp_privatelink(APPLICATION_SNOWSQL, hostname)
ocsp_cache_server = os.getenv("SF_OCSP_RESPONSE_CACHE_SERVER_URL", None)
assert (
ocsp_cache_server
== "http://ocsp.testaccount.us-east-1.privatelink.snowflakecomputing.com/ocsp_response_cache.json"
)
del os.environ["SF_OCSP_RESPONSE_CACHE_SERVER_URL"]
SnowflakeConnection.setup_ocsp_privatelink(CLIENT_NAME, hostname)
ocsp_cache_server = os.getenv("SF_OCSP_RESPONSE_CACHE_SERVER_URL", None)
assert (
ocsp_cache_server
== "http://ocsp.testaccount.us-east-1.privatelink.snowflakecomputing.com/ocsp_response_cache.json"
)
@pytest.mark.skipolddriver
def test_uppercase_privatelink_ocsp_url_creation():
account = "TESTACCOUNT.US-EAST-1.PRIVATELINK"
hostname = account + ".snowflakecomputing.com"
SnowflakeConnection.setup_ocsp_privatelink(CLIENT_NAME, hostname)
ocsp_cache_server = os.getenv("SF_OCSP_RESPONSE_CACHE_SERVER_URL", None)
assert (
ocsp_cache_server
== "http://ocsp.testaccount.us-east-1.privatelink.snowflakecomputing.com/ocsp_response_cache.json"
)
def test_privatelink_ocsp_url_multithreaded():
bucket = queue.Queue()
hostname = "testaccount.us-east-1.privatelink.snowflakecomputing.com"
expectation = "http://ocsp.testaccount.us-east-1.privatelink.snowflakecomputing.com/ocsp_response_cache.json"
thread_obj = []
for _ in range(15):
thread_obj.append(
ExecPrivatelinkThread(bucket, hostname, expectation, CLIENT_NAME)
)
for t in thread_obj:
t.start()
fail_flag = False
for t in thread_obj:
t.join()
exc = bucket.get(block=False)
if exc != "Success" and not fail_flag:
fail_flag = True
if fail_flag:
raise AssertionError()
if os.getenv("SF_OCSP_RESPONSE_CACHE_SERVER_URL", None) is not None:
del os.environ["SF_OCSP_RESPONSE_CACHE_SERVER_URL"]
def test_privatelink_ocsp_url_multithreaded_snowsql():
bucket = queue.Queue()
hostname = "testaccount.us-east-1.privatelink.snowflakecomputing.com"
expectation = "http://ocsp.testaccount.us-east-1.privatelink.snowflakecomputing.com/ocsp_response_cache.json"
thread_obj = []
for _ in range(15):
thread_obj.append(
ExecPrivatelinkThread(bucket, hostname, expectation, APPLICATION_SNOWSQL)
)
for t in thread_obj:
t.start()
fail_flag = False
for i in range(15):
thread_obj[i].join()
exc = bucket.get(block=False)
if exc != "Success" and not fail_flag:
fail_flag = True
if fail_flag:
raise AssertionError()
class ExecPrivatelinkThread(threading.Thread):
def __init__(self, bucket, hostname, expectation, client_name):
threading.Thread.__init__(self)
self.bucket = bucket
self.hostname = hostname
self.expectation = expectation
self.client_name = client_name
def run(self):
SnowflakeConnection.setup_ocsp_privatelink(self.client_name, self.hostname)
ocsp_cache_server = os.getenv("SF_OCSP_RESPONSE_CACHE_SERVER_URL", None)
if ocsp_cache_server is not None and ocsp_cache_server != self.expectation:
print(f"Got {ocsp_cache_server} Expected {self.expectation}")
self.bucket.put("Fail")
else:
self.bucket.put("Success")
@pytest.mark.skipolddriver
def test_okta_url(conn_cnx):
orig_authenticator = "https://someaccount.okta.com/snowflake/oO56fExYCGnfV83/2345"
def mock_auth(self, auth_instance):
assert isinstance(auth_instance, AuthByOkta)
assert self._authenticator == orig_authenticator
with mock.patch(
"snowflake.connector.connection.SnowflakeConnection._authenticate",
mock_auth,
):
cnx = conn_cnx(
timezone="UTC",
authenticator=orig_authenticator,
)
assert cnx
def test_dashed_url(db_parameters):
"""Test whether dashed URLs get created correctly."""
with mock.patch(
"snowflake.connector.network.SnowflakeRestful.fetch",
return_value={"data": {"token": None, "masterToken": None}, "success": True},
) as mocked_fetch:
with snowflake.connector.connect(
user="test-user",
password="test-password",
host="test-host",
port="443",
account="test-account",
) as cnx:
assert cnx
cnx.commit = cnx.rollback = (
lambda: None
) # Skip tear down, there's only a mocked rest api
assert any(
[
c[0][1].startswith("https://test-host:443")
for c in mocked_fetch.call_args_list
]
)
def test_dashed_url_account_name(db_parameters):
"""Tests whether dashed URLs get created correctly when no hostname is provided."""
with mock.patch(
"snowflake.connector.network.SnowflakeRestful.fetch",
return_value={"data": {"token": None, "masterToken": None}, "success": True},
) as mocked_fetch:
with snowflake.connector.connect(
user="test-user",
password="test-password",
port="443",
account="test-account",
) as cnx:
assert cnx
cnx.commit = cnx.rollback = (
lambda: None
) # Skip tear down, there's only a mocked rest api
assert any(
[
c[0][1].startswith(
"https://test-account.snowflakecomputing.com:443"
)
for c in mocked_fetch.call_args_list
]
)
@pytest.mark.skipolddriver
@pytest.mark.parametrize(
"name,value,exc_warn",
[
# Not existing parameter
(
"no_such_parameter",
True,
UserWarning("'no_such_parameter' is an unknown connection parameter"),
),
# Typo in parameter name
(
"applucation",
True,
UserWarning(
"'applucation' is an unknown connection parameter, did you mean 'application'?"
),
),
# Single type error
(
"support_negative_year",
"True",
UserWarning(
"'support_negative_year' connection parameter should be of type "
"'bool', but is a 'str'"
),
),
# Multiple possible type error
(
"autocommit",
"True",
UserWarning(
"'autocommit' connection parameter should be of type "
"'(NoneType, bool)', but is a 'str'"
),
),
],
)
def test_invalid_connection_parameter(db_parameters, name, value, exc_warn):
with warnings.catch_warnings(record=True) as w:
conn_params = {
"account": db_parameters["account"],
"user": db_parameters["user"],
"password": db_parameters["password"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"validate_default_parameters": True,
name: value,
}
try:
conn = snowflake.connector.connect(**conn_params)
assert getattr(conn, "_" + name) == value
# TODO: SNOW-2114216 remove filtering once the root cause for deprecation warning is fixed
# Filter out the deprecation warning
filtered_w = [
warning for warning in w if warning.category != DeprecationWarning
]
assert len(filtered_w) == 1
assert str(filtered_w[0].message) == str(exc_warn)
finally:
conn.close()
def test_invalid_connection_parameters_turned_off(db_parameters):
"""Makes sure parameter checking can be turned off."""
with warnings.catch_warnings(record=True) as w:
conn_params = {
"account": db_parameters["account"],
"user": db_parameters["user"],
"password": db_parameters["password"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"validate_default_parameters": False,
"autocommit": "True", # Wrong type
"applucation": "this is a typo or my own variable", # Wrong name
}
try:
conn = snowflake.connector.connect(**conn_params)
assert conn._autocommit == conn_params["autocommit"]
assert conn._applucation == conn_params["applucation"]
# TODO: SNOW-2114216 remove filtering once the root cause for deprecation warning is fixed
# Filter out the deprecation warning
filtered_w = [
warning for warning in w if warning.category != DeprecationWarning
]
assert len(filtered_w) == 0
finally:
conn.close()
def test_invalid_connection_parameters_only_warns(db_parameters):
"""This test supresses warnings to only have warehouse, database and schema checking."""
with warnings.catch_warnings(record=True) as w:
conn_params = {
"account": db_parameters["account"],
"user": db_parameters["user"],
"password": db_parameters["password"],
"schema": db_parameters["schema"],
"database": db_parameters["database"],
"protocol": db_parameters["protocol"],
"host": db_parameters["host"],
"port": db_parameters["port"],
"validate_default_parameters": True,
"autocommit": "True", # Wrong type
"applucation": "this is a typo or my own variable", # Wrong name
}
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
conn = snowflake.connector.connect(**conn_params)
assert conn._autocommit == conn_params["autocommit"]
assert conn._applucation == conn_params["applucation"]
assert len(w) == 0
finally:
conn.close()
@pytest.mark.skipolddriver
def test_region_deprecation(conn_cnx):
"""Tests whether region raises a deprecation warning."""
with conn_cnx() as conn:
with warnings.catch_warnings(record=True) as w:
conn.region
assert len(w) == 1
assert issubclass(w[0].category, PendingDeprecationWarning)
assert "Region has been deprecated" in str(w[0].message)
def test_invalid_errorhander_error(conn_cnx):
"""Tests if no errorhandler cannot be set."""
with conn_cnx() as conn:
with pytest.raises(ProgrammingError, match="None errorhandler is specified"):
conn.errorhandler = None
original_handler = conn.errorhandler
conn.errorhandler = original_handler
assert conn.errorhandler is original_handler
def test_disable_request_pooling_setter(conn_cnx):
"""Tests whether request pooling can be set successfully."""
with conn_cnx() as conn:
original_value = conn.disable_request_pooling
conn.disable_request_pooling = not original_value
assert conn.disable_request_pooling == (not original_value)
conn.disable_request_pooling = original_value
assert conn.disable_request_pooling == original_value
def test_autocommit_closed_already(conn_cnx):
"""Test if setting autocommit on an already closed connection raised right error."""
with conn_cnx() as conn:
pass
with pytest.raises(DatabaseError, match=r"Connection is closed") as dbe:
conn.autocommit(True)
assert dbe.errno == ER_CONNECTION_IS_CLOSED
def test_autocommit_invalid_type(conn_cnx):
"""Tests if setting autocommit on an already closed connection raised right error."""
with conn_cnx() as conn:
with pytest.raises(ProgrammingError, match=r"Invalid parameter: True") as dbe:
conn.autocommit("True")
assert dbe.errno == ER_INVALID_VALUE
def test_autocommit_unsupported(conn_cnx, caplog):
"""Tests if server-side error is handled correctly when setting autocommit."""