forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_redis.py
389 lines (333 loc) · 12.4 KB
/
test_redis.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
#
# 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.
#
import json
from contextlib import asynccontextmanager
from unittest import mock
from unittest.mock import ANY, AsyncMock, Mock
import pytest
import redis
from freezegun import freeze_time
from connectors.filtering.validation import SyncRuleValidationResult
from connectors.protocol import Filter
from connectors.source import ConfigurableFieldValueError
from connectors.sources.redis import (
RedisAdvancedRulesValidator,
RedisDataSource,
)
from tests.commons import AsyncIterator
from tests.sources.support import create_source
ADVANCED_SNIPPET = "advanced_snippet"
DOCUMENTS = [
{
"_id": "aa00c4c0f44c5cb7cad68df40e8f8877",
"key": "0",
"value": "this is value",
"size_in_bytes": 10,
"database": 0,
"key_type": "string",
"_timestamp": "2023-01-24T04:07:19+00:00",
}
]
class RedisClientMock:
async def execute_command(self, SELECT="JSON.GET", key="json_key"):
return json.dumps({"1": "1", "2": "2"})
async def zrange(self, key, start, skip, withscores=True):
return {1, 2, 3}
async def smembers(self, key):
return {1, 2, 3}
async def get(self, key):
return "this is value"
async def hgetall(self, key):
return "hash"
async def xread(self, key):
return "stream"
async def lrange(self, key, start, skip):
return [1, 2, 3]
async def config_get(self, databases):
return {"databases": "1"}
async def ping(self):
return False
async def aclose(self):
return True
async def type(self, key): # NOQA
return "string"
async def memory_usage(self, key):
return 10
async def scan_iter(self, match, count, _type):
yield "0"
async def validate_database(self, db=0):
await self.execute_command()
@asynccontextmanager
async def create_redis_source():
async with create_source(
RedisDataSource,
host="localhost",
port=6379,
database="0",
username="username",
password="password",
) as source:
yield source
@pytest.mark.asyncio
async def test_ping_positive():
async with create_redis_source() as source:
source.client.ping = AsyncMock()
await source.ping()
@pytest.mark.asyncio
async def test_ping_negative():
async with create_redis_source() as source:
mocked_client = AsyncMock()
with mock.patch("redis.asyncio.from_url", return_value=mocked_client):
mocked_client.ping = AsyncMock(
side_effect=redis.exceptions.AuthenticationError
)
with pytest.raises(Exception):
await source.ping()
@pytest.mark.asyncio
async def test_validate_config_when_database_is_not_integer():
async with create_redis_source() as source:
source.client.database = ["db123", "db456"]
with mock.patch("redis.asyncio.from_url", return_value=AsyncMock()):
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_with_wrong_configuration():
async with create_redis_source() as source:
mocked_client = AsyncMock()
with mock.patch("redis.asyncio.from_url", return_value=mocked_client):
mocked_client.ping = AsyncMock(
side_effect=redis.exceptions.AuthenticationError
)
with pytest.raises(Exception):
await source.validate_config()
@pytest.mark.asyncio
async def test_validate_config_when_database_is_invalid():
async with create_redis_source() as source:
source.client.database = ["123"]
source.client.validate_database = AsyncMock(return_value=False)
with mock.patch("redis.asyncio.from_url", return_value=AsyncMock()):
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
@freeze_time("2023-01-24T04:07:19+00:00")
async def test_get_docs():
async with create_redis_source() as source:
source.client.database = [1]
with mock.patch(
"redis.asyncio.from_url",
return_value=AsyncMock(),
):
source.get_db_records = AsyncIterator(items=DOCUMENTS)
async for (doc, _) in source.get_docs():
assert doc in DOCUMENTS
@pytest.mark.asyncio
async def test_get_databases_for_multiple_db():
async with create_redis_source() as source:
source.client.database = [1, 2]
async for database in source.client.get_databases():
assert database in [1, 2]
@pytest.mark.asyncio
async def test_get_databases_with_asterisk():
async with create_redis_source() as source:
source.client.database = ["*"]
source.client._client = RedisClientMock()
async for database in source.client.get_databases():
assert database == 0
@pytest.mark.asyncio
async def test_get_databases_expect_no_databases_on_auth_error():
async with create_redis_source() as source:
source.client.database = ["*"]
mocked_client = AsyncMock()
with mock.patch("redis.asyncio.from_url", return_value=mocked_client):
mocked_client.ping = AsyncMock(
side_effect=redis.exceptions.AuthenticationError
)
async for database in source.client.get_databases():
assert database == []
@pytest.mark.asyncio
@pytest.mark.parametrize(
"key, key_type, expected_response",
[
("json_key", "ReJSON-RL", {"1": "1", "2": "2"}),
("string_key", "string", "this is value"),
("list_key", "list", [1, 2, 3]),
("set_key", "set", {1, 2, 3}),
("sorted_set_key", "zset", {1, 2, 3}),
("hash_key", "hash", "hash"),
("stream_key", "stream", "stream"),
],
)
async def test_get_key_value(key, key_type, expected_response):
async with create_redis_source() as source:
source.client.database = ["*"]
source.client._client = RedisClientMock()
value = await source.client.get_key_value(key=key, key_type=key_type)
assert value == expected_response
@pytest.mark.asyncio
@freeze_time("2023-01-24T04:07:19+00:00")
async def test_get_key_metadata():
async with create_redis_source() as source:
source.client._client = RedisClientMock()
key_type, value, size = await source.client.get_key_metadata(key="0")
assert key_type == "string"
assert value == "this is value"
assert size == 10
@pytest.mark.asyncio
@freeze_time("2023-01-24T04:07:19+00:00")
async def test_get_db_records():
async with create_redis_source() as source:
source.client._client = RedisClientMock()
source.client.get_paginated_key = AsyncIterator(["0"])
async for record in source.get_db_records(db=0):
assert record == DOCUMENTS[0]
@pytest.mark.parametrize(
"filtering",
[
Filter(
{
ADVANCED_SNIPPET: {
"value": [
{"database": 0, "key_pattern": "0*", "type": "string"},
]
}
}
),
],
)
@pytest.mark.asyncio
@freeze_time("2023-01-24T04:07:19+00:00")
async def test_get_docs_with_sync_rules(filtering):
async with create_redis_source() as source:
source.client.database = ["*"]
source.client._client = Mock()
source.client._client.scan_iter = AsyncIterator(["0"])
source.client._client.execute_command = AsyncMock(return_value=True)
source.client._client.type = AsyncMock(return_value="string")
source.client._client.get = AsyncMock(return_value="this is value")
source.client._client.memory_usage = AsyncMock(return_value=10)
async for (doc, _) in source.get_docs(filtering):
assert doc in DOCUMENTS
source.client._client.scan_iter.assert_called_once_with(
match="0*", count=1000, _type="string"
)
@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: one custom pattern
[{"database": 0, "key_pattern": "*"}],
SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
),
),
(
# valid: two custom patterns
[
{"database": 0, "key_pattern": "test*"},
{"database": 1, "type": "string"},
],
SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
),
),
(
# invalid: database number
[{"database": -1}],
SyncRuleValidationResult(
SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=ANY,
),
),
(
# invalid: array of arrays -> wrong type
{"database": ["a/b/c", ""]},
SyncRuleValidationResult(
SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=ANY,
),
),
(
# invalid database name
{"database": 0, "key_pattern": "abc*"},
SyncRuleValidationResult(
SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=ANY,
),
),
(
# invalid: key_pattern or type is missing
{"database": 0},
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_redis_source() as source:
source.client._client = RedisClientMock()
validation_result = await RedisAdvancedRulesValidator(source).validate(
advanced_rules
)
assert validation_result == expected_validation_result
@pytest.mark.asyncio
async def test_client_when_mutual_ssl_enabled():
async with create_redis_source() as source:
source.client.database = ["*"]
source.client.ssl_enabled = True
source.client.mutual_tls_enabled = True
source.client.store_ssl_key = Mock(return_value="/tmp/tmp4vn0jxy7.crt")
with mock.patch(
"redis.asyncio.from_url",
return_value=AsyncMock(),
) as from_url_mock:
_ = source.client._client
connection_string = "rediss://username:password@localhost:6379?ssl_certfile=/tmp/tmp4vn0jxy7.crt&ssl_keyfile=/tmp/tmp4vn0jxy7.crt"
from_url_mock.assert_called_with(connection_string, decode_responses=True)
@pytest.mark.asyncio
async def test_client_when_ssl_enabled():
async with create_redis_source() as source:
source.client.database = ["*"]
source.client.ssl_enabled = True
with mock.patch(
"redis.asyncio.from_url",
return_value=AsyncMock(),
) as from_url_mock:
_ = source.client._client
connection_string = "rediss://username:password@localhost:6379"
from_url_mock.assert_called_with(connection_string, decode_responses=True)
@pytest.mark.asyncio
async def test_ping_when_mutual_ssl_enabled():
async with create_redis_source() as source:
source.client.database = ["*"]
source.client.ssl_enabled = True
source.client.mutual_tls_enabled = True
with mock.patch(
"redis.asyncio.from_url",
return_value=AsyncMock(),
):
await source.ping()
source.client._redis_client.ping.assert_awaited_once()