Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_validate_collection(self):
db = self.client.pymongo_test
self.assertRaises(TypeError, db.validate_collection, 5)
self.assertRaises(TypeError, db.validate_collection, None)
db.test.insert_one({"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_fetch_next_exception(self):
coll = self.collection
cursor = coll.find()
cursor.delegate._Cursor__id = 1234 # Not valid on server.
with self.assertRaises(OperationFailure):
yield from cursor.fetch_next
# Avoid the cursor trying to close itself when it goes out of scope.
cursor.delegate._Cursor__id = None
def clear_transactions(self):
try:
commands.rollback()
except OperationFailure as error:
message = utils.get_error_message(error)
if messages.NO_TRANSACTION_ERROR not in message:
raise
def test_mongo_write_failure():
"""Testing MongoDB core handling of writing failure scenarios."""
with pytest.raises(OperationFailure):
val1 = _func_w_bad_mongo(1, 2)
val2 = _func_w_bad_mongo(1, 2)
assert val1 == val2
# add one object to an array with push
edition = {
'year': '1997',
'editorial': 'planet'
}
db_replica.books.update({'_id': 'hobbit' }, {'$push': {'editions': edition}}) # quite similar to mongo shell
print db_replica.books.find_one({'_id': 'hobbit'})
# try to perform array operation over non-array element
try:
db_replica.books.update({'_id': 'lord_rings' }, {'$push': {'editions': edition}}) # non array operation
except OperationFailure as e:
print e
# Create another edition
edition = {
'year': '2001',
'editorial': 'planet-lion'
}
db_replica.books.update({'_id': 'hobbit' }, {'$push': {'editions': edition}})
# Result ..
for edition in db_replica.books.find_one({'_id': 'hobbit'})['editions']:
print edition
# How to update one document name inside array of object ?:
db_replica.books.update(
{'_id': 'hobbit', # find document hobbit
def create_index(self, cls_or_collection, *args, **kwargs):
if not isinstance(cls_or_collection, six.string_types):
collection = self.get_collection_for_cls(cls_or_collection)
else:
collection = cls_or_collection
if 'fields' not in kwargs:
raise AttributeError("You must specify the 'fields' parameter when creating an index!")
if 'opts' in kwargs:
opts = kwargs['opts']
else:
opts = {}
try:
self.db[collection].ensure_index(list(kwargs['fields'].items()), **opts)
except pymongo.errors.OperationFailure as failure:
traceback.print_exc()
#The index already exists with different options, so we drop it and recreate it...
self.db[collection].drop_index(list(kwargs['fields'].items()))
self.db[collection].ensure_index(list(kwargs['fields'].items()), **opts)
:param collection: The name of the collection where to save the results.
:type collection: str
:param db_options: The database connection parameters.
:type db_options: dict
"""
# Store the entire result from the comparison into a dedicated key.
# When searching with the comparison ID, we just extract the "data" key
# and return whatever has been saved there.
json_obj["data"] = result
database = utils.db.get_db_connection(db_options)
doc_id = None
try:
ret_value, doc_id = database[collection].save(json_obj)
except pymongo.errors.OperationFailure:
utils.LOG.error("Error saving delta doc for %s", collection)
return doc_id
def _legacy_write(self, sock_info, name, cmd, acknowledged, op_id,
bypass_doc_val, func, *args):
"""Internal legacy write helper."""
# Cannot have both unacknowledged write and bypass document validation.
if (bypass_doc_val and not acknowledged and
sock_info.max_wire_version >= 4):
raise OperationFailure("Cannot set bypass_document_validation with"
" unacknowledged write concern")
listeners = self.database.client._event_listeners
publish = listeners.enabled_for_commands
if publish:
start = datetime.datetime.now()
rqst_id, msg, max_size = func(*args)
if publish:
duration = datetime.datetime.now() - start
listeners.publish_command_start(
cmd, self.__database.name, rqst_id, sock_info.address, op_id)
start = datetime.datetime.now()
try:
result = sock_info.legacy_write(
rqst_id, msg, max_size, acknowledged)
except Exception as exc:
if current_member is None:
rs_config = rs_add_member(rs_config, member)
rs_reconfigure(client, rs_config)
return True
else:
return False
elif state == 'absent':
# check if given host is currently a member of replica set
current_member = rs_get_member(rs_config, member['host'])
if current_member:
rs_config = rs_remove_member(rs_config, member)
rs_reconfigure(client, rs_config)
return True
else:
return False
except OperationFailure as error:
if error.code == 109:
time.sleep(random.randint(2, 8))
elif error.code == 103:
pass
else:
raise OperationError(error)
return rs_alter(client, member, state, tries+1)
str(response['payload']))
if result == -1:
raise OperationFailure('Unknown kerberos '
'failure in step function.')
payload = kerberos.authGSSClientResponse(ctx) or ''
cmd = SON([('saslContinue', 1),
('conversationId', response['conversationId']),
('payload', payload)])
response = sock_info.command('$external', cmd)
if result == kerberos.AUTH_GSS_COMPLETE:
break
else:
raise OperationFailure('Kerberos '
'authentication failed to complete.')
# Once the security context is established actually authenticate.
# See RFC 4752, Section 3.1, last two paragraphs.
if kerberos.authGSSClientUnwrap(ctx,
str(response['payload'])) != 1:
raise OperationFailure('Unknown kerberos '
'failure during GSS_Unwrap step.')
if kerberos.authGSSClientWrap(ctx,
kerberos.authGSSClientResponse(ctx),
username) != 1:
raise OperationFailure('Unknown kerberos '
'failure during GSS_Wrap step.')
payload = kerberos.authGSSClientResponse(ctx)