-
Notifications
You must be signed in to change notification settings - Fork 3
/
tests.py
2293 lines (1835 loc) · 86.4 KB
/
tests.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
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
import functools
import os
import sys
import threading
import unittest
import warnings
try:
import msgpack
except ImportError:
msgpack = None
from kt import EmbeddedServer
from kt import EmbeddedTokyoTyrantServer
from kt import KT_BINARY
from kt import KT_MSGPACK
from kt import KT_JSON
from kt import KT_NONE
from kt import KT_PICKLE
from kt import KyotoTycoon
from kt import QueryBuilder
from kt import TokyoTyrant
from kt import TT_TABLE
from kt import constants
from kt.queue import Queue
class BaseTestCase(unittest.TestCase):
_server = None
db = None
lua_path = os.path.join(os.path.dirname(__file__), 'kt/scripts/')
server = None
server_kwargs = None
@classmethod
def setUpClass(cls):
if cls.server is None:
return
if sys.version_info[0] > 2:
warnings.filterwarnings(action='ignore', message='unclosed',
category=ResourceWarning)
kwargs = {'quiet': True}
if cls.server_kwargs:
kwargs.update(cls.server_kwargs)
cls._server = cls.server(**kwargs)
cls._server.run()
cls.db = cls._server.client
@classmethod
def tearDownClass(cls):
if cls._server is not None:
cls._server.stop()
cls.db.close()
cls.db = None
def tearDown(self):
if self.db is not None:
self.db.clear()
@classmethod
def get_embedded_server(cls):
if self.server is None:
raise NotImplementedError
class KyotoTycoonTests(object):
def test_basic_operations(self):
"""
Test operations of the KyotoTycoon client.
This class wraps two protocol handlers - binary and HTTP protocols. The
interface exposes a super-set of the methods available, preferring the
bulk/binary APIs where possible.
Note: protocols are also tested individually.
"""
self.assertEqual(len(self.db), 0)
# Test basic set and get.
self.db.set('k1', 'v1')
self.assertEqual(self.db.get('k1'), 'v1')
self.assertTrue(self.db.get('kx') is None)
# Test setting bulk data returns records set.
nkeys = self.db.set_bulk({'k1': 'v1-x', 'k2': 'v2', 'k3': 'v3'})
self.assertEqual(nkeys, 3)
# Test getting bulk data returns dict of just existing keys.
self.assertEqual(self.db.get_bulk(['k1', 'k2', 'k3', 'kx']),
{'k1': 'v1-x', 'k2': 'v2', 'k3': 'v3'})
# Test removing a record returns number of rows removed.
self.assertEqual(self.db.remove('k1'), 1)
self.assertEqual(self.db.remove('k1'), 0)
self.db['k1'] = 'v1'
self.assertTrue(self.db.exists('k1'))
self.assertEqual(self.db.length('k1'), 2)
self.assertEqual(self.db.remove_bulk(['k1', 'k3', 'kx']), 2)
self.assertEqual(self.db.remove_bulk([]), 0)
self.assertEqual(self.db.remove_bulk(['k2']), 1)
self.assertFalse(self.db.exists('k1'))
self.assertTrue(self.db.length('k1') is None)
self.db.append('key', 'abc')
self.db.append('key', 'def')
self.assertEqual(self.db['key'], 'abcdef')
# Test atomic replace and pop.
self.assertTrue(self.db.replace('key', 'xyz'))
self.assertEqual(self.db.seize('key'), 'xyz')
self.assertFalse(self.db.seize('key'))
self.assertFalse(self.db.replace('key', 'abc'))
self.assertTrue(self.db.add('key', 'foo'))
self.assertFalse(self.db.add('key', 'bar'))
self.assertEqual(self.db['key'], 'foo')
# Test compare-and-swap.
self.assertTrue(self.db.cas('key', 'foo', 'baz'))
self.assertFalse(self.db.cas('key', 'foo', 'bar'))
self.assertEqual(self.db['key'], 'baz')
# Test dict interface.
self.assertTrue('key' in self.db)
self.assertFalse('other' in self.db)
self.assertEqual(len(self.db), 1)
self.assertEqual(self.db.count(), 1)
self.db['k1'] = 'v1'
self.db.update({'k2': 'v2', 'k3': 'v3'})
self.assertEqual(self.db.pop('k1'), 'v1')
self.assertTrue(self.db.pop('k1') is None)
self.assertEqual(sorted(list(self.db)), ['k2', 'k3', 'key'])
del self.db['k3']
self.assertEqual(sorted(list(self.db.keys())), ['k2', 'key'])
self.assertEqual(sorted(list(self.db.values())), ['baz', 'v2'])
self.assertEqual(sorted(list(self.db.items())),
[('k2', 'v2'), ('key', 'baz')])
# Test matching.
self.assertEqual(sorted(self.db.match_prefix('k')), ['k2', 'key'])
self.assertEqual(self.db.match_regex('k[0-9]'), ['k2'])
self.assertEqual(self.db.match_regex('x\d'), [])
self.assertEqual(self.db.match_similar('k'), ['k2'])
self.assertEqual(sorted(self.db.match_similar('k', 2)), ['k2', 'key'])
# Test numeric operations.
self.assertEqual(self.db.incr('n'), 1)
self.assertEqual(self.db.incr('n', 3), 4)
self.assertEqual(self.db.incr_double('nd'), 1.)
self.assertEqual(self.db.incr_double('nd', 2.5), 3.5)
def test_noreply(self):
self.assertTrue(self.db.set('k1', 'v1', no_reply=True) is None)
self.assertEqual(self.db.get('k1'), 'v1')
self.assertTrue(self.db.remove('k1', no_reply=True) is None)
self.assertTrue(self.db.get('k1') is None)
self.assertTrue(self.db.set_bulk({'k1': 'v1'}, no_reply=True) is None)
self.assertEqual(self.db.get('k1'), 'v1')
self.assertTrue(self.db.remove_bulk(['k1'], no_reply=True) is None)
self.assertTrue(self.db.get('k1') is None)
def test_get_bytes(self):
self.db['k1'] = b'v1'
self.db['k2'] = b'\xff\x00\xff'
self.assertEqual(self.db.get_bytes('k1'), b'v1')
self.assertEqual(self.db.get_bytes('k2'), b'\xff\x00\xff')
self.assertEqual(self.db.get_bulk(['k1', 'k2'], decode_values=False), {
'k1': b'v1', 'k2': b'\xff\x00\xff'})
def test_large_read_write(self):
long_str = 'a' * (1024 * 1024 * 32) # 32MB string.
self.db['key'] = long_str
self.assertEqual(self.db['key'], long_str)
del self.db['key']
self.assertEqual(len(self.db), 0)
def test_protocol_binary(self):
self._test_protocol(self.db._protocol)
def test_http(self):
self._test_protocol(self.db._http)
def _test_protocol(self, p):
# Both protocols support some basic methods, which we will test (namely
# get/set/remove and their bulk equivalents).
self.assertEqual(self.db.count(), 0)
# Test basic set and get.
p.set('k1', 'v1', 0, None)
self.assertEqual(p.get('k1', 0), 'v1')
self.assertTrue(p.get('kx', 0) is None)
# Test setting bulk data returns records set.
nkeys = p.set_bulk({'k1': 'v1-x', 'k2': 'v2', 'k3': 'v3'}, 0, None)
self.assertEqual(nkeys, 3)
# Test getting bulk data returns dict of just existing keys.
self.assertEqual(p.get_bulk(['k1', 'k2', 'k3', 'kx'], 0),
{'k1': 'v1-x', 'k2': 'v2', 'k3': 'v3'})
# Test removing a record returns number of rows removed.
self.assertEqual(p.remove('k1', 0), 1)
self.assertEqual(p.remove('k1', 0), 0)
p.set('k1', 'v1', 0, None)
self.assertEqual(p.remove_bulk(['k1', 'k3', 'kx'], 0), 2)
self.assertEqual(p.remove_bulk([], 0), 0)
self.assertEqual(p.remove_bulk(['k2'], 0), 1)
def test_http_protocol_special(self):
p = self.db._http
p.append('key', 'abc', 0, None)
p.append('key', 'def', 0, None)
self.assertEqual(p.get('key', 0), 'abcdef')
# Test atomic replace and pop.
self.assertTrue(p.replace('key', 'xyz', 0, None))
self.assertEqual(p.seize('key', 0), 'xyz')
self.assertFalse(p.seize('key', 0))
self.assertFalse(p.replace('key', 'abc', 0, None))
self.assertTrue(p.add('key', 'foo', 0, None))
self.assertFalse(p.add('key', 'bar', 0, None))
self.assertEqual(p.get('key', 0), 'foo')
# Test compare-and-swap.
self.assertTrue(p.cas('key', 'foo', 'baz', 0, None))
self.assertFalse(p.cas('key', 'foo', 'bar', 0, None))
self.assertEqual(p.get('key', 0), 'baz')
self.assertTrue(p.check('key', 0))
self.assertFalse(p.check('other', 0))
self.assertEqual(p.count(), 1)
# Test numeric operations.
self.assertEqual(p.increment('n'), 1)
self.assertEqual(p.increment('n', 3, 0, None), 4)
self.assertEqual(p.increment_double('nd'), 1.)
self.assertEqual(p.increment_double('nd', 2.5, 0, None), 3.5)
# Flush db.
p.clear()
# Test bulk operations with and without atomic.
for atomic in (False, True):
accum = {}
keys = []
for i in range(100):
accum['k%064d' % i] = '%01024d' % i
keys.append('k%064d' % i)
self.assertEqual(p.set_bulk(accum, 0, None, atomic=atomic), 100)
resp = p.get_bulk(keys, 0, atomic=atomic)
self.assertEqual(resp, accum)
self.assertEqual(p.remove_bulk(keys, 0, atomic=atomic), 100)
# Set some data for matching tests.
p.set_bulk(dict(('k%04d' % i, 'v%01024d' % i) for i in range(100)), 0)
keys = ['k%04d' % i for i in range(100)]
# Test matching.
self.assertEqual(sorted(p.match_prefix('k')), keys)
self.assertEqual(sorted(p.match_regex('k00[25]3')), ['k0023', 'k0053'])
self.assertEqual(p.match_regex('x\d'), [])
self.assertEqual(p.match_similar('k0022'), [
'k0022', # Exact match is always first, regardless of storage.
'k0002', 'k0012',
'k0020', 'k0021', 'k0023', 'k0024', 'k0025', 'k0026', 'k0027',
'k0028', 'k0029', 'k0032', 'k0042', 'k0052', 'k0062', 'k0072',
'k0082', 'k0092'])
class TestKyotoTycoonHash(KyotoTycoonTests, BaseTestCase):
server = EmbeddedServer
server_kwargs = {'database': '*'}
class TestKyotoTycoonBTree(KyotoTycoonTests, BaseTestCase):
server = EmbeddedServer
server_kwargs = {'database': '%'}
class TestKyotoTycoonCursor(BaseTestCase):
server = EmbeddedServer
server_kwargs = {'database': '%'}
def setUp(self):
super(TestKyotoTycoonCursor, self).setUp()
self.db.update({'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'})
def test_multiple_cursors(self):
c1 = self.db.cursor()
c2 = self.db.cursor()
c3 = self.db.cursor()
self.assertTrue(c1.jump('k1'))
self.assertTrue(c2.jump('k2'))
self.assertTrue(c3.jump('k3'))
self.assertEqual(c1.get(), ('k1', 'v1'))
self.assertEqual(c2.get(), ('k2', 'v2'))
self.assertEqual(c3.get(), ('k3', 'v3'))
self.assertTrue(c1.step())
self.assertEqual(c1.get(), ('k2', 'v2'))
self.assertEqual(c1.seize(), ('k2', 'v2'))
self.assertEqual(c2.get(), ('k3', 'v3'))
self.assertEqual(c2.seize(), ('k3', 'v3'))
for c in (c1, c2, c3):
self.assertEqual(c.get(), ('k4', 'v4'))
self.assertTrue(c3.remove())
for c in (c1, c2, c3):
self.assertTrue(c.get() is None)
c1.jump()
self.assertEqual(c1.get(), ('k1', 'v1'))
self.assertTrue(c1.remove())
self.assertFalse(c2.jump())
def test_cursor_movement(self):
cursor = self.db.cursor()
self.assertEqual(list(cursor), [('k1', 'v1'), ('k2', 'v2'),
('k3', 'v3'), ('k4', 'v4')])
# Jumping in-between moves to closest without going under.
self.assertTrue(cursor.jump('k1x'))
self.assertEqual(cursor.key(), 'k2')
self.assertEqual(cursor.value(), 'v2')
# Jumping backwards in-between moves to closest while going over.
self.assertTrue(cursor.jump_back('k2x'))
self.assertEqual(cursor.key(), 'k2')
self.assertEqual(cursor.value(), 'v2')
# We cannot jump past the last record, but we can jump below the first.
# Similarly, we can't step_back prior to the first record.
self.assertFalse(cursor.jump('k5'))
self.assertTrue(cursor.jump('k0'))
self.assertEqual(cursor.key(), 'k1')
self.assertFalse(cursor.step_back())
# We cannot jump_back prior to the first record, but we can jump_back
# from after the last. Similarly, we can't step past the last record.
self.assertFalse(cursor.jump_back('k0'))
self.assertTrue(cursor.jump_back('k5'))
self.assertEqual(cursor.key(), 'k4')
self.assertFalse(cursor.step())
def test_cursor_write(self):
cursor = self.db.cursor()
cursor.jump('k2')
self.assertTrue(cursor.set_value('v2-x'))
self.assertEqual(cursor.get(), ('k2', 'v2-x'))
self.assertEqual(self.db['k2'], 'v2-x')
self.assertTrue(cursor.remove())
self.assertEqual(cursor.get(), ('k3', 'v3'))
self.assertFalse('k2' in self.db)
self.assertTrue(cursor.step_back())
self.assertEqual(cursor.get(), ('k1', 'v1'))
self.assertEqual(cursor.seize(), ('k1', 'v1'))
self.assertTrue(cursor.seize() is None)
self.assertFalse(cursor.is_valid())
self.assertTrue(cursor.jump())
self.assertEqual(cursor.seize(), ('k3', 'v3'))
self.assertTrue(cursor.jump_back())
self.assertEqual(cursor.get(), ('k4', 'v4'))
self.assertEqual(list(cursor), [('k4', 'v4')])
self.assertEqual(list(cursor), [('k4', 'v4')])
self.assertTrue(cursor.jump_back())
self.assertTrue(cursor.remove())
self.assertEqual(list(cursor), [])
def test_implicit_cursor_operations(self):
self.assertEqual(list(self.db.keys()), ['k1', 'k2', 'k3', 'k4'])
self.assertEqual(list(self.db.values()), ['v1', 'v2', 'v3', 'v4'])
self.assertEqual(list(self.db.items()), [
('k1', 'v1'),
('k2', 'v2'),
('k3', 'v3'),
('k4', 'v4')])
# Nonlazy.
self.assertEqual(self.db.keys_nonlazy(), ['k1', 'k2', 'k3', 'k4'])
class TestKyotoTycoonSerializers(BaseTestCase):
server = EmbeddedServer
server_kwargs = {'database': '*'}
def get_client(self, serializer):
return KyotoTycoon(self._server._host, self._server._port, serializer)
def test_serializer_binary(self):
db = self.get_client(KT_BINARY)
db.set('k1', 'v1')
db.set('k2', b'\xe1\x80\x80')
self.assertEqual(db.get('k1'), 'v1')
self.assertEqual(db.get('k2'), u'\u1000')
self.assertEqual(db.get_bulk(['k1', 'k2']),
{'k1': 'v1', 'k2': u'\u1000'})
def _test_serializer_object(self, serializer):
db = self.get_client(serializer)
obj = {'w': {'wk': 'wv'}, 'x': 0, 'y': ['aa', 'bb'], 'z': None}
db.set('k1', obj)
self.assertEqual(db.get('k1'), obj)
db.set('k2', '')
self.assertEqual(db.get('k2'), '')
self.assertEqual(db.get_bulk(['k1', 'k2']), {'k1': obj, 'k2': ''})
def test_serializer_json(self):
self._test_serializer_object(KT_JSON)
def test_serializer_pickle(self):
self._test_serializer_object(KT_PICKLE)
def test_serializer_none(self):
db = self.get_client(KT_NONE)
db.set('k1', b'v1')
self.assertEqual(self.db.get('k1'), 'v1')
db[b'k2'] = b'v2'
self.assertEqual(self.db.get_bulk([b'k1', b'k2']),
{'k1': 'v1', 'k2': 'v2'})
@unittest.skipIf(msgpack is None, 'msgpack-python not installed')
def test_serializer_msgpack(self):
db = self.get_client(KT_MSGPACK)
obj = {'w': {'wk': 'wv'}, 'x': 0, 'y': ['aa', 'bb'], b'z': None}
db.set('k1', obj)
self.assertEqual(db.get('k1'), {'w': {'wk': 'wv'}, 'x': 0,
'y': ['aa', 'bb'], b'z': None})
db.set('k2', '')
self.assertEqual(db.get('k2'), '')
db.set('k3', [u'foo', b'bar'])
self.assertEqual(db.get('k3'), [u'foo', b'bar'])
class TestKyotoTycoonScripting(BaseTestCase):
lua_script = os.path.join(BaseTestCase.lua_path, 'kt.lua')
server = EmbeddedServer
server_kwargs = {
'database': '%',
'server_args': ['-scr', lua_script]}
def test_script_set(self):
L = self.db.lua
# Test adding a single item.
self.assertEqual(L.sadd(key='s1', value='foo'), {'num': '1'})
self.assertEqual(L.sadd(key='s1', value='foo'), {'num': '0'})
# Test adding multiple items.
items = b'\x01'.join([b'bar', b'baz', b'nug'])
self.assertEqual(L.sadd(key='s1', value=items), {'num': '3'})
# Test get cardinality.
self.assertEqual(L.scard(key='s1'), {'num': '4'})
# Test membership.
self.assertEqual(L.sismember(key='s1', value='bar'), {'num': '1'})
self.assertEqual(L.sismember(key='s1', value='baze'), {'num': '0'})
keys = ['bar', 'baz', 'foo', 'nug']
# Test get members.
self.assertEqual(L.smembers(key='s1'), dict((k, '1') for k in keys))
self.assertEqual(L.scard(key='s1'), {'num': '4'})
# Test pop.
res = L.spop(key='s1')
self.assertEqual(res['num'], '1')
self.assertTrue(res['value'] in keys)
self.assertEqual(L.scard(key='s1'), {'num': '3'})
# Pop remaining 3 items.
for _ in range(3):
res = L.spop(key='s1')
self.assertTrue(res['value'] in keys)
self.assertEqual(L.scard(key='s1'), {'num': '0'})
res = L.spop(key='s1')
self.assertEqual(res, {'num': '0'})
# Restore all keys.
L.sadd(key='s1', value=b'\x01'.join(k.encode() for k in keys))
self.assertEqual(L.srem(key='s1', value='nug'), {'num': '1'})
self.assertEqual(L.srem(key='s1', value='nug'), {'num': '0'})
# Create another set, s2 {baze, foo, zai}.
L.sadd(key='s2', value=b'\x01'.join([b'baze', b'foo', b'zai']))
# Test multiple set operations, {bar, baz, foo} | {baze, foo, zai}.
self.assertEqual(L.sinter(key1='s1', key2='s2'), {'foo': '1'})
res = L.sunion(key1='s1', key2='s2')
self.assertEqual(res, dict((k, '1') for k in
('bar', 'baz', 'baze', 'foo', 'zai')))
res = L.sdiff(key1='s1', key2='s2')
self.assertEqual(res, {'bar': '1', 'baz': '1'})
res = L.sdiff(key1='s2', key2='s1')
self.assertEqual(res, {'baze': '1', 'zai': '1'})
res = L.sdiff(key1='s1', key2='s2', dest='s3')
self.assertEqual(res, {'bar': '1', 'baz': '1'})
res = L.smembers(key='s3')
self.assertEqual(res, {'bar': '1', 'baz': '1'})
def test_script_list(self):
L = self.db.lua
self.assertEqual(L.lrpush(key='l1', value='i0'), {})
# Test appending items to list.
for i in range(1, 5):
L.lrpush(key='l1', value='i%s' % i)
# Test accessing items by index.
for i in range(5):
self.assertEqual(L.lindex(key='l1', index=i), {'value': 'i%s' % i})
# Invalid index returns empty result set.
self.assertEqual(L.lindex(key='l1', index=6), {})
self.assertEqual(L.lindex(key='l1', index=-1), {'value': 'i4'})
# Get length of list, pop last item, verify length change.
self.assertEqual(L.llen(key='l1'), {'num': '5'})
self.assertEqual(L.lrpop(key='l1'), {'value': 'i4'})
self.assertEqual(L.llen(key='l1'), {'num': '4'})
# Verify setting indices.
self.assertEqual(L.lset(key='l1', index=2, value='i2-x'), {})
self.assertEqual(L.lindex(key='l1', index=2), {'value': 'i2-x'})
self.assertEqual(L.lrpop(key='l1'), {'value': 'i3'})
self.assertEqual(L.llpop(key='l1'), {'value': 'i0'})
self.assertEqual(L.lrpop(key='l1'), {'value': 'i2-x'})
self.assertEqual(L.llpop(key='l1'), {'value': 'i1'})
self.assertEqual(L.llen(key='l1'), {'num': '0'})
self.assertEqual(L.llpop(key='l1'), {})
self.assertEqual(L.lrpop(key='l1'), {})
def test_list_insert(self):
# Test getting ranges.
L = self.db.lua
for i in range(5):
L.lrpush(key='l1', value='i%s' % i)
R = functools.partial(L.lrange, key='l1')
L.linsert(key='l1', index=1, value='i0.5')
self.assertEqual(R(start=0, stop=3), {'0': 'i0', '1': 'i0.5',
'2': 'i1'})
L.linsert(key='l1', index=-1, value='i3.5')
self.assertEqual(R(), {'0': 'i0', '1': 'i0.5', '2': 'i1', '3': 'i2',
'4': 'i3', '5': 'i3.5', '6': 'i4'})
def test_script_list_ranges(self):
# Test getting ranges.
L = self.db.lua
for i in range(5):
L.lrpush(key='l1', value='i%s' % i)
R = functools.partial(L.lrange, key='l1')
all_items = dict((str(i), 'i%s' % i) for i in range(5))
self.assertEqual(R(), all_items)
self.assertEqual(R(start=0), all_items)
self.assertEqual(R(start=-5), all_items)
self.assertEqual(R(stop=5), all_items)
# Within bounds.
self.assertEqual(R(start=1, stop=4), {'1': 'i1', '2': 'i2', '3': 'i3'})
self.assertEqual(R(start=0, stop=1), {'0': 'i0'})
self.assertEqual(R(start=3), {'3': 'i3', '4': 'i4'})
self.assertEqual(R(stop=-3), {'0': 'i0', '1': 'i1'})
self.assertEqual(R(start=1, stop=-3), {'1': 'i1'})
self.assertEqual(R(start=3, stop=-1), {'3': 'i3'})
self.assertEqual(R(start=-1), {'4': 'i4'})
self.assertEqual(R(start=-2), {'3': 'i3', '4': 'i4'})
# Out-of-bounds or out-of-order.
self.assertEqual(R(start=5), {})
self.assertEqual(R(start=-6), {})
self.assertEqual(R(start=0, stop=0), {})
self.assertEqual(R(start=-1, stop=3), {})
self.assertEqual(R(start=3, stop=2), {})
self.assertEqual(R(start=1, stop=1), {})
def test_script_hash(self):
L = self.db.lua
# Set multiple items, returns number set.
res = L.hmset(table_key='h1', k1='v1', k2='v2', k3='v3')
self.assertEqual(res['num'], '3')
# Set individual item using key=..., value=...
res = L.hset(table_key='h1', key='k1', value='v1-x')
self.assertEqual(res['num'], '1')
# Retrieve an individual item.
self.assertEqual(L.hget(table_key='h1', key='k1'), {'value': 'v1-x'})
# Missing key returns empty response.
self.assertEqual(L.hget(table_key='h1', key='kx'), {})
# Retrieve multiple items. Missing keys are omitted.
res = L.hmget(table_key='h1', k1='', k2='', kx='')
self.assertEqual(res, {'k1': 'v1-x', 'k2': 'v2'})
# Retrieve all key/values in hash.
res = L.hgetall(table_key='h1')
self.assertEqual(res, {'k1': 'v1-x', 'k2': 'v2', 'k3': 'v3'})
# Delete individual key, returns number deleted.
self.assertEqual(L.hdel(table_key='h1', key='k2'), {'num': '1'})
self.assertEqual(L.hdel(table_key='h1', key='k2'), {'num': '0'})
# Delete multiple keys, returns number deleted.
self.assertEqual(L.hmdel(table_key='h1', k1='', k3=''), {'num': '2'})
self.assertEqual(L.hgetall(table_key='h1'), {})
# We can conditionally set a key (if it does not exist). Returns 1 if
# successful.
res = L.hsetnx(table_key='h1', key='k1', value='v1-y')
self.assertEqual(res, {'num': '1'})
res = L.hsetnx(table_key='h1', key='k1', value='v1-z')
self.assertEqual(res, {'num': '0'})
# Set an additional key and verify hash contents for subsequent checks.
L.hsetnx(table_key='h1', key='k2', value='v2')
self.assertEqual(L.hgetall(table_key='h1'), {'k1': 'v1-y', 'k2': 'v2'})
self.assertEqual(L.hlen(table_key='h1'), {'num': '2'})
self.assertEqual(L.hcontains(table_key='h1', key='k1'), {'num': '1'})
self.assertEqual(L.hcontains(table_key='h1', key='kx'), {'num': '0'})
# Getting values from a non-existent hash returns empty response.
self.assertEqual(L.hgetall(table_key='h2'), {})
def test_script_list_items(self):
self.assertEqual(self.db.script('list'), {})
self.db.update(k1='v1', k2='v2', k3='v3')
self.assertEqual(self.db.script('list'),
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'})
def test_script_get_range(self):
self.assertEqual(self.db.script('get_range'), {})
data = {'k%s' % i: 'v%s' % i for i in range(11)}
self.db.set_bulk(data)
def assertRange(start, stop, expected):
params = {}
if start: params['start'] = start
if stop: params['stop'] = stop
self.assertEqual(self.db.script('get_range', params), expected)
assertRange('k8', None, {'k8': 'v8', 'k9': 'v9'})
assertRange('k80', None, {'k9': 'v9'})
assertRange(None, 'k2', {'k0': 'v0', 'k1': 'v1', 'k10': 'v10',
'k2': 'v2'})
assertRange(None, 'k2.2', self.db.script('get_range', {'stop': 'k2'}))
assertRange('k10', 'k3', {'k10': 'v10', 'k2': 'v2', 'k3': 'v3'})
assertRange('k101', 'k3', {'k2': 'v2', 'k3': 'v3'})
assertRange('k10', 'k31', {'k10': 'v10', 'k2': 'v2', 'k3': 'v3'})
assertRange('a', 'k1', {'k0': 'v0', 'k1': 'v1'})
assertRange('k9', 'z', {'k9': 'v9'})
assertRange('a', 'b', {})
assertRange('x', 'y', {})
assertRange('x', None, {})
assertRange(None, 'a', {})
def test_get_part(self):
V = '0123456789'
self.db.update(k1=V, k2='')
def assertPart(key, start, stop, expected):
params = {'key': key, 'start': start}
if stop is not None:
params['stop'] = stop
result = self.db.script('get_part', params)
if expected is None:
self.assertTrue('value' not in result)
else:
self.assertEqual(result['value'], expected)
assertPart('k1', 0, None, V)
assertPart('k1', 0, -1, V[0:-1])
assertPart('k1', 1, 3, V[1:3])
assertPart('k1', 1, 30, V[1:])
assertPart('k1', 20, 30, '')
assertPart('k1', -3, None, V[-3:])
assertPart('k1', -5, -1, V[-5:-1])
assertPart('k1', -20, -10, '')
assertPart('k1', -20, None, V[-20:])
assertPart('k2', 0, None, '')
assertPart('k2', 1, -1, '')
assertPart('k2', -1, None, '')
assertPart('k3', 0, None, None)
assertPart('k3', 1, -1, None)
def test_queue_methods(self):
L = self.db.lua
for i in range(5):
L.queue_add(queue='tq', data='item-%s' % i)
self.assertEqual(L.queue_size(queue='tq'), {'num': '5'})
# By default one item is dequeued.
result = L.queue_pop(queue='tq')
self.assertEqual(result, {'0': 'item-0'})
self.assertEqual(L.queue_size(queue='tq'), {'num': '4'})
# We can also peek at items.
self.assertEqual(L.queue_peek(queue='tq'), {'0': 'item-1'})
self.assertEqual(L.queue_peek(queue='tq', n=2),
{'0': 'item-1', '1': 'item-2'})
# We can dequeue multiple items.
result = L.queue_pop(queue='tq', n=3)
self.assertEqual(result, {'0': 'item-1', '1': 'item-2', '2': 'item-3'})
# Peek when fewer items exist:
self.assertEqual(L.queue_peek(queue='tq', n=3), {'0': 'item-4'})
# It's OK to pop if fewer items exist.
result = L.queue_pop(queue='tq', n=3)
self.assertEqual(result, {'0': 'item-4'})
# No items -> empty string and zero count.
self.assertEqual(L.queue_pop(queue='tq'), {})
self.assertEqual(L.queue_peek(queue='tq'), {})
self.assertEqual(L.queue_size(queue='tq'), {'num': '0'})
L.queue_add(queue='tq', data='item-y')
L.queue_add(queue='tq', data='item-z')
self.assertEqual(L.queue_clear(queue='tq'), {'num': '2'})
self.assertEqual(L.queue_clear(queue='tq'), {'num': '0'})
for i in range(6):
L.queue_add(queue='tq', data='item-%s' % i)
# Reverse-peek.
self.assertEqual(L.queue_rpeek(queue='tq'), {'0': 'item-5'})
self.assertEqual(L.queue_rpeek(queue='tq', n=2),
{'0': 'item-5', '1': 'item-4'})
# Reverse-pop.
result = L.queue_rpop(queue='tq', n=2)
self.assertEqual(result, {'0': 'item-5', '1': 'item-4'})
self.assertEqual(L.queue_pop(queue='tq'), {'0': 'item-0'})
self.assertEqual(L.queue_peek(queue='tq'), {'0': 'item-1'})
self.assertEqual(L.queue_rpop(queue='tq'), {'0': 'item-3'})
self.assertEqual(L.queue_rpeek(queue='tq'), {'0': 'item-2'})
# We can request more items than exist with rpeek.
self.assertEqual(L.queue_rpeek(queue='tq', n=4),
{'0': 'item-2', '1': 'item-1'})
# We can attempt to reverse-pop more items than exist:
result = L.queue_rpop(queue='tq', n=4)
self.assertEqual(result, {'0': 'item-2', '1': 'item-1'})
self.assertEqual(L.queue_rpop(queue='tq'), {})
self.assertEqual(L.queue_pop(queue='tq'), {})
# Test loop termination logic when we have no keys in the db.
self.db.clear()
self.assertEqual(L.queue_rpop(queue='tq'), {})
self.assertEqual(L.queue_pop(queue='tq'), {})
# Test bulk-add feature.
data = {str(i): 'i%s' % (i % 2) for i in range(5)}
self.assertEqual(L.queue_madd(queue='tq', **data), {'num': '5'})
self.assertEqual(L.queue_peek(queue='tq', n=5), {
'0': 'i0', '1': 'i1', '2': 'i0', '3': 'i1', '4': 'i0'})
# Verify we can remove data by value.
self.assertEqual(L.queue_remove(queue='tq', data='i1'), {'num': '2'})
self.assertEqual(L.queue_remove(queue='tq', data='x'), {'num': '0'})
self.assertEqual(L.queue_size(queue='tq'), {'num': '3'})
# We can specify a limit on the number of items removed.
self.assertEqual(L.queue_remove(queue='tq', data='i0', n=2),
{'num': '2'})
self.assertEqual(L.queue_size(queue='tq'), {'num': '1'})
self.assertEqual(L.queue_pop(queue='tq'), {'0': 'i0'})
# Verify remove-by-value, reverse.
for i in range(10):
# i0, i1, i2, i0, i1, i2, i0, i1, i2, i0
L.queue_add(queue='tq', data='i%s' % (i % 3))
self.assertEqual(L.queue_rremove(queue='tq', data='i0', n=3),
{'num': '3'})
self.assertEqual(L.queue_peek(queue='tq', n=10), {
'0': 'i0', '1': 'i1', '2': 'i2', '3': 'i1', '4': 'i2',
'5': 'i1', '6': 'i2'})
self.assertEqual(L.queue_rremove(queue='tq', data='i1', n=2),
{'num': '2'})
self.assertEqual(L.queue_peek(queue='tq', n=10), {
'0': 'i0', '1': 'i1', '2': 'i2', '3': 'i2', '4': 'i2'})
self.assertEqual(L.queue_clear(queue='tq'), {'num': '5'})
def test_queue_helper(self):
qa = Queue(self.db, 'qa')
qb = Queue(self.db, 'qb')
for i in range(20):
qa.add('i%s' % i)
qb.add('i%s' % (i % 4))
self.assertEqual(len(qa), 20)
self.assertEqual(len(qb), 20)
self.assertEqual(qa.pop(), 'i0')
self.assertEqual(qa.rpop(), 'i19')
self.assertEqual(qa.pop(n=3), ['i1', 'i2', 'i3'])
self.assertEqual(qa.rpop(n=3), ['i18', 'i17', 'i16'])
self.assertEqual(qa.peek(n=3), ['i4', 'i5', 'i6'])
self.assertEqual(qa.rpeek(n=3), ['i15', 'i14', 'i13'])
# i0, i1, i2, i3 ... x5.
self.assertEqual(qb.remove('i1', n=4), 4)
self.assertEqual(qb.rremove('i2', n=4), 4)
self.assertEqual(len(qb), 12)
self.assertEqual(qb.peek(20), ['i0', 'i2', 'i3', 'i0', 'i3', 'i0',
'i3', 'i0', 'i3', 'i0', 'i1', 'i3'])
self.assertEqual(qb.remove('i3', n=5), 5)
self.assertEqual(qb.remove('i0', n=10), 5)
self.assertEqual(qb.pop(), 'i2')
self.assertEqual(qb.pop(), 'i1')
self.assertEqual(len(qb), 0)
self.assertEqual(qa.remove('i7'), 1)
self.assertEqual(qa.remove('i7'), 0)
self.assertEqual(qa.pop(n=5), ['i4', 'i5', 'i6', 'i8', 'i9'])
def test_hexastore(self):
L = self.db.lua
data = (
('charlie', 'likes', 'zaizee'),
('charlie', 'likes', 'huey'),
('charlie', 'likes', 'mickey'),
('huey', 'likes', 'zaizee'),
('zaizee', 'likes', 'huey'),
)
for s, p, o in data:
L.hx_add(s=s, p=p, o=o)
self.assertEqual(self.db.count(), 15) # 5 * 3.
data = L.hx_query(s='charlie', p='likes')
self.assertEqual(data, {'o0': 'huey', 'o1': 'mickey', 'o2': 'zaizee'})
L.hx_remove(s='charlie', p='likes', o='mickey')
data = L.hx_query(s='charlie', p='likes')
self.assertEqual(data, {'o0': 'huey', 'o1': 'zaizee'})
data = L.hx_query(o='zaizee')
self.assertEqual(data, {
's0': 'charlie', 'p0': 'likes',
's1': 'huey', 'p1': 'likes'})
self.db.clear()
def test_python_list_integration(self):
L = self.db.lua
P = self.db._protocol
data = ['foo', 'a' * 1024, '', 'b' * 1024 * 32, 'c']
self.db['l1'] = P.serialize_list(data)
self.assertEqual(L.llen(key='l1'), {'num': '5'})
self.assertEqual(L.lrpop(key='l1'), {'value': 'c'})
self.assertEqual(L.lrpop(key='l1'), {'value': 'b' * 1024 * 32})
self.assertEqual(L.lrpop(key='l1'), {'value': ''})
self.assertEqual(L.lrpop(key='l1'), {'value': 'a' * 1024})
self.assertEqual(L.lrpop(key='l1'), {'value': 'foo'})
for item in data:
L.lrpush(key='l1', value=item)
raw_data = self.db.get_bytes('l1')
self.assertEqual(P.deserialize_list(raw_data), data)
self.assertEqual(L.lrange(key='l1'), dict((str(i), data[i])
for i in range(len(data))))
db2 = KyotoTycoon(port=self.db._port, serializer=KT_NONE)
db2.set('l2', P.serialize_list(['i0', 'i1', 'i2', 'i3']))
self.assertEqual(L.llen(key='l2'), {'num': '4'})
self.assertEqual(L.lrpop(key='l2'), {'value': 'i3'})
self.assertEqual(P.deserialize_list(db2.get('l2')), ['i0', 'i1', 'i2'])
db2.close()
def test_python_dict_integration(self):
L = self.db.lua
P = self.db._protocol
data = {'a' * 64: 'b' * 128, 'c' * 1024: 'd' * 1024 * 32,
'e' * 256: 'f' * 1024 * 1024, 'g': ''}
self.db['h1'] = self.db._protocol.serialize_dict(data)
self.assertEqual(L.hgetall(table_key='h1'), data)
self.assertEqual(L.hget(table_key='h1', key='e' * 256),
{'value': 'f' * 1024 * 1024})
self.assertTrue(L.hcontains(table_key='h1', key='a' * 64))
del self.db['h1']
L.hmset(table_key='h1', **data)
raw_data = self.db.get_bytes('h1')
self.assertEqual(self.db._protocol.deserialize_dict(raw_data), data)
self.assertEqual(L.hgetall(table_key='h1'), data)
db2 = KyotoTycoon(port=self.db._port, serializer=KT_NONE)
db2.set('h2', P.serialize_dict({'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}))
self.assertEqual(L.hdel(table_key='h2', key='k2'), {'num': '1'})
self.assertEqual(L.hgetall(table_key='h2'), {'k1': 'v1', 'k3': 'v3'})
self.assertEqual(P.deserialize_dict(db2.get('h2')),
{'k1': 'v1', 'k3': 'v3'})
db2.close()
class TestKyotoTycoonScriptingMultiDB(BaseTestCase):
lua_script = os.path.join(BaseTestCase.lua_path, 'kt.lua')
server = EmbeddedServer
server_kwargs = {'database': '%', 'server_args': ['-scr', lua_script, '%']}
def test_script_multi_db(self):
self.db.clear(db=0)
self.db.clear(db=1)
for i in range(3):
self.db.set('k%s' % i, 'v%s' % i, db=(i % 2))
self.assertEqual(self.db.lua.list(), {'k0': 'v0', 'k2': 'v2'})
self.assertEqual(self.db.lua.list(db=0), {'k0': 'v0', 'k2': 'v2'})
self.assertEqual(self.db.lua.list(db=1), {'k1': 'v1'})
def test_script_datatypes_multi_db(self):
L = self.db.lua
# Test sets with multiple dbs.
for i in range(5):
L.sadd(key='s1', value='v%s' % i, db=(i % 2))
self.assertEqual(L.scard(key='s1', db=0), {'num': '3'})
self.assertEqual(L.scard(key='s1', db=1), {'num': '2'})
# By default the database is 0.
self.assertEqual(sorted(L.smembers(key='s1')), ['v0', 'v2', 'v4'])
self.assertEqual(sorted(L.smembers(key='s1', db=0)),
['v0', 'v2', 'v4'])
self.assertEqual(sorted(L.smembers(key='s1', db=1)), ['v1', 'v3'])
self.assertEqual(L.sismember(key='s1', value='v2', db=0), {'num': '1'})
self.assertEqual(L.sismember(key='s1', value='v2', db=1), {'num': '0'})
self.assertEqual(L.sismember(key='s1', value='v1', db=0), {'num': '0'})
self.assertEqual(L.sismember(key='s1', value='v1', db=1), {'num': '1'})
self.assertTrue(L.spop(key='s1')['value'] in ['v0', 'v2', 'v4'])
self.assertTrue(L.spop(key='s1', db=1)['value'] in ['v1', 'v3'])
# Test hashes with multiple dbs.
L.hmset(table_key='h1', k1='v1', k2='v2', db=0)
L.hmset(table_key='h1', k1='v1x', k2='v2x', db=1)
L.hset(table_key='h1', key='k1', value='v1z', db=0)
L.hset(table_key='h1', key='k1', value='v1y', db=1)
self.assertEqual(L.hgetall(table_key='h1'), {'k1': 'v1z', 'k2': 'v2'})
self.assertEqual(L.hgetall(table_key='h1', db=0),
{'k1': 'v1z', 'k2': 'v2'})
self.assertEqual(L.hgetall(table_key='h1', db=1),
{'k1': 'v1y', 'k2': 'v2x'})
# Test lists with multiple dbs.
for i in range(5):
L.llpush(key='l1', value='i%s' % i, db=(i % 2))
self.assertEqual(L.llen(key='l1')['num'], '3')
self.assertEqual(L.llen(key='l1', db=0)['num'], '3')
self.assertEqual(L.llen(key='l1', db=1)['num'], '2')
self.assertEqual(L.llpop(key='l1')['value'], 'i4')
self.assertEqual(L.lrpop(key='l1', db=0)['value'], 'i0')
self.assertEqual(L.llpop(key='l1', db=1)['value'], 'i3')
self.assertEqual(L.lrpop(key='l1', db=1)['value'], 'i1')
class TestKyotoTycoonMultiDatabase(BaseTestCase):