forked from plutec/nosqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
716 lines (577 loc) · 26.7 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
# coding: utf-8
import re
import sqlite3
from mock import Mock, call, patch
from pytest import fixture, mark, raises
import nosqlite
@fixture(scope="module")
def db(request):
_db = sqlite3.connect(':memory:')
request.addfinalizer(_db.close)
return _db
@fixture(scope="module")
def collection(db, request):
return nosqlite.Collection(db, 'foo', create=False)
class TestConnection:
def test_connect(self):
conn = nosqlite.Connection(':memory:')
assert conn.db.isolation_level is None
@patch('nosqlite.sqlite3')
def test_context_manager_closes_connection(self, sqlite):
with nosqlite.Connection() as conn:
pass
assert conn.db.close.called
@patch('nosqlite.sqlite3')
@patch('nosqlite.Collection')
def test_getitem_returns_collection(self, mock_collection, sqlite):
sqlite.connect.return_value = sqlite
mock_collection.return_value = mock_collection
conn = nosqlite.Connection()
assert 'foo' not in conn._collections
assert conn['foo'] == mock_collection
@patch('nosqlite.sqlite3')
def test_getitem_returns_cached_collection(self, sqlite):
conn = nosqlite.Connection()
conn._collections['foo'] = 'bar'
assert conn['foo'] == 'bar'
@patch('nosqlite.sqlite3')
def test_drop_collection(self, sqlite):
conn = nosqlite.Connection()
conn.drop_collection('foo')
conn.db.execute.assert_called_with('drop table if exists foo')
@patch('nosqlite.sqlite3')
def test_getattr_returns_attribute(self, sqlite):
conn = nosqlite.Connection()
assert conn.__getattr__('db') in list(conn.__dict__.values())
@patch('nosqlite.sqlite3')
def test_getattr_returns_collection(self, sqlite):
conn = nosqlite.Connection()
foo = conn.__getattr__('foo')
assert foo not in list(conn.__dict__.values())
assert isinstance(foo, nosqlite.Collection)
class TestCollection:
def setup(self):
self.db = sqlite3.connect(':memory:')
self.collection = nosqlite.Collection(self.db, 'foo', create=False)
def teardown(self):
self.db.close()
def unformat_sql(self, sql):
return re.sub(r'[\s]+', ' ', sql.strip().replace('\n', ''))
def test_create(self):
collection = nosqlite.Collection(Mock(), 'foo', create=False)
collection.create()
collection.db.execute.assert_any_call("""
create table if not exists foo (
id integer primary key autoincrement,
data text not null
)
""")
def test_clear(self):
collection = nosqlite.Collection(Mock(), 'foo')
collection.clear()
collection.db.execute.assert_any_call('delete from foo')
def test_exists_when_absent(self):
assert not self.collection.exists()
def test_exists_when_present(self):
self.collection.create()
assert self.collection.exists()
def test_insert_actually_save(self):
doc = {'_id': 1, 'foo': 'bar'}
self.collection.save = Mock()
self.collection.insert(doc)
self.collection.save.assert_called_with(doc)
def test_insert(self):
doc = {'foo': 'bar'}
self.collection.create()
inserted = self.collection.insert(doc)
assert inserted['_id'] == 1
def test_insert_non_dict_raise(self):
doc = "{'foo': 'bar'}"
self.collection.create()
with raises(nosqlite.MalformedDocument):
inserted = self.collection.insert(doc)
def test_update_without_upsert(self):
doc = {'foo': 'bar'}
self.collection.create()
updated = self.collection.update({}, doc)
assert updated is None
def test_update_with_upsert(self):
doc = {'foo': 'bar'}
self.collection.create()
updated = self.collection.update({}, doc, upsert=True)
assert isinstance(updated, dict)
assert updated['_id'] == 1
assert updated['foo'] == doc['foo'] == 'bar'
def test_save_calls_update(self):
with patch.object(self.collection, 'update'):
doc = {'foo': 'bar'}
self.collection.save(doc)
self.collection.update.assert_called_with(
{'_id':doc.pop('_id', None)},doc, upsert=True
)
def test_save(self):
doc = {'foo': 'bar'}
self.collection.create()
doc = self.collection.insert(doc)
doc['foo'] = 'baz'
updated = self.collection.save(doc)
assert updated['foo'] == 'baz'
def test_delete_calls_remove(self):
with patch.object(self.collection, '_remove'):
doc = {'foo': 'bar'}
self.collection.delete(doc)
self.collection._remove.assert_called_with(doc)
def test_remove_raises_when_no_id(self):
with raises(AssertionError):
self.collection._remove({'foo': 'bar'})
def test_remove(self):
self.collection.create()
doc = self.collection.insert({'foo': 'bar'})
assert 1 == int(self.collection.db.execute("select count(1) from foo").fetchone()[0])
self.collection._remove(doc)
assert 0 == int(self.collection.db.execute("select count(1) from foo").fetchone()[0])
def test_delete_one(self):
self.collection.create()
doc = {'foo':'bar'}
self.collection.insert(doc)
assert 1 == int(self.collection.db.execute("select count(1) from foo").fetchone()[0])
self.collection.delete_one(doc)
assert 0 == int(self.collection.db.execute("select count(1) from foo").fetchone()[0])
assert self.collection.delete_one(doc) is None
def test_insert_bulk_documents_on_a_transaction(self):
self.collection.create()
self.collection.begin()
self.collection.save({'a':1, 'b':'c'})
self.collection.save({'a':1, 'b':'a'})
self.collection.rollback()
assert 0 == self.collection.count({'a':1})
self.collection.begin()
self.collection.save({'a':1, 'b':'c'})
self.collection.save({'a':1, 'b':'a'})
self.collection.commit()
assert 2 == self.collection.count({'a':1})
def test_ensure_index(self):
self.collection.create()
doc = {'foo':'bar'}
self.collection.insert(doc)
self.collection.ensure_index('foo')
cmd = ("SELECT name FROM sqlite_master "
"WHERE type='table' and name like '{name}{{%}}'")
index_name = '%s{%s}' % (self.collection.name, 'foo')
assert index_name == self.collection.db.execute(
cmd.format(name=self.collection.name)
).fetchone()[0]
def test_create_index(self):
self.collection.create()
doc = {'foo':'bar'}
self.collection.insert(doc)
self.collection.create_index('foo', reindex=False)
cmd = ("SELECT name FROM sqlite_master "
"WHERE type='table' and name like '{name}{{%}}'")
index_name = '%s{%s}' % (self.collection.name, 'foo')
assert index_name == self.collection.db.execute(
cmd.format(name=self.collection.name)
).fetchone()[0]
def test_create_index_on_nested_keys(self):
self.collection.create()
doc = {'foo':{'bar':'zzz'},'bok':'bak'}
self.collection.insert(doc)
self.collection.insert({'a':1,'b':2})
self.collection.create_index('foo.bar', reindex=True)
index = '[%s{%s}]' % (self.collection.name, 'foo_bar')
assert index in self.collection.list_indexes()
self.collection.create_index(['foo_bar','bok'], reindex=True)
index = '[%s{%s}]' % (self.collection.name, 'foo_bar,bok')
assert index in self.collection.list_indexes()
def test_index_on_nested_keys(self):
self.test_create_index_on_nested_keys()
index_name = '%s{%s}' % (self.collection.name, 'foo_bar')
cmd = ("SELECT id, foo_bar FROM [%s]" % index_name)
assert (1, '"zzz"') == self.collection.db.execute(cmd).fetchone()
index_name = '%s{%s}' % (self.collection.name, 'foo_bar,bok')
cmd = ("SELECT * FROM [%s]" % index_name)
assert (1, '"zzz"', '"bak"') == self.collection.db.execute(cmd).fetchone()
def test_reindex(self):
self.test_create_index()
index_name = '%s{%s}' % (self.collection.name, 'foo')
self.collection.reindex('[%s]' % index_name)
cmd = ("SELECT id, foo FROM [%s]" % index_name)
assert (1, '"bar"') == self.collection.db.execute(cmd).fetchone()
def test_insert_auto_index(self):
self.test_reindex()
self.collection.insert({'foo':'baz'})
index_name = '%s{%s}' % (self.collection.name, 'foo')
cmd = ("SELECT id, foo FROM [%s]" % index_name)
assert (1, '"bar"') in self.collection.db.execute(cmd).fetchall()
assert (2, '"baz"') in self.collection.db.execute(cmd).fetchall()
def test_create_compound_index(self):
self.collection.create()
doc = {'foo':'bar', 'far':'boo'}
self.collection.insert(doc)
self.collection.create_index(('foo','far'))
cmd = ("SELECT name FROM sqlite_master "
"WHERE type='table' and name like '{name}{{%}}'")
assert '%s{%s}' % (self.collection.name, 'foo,far') == self.collection.db.execute(
cmd.format(name=self.collection.name)
).fetchone()[0]
def test_create_unique_index(self):
self.collection.create()
doc = {'foo':'bar'}
self.collection.insert(doc)
self.collection.create_index('foo', reindex=False, unique=True)
cmd = ("SELECT name FROM sqlite_master "
"WHERE type='table' and name like '{name}{{%}}'")
index_name = '%s{%s}' % (self.collection.name, 'foo')
assert index_name == self.collection.db.execute(
cmd.format(name=self.collection.name)
).fetchone()[0]
def test_reindex_unique_index(self):
self.test_create_unique_index()
index_name = '%s{%s}' % (self.collection.name, 'foo')
self.collection.reindex('[%s]' % index_name)
cmd = ("SELECT id, foo FROM [%s]" % index_name)
assert (1, '"bar"') == self.collection.db.execute(cmd).fetchone()
def test_uniqueness(self):
self.test_reindex_unique_index()
doc = {'foo':'bar'}
index_name = '%s{%s}' % (self.collection.name, 'foo')
cmd = ("SELECT id, foo FROM [%s]" % index_name)
assert [(1, '"bar"')] == self.collection.db.execute(cmd).fetchall()
with raises(sqlite3.IntegrityError):
self.collection.insert(doc)
assert [(1, '"bar"')] == self.collection.db.execute(cmd).fetchall()
def test_update_to_break_uniqueness(self):
self.test_uniqueness()
doc = {'foo':'baz'}
self.collection.insert(doc)
index_name = '%s{%s}' % (self.collection.name, 'foo')
cmd = ("SELECT id, foo FROM [%s]" % index_name)
assert [(1, '"bar"'),(3, '"baz"')] == self.collection.db.execute(cmd).fetchall()
doc = {'foo':'bar', '_id':3}
with raises(sqlite3.IntegrityError):
self.collection.save(doc)
assert [(1, '"bar"'),(3, '"baz"')] == self.collection.db.execute(cmd).fetchall()
def test_create_unique_index_on_non_unique_collection(self):
self.collection.create()
self.collection.insert({'foo':'bar','a':1})
self.collection.insert({'foo':'bar','a':2})
assert 2 == self.collection.count({'foo':'bar'})
with raises(sqlite3.IntegrityError):
self.collection.create_index('foo', unique=True)
assert 0 == len(self.collection.list_indexes())
def test_hint_index(self):
self.collection.create()
self.collection.insert({'foo':'bar','a':1})
self.collection.insert({'foo':'bar','a':2})
self.collection.insert({'fox':'baz','a':3})
self.collection.insert({'fox':'bar','a':4})
self.collection.create_index('foo')
self.collection.db = Mock(wraps=self.db)
docs_without_hint = self.collection.find({'foo':'bar', 'a':2})
self.collection.db.execute.assert_any_call(
'select id, data from foo '
)
docs_with_hint = self.collection.find({'foo':'bar', 'a':2}, hint='[foo{foo}]')
self.collection.db.execute.assert_any_call(
'select id, data from foo where id in (select id from [foo{foo}] where foo=\'"bar"\')'
)
assert docs_without_hint == docs_with_hint
def test_list_indexes(self):
self.test_create_index()
assert isinstance(self.collection.list_indexes(), list)
assert isinstance(self.collection.list_indexes()[0], str)
assert '[%s{%s}]' % (self.collection.name, 'foo') == self.collection.list_indexes()[0]
def test_list_indexes_as_keys(self):
self.test_create_index()
assert isinstance(self.collection.list_indexes(as_keys=True), list)
assert isinstance(self.collection.list_indexes(as_keys=True)[0], list)
assert ['foo'] == self.collection.list_indexes(as_keys=True)[0]
def test_drop_index(self):
self.test_create_index()
index_name = '[%s{%s}]' % (self.collection.name, 'foo')
self.collection.drop_index(index_name)
cmd = ("SELECT name FROM sqlite_master "
"WHERE type='table' and name like '{name}{{%}}'")
assert self.collection.db.execute(cmd.format(name=self.collection.name)).fetchone() is None
def test_drop_indexes(self):
self.test_create_index()
self.collection.drop_indexes()
cmd = ("SELECT name FROM sqlite_master "
"WHERE type='table' and name like '{name}{{%}}'")
assert self.collection.db.execute(cmd.format(name=self.collection.name)).fetchone() is None
def test_find_with_sort(self):
self.collection.create()
self.collection.save({'a':1, 'b':'c'})
self.collection.save({'a':1, 'b':'a'})
self.collection.save({'a':5, 'b':'x'})
self.collection.save({'a':3, 'b':'x'})
self.collection.save({'a':4, 'b':'z'})
assert [
{'a':1, 'b':'c', '_id':1},
{'a':1, 'b':'a', '_id':2},
{'a':5, 'b':'x', '_id':3},
{'a':3, 'b':'x', '_id':4},
{'a':4, 'b':'z', '_id':5},
] == self.collection.find()
assert [
{'a':1, 'b':'c', '_id':1},
{'a':1, 'b':'a', '_id':2},
{'a':3, 'b':'x', '_id':4},
{'a':4, 'b':'z', '_id':5},
{'a':5, 'b':'x', '_id':3},
] == self.collection.find(sort={'a':nosqlite.ASCENDING})
assert [
{'a':1, 'b':'a', '_id':2},
{'a':1, 'b':'c', '_id':1},
{'a':5, 'b':'x', '_id':3},
{'a':3, 'b':'x', '_id':4},
{'a':4, 'b':'z', '_id':5},
] == self.collection.find(sort={'b':nosqlite.ASCENDING})
assert [
{'a':5, 'b':'x', '_id':3},
{'a':4, 'b':'z', '_id':5},
{'a':3, 'b':'x', '_id':4},
{'a':1, 'b':'c', '_id':1},
{'a':1, 'b':'a', '_id':2},
] == self.collection.find(sort={'a':nosqlite.DESCENDING})
assert [
{'a':4, 'b':'z', '_id':5},
{'a':5, 'b':'x', '_id':3},
{'a':3, 'b':'x', '_id':4},
{'a':1, 'b':'c', '_id':1},
{'a':1, 'b':'a', '_id':2},
] == self.collection.find(sort={'b':nosqlite.DESCENDING})
assert [
{'a':1, 'b':'a', '_id':2},
{'a':1, 'b':'c', '_id':1},
{'a':3, 'b':'x', '_id':4},
{'a':4, 'b':'z', '_id':5},
{'a':5, 'b':'x', '_id':3},
] == self.collection.find(sort={'a':nosqlite.ASCENDING, 'b':nosqlite.ASCENDING})
assert [
{'a':5, 'b':'x', '_id':3},
{'a':4, 'b':'z', '_id':5},
{'a':3, 'b':'x', '_id':4},
{'a':1, 'b':'a', '_id':2},
{'a':1, 'b':'c', '_id':1},
] == self.collection.find(sort={'a':nosqlite.DESCENDING, 'b':nosqlite.ASCENDING})
assert [
{'a':5, 'b':'x', '_id':3},
{'a':4, 'b':'z', '_id':5},
{'a':3, 'b':'x', '_id':4},
{'a':1, 'b':'c', '_id':1},
{'a':1, 'b':'a', '_id':2},
] == self.collection.find(sort={'a':nosqlite.DESCENDING, 'b':nosqlite.DESCENDING})
def test_find_with_sort_on_nested_key(self):
self.collection.create()
self.collection.save({'a':{'b':5}, 'c':'B'})
self.collection.save({'a':{'b':9}, 'c':'A'})
self.collection.save({'a':{'b':7}, 'c':'C'})
assert [
{'a':{'b':5}, 'c':'B', '_id':1},
{'a':{'b':7}, 'c':'C', '_id':3},
{'a':{'b':9}, 'c':'A', '_id':2},
] == self.collection.find(sort={'a.b':nosqlite.ASCENDING})
assert [
{'a':{'b':9}, 'c':'A', '_id':2},
{'a':{'b':7}, 'c':'C', '_id':3},
{'a':{'b':5}, 'c':'B', '_id':1},
] == self.collection.find(sort={'a.b':nosqlite.DESCENDING})
@mark.parametrize('strdoc,doc', [
('{"foo": "bar"}', {'_id': 1, 'foo': 'bar'}),
('{"foo": "☃"}', {'_id': 1, 'foo': '☃'}),
])
def test_load(self, strdoc, doc):
assert doc == self.collection._load(1, strdoc)
def test_find(self):
query = {'foo': 'bar'}
documents = [
(1, {'foo': 'bar', 'baz': 'qux'}), # Will match
(2, {'foo': 'bar', 'bar': 'baz'}), # Will match
(2, {'foo': 'baz', 'bar': 'baz'}), # Will not match
(3, {'baz': 'qux'}), # Will not match
]
collection = nosqlite.Collection(Mock(), 'foo', create=False)
collection.db.execute.return_value = collection.db
collection.db.fetchall.return_value = documents
collection._load = lambda id, data: data
ret = collection.find(query)
assert len(ret) == 2
def test_find_honors_limit(self):
query = {'foo': 'bar'}
documents = [
(1, {'foo': 'bar', 'baz': 'qux'}), # Will match
(2, {'foo': 'bar', 'bar': 'baz'}), # Will match
(2, {'foo': 'baz', 'bar': 'baz'}), # Will not match
(3, {'baz': 'qux'}), # Will not match
]
collection = nosqlite.Collection(Mock(), 'foo', create=False)
collection.db.execute.return_value = collection.db
collection.db.fetchall.return_value = documents
collection._load = lambda id, data: data
ret = collection.find(query, limit=1)
assert len(ret) == 1
def test_apply_query_and_type(self):
query = {'$and': [{'foo': 'bar'}, {'baz': 'qux'}]}
assert self.collection._apply_query(query, {'foo': 'bar', 'baz': 'qux'})
assert not self.collection._apply_query(query, {'foo': 'bar', 'baz': 'foo'})
def test_apply_query_or_type(self):
query = {'$or': [{'foo': 'bar'}, {'baz': 'qux'}]}
assert self.collection._apply_query(query, {'foo': 'bar', 'abc': 'xyz'})
assert self.collection._apply_query(query, {'baz': 'qux', 'abc': 'xyz'})
assert not self.collection._apply_query(query, {'abc': 'xyz'})
def test_apply_query_not_type(self):
query = {'$not': {'foo': 'bar'}}
assert self.collection._apply_query(query, {'foo': 'baz'})
assert not self.collection._apply_query(query, {'foo': 'bar'})
def test_apply_query_nor_type(self):
query = {'$nor': [{'foo': 'bar'}, {'baz': 'qux'}]}
assert self.collection._apply_query(query, {'foo': 'baz', 'baz': 'bar'})
assert not self.collection._apply_query(query, {'foo': 'bar'})
assert not self.collection._apply_query(query, {'baz': 'qux'})
assert not self.collection._apply_query(query, {'foo': 'bar', 'baz': 'qux'})
def test_apply_query_gt_operator(self):
query = {'foo': {'$gt': 5}}
assert self.collection._apply_query(query, {'foo': 10})
assert not self.collection._apply_query(query, {'foo': 4})
def test_apply_query_gte_operator(self):
query = {'foo': {'$gte': 5}}
assert self.collection._apply_query(query, {'foo': 5})
assert not self.collection._apply_query(query, {'foo': 4})
def test_apply_query_lt_operator(self):
query = {'foo': {'$lt': 5}}
assert self.collection._apply_query(query, {'foo': 4})
assert not self.collection._apply_query(query, {'foo': 10})
def test_apply_query_lte_operator(self):
query = {'foo': {'$lte': 5}}
assert self.collection._apply_query(query, {'foo': 5})
assert not self.collection._apply_query(query, {'foo': 10})
def test_apply_query_eq_operator(self):
query = {'foo': {'$eq': 5}}
assert self.collection._apply_query(query, {'foo': 5})
assert not self.collection._apply_query(query, {'foo': 4})
assert not self.collection._apply_query(query, {'foo': 'bar'})
def test_apply_query_in_operator(self):
query = {'foo': {'$in': [1, 2, 3]}}
assert self.collection._apply_query(query, {'foo': 1})
assert not self.collection._apply_query(query, {'foo': 4})
assert not self.collection._apply_query(query, {'foo': 'bar'})
def test_apply_query_in_operator_raises(self):
query = {'foo': {'$in': 5}}
with raises(nosqlite.MalformedQueryException):
self.collection._apply_query(query, {'foo': 1})
def test_apply_query_nin_operator(self):
query = {'foo': {'$nin': [1, 2, 3]}}
assert self.collection._apply_query(query, {'foo': 4})
assert self.collection._apply_query(query, {'foo': 'bar'})
assert not self.collection._apply_query(query, {'foo': 1})
def test_apply_query_nin_operator_raises(self):
query = {'foo': {'$nin': 5}}
with raises(nosqlite.MalformedQueryException):
self.collection._apply_query(query, {'foo': 1})
def test_apply_query_ne_operator(self):
query = {'foo': {'$ne': 5}}
assert self.collection._apply_query(query, {'foo': 1})
assert self.collection._apply_query(query, {'foo': 'bar'})
assert not self.collection._apply_query(query, {'foo': 5})
def test_apply_query_all_operator(self):
query = {'foo': {'$all': [1, 2, 3]}}
assert self.collection._apply_query(query, {'foo': list(range(10))})
assert not self.collection._apply_query(query, {'foo': ['bar', 'baz']})
assert not self.collection._apply_query(query, {'foo': 3})
def test_apply_query_all_operator_raises(self):
query = {'foo': {'$all': 3}}
with raises(nosqlite.MalformedQueryException):
self.collection._apply_query(query, {'foo': 'bar'})
def test_apply_query_mod_operator(self):
query = {'foo': {'$mod': [2, 0]}}
assert self.collection._apply_query(query, {'foo': 4})
assert not self.collection._apply_query(query, {'foo': 3})
assert not self.collection._apply_query(query, {'foo': 'bar'})
def test_apply_query_mod_operator_raises(self):
query = {'foo': {'$mod': 2}}
with raises(nosqlite.MalformedQueryException):
self.collection._apply_query(query, {'foo': 5})
def test_apply_query_honors_multiple_operators(self):
query = {'foo': {'$gte': 0, '$lte': 10, '$mod': [2, 0]}}
assert self.collection._apply_query(query, {'foo': 4})
assert not self.collection._apply_query(query, {'foo': 3})
assert not self.collection._apply_query(query, {'foo': 15})
assert not self.collection._apply_query(query, {'foo': 'foo'})
def test_apply_query_honors_logical_and_operators(self):
# 'bar' must be 'baz', and 'foo' must be an even number 0-10 or an odd number > 10
query = {
'bar': 'baz',
'$or': [
{'foo': {'$gte': 0, '$lte': 10, '$mod': [2, 0]}},
{'foo': {'$gt': 10, '$mod': [2, 1]}},
]
}
assert self.collection._apply_query(query, {'bar': 'baz', 'foo': 4})
assert self.collection._apply_query(query, {'bar': 'baz', 'foo': 15})
assert not self.collection._apply_query(query, {'bar': 'baz', 'foo': 14})
assert not self.collection._apply_query(query, {'bar': 'qux', 'foo': 4})
def test_apply_query_exists(self):
query_exists = {'foo': {'$exists': True}}
query_not_exists = {'foo': {'$exists': False}}
assert self.collection._apply_query(query_exists, {'foo': 'bar'})
assert self.collection._apply_query(query_not_exists, {'bar': 'baz'})
assert not self.collection._apply_query(query_exists, {'baz': 'bar'})
assert not self.collection._apply_query(query_not_exists, {'foo': 'bar'})
def test_apply_query_exists_raises(self):
query = {'foo': {'$exists': 'foo'}}
with raises(nosqlite.MalformedQueryException):
self.collection._apply_query(query, {'foo': 'bar'})
def test_get_operator_fn_improper_op(self):
with raises(nosqlite.MalformedQueryException):
self.collection._get_operator_fn('foo')
def test_get_operator_fn_valid_op(self):
assert self.collection._get_operator_fn('$in') == nosqlite._in
def test_get_operator_fn_no_op(self):
with raises(nosqlite.MalformedQueryException):
self.collection._get_operator_fn('$foo')
def test_find_and_modify(self):
update = {'foo': 'bar'}
docs = [
{'foo': 'foo'},
{'baz': 'qux'},
]
with patch.object(self.collection, 'find'):
with patch.object(self.collection, 'save'):
self.collection.find.return_value = docs
self.collection.find_and_modify(update=update)
self.collection.save.assert_has_calls([
call({'foo': 'bar'}),
call({'foo': 'bar', 'baz': 'qux'}),
])
def test_count(self):
with patch.object(self.collection, 'find'):
self.collection.find.return_value = list(range(10))
assert self.collection.count() == 10
def test_distinct(self):
docs = [
{'foo': 'bar'},
{'foo': 'baz'},
{'foo': 10},
{'bar': 'foo'}
]
self.collection.find = lambda: docs
assert set(('bar', 'baz', 10)) == self.collection.distinct('foo')
def test_rename_raises_for_collision(self):
nosqlite.Collection(self.db, 'bar') # Create a collision point
self.collection.create()
with raises(AssertionError):
self.collection.rename('bar')
def test_rename(self):
self.collection.create()
assert self.collection.exists()
self.collection.rename('bar')
assert self.collection.name == 'bar'
assert self.collection.exists()
assert not nosqlite.Collection(self.db, 'foo', create=False).exists()
class TestFindOne:
def test_returns_None_if_collection_does_not_exist(self, collection):
assert collection.find_one({}) is None
def test_returns_None_if_document_is_not_found(self, collection):
collection.create()
assert collection.find_one({}) is None