-
Notifications
You must be signed in to change notification settings - Fork 450
/
conftest.py
335 lines (278 loc) · 9.61 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved.
#
import os
import sys
import time
import uuid
from contextlib import contextmanager
from logging import getLogger
from typing import Callable, Generator
import pytest
from generate_test_files import generate_k_lines_of_n_files
import snowflake.connector
from parameters import CONNECTION_PARAMETERS
from snowflake.connector.compat import IS_WINDOWS, TO_UNICODE
from snowflake.connector.connection import DefaultConverterClass
MYPY = False
if MYPY: # from typing import TYPE_CHECKING once 3.5 is deprecated
from snowflake.connector import SnowflakeConnection
try:
from parameters import CONNECTION_PARAMETERS_S3
except ImportError:
CONNECTION_PARAMETERS_S3 = {}
try:
from parameters import CONNECTION_PARAMETERS_AZURE
except ImportError:
CONNECTION_PARAMETERS_AZURE = {}
try:
from parameters import CONNECTION_PARAMETERS_GCP
except ImportError:
CONNECTION_PARAMETERS_GCP = {}
try:
from parameters import CONNECTION_PARAMETERS_ADMIN
except ImportError:
CONNECTION_PARAMETERS_ADMIN = {}
logger = getLogger(__name__)
if os.getenv('TRAVIS') == 'true':
TEST_SCHEMA = 'TRAVIS_JOB_{}'.format(os.getenv('TRAVIS_JOB_ID'))
elif os.getenv('APPVEYOR') == 'True':
TEST_SCHEMA = 'APPVEYOR_JOB_{}'.format(os.getenv('APPVEYOR_BUILD_ID'))
else:
TEST_SCHEMA = 'python_connector_tests_' + TO_UNICODE(uuid.uuid4()).replace(
'-', '_')
DEFAULT_PARAMETERS = {
'account': '<account_name>',
'user': '<user_name>',
'password': '<password>',
'database': '<database_name>',
'schema': '<schema_name>',
'protocol': 'https',
'host': '<host>',
'port': '443',
}
def help():
print("""Connection parameter must be specified in parameters.py,
for example:
CONNECTION_PARAMETERS = {
'account': 'testaccount',
'user': 'user1',
'password': 'test',
'database': 'testdb',
'schema': 'public',
}
""")
@pytest.fixture(scope='session')
def is_public_test():
return is_public_testaccount()
def is_public_testaccount():
db_parameters = get_db_parameters()
return os.getenv('TRAVIS') == 'true' or \
os.getenv('APPVEYOR') == 'True' or \
db_parameters.get('account').startswith('sfctest0')
@pytest.fixture(scope='session')
def db_parameters():
return get_db_parameters()
def get_db_parameters():
"""
Sets the db connection parameters
"""
ret = {}
os.environ['TZ'] = 'UTC'
if not IS_WINDOWS:
time.tzset()
# testaccount connection info
for k, v in CONNECTION_PARAMETERS.items():
ret[k] = v
for k, v in DEFAULT_PARAMETERS.items():
if k not in ret:
ret[k] = v
# s3 testaccount connection info. Not available in TravisCI
if CONNECTION_PARAMETERS_S3:
for k, v in CONNECTION_PARAMETERS_S3.items():
ret['s3_' + k] = v
else:
for k, v in CONNECTION_PARAMETERS.items():
ret['s3_' + k] = v
# azure testaccount connection info. Not available in TravisCI
if CONNECTION_PARAMETERS_AZURE:
for k, v in CONNECTION_PARAMETERS_AZURE.items():
ret['azure_' + k] = v
else:
for k, v in CONNECTION_PARAMETERS.items():
ret['azure_' + k] = v
# azure testaccount connection info. Not available in TravisCI
if CONNECTION_PARAMETERS_GCP:
for k, v in CONNECTION_PARAMETERS_GCP.items():
ret['gcp_' + k] = v
else:
for k, v in CONNECTION_PARAMETERS.items():
ret['gcp_' + k] = v
# snowflake admin account. Not available in TravisCI
for k, v in CONNECTION_PARAMETERS_ADMIN.items():
ret['sf_' + k] = v
if 'host' in ret and ret['host'] == DEFAULT_PARAMETERS['host']:
ret['host'] = ret['account'] + '.snowflakecomputing.com'
if 'account' in ret and ret['account'] == DEFAULT_PARAMETERS['account']:
help()
sys.exit(2)
# a unique table name
ret['name'] = 'python_tests_' + TO_UNICODE(uuid.uuid4()).replace('-', '_')
ret['name_wh'] = ret['name'] + 'wh'
ret['schema'] = TEST_SCHEMA
# This reduces a chance to exposing password in test output.
ret['a00'] = 'dummy parameter'
ret['a01'] = 'dummy parameter'
ret['a02'] = 'dummy parameter'
ret['a03'] = 'dummy parameter'
ret['a04'] = 'dummy parameter'
ret['a05'] = 'dummy parameter'
ret['a06'] = 'dummy parameter'
ret['a07'] = 'dummy parameter'
ret['a08'] = 'dummy parameter'
ret['a09'] = 'dummy parameter'
ret['a10'] = 'dummy parameter'
ret['a11'] = 'dummy parameter'
ret['a12'] = 'dummy parameter'
ret['a13'] = 'dummy parameter'
ret['a14'] = 'dummy parameter'
ret['a15'] = 'dummy parameter'
ret['a16'] = 'dummy parameter'
return ret
@pytest.fixture(scope='session', autouse=True)
def init_test_schema(request, db_parameters):
"""
Initializes and Deinitializes the test schema
This is automatically called per test session.
"""
ret = db_parameters
with snowflake.connector.connect(
user=ret['user'],
password=ret['password'],
host=ret['host'],
port=ret['port'],
database=ret['database'],
account=ret['account'],
protocol=ret['protocol']
) as con:
con.cursor().execute(
"CREATE SCHEMA IF NOT EXISTS {}".format(TEST_SCHEMA))
if CONNECTION_PARAMETERS_S3:
with snowflake.connector.connect(
user=ret['s3_user'],
password=ret['s3_password'],
host=ret['s3_host'],
port=ret['s3_port'],
database=ret['s3_database'],
account=ret['s3_account'],
protocol=ret['s3_protocol']
) as con:
con.cursor().execute(
"CREATE SCHEMA IF NOT EXISTS {}".format(TEST_SCHEMA))
if CONNECTION_PARAMETERS_AZURE:
with snowflake.connector.connect(
user=ret['azure_user'],
password=ret['azure_password'],
host=ret['azure_host'],
port=ret['azure_port'],
database=ret['azure_database'],
account=ret['azure_account'],
protocol=ret['azure_protocol']
) as con:
con.cursor().execute(
"CREATE SCHEMA IF NOT EXISTS {}".format(TEST_SCHEMA))
if CONNECTION_PARAMETERS_GCP:
with snowflake.connector.connect(
user=ret['gcp_user'],
password=ret['gcp_password'],
host=ret['gcp_host'],
port=ret['gcp_port'],
database=ret['gcp_database'],
account=ret['gcp_account'],
protocol=ret['gcp_protocol']
) as con:
con.cursor().execute(
"CREATE SCHEMA IF NOT EXISTS {}".format(TEST_SCHEMA))
def fin():
ret1 = db_parameters
with snowflake.connector.connect(
user=ret1['user'],
password=ret1['password'],
host=ret1['host'],
port=ret1['port'],
database=ret1['database'],
account=ret1['account'],
protocol=ret1['protocol']
) as con1:
con1.cursor().execute(
"DROP SCHEMA IF EXISTS {}".format(TEST_SCHEMA))
if CONNECTION_PARAMETERS_S3:
with snowflake.connector.connect(
user=ret1['s3_user'],
password=ret1['s3_password'],
host=ret1['s3_host'],
port=ret1['s3_port'],
database=ret1['s3_database'],
account=ret1['s3_account'],
protocol=ret1['s3_protocol']
) as con1:
con1.cursor().execute(
"DROP SCHEMA IF EXISTS {}".format(TEST_SCHEMA))
request.addfinalizer(fin)
def create_connection(**kwargs) -> 'SnowflakeConnection':
"""
Creates a connection using the parameters defined in JDBC connect string
"""
ret = get_db_parameters()
ret.update(kwargs)
connection = snowflake.connector.connect(**ret)
return connection
@contextmanager
def db(**kwargs) -> Generator['SnowflakeConnection', None, None]:
if not kwargs.get(u'timezone'):
kwargs[u'timezone'] = u'UTC'
if not kwargs.get(u'converter_class'):
kwargs[u'converter_class'] = DefaultConverterClass()
cnx = create_connection(**kwargs)
try:
yield cnx
finally:
cnx.close()
@contextmanager
def negative_db(**kwargs):
if not kwargs.get(u'timezone'):
kwargs[u'timezone'] = u'UTC'
if not kwargs.get(u'converter_class'):
kwargs[u'converter_class'] = DefaultConverterClass()
cnx = create_connection(**kwargs)
if not is_public_testaccount():
cnx.cursor().execute("alter session set SUPPRESS_INCIDENT_DUMPS=true")
try:
yield cnx
finally:
cnx.close()
@pytest.fixture()
def conn_testaccount(request):
connection = create_connection()
def fin():
connection.close() # close when done
request.addfinalizer(fin)
return connection
@pytest.fixture()
def conn_cnx() -> Callable[..., Generator['SnowflakeConnection', None, None]]:
return db
@pytest.fixture()
def negative_conn_cnx():
"""
Use this if an incident is expected and we don't want GS to create a
dump file about the incident"""
return negative_db
@pytest.fixture()
def test_files():
return generate_k_lines_of_n_files
def pytest_runtest_setup(item):
for _ in item.iter_markers(name="internal"):
if is_public_testaccount():
pytest.skip("cannot run on public CI")