Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
map_fn = bson.Code('function map() { emit(this._id % 2, 1); }')
reduce_fn = bson.Code('''
function reduce(key, values) {
r = 0;
values.forEach(function(value) { r += value; });
return r;
}''')
yield self.db.tmp_mr.drop()
# First do a standard mapreduce, should return MotorCollection
collection = self.collection
tmp_mr = yield collection.map_reduce(map_fn, reduce_fn, 'tmp_mr')
self.assertTrue(
isinstance(tmp_mr, motor.MotorCollection),
'map_reduce should return MotorCollection, not %s' % tmp_mr)
result = yield tmp_mr.find().sort([('_id', 1)]).to_list(length=1000)
self.assertEqual(expected_result, result)
# Standard mapreduce with full response
yield self.db.tmp_mr.drop()
response = yield collection.map_reduce(
map_fn, reduce_fn, 'tmp_mr', full_response=True)
self.assertTrue(
isinstance(response, dict),
'map_reduce should return dict, not %s' % response)
self.assertEqual('tmp_mr', response['result'])
result = yield tmp_mr.find().sort([('_id', 1)]).to_list(length=1000)
yield db.drop_collection('test_collection2')
collection = yield db.create_collection('test_collection2')
self.assertTrue(isinstance(collection, motor.MotorCollection))
self.assertTrue(
'test_collection2' in (yield db.list_collection_names()))
with self.assertRaises(CollectionInvalid):
yield db.create_collection('test_collection2')
yield db.drop_collection('test_collection2')
# Test creating capped collection
collection = yield db.create_collection(
'test_capped', capped=True, size=4096)
self.assertTrue(isinstance(collection, motor.MotorCollection))
self.assertEqual(
{"capped": True, 'size': 4096},
(yield db.test_capped.options()))
yield db.drop_collection('test_capped')
def test_collection(self):
# Test that we can create a collection directly, not just from
# MotorClient's accessors
collection = motor.MotorCollection(self.db, 'test_collection')
# Make sure we got the right collection and it can do an operation
self.assertEqual('test_collection', collection.name)
yield collection.insert({'_id': 1})
doc = yield collection.find_one({'_id': 1})
self.assertEqual(1, doc['_id'])
# If you pass kwargs to PyMongo's Collection(), it calls
# db.create_collection(). Motor can't do I/O in a constructor
# so this is prohibited.
self.assertRaises(
TypeError,
motor.MotorCollection,
self.db,
'test_collection',
capped=True)
def test_collection(self):
# Test that we can create a collection directly, not just from
# MotorClient's accessors
collection = motor.MotorCollection(self.db, 'test_collection')
# Make sure we got the right collection and it can do an operation
self.assertEqual('test_collection', collection.name)
yield collection.insert_one({'_id': 1})
doc = yield collection.find_one({'_id': 1})
self.assertEqual(1, doc['_id'])
# If you pass kwargs to PyMongo's Collection(), it calls
# db.create_collection(). Motor can't do I/O in a constructor
# so this is prohibited.
self.assertRaises(
TypeError,
motor.MotorCollection,
self.db,
'test_collection',
capped=True)
def test_underscore(self):
self.assertIsInstance(self.cx['_db'],
motor.MotorDatabase)
self.assertIsInstance(self.db['_collection'],
motor.MotorCollection)
self.assertIsInstance(self.collection['_collection'],
motor.MotorCollection)
with self.assertRaises(AttributeError):
self.cx._db
with self.assertRaises(AttributeError):
self.db._collection
with self.assertRaises(AttributeError):
self.collection._collection
def test_insert_find_motor(self):
"""Motor: Test document save, find, find_one"""
MOTOR_CLIENT = motor.MotorClient(io_loop=self.io_loop)
class Doc(BaseDocument):
dot_notation = True
foo = Field(six.text_type)
bar = Field(int, required=False)
Doc.register(client=MOTOR_CLIENT, db='nanotestdb')
col = Doc.get_collection()
self.assertTrue(isinstance(col, motor.MotorCollection))
result = yield motor.Op(Doc.find_one)
self.assertEqual(None, result)
d = Doc(foo=six.u('foo value'), bar=42)
_id = yield motor.Op(d.insert)
self.assertTrue(isinstance(_id, ObjectId))
result = yield motor.Op(Doc.find({'foo': 'foo value'}).count)
self.assertEqual(1, result)
result = yield motor.Op(Doc.find_one, {'bar': 42})
self.assertEqual(d, result)
def _wrap_synchro(*args, **kwargs):
motor_obj = fn(*args, **kwargs)
# Not all Motor classes appear here, only those we need to return
# from methods like map_reduce() or create_collection()
if isinstance(motor_obj, motor.MotorCollection):
client = MongoClient(delegate=motor_obj.database.client)
database = Database(client, motor_obj.database.name)
return Collection(database, motor_obj.name, delegate=motor_obj)
if isinstance(motor_obj, motor.motor_tornado.MotorClientSession):
return ClientSession(delegate=motor_obj)
if isinstance(motor_obj, _MotorTransactionContext):
return _SynchroTransactionContext(motor_obj)
if isinstance(motor_obj, motor.MotorDatabase):
client = MongoClient(delegate=motor_obj.client)
return Database(client, motor_obj.name, delegate=motor_obj)
if isinstance(motor_obj, motor.motor_tornado.MotorChangeStream):
# Send the initial aggregate as PyMongo expects.
motor_obj._lazy_init()
return ChangeStream(motor_obj)
if isinstance(motor_obj, motor.motor_tornado.MotorLatentCommandCursor):
return CommandCursor(motor_obj)
def __init__(self):
"""
:return:
"""
self.__get_db()
self._collection = self.__get_collection(self.get_name_collection())
motor.MotorCollection.__init__(self, self._client, self.get_name_collection())
Loader.__init__(self)
self.synchronize(cursor.delegate._get_more)()
return cursor
@property
def client(self):
return self._client
def __getattr__(self, name):
return Collection(self, name, delegate=getattr(self.delegate, name))
def __getitem__(self, name):
return Collection(self, name, delegate=self.delegate[name])
class Collection(Synchro):
__delegate_class__ = motor.MotorCollection
find = WrapOutgoing()
find_raw_batches = WrapOutgoing()
list_indexes = WrapOutgoing()
watch = WrapOutgoing()
def __init__(self, database, name, **kwargs):
if not isinstance(database, Database):
raise TypeError(
"First argument to synchro Collection must be synchro "
"Database, not %s" % repr(database))
self.database = database
self.delegate = kwargs.get('delegate') or motor.MotorCollection(
self.database.delegate, name, **kwargs)
def __init__(self, database, name, **kwargs):
if not isinstance(database, Database):
raise TypeError(
"First argument to synchro Collection must be synchro "
"Database, not %s" % repr(database))
self.database = database
self.delegate = kwargs.get('delegate') or motor.MotorCollection(
self.database.delegate, name, **kwargs)
if not isinstance(self.delegate, motor.MotorCollection):
raise TypeError(
"Expected to get synchro Collection from Database,"
" got %s" % repr(self.delegate))