-
Notifications
You must be signed in to change notification settings - Fork 33
/
test_db.py
730 lines (550 loc) · 23 KB
/
test_db.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
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
import datetime
from typing import Any, Dict, Optional
from unittest import TestCase
from unittest.mock import MagicMock, patch
import httpx
try:
from unittest import IsolatedAsyncioTestCase
except ImportError:
from mock.backports import IsolatedAsyncioTestCase
try:
from unittest.mock import AsyncMock
except ImportError:
from mock import AsyncMock
from pinotdb import db, exceptions
class ConnectionTest(TestCase):
def test_starts_without_session_by_default(self):
connection = db.Connection()
self.assertIsNone(connection.session)
self.assertFalse(connection.is_session_external)
def test_verifies_httpx_session_upon_initializing_if_provided(self):
client = httpx.Client()
connection = db.Connection(session=client)
self.assertIs(connection.session, client)
self.assertTrue(connection.is_session_external)
def test_verifies_httpx_session(self):
client = httpx.Client()
connection = db.Connection()
connection.session = client
connection.verify_session()
# All good, no errors.
def test_fails_to_verify_session_if_unexpected_type(self):
connection = db.Connection()
connection.session = object()
with self.assertRaises(AssertionError):
connection.verify_session()
def test_bypasses_verification_if_no_session_initialized(self):
connection = db.Connection()
connection.verify_session()
def test_gets_cursor_from_connection(self):
connection = db.Connection(host='localhost')
cursor = connection.cursor()
self.assertIsInstance(cursor, db.Cursor)
def test_gets_cursor_from_connection_with_explicit_session(self):
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
connection.session.is_closed = False
cursor = connection.cursor()
self.assertIsInstance(cursor, db.Cursor)
def test_renews_session_if_closed_when_getting_cursor(self):
connection = db.Connection(host='localhost')
connection.cursor()
session1 = connection.session
session1.close()
connection.cursor()
session2 = connection.session
self.assertIsNot(session1, session2)
def test_starts_not_closed(self):
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
cursor = connection.cursor()
self.assertFalse(connection.closed)
self.assertFalse(cursor.closed)
def test_closes_connection(self):
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
cursor = connection.cursor()
connection.close()
self.assertTrue(connection.closed)
self.assertTrue(cursor.closed)
def test_closes_connection_even_if_cursor_already_closed(self):
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
cursor = connection.cursor()
cursor.close()
connection.close()
self.assertTrue(connection.closed)
self.assertTrue(cursor.closed)
def test_closes_underlying_session_as_well(self):
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
# Just to simulate an implicitly created session.
connection.is_session_external = False
connection.close()
self.assertTrue(connection.session.close.called)
def test_cant_close_connection_twice(self):
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
connection.close()
with self.assertRaises(exceptions.Error):
connection.close()
def test_commits_nothing(self):
"""
This is just a sanity test, to make sure we follow the expected
interface.
"""
connection = db.Connection()
connection.commit()
def test_executes_a_statement(self):
"""
This test tests whether the library is capable of executing statements
against Pinot by sending requests to it via its API endpoints.
With this test we're not yet focusing on how the request format or
anything like that, since it's not the Connection's responsibility to
do that.
"""
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
connection.session.is_closed = False
response = connection.session.post.return_value
response.json.return_value = {
'numServersResponded': 1,
'numServersQueried': 1,
}
response.status_code = 200
cursor = connection.execute('some statement')
self.assertIsInstance(cursor, db.Cursor)
def test_uses_cursor_in_context_manager_block(self):
connection = db.Connection(
host='localhost', session=MagicMock(spec=httpx.Client))
connection.session.is_closed = False
with connection as cursor:
self.assertIsInstance(cursor, db.Cursor)
self.assertFalse(cursor.closed)
self.assertTrue(cursor.closed)
def test_connects_sync_via_function(self):
connection = db.connect(
host='localhost', session=MagicMock(spec=httpx.Client))
self.assertIsInstance(connection, db.Connection)
class AsyncConnectionTest(IsolatedAsyncioTestCase):
def test_starts_without_session_by_default(self):
connection = db.AsyncConnection()
self.assertIsNone(connection.session)
self.assertFalse(connection.is_session_external)
def test_verifies_httpx_session_upon_initializing_if_provided(self):
client = httpx.AsyncClient()
connection = db.AsyncConnection(session=client)
self.assertIs(connection.session, client)
self.assertTrue(connection.is_session_external)
def test_verifies_httpx_session(self):
client = httpx.AsyncClient()
connection = db.AsyncConnection()
connection.session = client
connection.verify_session()
# All good, no errors.
def test_fails_to_verify_session_if_unexpected_type(self):
connection = db.AsyncConnection()
connection.session = object()
with self.assertRaises(AssertionError):
connection.verify_session()
def test_bypasses_verification_if_no_session_initialized(self):
connection = db.AsyncConnection()
connection.verify_session()
async def test_uses_cursor_in_context_manager_block(self):
connection = db.AsyncConnection(
host='localhost', session=MagicMock(spec=httpx.AsyncClient))
connection.session.is_closed = False
async with connection as cursor:
self.assertIsInstance(cursor, db.AsyncCursor)
self.assertFalse(cursor.closed)
self.assertTrue(cursor.closed)
async def test_renews_session_if_closed_when_getting_cursor(self):
connection = db.AsyncConnection(host='localhost')
connection.cursor()
session1 = connection.session
await session1.aclose()
connection.cursor()
session2 = connection.session
self.assertIsNot(session1, session2)
async def test_closes_connection_even_if_cursor_already_closed(self):
connection = db.AsyncConnection(
host='localhost', session=MagicMock(spec=httpx.AsyncClient))
cursor = connection.cursor()
await cursor.close()
await connection.close()
self.assertTrue(connection.closed)
self.assertTrue(cursor.closed)
async def test_closes_underlying_session_as_well(self):
connection = db.AsyncConnection(
host='localhost', session=MagicMock(spec=httpx.AsyncClient))
# Just to simulate an implicitly created session.
connection.is_session_external = False
await connection.close()
self.assertTrue(connection.session.aclose.called)
async def test_executes_a_statement(self):
"""
This test tests whether the library is capable of executing statements
against Pinot by sending requests to it via its API endpoints.
With this test we're not yet focusing on the request format or
anything like that, since it's not the Connection's responsibility to
do that.
"""
connection = db.AsyncConnection(
host='localhost', session=AsyncMock(spec=httpx.AsyncClient))
connection.session.is_closed = False
response = connection.session.post.return_value
response.json = MagicMock()
response.json.return_value = {
'numServersResponded': 1,
'numServersQueried': 1,
}
response.status_code = 200
cursor = await connection.execute('some statement')
self.assertIsInstance(cursor, db.AsyncCursor)
def test_connects_async_via_function(self):
connection = db.connect_async()
self.assertIsInstance(connection, db.AsyncConnection)
class CursorTest(TestCase):
def create_cursor(
self, result_table: Optional[Dict[str, Any]] = None,
status_code: int = 200, debug: bool = False,
extra_payload: Optional[Dict[str, Any]] = None,
username: Optional[str] = None,
password: Optional[str] = None,
preserve_types: bool = False,
) -> db.Cursor:
cursor = db.Cursor(
host='localhost', session=MagicMock(spec=httpx.Client),
debug=debug, username=username, password=password,
preserve_types=preserve_types,
)
cursor.session.is_closed = False
response = cursor.session.post.return_value
payload = {
'numServersResponded': 1,
'numServersQueried': 1,
}
if result_table is not None:
payload['resultTable'] = result_table
if extra_payload:
payload.update(extra_payload)
response.json.return_value = payload
response.status_code = status_code
return cursor
def test_instantiates_with_basic_url(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
self.assertEqual(cursor.url, 'http://localhost:8099/query/sql')
def test_instantiates_with_auth(self):
cursor = db.Cursor(
host='localhost', session=httpx.Client(),
username='john', password='my-pass')
self.assertIsInstance(cursor.auth, httpx.DigestAuth)
def test_fixes_query_path_when_instantiating(self):
cursor = db.Cursor(
host='localhost', path='query', session=httpx.Client())
self.assertEqual(cursor.url, 'http://localhost:8099/query/sql')
def test_instantiates_with_extra_headers(self):
cursor = db.Cursor(
host='localhost', session=httpx.Client(),
extra_request_headers='foo=bar,baz=yo')
self.assertEqual(cursor.session.headers['foo'], 'bar')
self.assertEqual(cursor.session.headers['baz'], 'yo')
def test_checks_valid_exception_if_not_containing_error_code(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
self.assertTrue(cursor.is_valid_exception({}))
def test_checks_valid_exception_if_error_code_not_ignored(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
self.assertTrue(cursor.is_valid_exception({
'errorCode': 123,
}))
def test_checks_invalid_exception_if_error_code_ignored(self):
cursor = db.Cursor(
host='localhost', session=httpx.Client(),
ignore_exception_error_codes='123,234')
self.assertFalse(cursor.is_valid_exception({
'errorCode': 123,
}))
def test_cant_close_connection_twice(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
cursor.close()
with self.assertRaises(exceptions.Error):
cursor.close()
def test_closes_underlying_session_as_well(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
cursor.close()
self.assertTrue(cursor.session.is_closed)
def test_bypasses_session_close_if_already_closed(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
cursor.session.close()
cursor.close()
def test_checks_sufficient_responded_0_queried_0_responded(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
cursor.check_sufficient_responded('foo', 0, 0)
def test_checks_sufficient_responded_min1_queried_min1_responded(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
with self.assertRaises(exceptions.DatabaseError):
cursor.check_sufficient_responded('foo', -1, -1)
def test_checks_sufficient_responded_3_queried_3_responded(self):
cursor = db.Cursor(host='localhost', session=httpx.Client())
cursor.check_sufficient_responded('foo', 3, 3)
def test_checks_sufficient_responded_5_queried_3_responded(self):
cursor = db.Cursor(
host='localhost', session=httpx.Client(),
acceptable_respond_fraction=2)
cursor.check_sufficient_responded('foo', 5, 3)
def test_checks_sufficient_responded_4_queried_half_responded(self):
cursor = db.Cursor(
host='localhost', session=httpx.Client(),
acceptable_respond_fraction=0.5)
cursor.check_sufficient_responded('foo', 4, 2)
def test_checks_sufficient_responded_but_zero_needed(self):
cursor = db.Cursor(
host='localhost', session=httpx.Client(),
acceptable_respond_fraction=0)
cursor.check_sufficient_responded('foo', 10, 0)
def test_does_not_allow_fetching_if_not_executed_yet(self):
cursor = db.Cursor(
host='localhost', session=httpx.Client())
with self.assertRaises(exceptions.Error):
cursor.fetchone()
def test_executes_query_within_session_with_empty_results(self):
cursor = self.create_cursor()
cursor.execute('some statement')
results = list(iter(cursor))
self.assertEqual(results, [])
cursor.session.post.assert_called_once_with(
'http://localhost:8099/query/sql', json={'sql': 'some statement'})
def test_executes_query_within_session_with_query_options(self):
cursor = self.create_cursor()
cursor.execute('some statement', queryOptions={'foo': 'bar'})
results = list(iter(cursor))
self.assertEqual(results, [])
cursor.session.post.assert_called_once_with(
'http://localhost:8099/query/sql', json={
'sql': 'some statement', 'queryOptions': {'foo': 'bar'}})
def test_executes_query_preserving_types(self):
cursor = self.create_cursor(preserve_types=True)
cursor.execute('some statement')
results = list(iter(cursor))
self.assertEqual(results, [])
cursor.session.post.assert_called_once_with(
'http://localhost:8099/query/sql',
json={'sql': "some statement OPTION(preserveType='true')"})
def test_executes_query_with_complex_results(self):
data = [
('age', 'INT', 12),
('name', 'STRING', 'John'),
('is_old', 'BOOLEAN', False),
('born_at', 'TIMESTAMP', '2010-01-01T00:30'),
('extras', 'JSON', '{"foo": "bar"}'),
('pet_peeve', 'UNKNOWN', 'bicycles'),
]
cursor = self.create_cursor({
'dataSchema': {
'columnNames': [d[0] for d in data],
'columnDataTypes': [d[1] for d in data],
},
'rows': [
[d[2] for d in data],
],
})
cursor.execute('some statement')
results = list(iter(cursor))
self.assertEqual(results, [
[12, 'John', False, datetime.datetime(2010, 1, 1, 0, 30),
{'foo': 'bar'}, '"bicycles"'],
])
def test_executes_query_with_simple_results(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': ['age'],
'columnDataTypes': ['INT'],
},
'rows': [
[12],
],
})
cursor.execute('some statement')
results = list(iter(cursor))
self.assertEqual(results, [
[12],
])
def test_executes_query_with_none(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': ['age'],
'columnDataTypes': ['UNKNOWN'],
},
'rows': [
[None],
],
})
cursor.execute('some statement')
results = list(iter(cursor))
self.assertEqual(results, [
[None],
])
def test_executes_query_with_auth(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': ['age'],
'columnDataTypes': ['INT'],
},
'rows': [
[1],
],
}, username='john.doe', password='mypass')
cursor.execute('some statement')
cursor.session.post.assert_called_once_with(
'http://localhost:8099/query/sql',
json={'sql': 'some statement'},
auth=(b'john.doe', b'mypass'),
)
def test_raises_database_error_if_problem_with_json(self):
cursor = db.Cursor(
host='localhost', session=MagicMock(spec=httpx.Client))
cursor.session.is_closed = False
response = cursor.session.post.return_value
response.json.side_effect = ValueError()
response.status_code = 200
with self.assertRaises(exceptions.DatabaseError):
cursor.execute('some statement')
def test_raises_database_error_if_server_exception(self):
cursor = self.create_cursor({}, extra_payload={
'exceptions': ['something', 'wrong']
})
with self.assertRaises(exceptions.DatabaseError):
cursor.execute('some statement')
def test_raises_database_error_if_no_column_names(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': [],
'columnDataTypes': [],
},
'rows': [],
})
with self.assertRaises(exceptions.DatabaseError):
cursor.execute('some statement')
def test_executes_query_with_results_and_debug_enabled(self):
data = [
('age', 'INT', 12),
]
cursor = self.create_cursor({
'dataSchema': {
'columnNames': [d[0] for d in data],
'columnDataTypes': [d[1] for d in data],
},
'rows': [
[d[2] for d in data],
],
}, debug=True)
with patch.object(db, 'logger') as mock_logger:
cursor.execute('some statement')
self.assertGreater(len(mock_logger.info.mock_calls), 0)
def test_raises_exception_if_error_in_status_code(self):
cursor = self.create_cursor({}, status_code=400)
with self.assertRaises(exceptions.ProgrammingError):
cursor.execute('some statement')
def test_cannot_execute_many(self):
cursor = self.create_cursor({})
with self.assertRaises(exceptions.NotSupportedError):
cursor.executemany('some statement')
def test_fetches_many_results(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': ['age'],
'columnDataTypes': ['INT'],
},
'rows': [[1], [2], [3]],
})
cursor.execute('some statement')
self.assertEqual(cursor.fetchmany(2), [[1], [2]])
def test_fetches_all_results(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': ['age'],
'columnDataTypes': ['INT'],
},
'rows': [[1], [2], [3]],
})
cursor.execute('some statement')
self.assertEqual(cursor.fetchall(), [[1], [2], [3]])
def test_fetches_with_schema(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': ['age'],
'columnDataTypes': ['INT'],
},
'rows': [[1]],
})
cursor.execute('some statement')
self.assertEqual(cursor.fetchwithschema(), {
'results': [[1]],
'schema': [{'name': 'age', 'type': 'INT'}]
})
def test_does_nothing_for_setinputsizes(self):
cursor = self.create_cursor()
cursor.setinputsizes(123)
# All good, nothing happened
def test_does_nothing_for_setoutputsizes(self):
cursor = self.create_cursor()
cursor.setoutputsizes(123)
# All good, nothing happened
class AsyncCursorTest(IsolatedAsyncioTestCase):
def create_cursor(
self, result_table: Optional[Dict[str, Any]] = None,
status_code: int = 200, debug: bool = False,
extra_payload: Optional[Dict[str, Any]] = None,
username: Optional[str] = None,
password: Optional[str] = None,
preserve_types: bool = False,
) -> db.AsyncCursor:
cursor = db.AsyncCursor(
host='localhost', session=AsyncMock(spec=httpx.AsyncClient),
debug=debug, username=username, password=password,
preserve_types=preserve_types,
)
cursor.session.is_closed = False
payload = {
'numServersResponded': 1,
'numServersQueried': 1,
}
if result_table is not None:
payload['resultTable'] = result_table
if extra_payload:
payload.update(extra_payload)
response = httpx.Response(200, json=payload)
cursor.session.post.return_value = response
return cursor
async def test_executes_query_with_auth(self):
cursor = self.create_cursor({
'dataSchema': {
'columnNames': ['age'],
'columnDataTypes': ['INT'],
},
'rows': [
[1],
],
}, username='john.doe', password='mypass')
await cursor.execute('some statement')
cursor.session.post.assert_called_once_with(
'http://localhost:8099/query/sql',
json={'sql': 'some statement'},
auth=(b'john.doe', b'mypass'),
)
class EscapeTest(TestCase):
def test_escapes_asterisk(self):
self.assertEqual(db.escape('*'), '*')
def test_escapes_string(self):
self.assertEqual(db.escape("what 'foo' means"), "'what ''foo'' means'")
def test_escapes_int(self):
self.assertEqual(db.escape(1), 1)
def test_escapes_float(self):
self.assertEqual(db.escape(1.0), 1.0)
def test_escapes_bool(self):
self.assertEqual(db.escape(True), 'TRUE')
self.assertEqual(db.escape(False), 'FALSE')
def test_escapes_list(self):
self.assertEqual(db.escape([1, 'two']), "1, 'two'")
def test_bypasses_escaping_unknown_types(self):
self.assertEqual(db.escape({1, 2}), {1, 2})