forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_database.py
More file actions
738 lines (587 loc) · 27.5 KB
/
test_database.py
File metadata and controls
738 lines (587 loc) · 27.5 KB
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
# Copyright 2009-2012 10gen, Inc.
#
# 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.
"""Test the database module."""
import datetime
import os
import sys
sys.path[0:0] = [""]
import unittest
from nose.plugins.skip import SkipTest
from bson.code import Code
from bson.dbref import DBRef
from bson.objectid import ObjectId
from bson.son import SON
from pymongo import (ALL,
auth,
helpers,
OFF,
SLOW_ONLY)
from pymongo.collection import Collection
from pymongo.database import Database
from pymongo.errors import (CollectionInvalid,
ConfigurationError,
InvalidName,
OperationFailure)
from pymongo.son_manipulator import (AutoReference,
NamespaceInjector,
ObjectIdShuffler)
from test import version
from test.utils import is_mongos, server_started_with_auth
from test.test_connection import get_connection
class TestDatabase(unittest.TestCase):
def setUp(self):
self.connection = get_connection()
def test_name(self):
self.assertRaises(TypeError, Database, self.connection, 4)
self.assertRaises(InvalidName, Database, self.connection, "my db")
self.assertRaises(InvalidName, Database, self.connection, "my\x00db")
self.assertRaises(InvalidName, Database,
self.connection, u"my\u0000db")
self.assertEqual("name", Database(self.connection, "name").name)
def test_equality(self):
self.assertNotEqual(Database(self.connection, "test"),
Database(self.connection, "mike"))
self.assertEqual(Database(self.connection, "test"),
Database(self.connection, "test"))
# Explicitly test inequality
self.assertFalse(Database(self.connection, "test") !=
Database(self.connection, "test"))
def test_repr(self):
self.assertEqual(repr(Database(self.connection, "pymongo_test")),
"Database(%r, %s)" % (self.connection,
repr(u"pymongo_test")))
def test_get_coll(self):
db = Database(self.connection, "pymongo_test")
self.assertEqual(db.test, db["test"])
self.assertEqual(db.test, Collection(db, "test"))
self.assertNotEqual(db.test, Collection(db, "mike"))
self.assertEqual(db.test.mike, db["test.mike"])
def test_create_collection(self):
db = Database(self.connection, "pymongo_test")
db.test.insert({"hello": "world"})
self.assertRaises(CollectionInvalid, db.create_collection, "test")
db.drop_collection("test")
self.assertRaises(TypeError, db.create_collection, 5)
self.assertRaises(TypeError, db.create_collection, None)
self.assertRaises(InvalidName, db.create_collection, "coll..ection")
test = db.create_collection("test")
test.save({"hello": u"world"})
self.assertEqual(db.test.find_one()["hello"], "world")
self.assertTrue(u"test" in db.collection_names())
db.drop_collection("test.foo")
db.create_collection("test.foo")
self.assertTrue(u"test.foo" in db.collection_names())
self.assertEqual(db.test.foo.options(), {})
self.assertRaises(CollectionInvalid, db.create_collection, "test.foo")
def test_collection_names(self):
db = Database(self.connection, "pymongo_test")
db.test.save({"dummy": u"object"})
db.test.mike.save({"dummy": u"object"})
colls = db.collection_names()
self.assertTrue("test" in colls)
self.assertTrue("test.mike" in colls)
for coll in colls:
self.assertTrue("$" not in coll)
def test_drop_collection(self):
db = Database(self.connection, "pymongo_test")
self.assertRaises(TypeError, db.drop_collection, 5)
self.assertRaises(TypeError, db.drop_collection, None)
db.test.save({"dummy": u"object"})
self.assertTrue("test" in db.collection_names())
db.drop_collection("test")
self.assertFalse("test" in db.collection_names())
db.test.save({"dummy": u"object"})
self.assertTrue("test" in db.collection_names())
db.drop_collection(u"test")
self.assertFalse("test" in db.collection_names())
db.test.save({"dummy": u"object"})
self.assertTrue("test" in db.collection_names())
db.drop_collection(db.test)
self.assertFalse("test" in db.collection_names())
db.test.save({"dummy": u"object"})
self.assertTrue("test" in db.collection_names())
db.test.drop()
self.assertFalse("test" in db.collection_names())
db.test.drop()
db.drop_collection(db.test.doesnotexist)
def test_validate_collection(self):
db = self.connection.pymongo_test
self.assertRaises(TypeError, db.validate_collection, 5)
self.assertRaises(TypeError, db.validate_collection, None)
db.test.save({"dummy": u"object"})
self.assertRaises(OperationFailure, db.validate_collection,
"test.doesnotexist")
self.assertRaises(OperationFailure, db.validate_collection,
db.test.doesnotexist)
self.assertTrue(db.validate_collection("test"))
self.assertTrue(db.validate_collection(db.test))
self.assertTrue(db.validate_collection(db.test, full=True))
self.assertTrue(db.validate_collection(db.test, scandata=True))
self.assertTrue(db.validate_collection(db.test, scandata=True, full=True))
self.assertTrue(db.validate_collection(db.test, True, True))
def test_profiling_levels(self):
if is_mongos(self.connection):
raise SkipTest('profile is not supported by mongos')
db = self.connection.pymongo_test
self.assertEqual(db.profiling_level(), OFF) # default
self.assertRaises(ValueError, db.set_profiling_level, 5.5)
self.assertRaises(ValueError, db.set_profiling_level, None)
self.assertRaises(ValueError, db.set_profiling_level, -1)
self.assertRaises(TypeError, db.set_profiling_level, SLOW_ONLY, 5.5)
self.assertRaises(TypeError, db.set_profiling_level, SLOW_ONLY, '1')
db.set_profiling_level(SLOW_ONLY)
self.assertEqual(db.profiling_level(), SLOW_ONLY)
db.set_profiling_level(ALL)
self.assertEqual(db.profiling_level(), ALL)
db.set_profiling_level(OFF)
self.assertEqual(db.profiling_level(), OFF)
db.set_profiling_level(SLOW_ONLY, 50)
self.assertEqual(50, db.command("profile", -1)['slowms'])
db.set_profiling_level(ALL, -1)
self.assertEqual(-1, db.command("profile", -1)['slowms'])
db.set_profiling_level(OFF, 100) # back to default
self.assertEqual(100, db.command("profile", -1)['slowms'])
def test_profiling_info(self):
if is_mongos(self.connection):
raise SkipTest('profile is not supported by mongos')
db = self.connection.pymongo_test
db.set_profiling_level(ALL)
db.test.find()
db.set_profiling_level(OFF)
info = db.profiling_info()
self.assertTrue(isinstance(info, list))
# Check if we're going to fail because of SERVER-4754, in which
# profiling info isn't collected if mongod was started with --auth
if server_started_with_auth(self.connection):
raise SkipTest(
"We need SERVER-4754 fixed for the rest of this test to pass"
)
self.assertTrue(len(info) >= 1)
# These basically clue us in to server changes.
if version.at_least(db.connection, (1, 9, 1, -1)):
self.assertTrue(isinstance(info[0]['responseLength'], int))
self.assertTrue(isinstance(info[0]['millis'], int))
self.assertTrue(isinstance(info[0]['client'], basestring))
self.assertTrue(isinstance(info[0]['user'], basestring))
self.assertTrue(isinstance(info[0]['ntoreturn'], int))
self.assertTrue(isinstance(info[0]['ns'], basestring))
self.assertTrue(isinstance(info[0]['op'], basestring))
else:
self.assertTrue(isinstance(info[0]["info"], basestring))
self.assertTrue(isinstance(info[0]["millis"], float))
self.assertTrue(isinstance(info[0]["ts"], datetime.datetime))
def test_iteration(self):
db = self.connection.pymongo_test
def iterate():
[a for a in db]
self.assertRaises(TypeError, iterate)
def test_errors(self):
if is_mongos(self.connection):
raise SkipTest('getpreverror not supported by mongos')
db = self.connection.pymongo_test
db.reset_error_history()
self.assertEqual(None, db.error())
self.assertEqual(None, db.previous_error())
db.command("forceerror", check=False)
self.assertTrue(db.error())
self.assertTrue(db.previous_error())
db.command("forceerror", check=False)
self.assertTrue(db.error())
prev_error = db.previous_error()
self.assertEqual(prev_error["nPrev"], 1)
del prev_error["nPrev"]
prev_error.pop("lastOp", None)
error = db.error()
error.pop("lastOp", None)
# getLastError includes "connectionId" in recent
# server versions, getPrevError does not.
error.pop("connectionId", None)
self.assertEqual(error, prev_error)
db.test.find_one()
self.assertEqual(None, db.error())
self.assertTrue(db.previous_error())
self.assertEqual(db.previous_error()["nPrev"], 2)
db.reset_error_history()
self.assertEqual(None, db.error())
self.assertEqual(None, db.previous_error())
def test_command(self):
db = self.connection.admin
self.assertEqual(db.command("buildinfo"), db.command({"buildinfo": 1}))
def test_last_status(self):
db = self.connection.pymongo_test
db.test.remove({})
db.test.save({"i": 1})
db.test.update({"i": 1}, {"$set": {"i": 2}})
self.assertTrue(db.last_status()["updatedExisting"])
db.test.update({"i": 1}, {"$set": {"i": 500}})
self.assertFalse(db.last_status()["updatedExisting"])
def test_password_digest(self):
self.assertRaises(TypeError, auth._password_digest, 5)
self.assertRaises(TypeError, auth._password_digest, True)
self.assertRaises(TypeError, auth._password_digest, None)
self.assertTrue(isinstance(auth._password_digest("mike", "password"),
unicode))
self.assertEqual(auth._password_digest("mike", "password"),
u"cd7e45b3b2767dc2fa9b6b548457ed00")
self.assertEqual(auth._password_digest("mike", "password"),
auth._password_digest(u"mike", u"password"))
self.assertEqual(auth._password_digest("Gustave", u"Dor\xe9"),
u"81e0e2364499209f466e75926a162d73")
def test_authenticate_add_remove_user(self):
if (is_mongos(self.connection) and not
version.at_least(self.connection, (2, 0, 0))):
raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
db = self.connection.pymongo_test
db.system.users.remove({})
db.remove_user("mike")
self.assertRaises(TypeError, db.add_user, "user", None)
self.assertRaises(TypeError, db.add_user, "user", '')
self.assertRaises(TypeError, db.add_user, "user", 'password', None)
self.assertRaises(ConfigurationError, db.add_user,
"user", 'password', 'True')
db.add_user("mike", "password")
self.assertRaises(TypeError, db.authenticate, 5, "password")
self.assertRaises(TypeError, db.authenticate, "mike", 5)
self.assertFalse(db.authenticate("mike", "not a real password"))
self.assertFalse(db.authenticate("faker", "password"))
self.assertTrue(db.authenticate("mike", "password"))
self.assertTrue(db.authenticate(u"mike", u"password"))
db.logout()
db.remove_user("mike")
self.assertFalse(db.authenticate("mike", "password"))
self.assertFalse(db.authenticate("Gustave", u"Dor\xe9"))
db.add_user("Gustave", u"Dor\xe9")
self.assertTrue(db.authenticate("Gustave", u"Dor\xe9"))
db.logout()
db.add_user("Gustave", "password")
self.assertFalse(db.authenticate("Gustave", u"Dor\xe9"))
self.assertTrue(db.authenticate("Gustave", u"password"))
db.logout()
db.add_user("Ross", "password", read_only=True)
self.assertTrue(db.authenticate("Ross", u"password"))
self.assertTrue(db.system.users.find({"readOnly": True}).count())
db.logout()
def test_authenticate_and_safe(self):
if (is_mongos(self.connection) and not
version.at_least(self.connection, (2, 0, 0))):
raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
db = self.connection.auth_test
db.system.users.remove({})
db.add_user("bernie", "password")
db.authenticate("bernie", "password")
db.test.remove({})
self.assertTrue(db.test.insert({"bim": "baz"}, safe=True))
self.assertEqual(1, db.test.count())
self.assertEqual(1,
db.test.update({"bim": "baz"},
{"$set": {"bim": "bar"}},
safe=True).get('n'))
self.assertEqual(1,
db.test.remove({}, safe=True).get('n'))
self.assertEqual(0, db.test.count())
self.connection.drop_database("auth_test")
def test_authenticate_and_request(self):
if (is_mongos(self.connection) and not
version.at_least(self.connection, (2, 0, 0))):
raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
# Database.authenticate() needs to be in a request - check that it
# always runs in a request, and that it restores the request state
# (in or not in a request) properly when it's finished.
self.assertTrue(self.connection.auto_start_request)
db = self.connection.pymongo_test
db.system.users.remove({})
db.remove_user("mike")
db.add_user("mike", "password")
self.assertTrue(self.connection.in_request())
self.assertTrue(db.authenticate("mike", "password"))
self.assertTrue(self.connection.in_request())
no_request_cx = get_connection(auto_start_request=False)
no_request_db = no_request_cx.pymongo_test
self.assertFalse(no_request_cx.in_request())
self.assertTrue(no_request_db.authenticate("mike", "password"))
self.assertFalse(no_request_cx.in_request())
# just make sure there are no exceptions here
db.logout()
no_request_db.logout()
def test_authenticate_multiple(self):
conn = get_connection()
if (is_mongos(conn) and not
version.at_least(self.connection, (2, 0, 0))):
raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
if not server_started_with_auth(conn):
raise SkipTest("Authentication is not enabled on server")
# Setup
users_db = conn.pymongo_test
admin_db = conn.admin
other_db = conn.pymongo_test1
users_db.system.users.remove(safe=True)
admin_db.system.users.remove(safe=True)
users_db.test.remove(safe=True)
other_db.test.remove(safe=True)
admin_db.add_user('admin', 'pass')
self.assertTrue(admin_db.authenticate('admin', 'pass'))
admin_db.add_user('ro-admin', 'pass', read_only=True)
users_db.add_user('user', 'pass')
admin_db.logout()
self.assertRaises(OperationFailure, users_db.test.find_one)
# Regular user should be able to query its own db, but
# no other.
users_db.authenticate('user', 'pass')
self.assertEqual(0, users_db.test.count())
self.assertRaises(OperationFailure, other_db.test.find_one)
# Admin read-only user should be able to query any db,
# but not write.
admin_db.authenticate('ro-admin', 'pass')
self.assertEqual(0, other_db.test.count())
self.assertRaises(OperationFailure,
other_db.test.insert, {}, safe=True)
# Force close all sockets
conn.disconnect()
# We should still be able to write to the regular user's db
self.assertTrue(users_db.test.remove(safe=True))
# And read from other dbs...
self.assertEqual(0, other_db.test.count())
# But still not write to other dbs...
self.assertRaises(OperationFailure,
other_db.test.insert, {}, safe=True)
# Cleanup
admin_db.logout()
users_db.logout()
self.assertTrue(admin_db.authenticate('admin', 'pass'))
self.assertTrue(admin_db.system.users.remove(safe=True))
self.assertEqual(0, admin_db.system.users.count())
self.assertTrue(users_db.system.users.remove(safe=True))
def test_id_ordering(self):
# PyMongo attempts to have _id show up first
# when you iterate key/value pairs in a document.
# This isn't reliable since python dicts don't
# guarantee any particular order. This will never
# work right in Jython or Python >= 3.3 with
# hash randomization enabled.
db = self.connection.pymongo_test
db.test.remove({})
db.test.insert({"hello": "world", "_id": 5})
db.test.insert(SON([("hello", "world"),
("_id", 5)]))
if ((sys.version_info >= (3, 3) and
os.environ.get('PYTHONHASHSEED') != '0') or
sys.platform.startswith('java')):
# See http://bugs.python.org/issue13703 for why we
# use as_class=SON in certain environments.
cursor = db.test.find(as_class=SON)
else:
cursor = db.test.find()
for x in cursor:
for (k, v) in x.items():
self.assertEqual(k, "_id")
break
def test_deref(self):
db = self.connection.pymongo_test
db.test.remove({})
self.assertRaises(TypeError, db.dereference, 5)
self.assertRaises(TypeError, db.dereference, "hello")
self.assertRaises(TypeError, db.dereference, None)
self.assertEqual(None, db.dereference(DBRef("test", ObjectId())))
obj = {"x": True}
key = db.test.save(obj)
self.assertEqual(obj, db.dereference(DBRef("test", key)))
self.assertEqual(obj,
db.dereference(DBRef("test", key, "pymongo_test")))
self.assertRaises(ValueError,
db.dereference, DBRef("test", key, "foo"))
self.assertEqual(None, db.dereference(DBRef("test", 4)))
obj = {"_id": 4}
db.test.save(obj)
self.assertEqual(obj, db.dereference(DBRef("test", 4)))
def test_eval(self):
db = self.connection.pymongo_test
db.test.remove({})
self.assertRaises(TypeError, db.eval, None)
self.assertRaises(TypeError, db.eval, 5)
self.assertRaises(TypeError, db.eval, [])
self.assertEqual(3, db.eval("function (x) {return x;}", 3))
self.assertEqual(3, db.eval(u"function (x) {return x;}", 3))
self.assertEqual(None,
db.eval("function (x) {db.test.save({y:x});}", 5))
self.assertEqual(db.test.find_one()["y"], 5)
self.assertEqual(5, db.eval("function (x, y) {return x + y;}", 2, 3))
self.assertEqual(5, db.eval("function () {return 5;}"))
self.assertEqual(5, db.eval("2 + 3;"))
self.assertEqual(5, db.eval(Code("2 + 3;")))
self.assertRaises(OperationFailure, db.eval, Code("return i;"))
self.assertEqual(2, db.eval(Code("return i;", {"i": 2})))
self.assertEqual(5, db.eval(Code("i + 3;", {"i": 2})))
self.assertRaises(OperationFailure, db.eval, "5 ++ 5;")
# TODO some of these tests belong in the collection level testing.
def test_save_find_one(self):
db = Database(self.connection, "pymongo_test")
db.test.remove({})
a_doc = SON({"hello": u"world"})
a_key = db.test.save(a_doc)
self.assertTrue(isinstance(a_doc["_id"], ObjectId))
self.assertEqual(a_doc["_id"], a_key)
self.assertEqual(a_doc, db.test.find_one({"_id": a_doc["_id"]}))
self.assertEqual(a_doc, db.test.find_one(a_key))
self.assertEqual(None, db.test.find_one(ObjectId()))
self.assertEqual(a_doc, db.test.find_one({"hello": u"world"}))
self.assertEqual(None, db.test.find_one({"hello": u"test"}))
b = db.test.find_one()
b["hello"] = u"mike"
db.test.save(b)
self.assertNotEqual(a_doc, db.test.find_one(a_key))
self.assertEqual(b, db.test.find_one(a_key))
self.assertEqual(b, db.test.find_one())
count = 0
for _ in db.test.find():
count += 1
self.assertEqual(count, 1)
def test_long(self):
db = self.connection.pymongo_test
db.test.remove({})
db.test.save({"x": 9223372036854775807L})
self.assertEqual(9223372036854775807L, db.test.find_one()["x"])
def test_remove(self):
db = self.connection.pymongo_test
db.test.remove({})
one = db.test.save({"x": 1})
db.test.save({"x": 2})
db.test.save({"x": 3})
length = 0
for _ in db.test.find():
length += 1
self.assertEqual(length, 3)
db.test.remove(one)
length = 0
for _ in db.test.find():
length += 1
self.assertEqual(length, 2)
db.test.remove(db.test.find_one())
db.test.remove(db.test.find_one())
self.assertEqual(db.test.find_one(), None)
one = db.test.save({"x": 1})
db.test.save({"x": 2})
db.test.save({"x": 3})
self.assertTrue(db.test.find_one({"x": 2}))
db.test.remove({"x": 2})
self.assertFalse(db.test.find_one({"x": 2}))
self.assertTrue(db.test.find_one())
db.test.remove({})
self.assertFalse(db.test.find_one())
def test_save_a_bunch(self):
db = self.connection.pymongo_test
db.test.remove({})
for i in xrange(1000):
db.test.save({"x": i})
count = 0
for _ in db.test.find():
count += 1
self.assertEqual(1000, count)
# test that kill cursors doesn't assert or anything
for _ in xrange(62):
for _ in db.test.find():
break
def test_auto_ref_and_deref(self):
db = self.connection.pymongo_test
db.add_son_manipulator(AutoReference(db))
db.add_son_manipulator(NamespaceInjector())
db.test.a.remove({})
db.test.b.remove({})
db.test.c.remove({})
a = {"hello": u"world"}
db.test.a.save(a)
b = {"test": a}
db.test.b.save(b)
c = {"another test": b}
db.test.c.save(c)
a["hello"] = "mike"
db.test.a.save(a)
self.assertEqual(db.test.a.find_one(), a)
self.assertEqual(db.test.b.find_one()["test"], a)
self.assertEqual(db.test.c.find_one()["another test"]["test"], a)
self.assertEqual(db.test.b.find_one(), b)
self.assertEqual(db.test.c.find_one()["another test"], b)
self.assertEqual(db.test.c.find_one(), c)
# some stuff the user marc wanted to be able to do, make sure it works
def test_marc(self):
db = self.connection.pymongo_test
db.add_son_manipulator(AutoReference(db))
db.add_son_manipulator(NamespaceInjector())
db.drop_collection("users")
db.drop_collection("messages")
message_1 = {"title": "foo"}
db.messages.save(message_1)
message_2 = {"title": "bar"}
db.messages.save(message_2)
user = {"name": "marc",
"messages": [message_1, message_2]}
db.users.save(user)
message = db.messages.find_one()
db.messages.update(message, {"title": "buzz"})
self.assertEqual("buzz", db.users.find_one()["messages"][0]["title"])
self.assertEqual("bar", db.users.find_one()["messages"][1]["title"])
def test_system_js(self):
db = self.connection.pymongo_test
db.system.js.remove()
self.assertEqual(0, db.system.js.count())
db.system_js.add = "function(a, b) { return a + b; }"
self.assertEqual('add', db.system.js.find_one()['_id'])
self.assertEqual(1, db.system.js.count())
self.assertEqual(6, db.system_js.add(1, 5))
del db.system_js.add
self.assertEqual(0, db.system.js.count())
db.system_js['add'] = "function(a, b) { return a + b; }"
self.assertEqual('add', db.system.js.find_one()['_id'])
self.assertEqual(1, db.system.js.count())
self.assertEqual(6, db.system_js['add'](1, 5))
del db.system_js['add']
self.assertEqual(0, db.system.js.count())
if version.at_least(db.connection, (1, 3, 2, -1)):
self.assertRaises(OperationFailure, db.system_js.add, 1, 5)
# TODO right now CodeWScope doesn't work w/ system js
# db.system_js.scope = Code("return hello;", {"hello": 8})
# self.assertEqual(8, db.system_js.scope())
self.assertRaises(OperationFailure, db.system_js.non_existant)
# XXX: Broken in V8, works in SpiderMonkey
if not version.at_least(db.connection, (2, 3, 0)):
db.system_js.no_param = Code("return 5;")
self.assertEqual(5, db.system_js.no_param())
def test_system_js_list(self):
db = self.connection.pymongo_test
db.system.js.remove()
self.assertEqual([], db.system_js.list())
db.system_js.foo = "function() { return 'blah'; }"
self.assertEqual(["foo"], db.system_js.list())
db.system_js.bar = "function() { return 'baz'; }"
self.assertEqual(set(["foo", "bar"]), set(db.system_js.list()))
del db.system_js.foo
self.assertEqual(["bar"], db.system_js.list())
def test_manipulator_properties(self):
db = self.connection.foo
self.assertEqual(['ObjectIdInjector'], db.incoming_manipulators)
self.assertEqual([], db.incoming_copying_manipulators)
self.assertEqual([], db.outgoing_manipulators)
self.assertEqual([], db.outgoing_copying_manipulators)
db.add_son_manipulator(AutoReference(db))
db.add_son_manipulator(NamespaceInjector())
db.add_son_manipulator(ObjectIdShuffler())
self.assertEqual(2, len(db.incoming_manipulators))
for name in db.incoming_manipulators:
self.assertTrue(name in ('ObjectIdInjector', 'NamespaceInjector'))
self.assertEqual(2, len(db.incoming_copying_manipulators))
for name in db.incoming_copying_manipulators:
self.assertTrue(name in ('ObjectIdShuffler', 'AutoReference'))
self.assertEqual([], db.outgoing_manipulators)
self.assertEqual(['AutoReference'], db.outgoing_copying_manipulators)
if __name__ == "__main__":
unittest.main()