PYTHON-821 - Migrate most tests to new the CRUD API.

This commit is contained in:
Bernie Hackett 2015-02-13 08:46:43 -08:00
parent 13f20bb45a
commit 30af616009
20 changed files with 475 additions and 497 deletions

View File

@ -32,6 +32,7 @@ from pymongo.errors import (AutoReconnect,
from pymongo.mongo_client import MongoClient
from pymongo.read_preferences import ReadPreference
from pymongo.server_description import ServerDescription
from pymongo.write_concern import WriteConcern
from test import SkipTest, unittest, utils, client_knobs
from test.utils import one, wait_until, connected
from test.version import Version
@ -96,12 +97,13 @@ class TestDirectConnection(HATestCase):
def test_secondary_connection(self):
self.c = MongoClient(self.seed, replicaSet=self.name)
wait_until(lambda: len(self.c.secondaries), "discover secondary")
db = self.c.pymongo_test
# Wait for replication...
w = len(self.c.secondaries) + 1
db.test.remove({}, w=w)
db.test.insert({'foo': 'bar'}, w=w)
db = self.c.get_database("pymongo_test",
write_concern=WriteConcern(w=w))
db.test.delete_many({})
db.test.insert_one({'foo': 'bar'})
# Test direct connection to a primary or secondary
primary_host, primary_port = ha_tools.get_primary().split(':')
@ -149,7 +151,9 @@ class TestDirectConnection(HATestCase):
# direct connection raises AutoReconnect('not master'), MongoClient
# should do the same for unacknowledged writes.
try:
client.pymongo_test.test.insert({}, w=0)
client.get_database(
"pymongo_test",
write_concern=WriteConcern(w=0)).test.insert_one({})
except AutoReconnect as e:
self.assertEqual('not master', e.args[0])
else:
@ -167,7 +171,9 @@ class TestDirectConnection(HATestCase):
# See explanation above
try:
client.pymongo_test.test.insert({}, w=0)
client.get_database(
"pymongo_test",
write_concern=WriteConcern(w=0)).test.insert_one({})
except AutoReconnect as e:
self.assertEqual('not master', e.args[0])
else:
@ -389,10 +395,11 @@ class TestWritesWithFailover(HATestCase):
wait_until(lambda: c.primary, "discover primary")
wait_until(lambda: len(c.secondaries) == 2, "discover secondaries")
primary = c.primary
db = c.pymongo_test
w = len(c.secondaries) + 1
db.test.remove({}, w=w)
db.test.insert({'foo': 'bar'}, w=w)
db = c.get_database("pymongo_test",
write_concern=WriteConcern(w=w))
db.test.delete_many({})
db.test.insert_one({'foo': 'bar'})
self.assertEqual('bar', db.test.find_one()['foo'])
killed = ha_tools.kill_primary(9)
@ -406,7 +413,7 @@ class TestWritesWithFailover(HATestCase):
# while we wait for new primary.
for _ in xrange(10000):
try:
db.test.insert({'bar': 'baz'})
db.test.insert_one({'bar': 'baz'})
# No error, found primary.
break
@ -438,11 +445,12 @@ class TestReadWithFailover(HATestCase):
pass
return True
db = c.pymongo_test
w = len(c.secondaries) + 1
db.test.remove({}, w=w)
db = c.get_database("pymongo_test",
write_concern=WriteConcern(w=w))
db.test.delete_many({})
# Force replication
db.test.insert([{'foo': i} for i in xrange(10)], w=w)
db.test.insert_many([{'foo': i} for i in xrange(10)])
self.assertEqual(10, db.test.count())
db.read_preference = SECONDARY_PREFERRED
@ -505,11 +513,11 @@ class TestReadPreference(HATestCase):
self.other_secondary_dc = {'dc': self.other_secondary_tags['dc']}
self.c = MongoClient(self.seed, replicaSet=self.name)
self.db = self.c.pymongo_test
self.w = len(self.c.secondaries) + 1
self.db.test.remove({}, w=self.w)
self.db.test.insert(
[{'foo': i} for i in xrange(10)], w=self.w)
self.db = self.c.get_database("pymongo_test",
write_concern=WriteConcern(w=self.w))
self.db.test.delete_many({})
self.db.test.insert_many([{'foo': i} for i in xrange(10)])
self.clear_ping_times()
@ -754,8 +762,9 @@ class TestReplicaSetAuth(HATestCase):
def test_auth_during_failover(self):
self.assertTrue(self.db.authenticate('user', 'userpass'))
self.assertTrue(self.db.foo.insert({'foo': 'bar'},
w=3, wtimeout=3000))
db = self.db.connection.get_database(
self.db.name, write_concern=WriteConcern(w=3, wtimeout=3000))
self.assertTrue(db.foo.insert_one({'foo': 'bar'})
self.db.logout()
self.assertRaises(OperationFailure, self.db.foo.find_one)
@ -820,7 +829,7 @@ class TestMongosHighAvailability(HATestCase):
def test_mongos_ha(self):
coll = self.client[self.dbname].test
self.assertTrue(coll.insert({'foo': 'bar'}))
coll.insert_one({'foo': 'bar'}))
first = '%s:%d' % (self.client.host, self.client.port)
ha_tools.kill_mongos(first)
@ -873,13 +882,11 @@ class TestLastErrorDefaults(HATestCase):
self.c.admin.command("replSetReconfig", replset)
self.assertRaises(WTimeoutError, self.c.pymongo_test.test.insert,
self.assertRaises(WTimeoutError, self.c.pymongo_test.test.insert_one,
{'_id': 0})
self.assertRaises(WTimeoutError, self.c.pymongo_test.test.save,
{'_id': 0, "a": 5})
self.assertRaises(WTimeoutError, self.c.pymongo_test.test.update,
self.assertRaises(WTimeoutError, self.c.pymongo_test.test.update_one,
{'_id': 0}, {"$set": {"a": 10}})
self.assertRaises(WTimeoutError, self.c.pymongo_test.test.remove,
self.assertRaises(WTimeoutError, self.c.pymongo_test.test.delete_one,
{'_id': 0})
@ -893,8 +900,10 @@ class TestShipOfTheseus(HATestCase):
def test_ship_of_theseus(self):
c = MongoClient(self.seed, replicaSet=self.name)
db = c.pymongo_test
db.test.insert({}, w=len(c.secondaries) + 1)
db = c.get_database(
"pymongo_test",
write_concern=WriteConcern(w=len(c.secondaries) + 1))
db.test.insert_one({})
find_one = db.test.find_one
primary = ha_tools.get_primary()
@ -985,9 +994,10 @@ class TestLastError(HATestCase):
wait_until(lambda: c.primary, "discover primary")
wait_until(lambda: c.secondaries, "discover secondary")
ha_tools.stepdown_primary()
db = c.pymongo_test
db = c.get_database(
"pymongo_test", write_concern=WriteConcern(w=0))
db.test.insert({}, w=0)
db.test.insert_one({})
response = db.error()
self.assertTrue('err' in response and 'not master' in response['err'])
wait_until(lambda: len(c.secondaries) == 2, "discover two secondaries")

View File

@ -39,7 +39,7 @@ collection = client.test.test
ndocs = 20
collection.drop()
collection.insert([{'i': i} for i in range(ndocs)])
collection.insert_many([{'i': i} for i in range(ndocs)])
client.disconnect() # Discard main thread's request socket.
try:

View File

@ -161,8 +161,8 @@ class TestGSSAPI(unittest.TestCase):
# multiple sockets from the pool concurrently, proving that
# auto-authentication works with GSSAPI.
collection = client.test.collection
collection.remove()
collection.insert({'_id': 1})
collection.drop()
collection.insert_one({'_id': 1})
threads = []
for _ in range(4):
@ -239,14 +239,14 @@ class TestSASLPlain(unittest.TestCase):
self.assertRaises(OperationFailure, client.ldap.authenticate,
'not-user', SASL_PASS, SASL_DB, 'PLAIN')
self.assertRaises(OperationFailure, client.ldap.test.find_one)
self.assertRaises(OperationFailure, client.ldap.test.insert,
self.assertRaises(OperationFailure, client.ldap.test.insert_one,
{"failed": True})
# Bad password
self.assertRaises(OperationFailure, client.ldap.authenticate,
SASL_USER, 'not-pwd', SASL_DB, 'PLAIN')
self.assertRaises(OperationFailure, client.ldap.test.find_one)
self.assertRaises(OperationFailure, client.ldap.test.insert,
self.assertRaises(OperationFailure, client.ldap.test.insert_one,
{"failed": True})
def auth_string(user, password):
@ -412,8 +412,8 @@ class TestDelegatedAuth(unittest.TestCase):
self.client.pymongo_test2.foo.drop()
def test_delegated_auth(self):
self.client.pymongo_test2.foo.remove()
self.client.pymongo_test2.foo.insert({})
self.client.pymongo_test2.foo.drop()
self.client.pymongo_test2.foo.insert_one({})
# User definition with no roles in pymongo_test.
self.client.pymongo_test.add_user('user', 'pass', roles=[])
# Delegate auth to pymongo_test.

View File

@ -187,7 +187,7 @@ class TestBinary(unittest.TestCase):
coll = db.get_collection(
'java_uuid', CodecOptions(uuid_representation=JAVA_LEGACY))
coll.insert(docs)
coll.insert_many(docs)
self.assertEqual(5, coll.count())
for d in coll.find():
self.assertEqual(d['newguid'], uuid.UUID(d['newguidstring']))
@ -257,7 +257,7 @@ class TestBinary(unittest.TestCase):
coll = db.get_collection(
'csharp_uuid', CodecOptions(uuid_representation=CSHARP_LEGACY))
coll.insert(docs)
coll.insert_many(docs)
self.assertEqual(5, coll.count())
for d in coll.find():
self.assertEqual(d['newguid'], uuid.UUID(d['newguidstring']))
@ -284,7 +284,7 @@ class TestBinary(unittest.TestCase):
coll.drop()
uu = uuid.uuid4()
coll.insert({'uuid': Binary(uu.bytes, 3)})
coll.insert_one({'uuid': Binary(uu.bytes, 3)})
self.assertEqual(1, coll.count())
# Test UUIDLegacy queries.
@ -297,7 +297,7 @@ class TestBinary(unittest.TestCase):
self.assertEqual(uu, retrieved['uuid'])
# Test regular UUID queries (using subtype 4).
coll.insert({'uuid': uu})
coll.insert_one({'uuid': uu})
self.assertEqual(2, coll.count())
cur = coll.find({'uuid': uu})
self.assertEqual(1, cur.count())

View File

@ -45,7 +45,7 @@ class BulkTestBase(IntegrationTest):
def setUp(self):
super(BulkTestBase, self).setUp()
self.coll.remove()
self.coll.drop()
def assertEqualResponse(self, expected, actual):
"""Compare response from bulk.execute() to expected response."""
@ -197,7 +197,7 @@ class TestBulk(BulkTestBase):
'writeErrors': [],
'writeConcernErrors': []
}
self.coll.insert([{}, {}])
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_ordered_bulk_op()
@ -216,8 +216,8 @@ class TestBulk(BulkTestBase):
self.assertEqualResponse(expected, result)
self.assertEqual(self.coll.find({'foo': 'bar'}).count(), 2)
self.coll.remove()
self.coll.insert([{}, {}])
self.coll.delete_many({})
self.coll.insert_many([{}, {}])
result = self.coll.bulk_write([UpdateMany({},
{'$set': {'foo': 'bar'}})])
self.assertEqualResponse(expected, result.bulk_api_result)
@ -230,8 +230,8 @@ class TestBulk(BulkTestBase):
bulk.find({}).update(updates)
self.assertRaises(BulkWriteError, bulk.execute)
self.coll.remove()
self.coll.insert([{}, {}])
self.coll.delete_many({})
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({}).update({'$set': {'bim': 'baz'}})
@ -249,7 +249,7 @@ class TestBulk(BulkTestBase):
self.assertEqual(self.coll.find({'bim': 'baz'}).count(), 2)
self.coll.insert({'x': 1})
self.coll.insert_one({'x': 1})
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({'x': 1}).update({'$set': {'x': 42}})
result = bulk.execute()
@ -294,7 +294,7 @@ class TestBulk(BulkTestBase):
'writeConcernErrors': []
}
self.coll.insert([{}, {}])
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_ordered_bulk_op()
@ -312,16 +312,16 @@ class TestBulk(BulkTestBase):
self.assertEqual(self.coll.find({'foo': 'bar'}).count(), 1)
self.coll.remove()
self.coll.insert([{}, {}])
self.coll.delete_many({})
self.coll.insert_many([{}, {}])
result = self.coll.bulk_write([UpdateOne({},
{'$set': {'foo': 'bar'}})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.matched_count)
self.assertTrue(result.modified_count in (1, None))
self.coll.remove()
self.coll.insert([{}, {}])
self.coll.delete_many({})
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({}).update_one({'$set': {'bim': 'baz'}})
@ -349,7 +349,7 @@ class TestBulk(BulkTestBase):
'writeConcernErrors': []
}
self.coll.insert([{}, {}])
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_ordered_bulk_op()
self.assertRaises(TypeError, bulk.find({}).replace_one, 1)
@ -361,15 +361,15 @@ class TestBulk(BulkTestBase):
self.assertEqual(self.coll.find({'foo': 'bar'}).count(), 1)
self.coll.remove()
self.coll.insert([{}, {}])
self.coll.delete_many({})
self.coll.insert_many([{}, {}])
result = self.coll.bulk_write([ReplaceOne({}, {'foo': 'bar'})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.matched_count)
self.assertTrue(result.modified_count in (1, None))
self.coll.remove()
self.coll.insert([{}, {}])
self.coll.delete_many({})
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({}).replace_one({'bim': 'baz'})
@ -390,7 +390,7 @@ class TestBulk(BulkTestBase):
'writeErrors': [],
'writeConcernErrors': []
}
self.coll.insert([{}, {}])
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_ordered_bulk_op()
@ -402,13 +402,13 @@ class TestBulk(BulkTestBase):
self.assertEqual(self.coll.count(), 0)
self.coll.insert([{}, {}])
self.coll.insert_many([{}, {}])
result = self.coll.bulk_write([DeleteMany({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(2, result.deleted_count)
# Test removing some documents, ordered.
self.coll.insert([{}, {'x': 1}, {}, {'x': 1}])
self.coll.insert_many([{}, {'x': 1}, {}, {'x': 1}])
bulk = self.coll.initialize_ordered_bulk_op()
@ -426,10 +426,10 @@ class TestBulk(BulkTestBase):
result)
self.assertEqual(self.coll.count(), 2)
self.coll.remove()
self.coll.delete_many({})
# Test removing all documents, unordered.
self.coll.insert([{}, {}])
self.coll.insert_many([{}, {}])
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({}).remove()
@ -448,7 +448,7 @@ class TestBulk(BulkTestBase):
# Test removing some documents, unordered.
self.assertEqual(self.coll.count(), 0)
self.coll.insert([{}, {'x': 1}, {}, {'x': 1}])
self.coll.insert_many([{}, {'x': 1}, {}, {'x': 1}])
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({'x': 1}).remove()
@ -465,7 +465,7 @@ class TestBulk(BulkTestBase):
result)
self.assertEqual(self.coll.count(), 2)
self.coll.remove()
self.coll.delete_many({})
def test_remove_one(self):
@ -476,7 +476,7 @@ class TestBulk(BulkTestBase):
# Test removing one document, empty selector.
# First ordered, then unordered.
self.coll.insert([{}, {}])
self.coll.insert_many([{}, {}])
expected = {
'nMatched': 0,
'nModified': 0,
@ -494,13 +494,13 @@ class TestBulk(BulkTestBase):
self.assertEqual(self.coll.count(), 1)
self.coll.insert({})
self.coll.insert_one({})
result = self.coll.bulk_write([DeleteOne({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.deleted_count)
self.assertEqual(self.coll.count(), 1)
self.coll.insert({})
self.coll.insert_one({})
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({}).remove_one()
@ -511,7 +511,7 @@ class TestBulk(BulkTestBase):
# Test removing one document, with a selector.
# First ordered, then unordered.
self.coll.insert([{'x': 1}])
self.coll.insert_one({'x': 1})
bulk = self.coll.initialize_ordered_bulk_op()
bulk.find({'x': 1}).remove_one()
@ -519,7 +519,7 @@ class TestBulk(BulkTestBase):
self.assertEqualResponse(expected, result)
self.assertEqual([{}], list(self.coll.find({}, {'_id': False})))
self.coll.insert({'x': 1})
self.coll.insert_one({'x': 1})
bulk = self.coll.initialize_unordered_bulk_op()
bulk.find({'x': 1}).remove_one()
@ -551,7 +551,7 @@ class TestBulk(BulkTestBase):
result = bulk.execute()
self.assertEqualResponse(expected, result)
self.coll.remove()
self.coll.delete_many({})
result = self.coll.bulk_write([ReplaceOne({},
{'foo': 'bar'},
upsert=True)])
@ -837,7 +837,7 @@ class TestBulk(BulkTestBase):
self.assertEqual(1, result['nInserted'])
self.coll.remove()
self.coll.delete_many({})
big = 'x' * (1024 * 1024 * 4)
batch = self.coll.initialize_ordered_bulk_op()
@ -869,7 +869,7 @@ class TestBulk(BulkTestBase):
self.assertEqual(2, result['nInserted'])
self.coll.remove()
self.coll.delete_many({})
big = 'x' * (1024 * 1024 * 4)
batch = self.coll.initialize_ordered_bulk_op()
@ -896,7 +896,7 @@ class TestBulk(BulkTestBase):
self.assertEqual(n_docs, self.coll.count())
# Same with ordered bulk.
self.coll.remove()
self.coll.delete_many({})
batch = self.coll.initialize_ordered_bulk_op()
for _ in range(n_docs):
batch.insert({})
@ -995,7 +995,7 @@ class TestBulkWriteConcern(BulkTestBase):
self.assertEqual(64, failed['code'])
self.assertTrue(isinstance(failed['errmsg'], string_type))
self.coll.remove()
self.coll.delete_many({})
self.coll.ensure_index('a', unique=True)
self.addCleanup(self.coll.drop_index, [('a', 1)])
@ -1061,7 +1061,7 @@ class TestBulkWriteConcern(BulkTestBase):
# write concern error for each operation.
self.assertTrue(len(result['writeConcernErrors']) > 1)
self.coll.remove()
self.coll.delete_many({})
self.coll.ensure_index('a', unique=True)
self.addCleanup(self.coll.drop_index, [('a', 1)])

View File

@ -278,8 +278,8 @@ class TestClient(IntegrationTest):
self.assertEqual(client_context.nodes, self.client.nodes)
def test_database_names(self):
self.client.pymongo_test.test.save({"dummy": u("object")})
self.client.pymongo_test_mike.test.save({"dummy": u("object")})
self.client.pymongo_test.test.insert_one({"dummy": u("object")})
self.client.pymongo_test_mike.test.insert_one({"dummy": u("object")})
dbs = self.client.database_names()
self.assertTrue("pymongo_test" in dbs)
@ -289,8 +289,8 @@ class TestClient(IntegrationTest):
self.assertRaises(TypeError, self.client.drop_database, 5)
self.assertRaises(TypeError, self.client.drop_database, None)
self.client.pymongo_test.test.save({"dummy": u("object")})
self.client.pymongo_test2.test.save({"dummy": u("object")})
self.client.pymongo_test.test.insert_one({"dummy": u("object")})
self.client.pymongo_test2.test.insert_one({"dummy": u("object")})
dbs = self.client.database_names()
self.assertIn("pymongo_test", dbs)
self.assertIn("pymongo_test2", dbs)
@ -409,7 +409,7 @@ class TestClient(IntegrationTest):
# Confirm we can do operations via the socket.
client = MongoClient(uri)
client.pymongo_test.test.save({"dummy": "object"})
client.pymongo_test.test.insert_one({"dummy": "object"})
dbs = client.database_names()
self.assertTrue("pymongo_test" in dbs)
@ -470,7 +470,7 @@ class TestClient(IntegrationTest):
def test_document_class(self):
c = self.client
db = c.pymongo_test
db.test.insert({"x": 1})
db.test.insert_one({"x": 1})
self.assertEqual(dict, c.document_class)
self.assertTrue(isinstance(db.test.find_one(), dict))
@ -521,7 +521,7 @@ class TestClient(IntegrationTest):
timeout = rs_or_single_client(socketTimeoutMS=1000 * timeout_sec)
no_timeout.pymongo_test.drop_collection("test")
no_timeout.pymongo_test.test.insert({"x": 1})
no_timeout.pymongo_test.test.insert_one({"x": 1})
# A $where clause that takes a second longer than the timeout
where_func = delay(timeout_sec + 1)
@ -554,7 +554,7 @@ class TestClient(IntegrationTest):
aware.pymongo_test.drop_collection("test")
now = datetime.datetime.utcnow()
aware.pymongo_test.test.insert({"x": now})
aware.pymongo_test.test.insert_one({"x": now})
self.assertEqual(None, naive.pymongo_test.test.find_one()["x"].tzinfo)
self.assertEqual(utc, aware.pymongo_test.test.find_one()["x"].tzinfo)
@ -574,8 +574,8 @@ class TestClient(IntegrationTest):
uri += '/?replicaSet=' + client_context.replica_set_name
client = rs_or_single_client_noauth(uri)
client.pymongo_test.test.save({"dummy": u("object")})
client.pymongo_test_bernie.test.save({"dummy": u("object")})
client.pymongo_test.test.insert_one({"dummy": u("object")})
client.pymongo_test_bernie.test.insert_one({"dummy": u("object")})
dbs = client.database_names()
self.assertTrue("pymongo_test" in dbs)
@ -606,7 +606,7 @@ class TestClient(IntegrationTest):
def test_contextlib(self):
client = rs_or_single_client()
client.pymongo_test.drop_collection("test")
client.pymongo_test.test.insert({"foo": "bar"})
client.pymongo_test.test.insert_one({"foo": "bar"})
# The socket used for the previous commands has been returned to the
# pool
@ -638,7 +638,7 @@ class TestClient(IntegrationTest):
# Need exactly 1 document so find() will execute its $where clause once
db.drop_collection('foo')
db.foo.insert({'_id': 1})
db.foo.insert_one({'_id': 1})
def interrupter():
# Raises KeyboardInterrupt in the main thread
@ -674,10 +674,10 @@ class TestClient(IntegrationTest):
self.assertGreaterEqual(socket_count, 1)
old_sock_info = next(iter(pool.sockets))
self.client.pymongo_test.test.drop()
self.client.pymongo_test.test.insert({'_id': 'foo'})
self.client.pymongo_test.test.insert_one({'_id': 'foo'})
self.assertRaises(
OperationFailure,
self.client.pymongo_test.test.insert, {'_id': 'foo'})
self.client.pymongo_test.test.insert_one, {'_id': 'foo'})
self.assertEqual(socket_count, len(pool.sockets))
new_sock_info = next(iter(pool.sockets))
@ -697,9 +697,9 @@ class TestClient(IntegrationTest):
raise SkipTest("Can't test kill_cursors against old mongos")
self.collection = self.client.pymongo_test.test
self.collection.remove()
self.collection.drop()
self.collection.insert({'_id': i} for i in range(200))
self.collection.insert_many([{'_id': i} for i in range(200)])
cursor = self.collection.find().batch_size(1)
next(cursor)
self.client.kill_cursors([cursor.cursor_id])
@ -740,14 +740,14 @@ class TestClient(IntegrationTest):
# Use a separate collection to avoid races where we're still
# completing an operation on a collection while the next test begins.
client = rs_or_single_client(connect=False)
client.test_lazy_connect_w0.test.insert({}, w=0)
client = rs_or_single_client(connect=False, w=0)
client.test_lazy_connect_w0.test.insert_one({})
client = rs_or_single_client(connect=False)
client.test_lazy_connect_w0.test.update({}, {'$set': {'x': 1}}, w=0)
client.test_lazy_connect_w0.test.update_one({}, {'$set': {'x': 1}})
client = rs_or_single_client(connect=False)
client.test_lazy_connect_w0.test.remove(w=0)
client.test_lazy_connect_w0.test.delete_one({})
@client_context.require_no_mongos
def test_exhaust_network_error(self):
@ -870,9 +870,9 @@ class TestExhaustCursor(IntegrationTest):
# out on success but it's checked in on error to avoid semaphore leaks.
client = rs_or_single_client(max_pool_size=1)
collection = client.pymongo_test.test
collection.remove()
collection.drop()
collection.insert([{} for _ in range(200)])
collection.insert_many([{} for _ in range(200)])
self.addCleanup(client_context.client.pymongo_test.test.drop)
pool = get_pool(client)
@ -928,8 +928,8 @@ class TestExhaustCursor(IntegrationTest):
# out on success but it's checked in on error to avoid semaphore leaks.
client = rs_or_single_client(max_pool_size=1)
collection = client.pymongo_test.test
collection.remove()
collection.insert([{} for _ in range(200)]) # More than one batch.
collection.drop()
collection.insert_many([{} for _ in range(200)]) # More than one batch.
pool = get_pool(client)
pool._check_interval_seconds = None # Never check.
@ -992,63 +992,51 @@ class TestClientLazyConnect(IntegrationTest):
def _get_client(self):
return rs_or_single_client(connect=False)
def test_insert(self):
def test_insert_one(self):
def reset(collection):
collection.drop()
def insert(collection, _):
collection.insert({})
def insert_one(collection, _):
collection.insert_one({})
def test(collection):
self.assertEqual(NTHREADS, collection.count())
lazy_client_trial(reset, insert, test, self._get_client)
lazy_client_trial(reset, insert_one, test, self._get_client)
def test_save(self):
def test_update_one(self):
def reset(collection):
collection.drop()
def save(collection, _):
collection.save({})
def test(collection):
self.assertEqual(NTHREADS, collection.count())
lazy_client_trial(reset, save, test, self._get_client)
def test_update(self):
def reset(collection):
collection.drop()
collection.insert([{'i': 0}])
collection.insert_one({'i': 0})
# Update doc 10 times.
def update(collection, _):
collection.update({}, {'$inc': {'i': 1}})
def update_one(collection, _):
collection.update_one({}, {'$inc': {'i': 1}})
def test(collection):
self.assertEqual(NTHREADS, collection.find_one()['i'])
lazy_client_trial(reset, update, test, self._get_client)
lazy_client_trial(reset, update_one, test, self._get_client)
def test_remove(self):
def test_delete_one(self):
def reset(collection):
collection.drop()
collection.insert([{'i': i} for i in range(NTHREADS)])
collection.insert_many([{'i': i} for i in range(NTHREADS)])
def remove(collection, i):
collection.remove({'i': i})
def delete_one(collection, i):
collection.delete_one({'i': i})
def test(collection):
self.assertEqual(0, collection.count())
lazy_client_trial(reset, remove, test, self._get_client)
lazy_client_trial(reset, delete_one, test, self._get_client)
def test_find_one(self):
results = []
def reset(collection):
collection.drop()
collection.insert({})
collection.insert_one({})
results[:] = []
def find_one(collection, _):

View File

@ -137,7 +137,7 @@ class TestCollection(IntegrationTest):
self.assertRaises(ValueError, db.test.create_index, [])
db.test.drop_indexes()
db.test.insert({})
db.test.insert_one({})
self.assertEqual(len(db.test.index_information()), 1)
db.test.create_index("hello")
@ -164,8 +164,8 @@ class TestCollection(IntegrationTest):
self.assertTrue("hello_-1_world_1" in db.test.index_information())
db.test.drop()
db.test.insert({'a': 1})
db.test.insert({'a': 1})
db.test.insert_one({'a': 1})
db.test.insert_one({'a': 1})
self.assertRaises(DuplicateKeyError, db.test.create_index,
'a', unique=True)
@ -247,14 +247,14 @@ class TestCollection(IntegrationTest):
def test_ensure_unique_index_threaded(self):
coll = self.db.test_unique_threaded
coll.drop()
coll.insert(({'foo': i} for i in range(10000)))
coll.insert_many([{'foo': i} for i in range(10000)])
class Indexer(threading.Thread):
def run(self):
try:
coll.ensure_index('foo', unique=True)
coll.insert({'foo': 'bar'})
coll.insert({'foo': 'bar'})
coll.insert_one({'foo': 'bar'})
coll.insert_one({'foo': 'bar'})
except OperationFailure:
pass
@ -301,7 +301,7 @@ class TestCollection(IntegrationTest):
def test_reindex(self):
db = self.db
db.drop_collection("test")
db.test.insert({"foo": "bar", "who": "what", "when": "how"})
db.test.insert_one({"foo": "bar", "who": "what", "when": "how"})
db.test.create_index("foo")
db.test.create_index("who")
db.test.create_index("when")
@ -326,9 +326,8 @@ class TestCollection(IntegrationTest):
def test_index_info(self):
db = self.db
db.test.drop_indexes()
db.test.remove({})
db.test.save({}) # create collection
db.test.drop()
db.test.insert_one({}) # create collection
self.assertEqual(len(db.test.index_information()), 1)
self.assertTrue("_id_" in db.test.index_information())
@ -358,16 +357,15 @@ class TestCollection(IntegrationTest):
@client_context.require_no_mongos
def test_index_haystack(self):
db = self.db
db.test.drop_indexes()
db.test.remove()
_id = db.test.insert({
db.test.drop()
_id = db.test.insert_one({
"pos": {"long": 34.2, "lat": 33.3},
"type": "restaurant"
})
db.test.insert({
}).inserted_id
db.test.insert_one({
"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"
})
db.test.insert({
db.test.insert_one({
"pos": {"long": 59.1, "lat": 87.2}, "type": "office"
})
db.test.create_index(
@ -475,10 +473,10 @@ class TestCollection(IntegrationTest):
def _drop_dups_setup(self, db):
db.drop_collection('test')
db.test.insert({'i': 1})
db.test.insert({'i': 2})
db.test.insert({'i': 2}) # duplicate
db.test.insert({'i': 3})
db.test.insert_one({'i': 1})
db.test.insert_one({'i': 2})
db.test.insert_one({'i': 2}) # duplicate
db.test.insert_one({'i': 3})
@client_context.require_version_max(2, 6)
def test_index_drop_dups(self):
@ -520,7 +518,7 @@ class TestCollection(IntegrationTest):
db.drop_collection("test")
doc = {"a": 1, "b": 5, "c": {"d": 5, "e": 10}}
db.test.insert(doc)
db.test.insert_one(doc)
# Test field inclusion
doc = next(db.test.find({}, ["_id"]))
@ -580,8 +578,9 @@ class TestCollection(IntegrationTest):
db.drop_collection("test")
def test_insert_find_one(self):
# Tests legacy insert.
db = self.db
db.test.remove({})
db.test.drop()
self.assertEqual(0, len(list(db.test.find())))
doc = {"hello": u("world")}
id = db.test.insert(doc)
@ -676,6 +675,7 @@ class TestCollection(IntegrationTest):
self.assertEqual(15, db.test.count())
def test_generator_insert(self):
# Only legacy insert currently supports insert from a generator.
db = self.db
db.test.remove({})
self.assertEqual(db.test.find().count(), 0)
@ -688,6 +688,7 @@ class TestCollection(IntegrationTest):
db.test.remove({})
def test_remove_one(self):
# Tests legacy remove.
self.db.test.remove()
self.assertEqual(0, self.db.test.count())
@ -702,6 +703,7 @@ class TestCollection(IntegrationTest):
self.assertEqual(0, self.db.test.count())
def test_remove_all(self):
# Tests legacy remove.
self.db.test.remove()
self.assertEqual(0, self.db.test.count())
@ -763,10 +765,10 @@ class TestCollection(IntegrationTest):
def test_find_w_fields(self):
db = self.db
db.test.remove({})
db.test.delete_many({})
db.test.insert({"x": 1, "mike": "awesome",
"extra thing": "abcdefghijklmnopqrstuvwxyz"})
db.test.insert_one({"x": 1, "mike": "awesome",
"extra thing": "abcdefghijklmnopqrstuvwxyz"})
self.assertEqual(1, db.test.count())
doc = next(db.test.find({}))
self.assertTrue("x" in doc)
@ -789,9 +791,9 @@ class TestCollection(IntegrationTest):
def test_fields_specifier_as_dict(self):
db = self.db
db.test.remove({})
db.test.delete_many({})
db.test.insert({"x": [1, 2, 3], "mike": "awesome"})
db.test.insert_one({"x": [1, 2, 3], "mike": "awesome"})
self.assertEqual([1, 2, 3], db.test.find_one()["x"])
self.assertEqual([2, 3],
@ -802,12 +804,12 @@ class TestCollection(IntegrationTest):
def test_find_w_regex(self):
db = self.db
db.test.remove({})
db.test.delete_many({})
db.test.insert({"x": "hello_world"})
db.test.insert({"x": "hello_mike"})
db.test.insert({"x": "hello_mikey"})
db.test.insert({"x": "hello_test"})
db.test.insert_one({"x": "hello_world"})
db.test.insert_one({"x": "hello_mike"})
db.test.insert_one({"x": "hello_mikey"})
db.test.insert_one({"x": "hello_test"})
self.assertEqual(db.test.find().count(), 4)
self.assertEqual(db.test.find({"x":
@ -822,17 +824,17 @@ class TestCollection(IntegrationTest):
def test_id_can_be_anything(self):
db = self.db
db.test.remove({})
db.test.delete_many({})
auto_id = {"hello": "world"}
db.test.insert(auto_id)
db.test.insert_one(auto_id)
self.assertTrue(isinstance(auto_id["_id"], ObjectId))
numeric = {"_id": 240, "hello": "world"}
db.test.insert(numeric)
db.test.insert_one(numeric)
self.assertEqual(numeric["_id"], 240)
object = {"_id": numeric, "hello": "world"}
db.test.insert(object)
db.test.insert_one(object)
self.assertEqual(object["_id"], numeric)
for x in db.test.find():
@ -843,30 +845,31 @@ class TestCollection(IntegrationTest):
db = self.db
db.test.drop()
db.test.insert({"hello": "world"})
db.test.insert({"hello": {"hello": "world"}})
db.test.insert_one({"hello": "world"})
db.test.insert_one({"hello": {"hello": "world"}})
self.assertRaises(InvalidDocument, db.test.insert, {"$hello": "world"})
self.assertRaises(InvalidDocument, db.test.insert,
self.assertRaises(InvalidDocument, db.test.insert_one, {"$hello": "world"})
self.assertRaises(InvalidDocument, db.test.insert_one,
{"hello": {"$hello": "world"}})
db.test.insert({"he$llo": "world"})
db.test.insert({"hello": {"hello$": "world"}})
db.test.insert_one({"he$llo": "world"})
db.test.insert_one({"hello": {"hello$": "world"}})
self.assertRaises(InvalidDocument, db.test.insert,
self.assertRaises(InvalidDocument, db.test.insert_one,
{".hello": "world"})
self.assertRaises(InvalidDocument, db.test.insert,
self.assertRaises(InvalidDocument, db.test.insert_one,
{"hello": {".hello": "world"}})
self.assertRaises(InvalidDocument, db.test.insert,
self.assertRaises(InvalidDocument, db.test.insert_one,
{"hello.": "world"})
self.assertRaises(InvalidDocument, db.test.insert,
self.assertRaises(InvalidDocument, db.test.insert_one,
{"hello": {"hello.": "world"}})
self.assertRaises(InvalidDocument, db.test.insert,
self.assertRaises(InvalidDocument, db.test.insert_one,
{"hel.lo": "world"})
self.assertRaises(InvalidDocument, db.test.insert,
self.assertRaises(InvalidDocument, db.test.insert_one,
{"hello": {"hel.lo": "world"}})
def test_insert_multiple(self):
# Tests legacy insert.
db = self.db
db.drop_collection("test")
doc1 = {"hello": u("world")}
@ -891,6 +894,7 @@ class TestCollection(IntegrationTest):
self.assertRaises(InvalidOperation, db.test.insert, (i for i in []))
def test_insert_multiple_with_duplicate(self):
# Tests legacy insert.
db = self.db
db.drop_collection("test")
db.test.ensure_index([('i', ASCENDING)], unique=True)
@ -933,6 +937,7 @@ class TestCollection(IntegrationTest):
)
def test_insert_iterables(self):
# Tests legacy insert.
db = self.db
self.assertRaises(TypeError, db.test.insert, 4)
@ -951,7 +956,7 @@ class TestCollection(IntegrationTest):
self.assertEqual(db.test.find().count(), 10)
def test_insert_manipulate_false(self):
# Test three aspects of insert with manipulate=False:
# Test three aspects of legacy insert with manipulate=False:
# 1. The return value is None or [None] as appropriate.
# 2. _id is not set on the passed-in document object.
# 3. _id is not sent to server.
@ -977,6 +982,7 @@ class TestCollection(IntegrationTest):
collection.drop()
def test_save(self):
# Tests legacy save.
self.db.drop_collection("test")
# Save a doc with autogenerated id
@ -1012,6 +1018,7 @@ class TestCollection(IntegrationTest):
{'_id': 'explicit_id', 'hello': 'world'})
def test_save_with_invalid_key(self):
# Tests legacy save.
self.db.drop_collection("test")
self.assertTrue(self.db.test.insert({"hello": "world"}))
doc = self.db.test.find_one()
@ -1027,15 +1034,15 @@ class TestCollection(IntegrationTest):
db.test.create_index("hello")
# No error.
db.test.save({"hello": "world"})
db.test.save({"hello": "world"})
db.test.insert_one({"hello": "world"})
db.test.insert_one({"hello": "world"})
db.drop_collection("test")
db.test.create_index("hello", unique=True)
with self.assertRaises(DuplicateKeyError):
db.test.save({"hello": "world"})
db.test.save({"hello": "world"})
db.test.insert_one({"hello": "world"})
db.test.insert_one({"hello": "world"})
def test_duplicate_key_error(self):
db = self.db
@ -1043,15 +1050,15 @@ class TestCollection(IntegrationTest):
db.test.create_index("x", unique=True)
db.test.insert({"_id": 1, "x": 1})
db.test.insert_one({"_id": 1, "x": 1})
with self.assertRaises(DuplicateKeyError) as context:
db.test.insert({"x": 1})
db.test.insert_one({"x": 1})
self.assertIsNotNone(context.exception.details)
with self.assertRaises(DuplicateKeyError) as context:
db.test.save({"x": 1})
db.test.insert_one({"x": 1})
self.assertIsNotNone(context.exception.details)
self.assertEqual(1, db.test.count())
@ -1060,18 +1067,19 @@ class TestCollection(IntegrationTest):
# Ensure setting wtimeout doesn't disable write concern altogether.
# See SERVER-12596.
collection = self.db.test
collection.remove()
collection.insert({'_id': 1})
collection.drop()
collection.insert_one({'_id': 1})
coll = collection.with_options(
write_concern=WriteConcern(w=1, wtimeout=1000))
self.assertRaises(DuplicateKeyError, coll.insert, {'_id': 1})
self.assertRaises(DuplicateKeyError, coll.insert_one, {'_id': 1})
coll = collection.with_options(
write_concern=WriteConcern(wtimeout=1000))
self.assertRaises(DuplicateKeyError, coll.insert, {'_id': 1})
self.assertRaises(DuplicateKeyError, coll.insert_one, {'_id': 1})
def test_continue_on_error(self):
# Tests legacy insert.
db = self.db
db.drop_collection("test")
oid = db.test.insert({"one": 1})
@ -1110,7 +1118,7 @@ class TestCollection(IntegrationTest):
def test_error_code(self):
try:
self.db.test.update({}, {"$thismodifierdoesntexist": 1})
self.db.test.update_many({}, {"$thismodifierdoesntexist": 1})
except OperationFailure as exc:
self.assertTrue(exc.code in (9, 10147, 16840, 17009))
# Just check that we set the error document. Fields
@ -1123,19 +1131,20 @@ class TestCollection(IntegrationTest):
db = self.db
db.drop_collection("test")
db.test.insert({"hello": {"a": 4, "b": 5}})
db.test.insert({"hello": {"a": 7, "b": 2}})
db.test.insert({"hello": {"a": 4, "b": 10}})
db.test.insert_one({"hello": {"a": 4, "b": 5}})
db.test.insert_one({"hello": {"a": 7, "b": 2}})
db.test.insert_one({"hello": {"a": 4, "b": 10}})
db.drop_collection("test")
db.test.create_index("hello.a", unique=True)
db.test.insert({"hello": {"a": 4, "b": 5}})
db.test.insert({"hello": {"a": 7, "b": 2}})
db.test.insert_one({"hello": {"a": 4, "b": 5}})
db.test.insert_one({"hello": {"a": 7, "b": 2}})
self.assertRaises(DuplicateKeyError,
db.test.insert, {"hello": {"a": 4, "b": 10}})
db.test.insert_one, {"hello": {"a": 4, "b": 10}})
def test_acknowledged_insert(self):
# Tests legacy insert.
db = self.db
db.drop_collection("test")
@ -1145,6 +1154,7 @@ class TestCollection(IntegrationTest):
self.assertRaises(OperationFailure, db.test.insert, a)
def test_update(self):
# Tests legacy update.
db = self.db
db.drop_collection("test")
@ -1279,6 +1289,7 @@ class TestCollection(IntegrationTest):
def test_update_manipulate(self):
# Tests legacy update.
db = self.db
db.drop_collection("test")
db.test.insert({'_id': 1})
@ -1304,6 +1315,7 @@ class TestCollection(IntegrationTest):
db.test.find_one())
def test_update_nmodified(self):
# Tests legacy update.
db = self.db
db.drop_collection("test")
used_write_commands = (self.client.max_wire_version > 1)
@ -1323,6 +1335,7 @@ class TestCollection(IntegrationTest):
self.assertFalse('nModified' in result)
def test_multi_update(self):
# Tests legacy update.
db = self.db
db.drop_collection("test")
@ -1340,6 +1353,7 @@ class TestCollection(IntegrationTest):
multi=True)["n"])
def test_upsert(self):
# Tests legacy update.
db = self.db
db.drop_collection("test")
@ -1350,6 +1364,7 @@ class TestCollection(IntegrationTest):
self.assertEqual(2, db.test.find_one()["count"])
def test_acknowledged_update(self):
# Tests legacy update.
db = self.db
db.drop_collection("test")
db.test.create_index("x", unique=True)
@ -1371,7 +1386,7 @@ class TestCollection(IntegrationTest):
def test_update_with_invalid_keys(self):
self.db.drop_collection("test")
self.assertTrue(self.db.test.insert({"hello": "world"}))
self.assertTrue(self.db.test.insert_one({"hello": "world"}))
doc = self.db.test.find_one()
doc['a.b'] = 'c'
@ -1380,24 +1395,24 @@ class TestCollection(IntegrationTest):
expected = OperationFailure
# Replace
self.assertRaises(expected,
self.db.test.update, {"hello": "world"}, doc)
self.assertRaises(expected, self.db.test.replace_one,
{"hello": "world"}, doc)
# Upsert
self.assertRaises(expected,
self.db.test.update, {"foo": "bar"}, doc, upsert=True)
self.assertRaises(expected, self.db.test.replace_one,
{"foo": "bar"}, doc, upsert=True)
# Check that the last two ops didn't actually modify anything
self.assertTrue('a.b' not in self.db.test.find_one())
# Modify shouldn't check keys...
self.assertTrue(self.db.test.update({"hello": "world"},
{"$set": {"foo.bar": "baz"}},
upsert=True))
self.assertTrue(self.db.test.update_one({"hello": "world"},
{"$set": {"foo.bar": "baz"}},
upsert=True))
# I know this seems like testing the server but I'd like to be notified
# by CI if the server's behavior changes here.
doc = SON([("$set", {"foo.bar": "bim"}), ("hello", "world")])
self.assertRaises(OperationFailure, self.db.test.update,
self.assertRaises(OperationFailure, self.db.test.update_one,
{"hello": "world"}, doc, upsert=True)
# This is going to cause keys to be checked and raise InvalidDocument.
@ -1405,14 +1420,16 @@ class TestCollection(IntegrationTest):
# doesn't change. If the behavior changes checking the first key for
# '$' in update won't be good enough anymore.
doc = SON([("hello", "world"), ("$set", {"foo.bar": "bim"})])
self.assertRaises(expected, self.db.test.update,
self.assertRaises(expected, self.db.test.replace_one,
{"hello": "world"}, doc, upsert=True)
# Replace with empty document
self.assertNotEqual(0, self.db.test.update({"hello": "world"},
{})['n'])
self.assertNotEqual(0,
self.db.test.replace_one(
{"hello": "world"}, {}).matched_count)
def test_acknowledged_save(self):
# Tests legacy save.
db = self.db
db.drop_collection("test")
db.test.create_index("hello", unique=True)
@ -1427,18 +1444,19 @@ class TestCollection(IntegrationTest):
db.drop_collection("test")
db.create_collection("test", capped=True, size=1000)
db.test.insert({"x": 1})
db.test.insert_one({"x": 1})
self.assertEqual(1, db.test.count())
# Can't remove from capped collection.
self.assertRaises(OperationFailure, db.test.remove, {"x": 1})
self.assertRaises(OperationFailure, db.test.delete_one, {"x": 1})
db.drop_collection("test")
db.test.insert({"x": 1})
db.test.insert({"x": 1})
self.assertEqual(2, db.test.remove({})["n"])
self.assertEqual(0, db.test.remove({})["n"])
db.test.insert_one({"x": 1})
db.test.insert_one({"x": 1})
self.assertEqual(2, db.test.delete_many({}).deleted_count)
self.assertEqual(0, db.test.delete_many({}).deleted_count)
def test_last_error_options(self):
# Tests legacy write methods.
self.db.test.save({"x": 1}, w=1, wtimeout=1)
self.db.test.insert({"x": 1}, w=1, wtimeout=1)
self.db.test.remove({"x": 1}, w=1, wtimeout=1)
@ -1475,7 +1493,8 @@ class TestCollection(IntegrationTest):
{"_id": 1}, j=True, fsync=True)
def test_manual_last_error(self):
self.db.test.save({"x": 1}, w=0)
coll = self.db.get_collection("test", write_concern=WriteConcern(w=0))
self.db.test.insert_one({"x": 1})
self.db.command("getlasterror", w=1, wtimeout=1)
def test_count(self):
@ -1483,11 +1502,9 @@ class TestCollection(IntegrationTest):
db.drop_collection("test")
self.assertEqual(db.test.count(), 0)
db.test.save({})
db.test.save({})
db.test.insert_many([{}, {}])
self.assertEqual(db.test.count(), 2)
db.test.save({'foo': 'bar'})
db.test.save({'foo': 'baz'})
db.test.insert_many([{'foo': 'bar'}, {'foo': 'baz'}])
self.assertEqual(db.test.find({'foo': 'bar'}).count(), 1)
self.assertEqual(db.test.count({'foo': 'bar'}), 1)
self.assertEqual(db.test.find({'foo': re.compile(r'ba.*')}).count(), 2)
@ -1497,7 +1514,7 @@ class TestCollection(IntegrationTest):
def test_aggregate(self):
db = self.db
db.drop_collection("test")
db.test.save({'foo': [1, 2]})
db.test.insert_one({'foo': [1, 2]})
self.assertRaises(TypeError, db.test.aggregate, "wow")
@ -1523,12 +1540,13 @@ class TestCollection(IntegrationTest):
if client_context.replica_set_name:
# Test that getMore messages are sent to the right server.
db = self.client.get_database(
db.name, read_preference=ReadPreference.SECONDARY)
db.name,
read_preference=ReadPreference.SECONDARY,
write_concern=WriteConcern(w=self.w))
for collection_size in (10, 1000):
db.drop_collection("test")
db.test.insert([{'_id': i} for i in range(collection_size)],
w=self.w)
db.test.insert_many([{'_id': i} for i in range(collection_size)])
expected_sum = sum(range(collection_size))
# Use batchSize to ensure multiple getMore messages
cursor = db.test.aggregate(
@ -1547,10 +1565,12 @@ class TestCollection(IntegrationTest):
if client_context.replica_set_name:
# Test that getMore messages are sent to the right server.
db = self.client.get_database(
db.name, read_preference=ReadPreference.SECONDARY)
db.name,
read_preference=ReadPreference.SECONDARY,
write_concern=WriteConcern(w=self.w))
coll = db.test
coll.insert(({'_id': i} for i in range(8000)), w=self.w)
coll.insert_many([{'_id': i} for i in range(8000)])
docs = []
threads = [threading.Thread(target=docs.extend, args=(cursor,))
for cursor in coll.parallel_scan(3)]
@ -1572,9 +1592,7 @@ class TestCollection(IntegrationTest):
"function (obj, prev) { prev.count++; }"
))
db.test.save({"a": 2})
db.test.save({"b": 5})
db.test.save({"a": 1})
db.test.insert_many([{"a": 2}, {"b": 5}, {"a": 1}])
self.assertEqual([{"count": 3}],
db.test.group([], {}, {"count": 0},
@ -1586,7 +1604,7 @@ class TestCollection(IntegrationTest):
"function (obj, prev) { prev.count++; }"
))
db.test.save({"a": 2, "b": 3})
db.test.insert_one({"a": 2, "b": 3})
self.assertEqual([{"a": 2, "count": 2},
{"a": None, "count": 1},
@ -1632,8 +1650,7 @@ class TestCollection(IntegrationTest):
def test_group_with_scope(self):
db = self.db
db.drop_collection("test")
db.test.save({"a": 1})
db.test.save({"b": 1})
db.test.insert_many([{"a": 1}, {"b": 1}])
reduce_function = "function (obj, prev) { prev.count += inc_value; }"
@ -1669,7 +1686,7 @@ class TestCollection(IntegrationTest):
for i in range(2000):
doc = {"x": i, "y": my_str}
db.test_large_limit.insert(doc)
db.test_large_limit.insert_one(doc)
i = 0
y = 0
@ -1685,7 +1702,7 @@ class TestCollection(IntegrationTest):
db.drop_collection("test")
for i in range(10):
db.test.insert({"x": i})
db.test.insert_one({"x": i})
self.assertEqual(10, db.test.count())
@ -1711,7 +1728,7 @@ class TestCollection(IntegrationTest):
self.assertEqual(0, db.foo.count())
for i in range(10):
db.test.insert({"x": i})
db.test.insert_one({"x": i})
self.assertEqual(10, db.test.count())
@ -1725,7 +1742,7 @@ class TestCollection(IntegrationTest):
self.assertEqual(x, doc["x"])
x += 1
db.test.insert({})
db.test.insert_one({})
self.assertRaises(OperationFailure, db.foo.rename, "test")
db.foo.rename("test", dropTarget=True)
@ -1733,7 +1750,7 @@ class TestCollection(IntegrationTest):
db = self.db
db.drop_collection("test")
id = db.test.save({"hello": "world", "foo": "bar"})
id = db.test.insert_one({"hello": "world", "foo": "bar"}).inserted_id
self.assertEqual("world", db.test.find_one()["hello"])
self.assertEqual(db.test.find_one(id), db.test.find_one())
@ -1753,16 +1770,17 @@ class TestCollection(IntegrationTest):
db = self.db
db.drop_collection("test")
db.test.save({"_id": 5})
db.test.insert_one({"_id": 5})
self.assertTrue(db.test.find_one(5))
self.assertFalse(db.test.find_one(6))
def test_remove_non_objectid(self):
# Tests legacy remove.
db = self.db
db.drop_collection("test")
db.test.save({"_id": 5})
db.test.insert_one({"_id": 5})
self.assertEqual(1, db.test.count())
db.test.remove(5)
@ -1772,9 +1790,7 @@ class TestCollection(IntegrationTest):
db = self.db
db.drop_collection("test")
db.test.save({"x": 1})
db.test.save({"x": 2})
db.test.save({"x": 3})
db.test.insert_many([{"x": i} for i in range(1, 4)])
self.assertEqual(1, db.test.find_one()["x"])
self.assertEqual(2, db.test.find_one(skip=1, limit=2)["x"])
@ -1783,9 +1799,7 @@ class TestCollection(IntegrationTest):
db = self.db
db.drop_collection("test")
db.test.save({"x": 2})
db.test.save({"x": 1})
db.test.save({"x": 3})
db.test.insert_many([{"x": 2}, {"x": 1}, {"x": 3}])
self.assertEqual(2, db.test.find_one()["x"])
self.assertEqual(1, db.test.find_one(sort=[("x", 1)])["x"])
@ -1803,6 +1817,7 @@ class TestCollection(IntegrationTest):
self.assertRaises(ValueError, db.test.find, sort=["hello", 1])
def test_insert_adds_id(self):
# Tests legacy insert.
doc = {"hello": "world"}
self.db.test.insert(doc)
self.assertTrue("_id" in doc)
@ -1813,6 +1828,7 @@ class TestCollection(IntegrationTest):
self.assertTrue("_id" in doc)
def test_save_adds_id(self):
# Tests legacy save.
doc = {"hello": "jesse"}
self.db.test.save(doc)
self.assertTrue("_id" in doc)
@ -1841,7 +1857,7 @@ class TestCollection(IntegrationTest):
self.db.drop_collection("test")
# Insert enough documents to require more than one batch
self.db.test.insert([{'i': i} for i in range(150)])
self.db.test.insert_many([{'i': i} for i in range(150)])
client = rs_or_single_client(max_pool_size=1)
socks = get_pool(client).sockets
@ -1876,11 +1892,7 @@ class TestCollection(IntegrationTest):
self.db.drop_collection("test")
test = self.db.test
test.save({"a": 1})
test.save({"a": 2})
test.save({"a": 2})
test.save({"a": 2})
test.save({"a": 3})
test.insert_many([{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}])
distinct = test.distinct("a")
distinct.sort()
@ -1897,10 +1909,10 @@ class TestCollection(IntegrationTest):
self.db.drop_collection("test")
test.save({"a": {"b": "a"}, "c": 12})
test.save({"a": {"b": "b"}, "c": 12})
test.save({"a": {"b": "c"}, "c": 12})
test.save({"a": {"b": "c"}, "c": 12})
test.insert_one({"a": {"b": "a"}, "c": 12})
test.insert_one({"a": {"b": "b"}, "c": 12})
test.insert_one({"a": {"b": "c"}, "c": 12})
test.insert_one({"a": {"b": "c"}, "c": 12})
distinct = test.distinct("a.b")
distinct.sort()
@ -1909,8 +1921,8 @@ class TestCollection(IntegrationTest):
def test_query_on_query_field(self):
self.db.drop_collection("test")
self.db.test.save({"query": "foo"})
self.db.test.save({"bar": "foo"})
self.db.test.insert_one({"query": "foo"})
self.db.test.insert_one({"bar": "foo"})
self.assertEqual(1,
self.db.test.find({"query": {"$ne": None}}).count())
@ -1920,8 +1932,7 @@ class TestCollection(IntegrationTest):
def test_min_query(self):
self.db.drop_collection("test")
self.db.test.save({"x": 1})
self.db.test.save({"x": 2})
self.db.test.insert_many([{"x": 1}, {"x": 2}])
self.db.test.create_index("x")
self.assertEqual(1, len(list(self.db.test.find({"$min": {"x": 2},
@ -1930,6 +1941,7 @@ class TestCollection(IntegrationTest):
"$query": {}})[0]["x"])
def test_insert_large_document(self):
# Tests legacy insert, save, and update.
max_size = self.db.connection.max_bson_size
half_size = int(max_size / 2)
self.assertEqual(max_size, 16777216)
@ -1955,6 +1967,7 @@ class TestCollection(IntegrationTest):
self.db.test.update({"bar": "x"}, {"bar": "x" * (max_size - 32)})
def test_insert_large_batch(self):
# Tests legacy insert.
db = self.client.test_insert_large_batch
self.addCleanup(self.client.drop_database, 'test_insert_large_batch')
max_bson_size = self.client.max_bson_size
@ -2011,20 +2024,20 @@ class TestCollection(IntegrationTest):
def test_numerous_inserts(self):
# Ensure we don't exceed server's 1000-document batch size limit.
self.db.test.remove()
self.db.test.drop()
n_docs = 2100
self.db.test.insert({} for _ in range(n_docs))
self.db.test.insert_many([{} for _ in range(n_docs)])
self.assertEqual(n_docs, self.db.test.count())
self.db.test.remove()
self.db.test.drop()
def test_map_reduce(self):
db = self.db
db.drop_collection("test")
db.test.insert({"id": 1, "tags": ["dog", "cat"]})
db.test.insert({"id": 2, "tags": ["cat"]})
db.test.insert({"id": 3, "tags": ["mouse", "cat", "dog"]})
db.test.insert({"id": 4, "tags": []})
db.test.insert_one({"id": 1, "tags": ["dog", "cat"]})
db.test.insert_one({"id": 2, "tags": ["cat"]})
db.test.insert_one({"id": 3, "tags": ["mouse", "cat", "dog"]})
db.test.insert_one({"id": 4, "tags": []})
map = Code("function () {"
" this.tags.forEach(function(z) {"
@ -2043,10 +2056,10 @@ class TestCollection(IntegrationTest):
self.assertEqual(2, result.find_one({"_id": "dog"})["value"])
self.assertEqual(1, result.find_one({"_id": "mouse"})["value"])
db.test.insert({"id": 5, "tags": ["hampster"]})
db.test.insert_one({"id": 5, "tags": ["hampster"]})
result = db.test.map_reduce(map, reduce, out='mrunittests')
self.assertEqual(1, result.find_one({"_id": "hampster"})["value"])
db.test.remove({"id": 5})
db.test.delete_one({"id": 5})
result = db.test.map_reduce(map, reduce,
out={'merge': 'mrunittests'})
@ -2107,9 +2120,9 @@ class TestCollection(IntegrationTest):
def test_messages_with_unicode_collection_names(self):
db = self.db
db[u("Employés")].insert({"x": 1})
db[u("Employés")].update({"x": 1}, {"x": 2})
db[u("Employés")].remove({})
db[u("Employés")].insert_one({"x": 1})
db[u("Employés")].replace_one({"x": 1}, {"x": 2})
db[u("Employés")].delete_many({})
db[u("Employés")].find_one()
list(db[u("Employés")].find())
@ -2122,14 +2135,14 @@ class TestCollection(IntegrationTest):
def test_bad_encode(self):
c = self.db.test
c.drop()
self.assertRaises(InvalidDocument, c.save, {"x": c})
self.assertRaises(InvalidDocument, c.insert_one, {"x": c})
class BadGetAttr(dict):
def __getattr__(self, name):
pass
bad = BadGetAttr([('foo', 'bar')])
c.insert({'bad': bad})
c.insert_one({'bad': bad})
self.assertEqual('bar', c.find_one()['bad']['foo'])
def test_bad_dbref(self):
@ -2139,11 +2152,11 @@ class TestCollection(IntegrationTest):
# Incomplete DBRefs.
self.assertRaises(
InvalidDocument,
c.insert, {'ref': {'$ref': 'collection'}})
c.insert_one, {'ref': {'$ref': 'collection'}})
self.assertRaises(
InvalidDocument,
c.insert, {'ref': {'$id': ObjectId()}})
c.insert_one, {'ref': {'$id': ObjectId()}})
ref_only = {'ref': {'$ref': 'collection'}}
id_only = {'ref': {'$id': ObjectId()}}
@ -2249,7 +2262,7 @@ class TestCollection(IntegrationTest):
def test_find_one_and(self):
c = self.db.test
c.drop()
c.insert({'_id': 1, 'i': 1})
c.insert_one({'_id': 1, 'i': 1})
self.assertEqual({'_id': 1, 'i': 1},
c.find_one_and_update({'_id': 1}, {'$inc': {'i': 1}}))
@ -2287,7 +2300,7 @@ class TestCollection(IntegrationTest):
c.drop()
for j in range(5):
c.insert({'j': j, 'i': 0})
c.insert_one({'j': j, 'i': 0})
sort=[('j', DESCENDING)]
self.assertEqual(4, c.find_one_and_update({},
@ -2298,6 +2311,7 @@ class TestCollection(IntegrationTest):
# MongoDB versions >= 2.6.0 don't return the updatedExisting field
# and return upsert _id in an array subdocument. This test should
# pass regardless of server version or type (mongod/s).
# Tests legacy update.
c = self.db.test
c.drop()
oid = ObjectId()
@ -2360,7 +2374,7 @@ class TestCollection(IntegrationTest):
def test_find_with_nested(self):
c = self.db.test
c.drop()
c.insert([{'i': i} for i in range(5)]) # [0, 1, 2, 3, 4]
c.insert_many([{'i': i} for i in range(5)]) # [0, 1, 2, 3, 4]
self.assertEqual(
[2],
[i['i'] for i in c.find({
@ -2422,12 +2436,12 @@ class TestCollection(IntegrationTest):
self.assertEqual(0, c.find_one(manipulate=False)['foo'])
self.assertEqual(2, c.find_one(manipulate=True)['foo'])
c.remove({})
c.drop()
def test_find_regex(self):
c = self.db.test
c.drop()
c.insert({'r': re.compile('.*')})
c.insert_one({'r': re.compile('.*')})
self.assertTrue(isinstance(c.find_one()['r'], Regex))
for doc in c.find():

View File

@ -48,7 +48,7 @@ class TestCommon(IntegrationTest):
# Test basic query
uu = uuid.uuid4()
# Insert as binary subtype 3
coll.insert({'uu': uu})
coll.insert_one({'uu': uu})
self.assertEqual(uu, coll.find_one({'uu': uu})['uu'])
coll = self.db.get_collection(
"uuid", CodecOptions(uuid_representation=STANDARD))
@ -62,34 +62,25 @@ class TestCommon(IntegrationTest):
"uuid", CodecOptions(uuid_representation=PYTHON_LEGACY))
self.assertEqual(1, coll.find({'uu': uu}).count())
# Test remove
# Test delete
coll = self.db.get_collection(
"uuid", CodecOptions(uuid_representation=STANDARD))
coll.remove({'uu': uu})
coll.delete_one({'uu': uu})
self.assertEqual(1, coll.count())
coll = self.db.get_collection(
"uuid", CodecOptions(uuid_representation=PYTHON_LEGACY))
coll.remove({'uu': uu})
coll.delete_one({'uu': uu})
self.assertEqual(0, coll.count())
# Test save
coll.insert({'_id': uu, 'i': 0})
self.assertEqual(1, coll.count())
self.assertEqual(1, coll.find({'_id': uu}).count())
self.assertEqual(0, coll.find_one({'_id': uu})['i'])
doc = coll.find_one({'_id': uu})
doc['i'] = 1
coll.save(doc)
self.assertEqual(1, coll.find_one({'_id': uu})['i'])
# Test update
# Test update_one
coll.insert_one({'_id': uu, 'i': 1})
coll = self.db.get_collection(
"uuid", CodecOptions(uuid_representation=STANDARD))
coll.update({'_id': uu}, {'$set': {'i': 2}})
coll.update_one({'_id': uu}, {'$set': {'i': 2}})
coll = self.db.get_collection(
"uuid", CodecOptions(uuid_representation=PYTHON_LEGACY))
self.assertEqual(1, coll.find_one({'_id': uu})['i'])
coll.update({'_id': uu}, {'$set': {'i': 2}})
coll.update_one({'_id': uu}, {'$set': {'i': 2}})
self.assertEqual(2, coll.find_one({'_id': uu})['i'])
# Test Cursor.distinct
@ -118,9 +109,9 @@ class TestCommon(IntegrationTest):
# Test (inline)_map_reduce
coll.drop()
coll.insert({"_id": uu, "x": 1, "tags": ["dog", "cat"]})
coll.insert({"_id": uuid.uuid4(), "x": 3,
"tags": ["mouse", "cat", "dog"]})
coll.insert_one({"_id": uu, "x": 1, "tags": ["dog", "cat"]})
coll.insert_one({"_id": uuid.uuid4(), "x": 3,
"tags": ["mouse", "cat", "dog"]})
map = Code("function () {"
" this.tags.forEach(function(z) {"
@ -158,8 +149,8 @@ class TestCommon(IntegrationTest):
coll.drop()
# Test group
coll.insert({"_id": uu, "a": 2})
coll.insert({"_id": uuid.uuid4(), "a": 1})
coll.insert_one({"_id": uu, "a": 2})
coll.insert_one({"_id": uuid.uuid4(), "a": 1})
reduce = "function (obj, prev) { prev.count++; }"
coll = self.db.get_collection(
@ -196,27 +187,27 @@ class TestCommon(IntegrationTest):
coll = m.pymongo_test.write_concern_test
coll.drop()
doc = {"_id": ObjectId()}
coll.insert(doc)
self.assertTrue(coll.insert(doc, w=0))
self.assertTrue(coll.insert(doc))
self.assertRaises(OperationFailure, coll.insert, doc, w=1)
coll.insert_one(doc)
self.assertTrue(coll.insert_one(doc))
coll = coll.with_options(write_concern=WriteConcern(w=1))
self.assertRaises(OperationFailure, coll.insert, doc)
m = rs_or_single_client()
coll = m.pymongo_test.write_concern_test
self.assertTrue(coll.insert(doc, w=0))
self.assertRaises(OperationFailure, coll.insert, doc)
self.assertRaises(OperationFailure, coll.insert, doc, w=1)
new_coll = coll.with_options(write_concern=WriteConcern(w=0))
self.assertTrue(new_coll.insert_one(doc))
self.assertRaises(OperationFailure, coll.insert_one, doc)
m = MongoClient("mongodb://%s/" % (pair,),
replicaSet=client_context.replica_set_name)
coll = m.pymongo_test.write_concern_test
self.assertRaises(OperationFailure, coll.insert, doc)
self.assertRaises(OperationFailure, coll.insert_one, doc)
m = MongoClient("mongodb://%s/?w=0" % (pair,),
replicaSet=client_context.replica_set_name)
coll = m.pymongo_test.write_concern_test
self.assertTrue(coll.insert(doc))
coll.insert_one(doc)
# Equality tests
direct = connected(single_client(w=0))

View File

@ -149,8 +149,8 @@ class TestCursor(IntegrationTest):
db.pymongo_test.drop()
coll = db.pymongo_test
self.assertRaises(TypeError, coll.find().max_time_ms, 'foo')
coll.insert({"amalia": 1})
coll.insert({"amalia": 2})
coll.insert_one({"amalia": 1})
coll.insert_one({"amalia": 2})
coll.find().max_time_ms(None)
coll.find().max_time_ms(long(1))
@ -194,7 +194,7 @@ class TestCursor(IntegrationTest):
def test_max_time_ms_getmore(self):
# Test that Cursor handles server timeout error in response to getmore.
coll = self.db.pymongo_test
coll.insert({} for _ in range(200))
coll.insert_many([{} for _ in range(200)])
cursor = coll.find().max_time_ms(100)
# Send initial query before turning on failpoint.
@ -229,8 +229,7 @@ class TestCursor(IntegrationTest):
self.assertRaises(TypeError, db.test.find().hint, 5.5)
db.test.drop()
for i in range(100):
db.test.insert({"num": i, "foo": i})
db.test.insert_many([{"num": i, "foo": i} for i in range(100)])
self.assertRaises(OperationFailure,
db.test.find({"num": 17, "foo": 17})
@ -260,8 +259,7 @@ class TestCursor(IntegrationTest):
db = self.db
db.test.drop()
for i in range(100):
db.test.insert({'i': i})
db.test.insert_many([{"i": i} for i in range(100)])
db.test.create_index([('i', DESCENDING)], name='fooindex')
first = next(db.test.find())
@ -278,8 +276,7 @@ class TestCursor(IntegrationTest):
self.assertTrue(db.test.find().limit(long(5)))
db.test.drop()
for i in range(100):
db.test.save({"x": i})
db.test.insert_many([{"x": i} for i in range(100)])
count = 0
for _ in db.test.find():
@ -322,8 +319,7 @@ class TestCursor(IntegrationTest):
db.test.drop()
db.test.ensure_index([("j", ASCENDING)])
for j in range(10):
db.test.insert({"j": j, "k": j})
db.test.insert_many([{"j": j, "k": j} for j in range(10)])
cursor = db.test.find().max([("j", 3)])
self.assertEqual(len(list(cursor)), 3)
@ -353,8 +349,7 @@ class TestCursor(IntegrationTest):
db.test.drop()
db.test.ensure_index([("j", ASCENDING)])
for j in range(10):
db.test.insert({"j": j, "k": j})
db.test.insert_many([{"j": j, "k": j} for j in range(10)])
cursor = db.test.find().min([("j", 3)])
self.assertEqual(len(list(cursor)), 7)
@ -382,8 +377,7 @@ class TestCursor(IntegrationTest):
def test_batch_size(self):
db = self.db
db.test.drop()
for x in range(200):
db.test.save({"x": x})
db.test.insert_many([{"x": x} for x in range(200)])
self.assertRaises(TypeError, db.test.find().batch_size, None)
self.assertRaises(TypeError, db.test.find().batch_size, "hello")
@ -425,8 +419,7 @@ class TestCursor(IntegrationTest):
def test_limit_and_batch_size(self):
db = self.db
db.test.drop()
for x in range(500):
db.test.save({"x": x})
db.test.insert_many([{"x": x} for x in range(500)])
curs = db.test.find().limit(0).batch_size(10)
next(curs)
@ -475,8 +468,7 @@ class TestCursor(IntegrationTest):
db.drop_collection("test")
for i in range(100):
db.test.save({"x": i})
db.test.insert_many([{"x": i} for i in range(100)])
for i in db.test.find():
self.assertEqual(i["x"], 0)
@ -525,8 +517,7 @@ class TestCursor(IntegrationTest):
unsort = list(range(10))
random.shuffle(unsort)
for i in unsort:
db.test.save({"x": i})
db.test.insert_many([{"x": i} for i in unsort])
asc = [i["x"] for i in db.test.find().sort("x", ASCENDING)]
self.assertEqual(asc, list(range(10)))
@ -550,7 +541,7 @@ class TestCursor(IntegrationTest):
db.test.drop()
for (a, b) in shuffled:
db.test.save({"a": a, "b": b})
db.test.insert_one({"a": a, "b": b})
result = [(i["a"], i["b"]) for i in
db.test.find().sort([("b", DESCENDING),
@ -569,8 +560,7 @@ class TestCursor(IntegrationTest):
self.assertEqual(0, db.test.find().count())
for i in range(10):
db.test.save({"x": i})
db.test.insert_many([{"x": i} for i in range(10)])
self.assertEqual(10, db.test.find().count())
self.assertTrue(isinstance(db.test.find().count(), int))
@ -592,8 +582,7 @@ class TestCursor(IntegrationTest):
collection = self.db.test
collection.drop()
collection.save({'i': 1})
collection.save({'i': 2})
collection.insert_many([{'i': 1}, {'i': 2}])
self.assertEqual(2, collection.find().count())
collection.create_index([('i', 1)])
@ -631,8 +620,7 @@ class TestCursor(IntegrationTest):
self.assertRaises(TypeError, a.where, None)
self.assertRaises(TypeError, a.where, {})
for i in range(10):
db.test.save({"x": i})
db.test.insert_many([{"x": i} for i in range(10)])
self.assertEqual(3, len(list(db.test.find().where('this.x < 3'))))
self.assertEqual(3,
@ -664,9 +652,7 @@ class TestCursor(IntegrationTest):
self.assertRaises(InvalidOperation, a.where, 'this.x < 3')
def test_rewind(self):
self.db.test.save({"x": 1})
self.db.test.save({"x": 2})
self.db.test.save({"x": 3})
self.db.test.insert_many([{"x": i} for i in range(1, 4)])
cursor = self.db.test.find().limit(2)
@ -698,9 +684,7 @@ class TestCursor(IntegrationTest):
self.assertEqual(cursor, cursor.rewind())
def test_clone(self):
self.db.test.save({"x": 1})
self.db.test.save({"x": 2})
self.db.test.save({"x": 3})
self.db.test.insert_many([{"x": i} for i in range(1, 4)])
cursor = self.db.test.find().limit(2)
@ -798,7 +782,7 @@ class TestCursor(IntegrationTest):
def test_count_with_fields(self):
self.db.test.drop()
self.db.test.save({"x": 1})
self.db.test.insert_one({"x": 1})
self.assertEqual(1, self.db.test.find({}, ["a"]).count())
def test_bad_getitem(self):
@ -808,8 +792,7 @@ class TestCursor(IntegrationTest):
def test_getitem_slice_index(self):
self.db.drop_collection("test")
for i in range(100):
self.db.test.save({"i": i})
self.db.test.insert_many([{"i": i} for i in range(100)])
count = itertools.count
@ -874,8 +857,7 @@ class TestCursor(IntegrationTest):
def test_getitem_numeric_index(self):
self.db.drop_collection("test")
for i in range(100):
self.db.test.save({"i": i})
self.db.test.insert_many([{"i": i} for i in range(100)])
self.assertEqual(0, self.db.test.find()[0]['i'])
self.assertEqual(50, self.db.test.find()[50]['i'])
@ -897,8 +879,7 @@ class TestCursor(IntegrationTest):
self.assertEqual(length, cursor.count(True))
self.db.drop_collection("test")
for i in range(100):
self.db.test.save({"i": i})
self.db.test.insert_many([{"i": i} for i in range(100)])
check_len(self.db.test.find(), 100)
@ -927,7 +908,7 @@ class TestCursor(IntegrationTest):
def test_get_more(self):
db = self.db
db.drop_collection("test")
db.test.insert([{'i': i} for i in range(10)])
db.test.insert_many([{'i': i} for i in range(10)])
self.assertEqual(10, len(list(db.test.find().batch_size(5))))
def test_tailable(self):
@ -937,21 +918,21 @@ class TestCursor(IntegrationTest):
self.addCleanup(db.drop_collection, "test")
cursor = db.test.find(cursor_type=TAILABLE)
db.test.insert({"x": 1})
db.test.insert_one({"x": 1})
count = 0
for doc in cursor:
count += 1
self.assertEqual(1, doc["x"])
self.assertEqual(1, count)
db.test.insert({"x": 2})
db.test.insert_one({"x": 2})
count = 0
for doc in cursor:
count += 1
self.assertEqual(2, doc["x"])
self.assertEqual(1, count)
db.test.insert({"x": 3})
db.test.insert_one({"x": 3})
count = 0
for doc in cursor:
count += 1
@ -961,7 +942,7 @@ class TestCursor(IntegrationTest):
# Capped rollover - the collection can never
# have more than 3 documents. Just make sure
# this doesn't raise...
db.test.insert(({"x": i} for i in range(4, 7)))
db.test.insert_many([{"x": i} for i in range(4, 7)])
self.assertEqual(0, len(list(cursor)))
# and that the cursor doesn't think it's still alive.
@ -973,11 +954,8 @@ class TestCursor(IntegrationTest):
def test_distinct(self):
self.db.drop_collection("test")
self.db.test.save({"a": 1})
self.db.test.save({"a": 2})
self.db.test.save({"a": 2})
self.db.test.save({"a": 2})
self.db.test.save({"a": 3})
self.db.test.insert_many(
[{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}])
distinct = self.db.test.find({"a": {"$lt": 3}}).distinct("a")
distinct.sort()
@ -986,10 +964,10 @@ class TestCursor(IntegrationTest):
self.db.drop_collection("test")
self.db.test.save({"a": {"b": "a"}, "c": 12})
self.db.test.save({"a": {"b": "b"}, "c": 8})
self.db.test.save({"a": {"b": "c"}, "c": 12})
self.db.test.save({"a": {"b": "c"}, "c": 8})
self.db.test.insert_one({"a": {"b": "a"}, "c": 12})
self.db.test.insert_one({"a": {"b": "b"}, "c": 8})
self.db.test.insert_one({"a": {"b": "c"}, "c": 12})
self.db.test.insert_one({"a": {"b": "c"}, "c": 8})
distinct = self.db.test.find({"c": 8}).distinct("a.b")
distinct.sort()
@ -998,8 +976,7 @@ class TestCursor(IntegrationTest):
def test_max_scan(self):
self.db.drop_collection("test")
for _ in range(100):
self.db.test.insert({})
self.db.test.insert_many([{} for _ in range(100)])
self.assertEqual(100, len(list(self.db.test.find())))
self.assertEqual(50, len(list(self.db.test.find().max_scan(50))))
@ -1008,8 +985,7 @@ class TestCursor(IntegrationTest):
def test_with_statement(self):
self.db.drop_collection("test")
for _ in range(100):
self.db.test.insert({})
self.db.test.insert_many([{} for _ in range(100)])
c1 = self.db.test.find()
with self.db.test.find() as c2:
@ -1062,7 +1038,7 @@ class TestCursor(IntegrationTest):
run_with_profiling(distinct)
self.db.test.insert([{}, {}])
self.db.test.insert_many([{}, {}])
cursor = self.db.test.find()
next(cursor)
self.assertRaises(InvalidOperation, cursor.comment, 'hello')
@ -1076,8 +1052,8 @@ class TestCursor(IntegrationTest):
client = client_context.rs_or_standalone_client
db = client.pymongo_test
db.test.remove({})
db.test.insert({'_id': i} for i in range(200))
db.test.delete_many({})
db.test.insert_many([{'_id': i} for i in range(200)])
class CManager(CursorManager):
def __init__(self, connection):

View File

@ -34,14 +34,14 @@ class TestCursorManager(IntegrationTest):
def setUpClass(cls):
super(TestCursorManager, cls).setUpClass()
cls.collection = cls.db.test
cls.collection.remove()
cls.collection.drop()
# Ensure two batches.
cls.collection.insert({'_id': i} for i in range(200))
cls.collection.insert_many([{'_id': i} for i in range(200)])
@classmethod
def tearDownClass(cls):
cls.collection.remove()
cls.collection.drop()
def test_cursor_manager_validation(self):
with self.assertRaises(TypeError):

View File

@ -150,7 +150,7 @@ class TestDatabase(IntegrationTest):
def test_create_collection(self):
db = Database(self.client, "pymongo_test")
db.test.insert({"hello": "world"})
db.test.insert_one({"hello": "world"})
self.assertRaises(CollectionInvalid, db.create_collection, "test")
db.drop_collection("test")
@ -161,7 +161,7 @@ class TestDatabase(IntegrationTest):
test = db.create_collection("test")
self.assertTrue(u("test") in db.collection_names())
test.save({"hello": u("world")})
test.insert_one({"hello": u("world")})
self.assertEqual(db.test.find_one()["hello"], "world")
db.drop_collection("test.foo")
@ -171,8 +171,8 @@ class TestDatabase(IntegrationTest):
def test_collection_names(self):
db = Database(self.client, "pymongo_test")
db.test.save({"dummy": u("object")})
db.test.mike.save({"dummy": u("object")})
db.test.insert_one({"dummy": u("object")})
db.test.mike.insert_one({"dummy": u("object")})
colls = db.collection_names()
self.assertTrue("test" in colls)
@ -190,22 +190,22 @@ class TestDatabase(IntegrationTest):
self.assertRaises(TypeError, db.drop_collection, 5)
self.assertRaises(TypeError, db.drop_collection, None)
db.test.save({"dummy": u("object")})
db.test.insert_one({"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")})
db.test.insert_one({"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")})
db.test.insert_one({"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")})
db.test.insert_one({"dummy": u("object")})
self.assertTrue("test" in db.collection_names())
db.test.drop()
self.assertFalse("test" in db.collection_names())
@ -219,7 +219,7 @@ class TestDatabase(IntegrationTest):
self.assertRaises(TypeError, db.validate_collection, 5)
self.assertRaises(TypeError, db.validate_collection, None)
db.test.save({"dummy": u("object")})
db.test.insert_one({"dummy": u("object")})
self.assertRaises(OperationFailure, db.validate_collection,
"test.doesnotexist")
@ -337,14 +337,15 @@ class TestDatabase(IntegrationTest):
def test_command_with_regex(self):
db = self.client.pymongo_test
db.test.drop()
db.test.insert({'r': re.compile('.*')})
db.test.insert({'r': Regex('.*')})
db.test.insert_one({'r': re.compile('.*')})
db.test.insert_one({'r': Regex('.*')})
result = db.command('aggregate', 'test', pipeline=[])
for doc in result['result']:
self.assertTrue(isinstance(doc['r'], Regex))
def test_last_status(self):
# Tests many legacy API elements.
with ignore_deprecations():
# We must call getlasterror on same socket as the last operation.
db = rs_or_single_client(max_pool_size=1).pymongo_test
@ -452,14 +453,14 @@ class TestDatabase(IntegrationTest):
# Check that we're read-write by default.
db.authenticate('jesse', 'pw')
db.collection.insert({})
db.collection.insert_one({})
db.logout()
# Make the user read-only.
auth_db.add_user('jesse', 'pw', read_only=True)
db.authenticate('jesse', 'pw')
self.assertRaises(OperationFailure, db.collection.insert, {})
self.assertRaises(OperationFailure, db.collection.insert_one, {})
@client_context.require_version_min(2, 5, 3, -1)
@client_context.require_auth
@ -550,20 +551,20 @@ class TestDatabase(IntegrationTest):
admin_db.authenticate('ro-admin', 'pass')
self.assertEqual(0, other_db.test.count())
self.assertRaises(OperationFailure,
other_db.test.insert, {})
other_db.test.insert_one, {})
# Close all sockets.
client.disconnect()
# We should still be able to write to the regular user's db.
self.assertTrue(users_db.test.remove())
self.assertTrue(users_db.test.delete_many({}))
# 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, {})
other_db.test.insert_one, {})
def test_id_ordering(self):
# PyMongo attempts to have _id show up first
@ -573,8 +574,8 @@ class TestDatabase(IntegrationTest):
# work right in Jython or any Python or environment
# with hash randomization enabled (e.g. tox).
db = self.client.pymongo_test
db.test.remove({})
db.test.insert(SON([("hello", "world"),
db.test.drop()
db.test.insert_one(SON([("hello", "world"),
("_id", 5)]))
db = self.client.get_database(
@ -587,7 +588,7 @@ class TestDatabase(IntegrationTest):
def test_deref(self):
db = self.client.pymongo_test
db.test.remove({})
db.test.drop()
self.assertRaises(TypeError, db.dereference, 5)
self.assertRaises(TypeError, db.dereference, "hello")
@ -595,7 +596,7 @@ class TestDatabase(IntegrationTest):
self.assertEqual(None, db.dereference(DBRef("test", ObjectId())))
obj = {"x": True}
key = db.test.save(obj)
key = db.test.insert_one(obj).inserted_id
self.assertEqual(obj, db.dereference(DBRef("test", key)))
self.assertEqual(obj,
db.dereference(DBRef("test", key, "pymongo_test")))
@ -604,14 +605,14 @@ class TestDatabase(IntegrationTest):
self.assertEqual(None, db.dereference(DBRef("test", 4)))
obj = {"_id": 4}
db.test.save(obj)
db.test.insert_one(obj)
self.assertEqual(obj, db.dereference(DBRef("test", 4)))
def test_deref_kwargs(self):
db = self.client.pymongo_test
db.test.remove({})
db.test.drop()
db.test.insert({"_id": 4, "foo": "bar"})
db.test.insert_one({"_id": 4, "foo": "bar"})
db = self.client.get_database(
"pymongo_test", codec_options=CodecOptions(as_class=SON))
self.assertEqual(SON([("foo", "bar")]),
@ -621,7 +622,7 @@ class TestDatabase(IntegrationTest):
@client_context.require_no_auth
def test_eval(self):
db = self.client.pymongo_test
db.test.remove({})
db.test.drop()
self.assertRaises(TypeError, db.eval, None)
self.assertRaises(TypeError, db.eval, 5)
@ -646,12 +647,12 @@ class TestDatabase(IntegrationTest):
self.assertRaises(OperationFailure, db.eval, "5 ++ 5;")
# TODO some of these tests belong in the collection level testing.
def test_save_find_one(self):
def test_insert_find_one(self):
db = self.client.pymongo_test
db.test.remove({})
db.test.drop()
a_doc = SON({"hello": u("world")})
a_key = db.test.save(a_doc)
a_key = db.test.insert_one(a_doc).inserted_id
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"]}))
@ -662,7 +663,7 @@ class TestDatabase(IntegrationTest):
b = db.test.find_one()
b["hello"] = u("mike")
db.test.save(b)
db.test.replace_one({"_id": b["_id"]}, b)
self.assertNotEqual(a_doc, db.test.find_one(a_key))
self.assertEqual(b, db.test.find_one(a_key))
@ -675,70 +676,53 @@ class TestDatabase(IntegrationTest):
def test_long(self):
db = self.client.pymongo_test
db.test.remove({})
db.test.save({"x": long(9223372036854775807)})
db.test.drop()
db.test.insert_one({"x": long(9223372036854775807)})
retrieved = db.test.find_one()['x']
self.assertEqual(Int64(9223372036854775807), retrieved)
self.assertIsInstance(retrieved, Int64)
db.test.remove({})
db.test.insert({"x": Int64(1)})
db.test.delete_many({})
db.test.insert_one({"x": Int64(1)})
retrieved = db.test.find_one()['x']
self.assertEqual(Int64(1), retrieved)
self.assertIsInstance(retrieved, Int64)
def test_remove(self):
def test_delete(self):
db = self.client.pymongo_test
db.test.remove({})
db.test.drop()
one = db.test.save({"x": 1})
db.test.save({"x": 2})
db.test.save({"x": 3})
db.test.insert_one({"x": 1})
db.test.insert_one({"x": 2})
db.test.insert_one({"x": 3})
length = 0
for _ in db.test.find():
length += 1
self.assertEqual(length, 3)
db.test.remove(one)
db.test.delete_one({"x": 1})
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())
db.test.delete_one(db.test.find_one())
db.test.delete_one(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})
db.test.insert_one({"x": 1})
db.test.insert_one({"x": 2})
db.test.insert_one({"x": 3})
self.assertTrue(db.test.find_one({"x": 2}))
db.test.remove({"x": 2})
db.test.delete_one({"x": 2})
self.assertFalse(db.test.find_one({"x": 2}))
self.assertTrue(db.test.find_one())
db.test.remove({})
db.test.delete_many({})
self.assertFalse(db.test.find_one())
def test_save_a_bunch(self):
db = self.client.pymongo_test
db.test.remove({})
for i in range(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 range(62):
for _ in db.test.find():
break
def test_auto_ref_and_deref(self):
# Legacy API.
db = self.client.pymongo_test
db.add_son_manipulator(AutoReference(db))
db.add_son_manipulator(NamespaceInjector())
@ -767,6 +751,7 @@ class TestDatabase(IntegrationTest):
self.assertEqual(db.test.c.find_one(), c)
def test_auto_ref_and_deref_list(self):
# Legacy API.
db = self.client.pymongo_test
db.add_son_manipulator(AutoReference(db))
db.add_son_manipulator(NamespaceInjector())
@ -789,7 +774,7 @@ class TestDatabase(IntegrationTest):
@client_context.require_no_auth
def test_system_js(self):
db = self.client.pymongo_test
db.system.js.remove()
db.system.js.delete_many({})
self.assertEqual(0, db.system.js.count())
db.system_js.add = "function(a, b) { return a + b; }"
@ -820,7 +805,7 @@ class TestDatabase(IntegrationTest):
def test_system_js_list(self):
db = self.client.pymongo_test
db.system.js.remove()
db.system.js.delete_many({})
self.assertEqual([], db.system_js.list())
db.system_js.foo = "function() { return 'blah'; }"
@ -912,6 +897,7 @@ class TestDatabase(IntegrationTest):
# before any other checks, so they can insert non-dict objects and
# have them dictified before the _id is inserted or any other
# processing.
# Tests legacy API elements.
class Thing(object):
def __init__(self, value):
self.value = value
@ -930,6 +916,7 @@ class TestDatabase(IntegrationTest):
self.assertEqual('value', out.get('value'))
def test_son_manipulator_inheritance(self):
# Tests legacy API elements.
class Thing(object):
def __init__(self, value):
self.value = value

View File

@ -123,8 +123,8 @@ class TestGridFile(IntegrationTest):
self.assertEqual("6f5902ac237024bdd0c176cb93063dc4", f.md5)
def test_alternate_collection(self):
self.db.alt.files.remove({})
self.db.alt.chunks.remove({})
self.db.alt.files.delete_many({})
self.db.alt.chunks.delete_many({})
f = GridIn(self.db.alt)
f.write(b"hello world")

View File

@ -363,7 +363,7 @@ class TestGridfs(IntegrationTest):
self.fs.put(b"", filename="empty")
doc = self.db.fs.files.find_one({"filename": "empty"})
doc.pop("length")
self.db.fs.files.save(doc)
self.db.fs.files.replace_one({"_id": doc["_id"]}, doc)
f = self.fs.get_last_version(filename="empty")
def iterate_file(grid_file):
@ -426,8 +426,8 @@ class TestGridfs(IntegrationTest):
# Lua, and perhaps other buggy GridFS clients, store size as a float.
data = b'data'
self.fs.put(data, filename='f')
self.db.fs.files.update({'filename': 'f'},
{'$set': {'chunkSize': 100.0}})
self.db.fs.files.update_one({'filename': 'f'},
{'$set': {'chunkSize': 100.0}})
self.assertEqual(data, self.fs.get_version('f').read())

View File

@ -228,7 +228,7 @@ class TestJsonUtilRoundtrip(IntegrationTest):
ObjectId('509b8db456c02c5ab7e63c34'))}}
]
db.test.insert(docs)
db.test.insert_many(docs)
reloaded_docs = json_util.loads(json_util.dumps(db.test.find()))
for doc in docs:
self.assertTrue(doc in reloaded_docs)

View File

@ -76,25 +76,25 @@ class MongoThread(threading.Thread):
raise NotImplementedError
class SaveAndFind(MongoThread):
class InsertOneAndFind(MongoThread):
def run_mongo_thread(self):
for _ in range(N):
rand = random.randint(0, N)
_id = self.db.sf.save({"x": rand})
_id = self.db.sf.insert_one({"x": rand}).inserted_id
assert rand == self.db.sf.find_one(_id)["x"]
class Unique(MongoThread):
def run_mongo_thread(self):
for _ in range(N):
self.db.unique.insert({}) # no error
self.db.unique.insert_one({}) # no error
class NonUnique(MongoThread):
def run_mongo_thread(self):
for _ in range(N):
try:
self.db.unique.insert({"_id": "jesse"})
self.db.unique.insert_one({"_id": "jesse"})
except DuplicateKeyError:
pass
else:
@ -159,8 +159,8 @@ class _TestPoolingBase(unittest.TestCase):
db = self.c[DB]
db.unique.drop()
db.test.drop()
db.unique.insert({"_id": "jesse"})
db.test.insert([{} for _ in range(10)])
db.unique.insert_one({"_id": "jesse"})
db.test.insert_many([{} for _ in range(10)])
def create_pool(self, pair=(host, port), *args, **kwargs):
return Pool(pair, PoolOptions(*args, **kwargs))
@ -180,10 +180,10 @@ class TestPooling(_TestPoolingBase):
self.assertEqual(c.max_pool_size, 100)
def test_no_disconnect(self):
run_cases(self.c, [NonUnique, Unique, SaveAndFind])
run_cases(self.c, [NonUnique, Unique, InsertOneAndFind])
def test_disconnect(self):
run_cases(self.c, [SaveAndFind, Disconnect, Unique])
run_cases(self.c, [InsertOneAndFind, Disconnect, Unique])
def test_pool_reuses_open_socket(self):
# Test Pool's _check_closed() method doesn't close a healthy socket.
@ -286,8 +286,8 @@ class TestPooling(_TestPoolingBase):
raise SkipTest("No multiprocessing module")
a = rs_or_single_client()
a.pymongo_test.test.remove()
a.pymongo_test.test.insert({'_id':1})
a.pymongo_test.test.drop()
a.pymongo_test.test.insert_one({'_id':1})
a.pymongo_test.test.find_one()
self.assertEqual(1, len(get_pool(a).sockets))
a_sock = one(get_pool(a).sockets)
@ -422,8 +422,8 @@ class TestPoolMaxSize(_TestPoolingBase):
collection = c[DB].test
# Need one document.
collection.remove()
collection.insert({})
collection.drop()
collection.insert_one({})
# nthreads had better be much larger than max_pool_size to ensure that
# max_pool_size sockets are actually required at some point in this
@ -457,8 +457,8 @@ class TestPoolMaxSize(_TestPoolingBase):
collection = c[DB].test
# Need one document.
collection.remove()
collection.insert({})
collection.drop()
collection.insert_one({})
cx_pool = get_pool(c)
nthreads = 10

View File

@ -20,6 +20,7 @@ sys.path[0:0] = [""]
from bson.py3compat import MAXSIZE
from pymongo.cursor import _QUERY_OPTIONS
from pymongo.errors import ConfigurationError
from pymongo.mongo_client import MongoClient
from pymongo.read_preferences import (ReadPreference, MovingAverage,
Primary, PrimaryPreferred,
@ -27,7 +28,7 @@ from pymongo.read_preferences import (ReadPreference, MovingAverage,
Nearest, ServerMode)
from pymongo.server_selectors import any_server_selector
from pymongo.server_type import SERVER_TYPE
from pymongo.errors import ConfigurationError
from pymongo.write_concern import WriteConcern
from test.test_replica_set_client import TestReplicaSetClientBase
from test import (client_context,
@ -48,8 +49,10 @@ class TestReadPreferencesBase(TestReplicaSetClientBase):
super(TestReadPreferencesBase, self).setUp()
# Insert some data so we can use cursors in read_from_which_host
self.client.pymongo_test.test.drop()
self.client.pymongo_test.test.insert(
[{'_id': i} for i in range(10)], w=self.w)
self.client.get_database(
"pymongo_test",
write_concern=WriteConcern(w=self.w)).test.insert_many(
[{'_id': i} for i in range(10)])
self.addCleanup(self.client.pymongo_test.test.drop)
@ -287,10 +290,12 @@ class TestCommandAndReadPreference(TestReplicaSetClientBase):
@client_context.require_version_min(2, 5, 2)
def test_aggregate_command_with_out(self):
# Tests aggregate command when pipeline contains $out.
self.c.pymongo_test.test.insert({"x": 1, "y": 1}, w=self.w)
self.c.pymongo_test.test.insert({"x": 1, "y": 2}, w=self.w)
self.c.pymongo_test.test.insert({"x": 2, "y": 1}, w=self.w)
self.c.pymongo_test.test.insert({"x": 2, "y": 2}, w=self.w)
db = self.c.get_database(
"pymongo_test", write_concern=WriteConcern(w=self.w))
db.test.insert_one({"x": 1, "y": 1})
db.test.insert_one({"x": 1, "y": 2})
db.test.insert_one({"x": 2, "y": 1})
db.test.insert_one({"x": 2, "y": 2})
# Test aggregate when sent through the collection aggregate
# function. Aggregate with $out always goes to primary, doesn't obey
@ -320,7 +325,9 @@ class TestCommandAndReadPreference(TestReplicaSetClientBase):
def test_map_reduce(self):
# mapreduce fails if no collection
self.c.pymongo_test.test.insert({}, w=self.w)
coll = self.c.pymongo_test.test.with_options(
write_concern=WriteConcern(w=self.w))
coll.insert_one({})
self._test_coll_helper(False, self.c.pymongo_test.test, 'map_reduce',
'function() { }', 'function() { }', 'mr_out')
@ -331,7 +338,9 @@ class TestCommandAndReadPreference(TestReplicaSetClientBase):
def test_inline_map_reduce(self):
# mapreduce fails if no collection
self.c.pymongo_test.test.insert({}, w=self.w)
coll = self.c.pymongo_test.test.with_options(
write_concern=WriteConcern(w=self.w))
coll.insert_one({})
self._test_coll_helper(True, self.c.pymongo_test.test,
'inline_map_reduce',

View File

@ -187,9 +187,9 @@ class TestReplicaSetClient(TestReplicaSetClientBase):
# Disable background refresh.
with client_knobs(heartbeat_frequency=999999):
c = rs_client(socketTimeoutMS=3000)
c = rs_client(socketTimeoutMS=3000, w=self.w)
collection = c.pymongo_test.test
collection.insert({}, w=self.w)
collection.insert_one({})
# Query the primary.
self.assertRaises(
@ -236,8 +236,8 @@ class TestReplicaSetClient(TestReplicaSetClientBase):
uri = "mongodb://%slocalhost:%d,[::1]:%d" % (auth_str, port, port)
client = MongoClient(uri, replicaSet=self.name)
client.pymongo_test.test.save({"dummy": u("object")})
client.pymongo_test_bernie.test.save({"dummy": u("object")})
client.pymongo_test.test.insert_one({"dummy": u("object")})
client.pymongo_test_bernie.test.insert_one({"dummy": u("object")})
dbs = client.database_names()
self.assertTrue("pymongo_test" in dbs)
@ -246,12 +246,12 @@ class TestReplicaSetClient(TestReplicaSetClientBase):
def _test_kill_cursor_explicit(self, read_pref):
with client_knobs(kill_cursor_frequency=0.01):
c = rs_client(read_preference=read_pref)
c = rs_client(read_preference=read_pref, w=self.w)
db = c.pymongo_test
db.drop_collection("test")
test = db.test
test.insert([{"i": i} for i in range(20)], w=self.w)
test.insert_many([{"i": i} for i in range(20)])
# Partially evaluate cursor so it's left alive, then kill it
cursor = test.find().batch_size(10)
@ -298,10 +298,12 @@ class TestReplicaSetClient(TestReplicaSetClientBase):
direct_client.pymongo_test.command('count', 'collection')
with self.assertRaises(NotMasterError):
direct_client.pymongo_test.collection.insert({})
direct_client.pymongo_test.collection.insert_one({})
db = direct_client.get_database(
"pymongo_test", write_concern=WriteConcern(w=0))
with self.assertRaises(NotMasterError):
direct_client.pymongo_test.collection.insert({}, w=0)
db.collection.insert_one({})
class TestReplicaSetWireVersion(MockClientTest):
@ -341,7 +343,7 @@ class TestReplicaSetWireVersion(MockClientTest):
wait_until(raises_configuration_error,
'notice we are incompatible with server')
self.assertRaises(ConfigurationError, c.db.collection.insert, {})
self.assertRaises(ConfigurationError, c.db.collection.insert_one, {})
class TestReplicaSetClientInternalIPs(MockClientTest):

View File

@ -193,7 +193,7 @@ class TestSSL(unittest.TestCase):
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
db.test.insert_one({'ssl': True})
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
@ -219,7 +219,7 @@ class TestSSL(unittest.TestCase):
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
db.test.insert_one({'ssl': True})
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
@ -245,7 +245,7 @@ class TestSSL(unittest.TestCase):
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
db.test.insert_one({'ssl': True})
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
@ -286,7 +286,7 @@ class TestSSL(unittest.TestCase):
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
db.test.insert_one({'ssl': True})
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
@ -328,7 +328,7 @@ class TestSSL(unittest.TestCase):
db = client.pymongo_ssl_test
db.test.drop()
self.assertTrue(db.test.insert({'ssl': True}))
db.test.insert_one({'ssl': True})
self.assertTrue(db.test.find_one()['ssl'])
client.drop_database('pymongo_ssl_test')
@ -395,7 +395,7 @@ class TestSSL(unittest.TestCase):
self.assertRaises(OperationFailure, coll.count)
self.assertTrue(ssl_client.admin.authenticate(
MONGODB_X509_USERNAME, mechanism='MONGODB-X509'))
self.assertTrue(coll.remove())
coll.drop()
uri = ('mongodb://%s@%s:%d/?authMechanism='
'MONGODB-X509' % (
quote_plus(MONGODB_X509_USERNAME), host, port))
@ -408,7 +408,7 @@ class TestSSL(unittest.TestCase):
port))
client_bad = MongoClient(uri, ssl=True, ssl_certfile=CLIENT_PEM)
self.assertRaises(OperationFailure,
client_bad.pymongo_test.test.remove)
client_bad.pymongo_test.test.delete_one, {})
# Auth should fail if username and certificate do not match
uri = ('mongodb://%s@%s:%d/?authMechanism='

View File

@ -43,7 +43,7 @@ class AutoAuthenticateThreads(threading.Thread):
def run(self):
for i in range(self.num):
self.coll.insert({'num': i})
self.coll.insert_one({'num': i})
self.coll.find_one({'num': i})
self.success = True
@ -80,7 +80,7 @@ class Insert(threading.Thread):
error = True
try:
self.collection.insert({"test": "insert"})
self.collection.insert_one({"test": "insert"})
error = False
except:
if not self.expect_exception:
@ -104,8 +104,8 @@ class Update(threading.Thread):
error = True
try:
self.collection.update({"test": "unique"},
{"$set": {"test": "update"}})
self.collection.update_one({"test": "unique"},
{"$set": {"test": "update"}})
error = False
except:
if not self.expect_exception:
@ -136,8 +136,7 @@ class TestThreads(IntegrationTest):
def test_threading(self):
self.db.drop_collection("test")
for i in range(1000):
self.db.test.save({"x": i})
self.db.test.insert_many([{"x": i} for i in range(1000)])
threads = []
for i in range(10):
@ -149,9 +148,9 @@ class TestThreads(IntegrationTest):
def test_safe_insert(self):
self.db.drop_collection("test1")
self.db.test1.insert({"test": "insert"})
self.db.test1.insert_one({"test": "insert"})
self.db.drop_collection("test2")
self.db.test2.insert({"test": "insert"})
self.db.test2.insert_one({"test": "insert"})
self.db.test2.create_index("test", unique=True)
self.db.test2.find_one()
@ -167,11 +166,11 @@ class TestThreads(IntegrationTest):
def test_safe_update(self):
self.db.drop_collection("test1")
self.db.test1.insert({"test": "update"})
self.db.test1.insert({"test": "unique"})
self.db.test1.insert_one({"test": "update"})
self.db.test1.insert_one({"test": "unique"})
self.db.drop_collection("test2")
self.db.test2.insert({"test": "update"})
self.db.test2.insert({"test": "unique"})
self.db.test2.insert_one({"test": "update"})
self.db.test2.insert_one({"test": "unique"})
self.db.test2.create_index("test", unique=True)
self.db.test2.find_one()
@ -187,8 +186,7 @@ class TestThreads(IntegrationTest):
def test_client_disconnect(self):
self.db.drop_collection("test")
for i in range(1000):
self.db.test.save({"x": i})
self.db.test.insert_many([{"x": i} for i in range(1000)])
# Start 10 threads that execute a query, and 10 threads that call
# client.disconnect() 10 times in a row.

View File

@ -28,6 +28,7 @@ from pymongo import MongoClient
from pymongo.errors import AutoReconnect, OperationFailure
from pymongo.server_selectors import (any_server_selector,
writable_server_selector)
from pymongo.write_concern import WriteConcern
from test import (client_context,
db_user,
db_pwd,
@ -191,7 +192,9 @@ def remove_all_users(db):
db.command("dropAllUsersFromDatabase", 1,
writeConcern={"w": client_context.w})
else:
db.system.users.remove({}, w=client_context.w)
db = db.connetion.get_database(
db.name, write_concern=WriteConcern(w=client_context.w))
db.system.users.delete_many({})
def joinall(threads):