CodernityDB / tests / hash_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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011-2012 Codernity (http://codernity.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from CodernityDB.database import Database, RecordDeleted, RecordNotFound
from CodernityDB.database import DatabaseException

from CodernityDB.hash_index import HashIndex, UniqueHashIndex
from CodernityDB.index import IndexException
from CodernityDB.misc import random_hex_32

from CodernityDB import rr_cache

import pytest
import os
import random
from hashlib import md5

try:
    from collections import Counter
except ImportError:
    class Counter(dict):
        'Mapping where default values are zero'
        def __missing__(self, key):
            return 0


class CustomHashIndex(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = 'I'
        kwargs['hash_lim'] = 1
        super(CustomHashIndex, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        d = data.get('test')
        if d is None:
            return None
        if d > 5:
            k = 1
        else:
            k = 0
        return k, dict(test=d)

    def make_key(self, key):
        return key


class Md5Index(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = '16s'
        kwargs['hash_lim'] = 4 * 1024
        super(Md5Index, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        return md5(data['name']).digest(), {}

    def make_key(self, key):
        return md5(key).digest()


class WithAIndex(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = '16s'
        kwargs['hash_lim'] = 4 * 1024
        super(WithAIndex, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        a_val = data.get("a")
        if a_val:
            if not isinstance(a_val, basestring):
                a_val = str(a_val)
            return md5(a_val).digest(), {}
        return None

    def make_key(self, key):
        if not isinstance(key, basestring):
            key = str(key)
        return md5(key).digest()


class HashIndexTests:

    def setup_method(self, method):
        self.counter = Counter()

    def test_simple(self, tmpdir):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        # db.set_indexes([UniqueHashIndex(db.path, 'id')])
        # db.initialize()
        db.add_index(UniqueHashIndex(db.path, 'id'), False)
        db.create()

        with pytest.raises(RecordNotFound):
            db.get("id", "not_existing")
        a1 = dict(a=1)
        db.insert(a1)
        test = db.get('id', a1['_id'])
        assert test['_id'] == a1['_id']
        a_id = a1['_id']
        assert test == a1
        a1['x'] = 'x'
        db.update(a1)
        test2 = db.get('id', a_id)
        assert test2['x'] == 'x'
        assert test2 != test
        db.delete(a1)
        with pytest.raises(RecordDeleted):
            db.get('id', a_id)
        db.close()

    def test_insert_with_id(self, tmpdir):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        # db.set_indexes([UniqueHashIndex(db.path, 'id')])
        # db.initialize()
        db.add_index(UniqueHashIndex(db.path, 'id'), False)
        db.create()

        doc = dict(a=1, _id=random_hex_32())
        ins = db.insert(doc)
        assert ins['_id'] == doc["_id"]
        db.close()

    def test_delete(self, tmpdir, inserts):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id')])
        db.create()

        ins = []
        for x in xrange(inserts):
            doc = dict(x=x)
            db.insert(doc)
            ins.append(doc)
            self.counter['ins'] += 1

        for i in xrange(inserts / 10):
            curr = ins.pop(random.randint(0, len(ins) - 1))
            db.delete(curr)

        assert len(ins) == db.count(db.all, 'id')

        for x in xrange(inserts):
            doc = dict(x=x)
            db.insert(doc)
            ins.append(doc)
            self.counter['ins'] += 1

        for i in xrange(inserts / 10):
            curr = ins.pop(random.randint(0, len(ins) - 1))
            db.delete(curr)

        assert len(ins) == db.count(db.all, 'id')

    def test_get_after_delete(self, tmpdir):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id'),
                        CustomHashIndex(db.path, 'custom')])
        db.create()

        for x in xrange(100):
            doc = dict(test=6)
            doc.update(db.insert(doc))
            if doc['test'] > 5:
                self.counter['r'] += 1
            else:
                self.counter['l'] += 1

        counted_bef = db.count(db.all, 'custom')
        elem = db.all('custom', with_doc=True, limit=1)

        doc = next(elem)['doc']
        assert db.delete(doc) == True

        counted_aft = db.count(db.all, 'custom')
        assert counted_bef - 1 == counted_aft

        from_ind = db.get('custom', 1, with_doc=True)
        assert from_ind['doc']['_id'] != doc['_id']

        alls = db.all('custom', with_doc=True, limit=90)
        for curr in alls:
            assert db.delete(curr['doc']) == True

        from_ind = db.get('custom', 1, with_doc=True)
        assert from_ind['doc'] != {}

    def test_delete_with_id_and_rev_only(self, tmpdir, inserts):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id')])
        db.create()

        ins = []
        for x in xrange(inserts):
            doc = dict(x=x)
            db.insert(doc)
            ins.append(doc)
            self.counter['ins'] += 1

        for i in xrange(inserts / 10):
            curr = ins.pop(random.randint(0, len(ins) - 1))
            d = {"_id": curr['_id'], '_rev': curr['_rev']}
            db.delete(d)

        assert len(ins) == db.count(db.all, 'id')

        for x in xrange(inserts):
            doc = dict(x=x)
            db.insert(doc)
            ins.append(doc)
            self.counter['ins'] += 1

        for i in xrange(inserts / 10):
            curr = ins.pop(random.randint(0, len(ins) - 1))
            db.delete(curr)

        assert len(ins) == db.count(db.all, 'id')

    def test_update_custom_unique(self, tmpdir, inserts):
            db = self._db(os.path.join(str(tmpdir), 'db'))
            db.set_indexes([UniqueHashIndex(db.path, 'id'),
                            CustomHashIndex(db.path, 'custom')])
            db.create()

            ins = []

            for x in xrange(inserts):
                doc = dict(test=1)
                db.insert(doc)
                ins.append(doc)
                self.counter['ins'] += 1

            assert len(ins) == db.count(db.all, 'id')
            assert len(ins) == db.count(db.all, 'custom')
            assert len(ins) == db.count(
                db.get_many, 'custom', key=0, limit=inserts + 1)
            assert 0 == db.count(
                db.get_many, 'custom', key=1, limit=inserts + 1)

            sample = random.sample(ins, inserts / 10)
            for curr in sample:
                curr['test'] = 10
                db.update(curr)
                self.counter['upd'] += 1

            assert self.counter['ins'] == db.count(db.all, 'id')
            assert self.counter['ins'] == db.count(db.all, 'custom')
            assert self.counter['upd'] == db.count(
                db.get_many, 'custom', key=1, limit=inserts + 1)
            assert self.counter['ins'] - self.counter['upd'] == db.count(
                db.get_many, 'custom', key=0, limit=inserts + 1)

    def test_update_custom_same_key_new_value(self, tmpdir, inserts):
            db = self._db(os.path.join(str(tmpdir), 'db'))
            db.set_indexes([UniqueHashIndex(db.path, 'id'),
                            CustomHashIndex(db.path, 'custom')])
            db.create()

            inserted = []
            for x in xrange(inserts):
                inserted.append(db.insert(dict(test=x)))
                inserted[-1]['test'] = x
            for el in inserted[::20]:
                for i in xrange(4):
                    curr = db.get('id', el['_id'], with_storage=True)
                    assert el['test'] == curr['test']
                    el['test'] += random.randint(1, 3)
                    db.update(el)
            assert len(inserted) == db.count(db.all, 'custom')

            db.close()

    def test_double_insert(self, tmpdir):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id')])
        db.create()

        a_id = '54bee5c4628648b5a742379a1de89b2d'
        a1 = dict(a=1, _id=a_id)
        db.insert(a1)
        a2 = dict(a=2, _id=a_id)
        with pytest.raises(IndexException):
            db.insert(a2)

    def test_adv1(self, tmpdir, inserts):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id')])
        db.create()
        l = []
        for i in xrange(inserts):
            c = dict(i=i)
            db.insert(c)
            l.append(c)
        for j in range(inserts):
            curr = l[j]
            c = db.get('id', curr['_id'])
            assert c['_id'] == curr['_id']
            assert c['i'] == j
        for i in xrange(inserts):
            curr = l[i]
            c = db.get("id", curr['_id'])
            c['update'] = True
            db.update(c)

        for j in xrange(inserts):
            curr = l[i]
            c = db.get('id', curr['_id'])
            assert c['update'] == True

        for j in xrange(inserts):
            curr = l[j]
            c = db.get('id', curr['_id'])
            assert db.delete(c) == True

        for j in xrange(inserts):
            with pytest.raises(RecordDeleted):
                db.get('id', l[j]['_id'])

        db.close()

    def test_all(self, tmpdir, inserts):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id')])
        db.create()
        l = []
        for i in xrange(inserts):
            c = dict(i=i)
            db.insert(c)
            l.append(c)

        assert db.count(db.all, 'id') == inserts

        to_delete = random.randint(0, inserts - 1)
        db.delete(l[to_delete])

        assert db.count(db.all, 'id') == inserts - 1

    def test_compact(self, tmpdir):
            db = self._db(os.path.join(str(tmpdir), 'db'))
            db.set_indexes([UniqueHashIndex(db.path, 'id')])
            db.create()
            l = []
            for i in xrange(10):
                c = dict(i=i)
                db.insert(c)
                l.append(c)

            for i in xrange(10):
                curr = l[i]
                c = db.get("id", curr['_id'])
                c['update'] = True
                c.update(db.update(c))

            db.compact()

            for j in range(10):
                curr = l[j]
                c = db.get('id', curr['_id'])
                assert c['_id'] == curr['_id']
                assert c['i'] == j

            db.close()

    def test_compact2(self, tmpdir):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id')])
        db.create()
        l = []
        for i in xrange(10):
            if i % 2 == 0:
                c = dict(i=i, even=True)
            else:
                c = dict(i=i)
            c.update(db.insert(c))
            l.append(c)

        for i, curr in enumerate(db.all('id')):
            if i % 2:
                db.delete(curr)

        db.compact()
        db.compact()
        db.compact()
        assert len(list(db.all('id', with_doc=True))) == 5

        for curr in db.all('id'):
            db.delete(curr)

        assert len(list(db.all('id', with_doc=True))) == 0

    def test_similar(self, tmpdir):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes(
            [UniqueHashIndex(db.path, 'id'), Md5Index(db.path, 'md5')])
        db.create()

        a = dict(name='pigmej')
        db.insert(a)
        db.get('md5', 'pigmej')

        with pytest.raises(RecordNotFound):
            db.get("md5", 'pigme')

    def test_custom_index(self, tmpdir):

        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(
            db.path, 'id'), CustomHashIndex(db.path, 'custom')])
        db.create()

        l_1 = []
        l_0 = []
        for i in xrange(10):
            c = dict(test=i)
            db.insert(c)
            if i > 5:
                l_1.append(c)
            else:
                l_0.append(c)

        i = 0
        for curr in db.all('custom', with_doc=False):
            i += 1

        assert i == len(l_1) + len(l_0)

        db.compact()

        gen = db.get_many('custom', key=1, limit=10, offset=0, with_doc=True)
        got = []
        while True:
            try:
                d = gen.next()
            except StopIteration:
                break
            else:
                got.append(d)
        assert len(l_1) == len(got)

        for doc in l_1:
            doc['test'] = 0
            db.update(doc)

        gen = db.get_many('custom', key=0, limit=100, offset=0, with_doc=False)
        got = []
        while True:
            try:
                d = gen.next()
            except StopIteration:
                break
            else:
                got.append(d)

        assert len(l_1) + len(l_0) == len(got)

        db.compact()

        gen = db.get_many('custom', key=0, limit=100, offset=0, with_doc=False)
        got = []
        while True:
            try:
                d = gen.next()
            except StopIteration:
                break
            else:
                got.append(d)

        assert len(l_1) + len(l_0) == len(got)

    def test_custom_index_2(self, tmpdir):

        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes(
            [UniqueHashIndex(db.path, 'id'), WithAIndex(db.path, 'with_a')])
        db.create()

        all_ins = []
        for i in range(10):
            curr = dict(something='other')
            if i % 2 == 0:
                curr['a'] = str(i)
            all_ins.append(curr)
            db.insert(curr)

        l_0 = len(list(db.all('id')))
        l_1 = len(list(db.all('with_a')))
        assert l_1 != l_0

        all_a = list(db.all('with_a', with_doc=True))
        curr_a = all_a[0]['doc']
        del curr_a['a']
        db.update(curr_a)
        l_2 = len(list(db.all('with_a')))
        assert l_2 + 1 == l_1

        curr_a = all_a[-1]['doc']
        db.delete(curr_a)

        l_3 = len(list(db.all('with_a')))
        assert l_3 + 2 == l_1

    def test_insert_delete_compact_get_huge(self, tmpdir, inserts):
        inserts *= 10
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id')])
        db.create()
        l = []
        for i in xrange(inserts):
            c = dict(i=i)
            db.insert(c)
            l.append(c)

        assert db.count(db.all, 'id') == inserts

        will_delete = random.randint(0, inserts / 15)
        for x in range(will_delete):
            to_delete = random.randint(0, len(l) - 1)
            db.delete(l.pop(to_delete))

        assert db.count(db.all, 'id') == inserts - will_delete

        db.compact()

        assert db.count(db.all, 'id') == inserts - will_delete

    def test_all_same_keys(self, tmpdir, inserts):

            db = self._db(os.path.join(str(tmpdir), 'db'))
            db.set_indexes([UniqueHashIndex(db.path, 'id'),
                            WithAIndex(db.path, 'with_a')])

            db.create()
            l = 0
            r = 0
            z = 0
            data = []
            for i in xrange(inserts):
                a = random.randint(0, 10)
                if a > 5:
                    r += 1
                elif a == 0:
                    z += 1
                else:
                    l += 1
                c = dict(a=a)
                db.insert(c)
                data.append(c)

            assert l + r + z == db.count(db.all, "id")

            assert l + r == db.count(db.all, "with_a")

    def test_update_same(self, tmpdir, inserts):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id'),
                        WithAIndex(db.path, 'with_a'),
                        CustomHashIndex(db.path, 'custom')])
        db.create()

        inserted = {}

        for i in xrange(inserts):
            a = random.randint(1, 9)
            # a = 10
            if a > 5:
                self.counter['r'] += 1
            else:
                self.counter['l'] += 1
            c = dict(test=a)
            db.insert(c)
            inserted[c['_id']] = c

        def _check():

            assert self.counter['l'] == db.count(db.get_many,
                                                 'custom', key=0, limit=inserts)
            assert self.counter['r'] == db.count(db.get_many,
                                                 'custom', key=1, limit=inserts)
            assert self.counter['r'] + self.counter[
                'l'] == db.count(db.all, "custom")

        _check()

        d = inserted.values()[inserts / 2]
        for curr_u in range(20):
            last_test = d['test']
            if last_test > 5:
                d['test'] = 1
                self.counter['r'] -= 1
                self.counter['l'] += 1
            else:
                d['test'] = 6
                self.counter['l'] -= 1
                self.counter['r'] += 1
            d['upd'] = curr_u
            db.update(d)
        _check()

        num = inserts / 10
        num = num if num < 20 else 20

        to_update = random.sample(inserted.values(), num)
        for d in to_update:
            for curr_u in range(10):
                last_test = d['test']
                if last_test > 5:
                    d['test'] = 1
                    self.counter['r'] -= 1
                    self.counter['l'] += 1
                else:
                    d['test'] = 6
                    self.counter['l'] -= 1
                    self.counter['r'] += 1
                d['upd'] = curr_u
                db.update(d)
        _check()

        to_update = random.sample(inserted.values(), num)
        for curr_u in range(10):
            for d in to_update:
                last_test = d['test']
                if last_test > 5:
                    d['test'] = 1
                    self.counter['r'] -= 1
                    self.counter['l'] += 1
                else:
                    d['test'] = 6
                    self.counter['l'] -= 1
                    self.counter['r'] += 1
                d['upd'] = curr_u
                db.update(d)
        _check()

        db.close()

    def test_insert_on_deleted(self, tmpdir):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.create()
        a = db.insert(dict(_id='dd0604e2110d41e9a2ec630461ffd067'))
        db.insert(dict(_id='892508163deb4da0b44e8a00802dc75a'))
        db.delete(a)
        db.insert(dict(_id='d0a6e4e1aa74476a9012f9b8d7181a95'))
        db.get('id', '892508163deb4da0b44e8a00802dc75a')

        db.close()

    def test_offset_in_functions(self, tmpdir, inserts):
        db = self._db(os.path.join(str(tmpdir), 'db'))
        db.set_indexes([UniqueHashIndex(db.path, 'id'),
                        CustomHashIndex(db.path, 'custom')])
        db.create()
        offset = inserts // 10 or 1
        real_inserts = inserts if inserts < 1000 else 1000
        for x in xrange(real_inserts):
                db.insert(dict(test=x))
        assert real_inserts - offset == db.count(db.all, 'id', offset=offset)
        assert real_inserts - offset == db.count(db.all, 'custom',
                                                 offset=offset)
        assert 1 == db.count(db.get_many, 'custom', 1, limit=1, offset=offset)

        db.close()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.