forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_postgresql.py
436 lines (391 loc) · 13.7 KB
/
test_postgresql.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
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
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
"""Tests the PostgreSQL database source class methods"""
import ssl
from contextlib import asynccontextmanager
from unittest.mock import ANY, Mock, patch
import pytest
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio.engine import AsyncEngine
from connectors.filtering.validation import SyncRuleValidationResult
from connectors.protocol import Filter
from connectors.sources.postgresql import (
PostgreSQLAdvancedRulesValidator,
PostgreSQLClient,
PostgreSQLDataSource,
PostgreSQLQueries,
)
from tests.sources.support import create_source
ADVANCED_SNIPPET = "advanced_snippet"
POSTGRESQL_CONNECTION_STRING = (
"postgresql+asyncpg://admin:[email protected]:5432/testdb"
)
SCHEMA = "public"
TABLE = "emp_table"
CUSTOMER_TABLE = "customer"
@asynccontextmanager
async def create_postgresql_source():
async with create_source(
PostgreSQLDataSource,
host="127.0.0.1",
port="9090",
database="xe",
tables="*",
schema=SCHEMA,
) as source:
yield source
class MockSsl:
"""This class contains methods which returns dummy ssl context"""
def load_verify_locations(self, cadata):
"""This method verify locations"""
pass
class ConnectionAsync:
"""This class creates dummy connection with database and return dummy cursor"""
async def __aenter__(self):
"""Make a dummy database connection and return it"""
return self
async def __aexit__(self, exception_type, exception_value, exception_traceback):
"""Make sure the dummy database connection gets closed"""
pass
async def execute(self, query):
"""This method returns dummy cursor"""
return CursorAsync(query=query)
class CursorAsync:
"""This class contains methods which returns dummy response"""
async def __aenter__(self):
"""Make a dummy database connection and return it"""
return self
def __init__(self, *args, **kw):
"""Setup dummy cursor"""
self.query = kw["query"]
self.first_call = True
def keys(self):
"""Return Columns of table
Returns:
list: List of columns
"""
return ["ids", "names"]
def fetchmany(self, size):
"""This method returns response of fetchmany
Args:
size (int): Number of rows
Returns:
list: List of rows
"""
if self.first_call:
self.first_call = False
self.query = str(self.query)
query_object = PostgreSQLQueries()
if self.query == query_object.all_tables(database="xe", schema=SCHEMA):
return [(TABLE,)]
elif self.query == query_object.table_data_count(
schema=SCHEMA, table=TABLE
):
return [(10,)]
elif self.query == query_object.table_primary_key(
schema=SCHEMA, table=TABLE
):
return [("ids",)]
elif self.query == query_object.table_primary_key(
schema=SCHEMA, table=CUSTOMER_TABLE
):
return [("ids",)]
elif self.query == query_object.table_last_update_time(
schema=SCHEMA, table=TABLE
):
return [("2023-02-21T08:37:15+00:00",)]
elif self.query == query_object.table_last_update_time(
schema=SCHEMA, table=CUSTOMER_TABLE
):
return [("2023-02-21T08:37:15+00:00",)]
elif self.query.lower() == "select * from customer":
return [(1, "customer_1"), (2, "customer_2")]
elif self.query == query_object.ping():
return [(2,)]
else:
return [
(
1,
"abcd",
),
(
2,
"xyz",
),
]
return []
async def __aexit__(self, exception_type, exception_value, exception_traceback):
"""Make sure the dummy database connection gets closed"""
pass
def test_get_connect_args():
"""This function test _get_connect_args with dummy certificate"""
# Setup
client = PostgreSQLClient(
host="",
port="",
user="",
password="",
database="",
schema="",
tables="*",
ssl_enabled=True,
ssl_ca="-----BEGIN CERTIFICATE----- Certificate -----END CERTIFICATE-----",
logger_=None,
)
# Execute
with patch.object(ssl, "create_default_context", return_value=MockSsl()):
client._get_connect_args()
@pytest.mark.asyncio
async def test_postgresql_ping():
# Setup
async with create_postgresql_source() as source:
with patch.object(AsyncEngine, "connect", return_value=ConnectionAsync()):
await source.ping()
await source.close()
@pytest.mark.asyncio
async def test_ping():
async with create_postgresql_source() as source:
with patch.object(AsyncEngine, "connect", return_value=ConnectionAsync()):
await source.ping()
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_ping_negative():
with pytest.raises(Exception):
async with create_source(PostgreSQLDataSource, port=5432) as source:
with patch.object(AsyncEngine, "connect", side_effect=Exception()):
await source.ping()
@pytest.mark.parametrize(
"advanced_rules, expected_validation_result",
[
(
# valid: empty array should be valid
[],
SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
),
),
(
# valid: empty object should also be valid -> default value in Kibana
{},
SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
),
),
(
# valid: valid queries
[
{
"tables": ["emp_table"],
"query": "select * from emp_table",
}
],
SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
),
),
(
# invalid: tables not present in database
[
{
"tables": ["table_name"],
"query": "select * from table_name",
}
],
SyncRuleValidationResult(
SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=ANY,
),
),
(
# invalid: tables key missing
[{"query": "select * from table_name"}],
SyncRuleValidationResult(
SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=ANY,
),
),
(
# invalid: invalid key
[
{
"tables": "table_name",
"query": "select * from table_name",
}
],
SyncRuleValidationResult(
SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=ANY,
),
),
(
# invalid: tables can be empty
[
{
"tables": [],
"query": "select * from table_name",
}
],
SyncRuleValidationResult(
SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=ANY,
),
),
],
)
@pytest.mark.asyncio
async def test_advanced_rules_validation(advanced_rules, expected_validation_result):
async with create_source(
PostgreSQLDataSource, database="xe", tables="*", schema="public", port=5432
) as source:
with patch.object(AsyncEngine, "connect", return_value=ConnectionAsync()):
validation_result = await PostgreSQLAdvancedRulesValidator(source).validate(
advanced_rules
)
assert validation_result == expected_validation_result
@pytest.mark.asyncio
async def test_get_docs():
# Setup
async with create_postgresql_source() as source:
with patch.object(AsyncEngine, "connect", return_value=ConnectionAsync()):
source.engine = create_async_engine(POSTGRESQL_CONNECTION_STRING)
actual_response = []
expected_response = [
{
"public_emp_table_ids": 1,
"public_emp_table_names": "abcd",
"_id": "xe_public_emp_table_1",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": "emp_table",
"schema": "public",
},
{
"public_emp_table_ids": 2,
"public_emp_table_names": "xyz",
"_id": "xe_public_emp_table_2",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": "emp_table",
"schema": "public",
},
]
# Execute
async for doc in source.get_docs():
actual_response.append(doc[0])
# Assert
assert actual_response == expected_response
@pytest.mark.parametrize(
"filtering, expected_response",
[
# Configured valid query
(
Filter(
{
ADVANCED_SNIPPET: {
"value": [
{
"tables": ["emp_table"],
"query": "select * from emp_table",
},
]
}
}
),
[
{
"public_emp_table_ids": 1,
"public_emp_table_names": "abcd",
"_id": "xe_public_emp_table_1",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": ["emp_table"],
"schema": "public",
},
{
"public_emp_table_ids": 2,
"public_emp_table_names": "xyz",
"_id": "xe_public_emp_table_2",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": ["emp_table"],
"schema": "public",
},
],
),
(
# Configured multiple rules
Filter(
{
ADVANCED_SNIPPET: {
"value": [
{
"tables": ["emp_table"],
"query": "select * from emp_table",
},
{"tables": ["customer"], "query": "select * from customer"},
]
}
}
),
[
{
"public_emp_table_ids": 1,
"public_emp_table_names": "abcd",
"_id": "xe_public_emp_table_1",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": ["emp_table"],
"schema": "public",
},
{
"public_emp_table_ids": 2,
"public_emp_table_names": "xyz",
"_id": "xe_public_emp_table_2",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": ["emp_table"],
"schema": "public",
},
{
"public_customer_ids": 1,
"public_customer_names": "customer_1",
"_id": "xe_public_customer_1",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": ["customer"],
"schema": "public",
},
{
"public_customer_ids": 2,
"public_customer_names": "customer_2",
"_id": "xe_public_customer_2",
"_timestamp": "2023-02-21T08:37:15+00:00",
"database": "xe",
"table": ["customer"],
"schema": "public",
},
],
),
],
)
@pytest.mark.asyncio
async def test_get_docs_with_advanced_rules(filtering, expected_response):
async with create_source(
PostgreSQLDataSource,
database="xe",
tables="*",
schema="public",
port=5432,
) as source:
with patch.object(AsyncEngine, "connect", return_value=ConnectionAsync()):
actual_response = []
async for doc in source.get_docs(filtering=filtering):
actual_response.append(doc[0])
assert actual_response == expected_response