diff --git a/pymongo/_csot.py b/pymongo/_csot.py index 8a599af403..f586c21a9f 100644 --- a/pymongo/_csot.py +++ b/pymongo/_csot.py @@ -75,7 +75,7 @@ class _TimeoutContext(AbstractContextManager[Any]): Use :func:`pymongo.timeout` instead:: with pymongo.timeout(0.5): - client.test.test.insert_one({}) + client.db.coll.insert_one({}) """ def __init__(self, timeout: Optional[float]): diff --git a/test/asynchronous/test_async_cancellation.py b/test/asynchronous/test_async_cancellation.py index a96e28d832..63688e413c 100644 --- a/test/asynchronous/test_async_cancellation.py +++ b/test/asynchronous/test_async_cancellation.py @@ -30,13 +30,13 @@ class TestAsyncCancellation(AsyncIntegrationTest): async def test_async_cancellation_closes_connection(self): pool = await async_get_pool(self.client) - await self.client.db.test.insert_one({"x": 1}) - self.addAsyncCleanup(self.client.db.test.delete_many, {}) + await self.client.db.coll.insert_one({"x": 1}) + self.addAsyncCleanup(self.client.db.coll.delete_many, {}) conn = one(pool.conns) async def task(): - await self.client.db.test.find_one({"$where": delay(0.2)}) + await self.client.db.coll.find_one({"$where": delay(0.2)}) task = asyncio.create_task(task()) @@ -50,13 +50,13 @@ async def task(): @async_client_context.require_transactions async def test_async_cancellation_aborts_transaction(self): - await self.client.db.test.insert_one({"x": 1}) - self.addAsyncCleanup(self.client.db.test.delete_many, {}) + await self.client.db.coll.insert_one({"x": 1}) + self.addAsyncCleanup(self.client.db.coll.delete_many, {}) session = self.client.start_session() async def callback(session): - await self.client.db.test.find_one({"$where": delay(0.2)}, session=session) + await self.client.db.coll.find_one({"$where": delay(0.2)}, session=session) async def task(): await session.with_transaction(callback) @@ -73,10 +73,10 @@ async def task(): @async_client_context.require_failCommand_blockConnection async def test_async_cancellation_closes_cursor(self): - await self.client.db.test.insert_many([{"x": 1}, {"x": 2}]) - self.addAsyncCleanup(self.client.db.test.delete_many, {}) + await self.client.db.coll.insert_many([{"x": 1}, {"x": 2}]) + self.addAsyncCleanup(self.client.db.coll.delete_many, {}) - cursor = self.client.db.test.find({}, batch_size=1) + cursor = self.client.db.coll.find({}, batch_size=1) await cursor.next() # Make sure getMore commands block @@ -103,8 +103,8 @@ async def task(): @async_client_context.require_change_streams @async_client_context.require_failCommand_blockConnection async def test_async_cancellation_closes_change_stream(self): - self.addAsyncCleanup(self.client.db.test.delete_many, {}) - change_stream = await self.client.db.test.watch(batch_size=2) + self.addAsyncCleanup(self.client.db.coll.delete_many, {}) + change_stream = await self.client.db.coll.watch(batch_size=2) event = asyncio.Event() # Make sure getMore commands block @@ -116,7 +116,7 @@ async def test_async_cancellation_closes_change_stream(self): async def task(): async with self.fail_point(fail_command): - await self.client.db.test.insert_many([{"x": 1}, {"x": 2}]) + await self.client.db.coll.insert_many([{"x": 1}, {"x": 2}]) event.set() await change_stream.next() diff --git a/test/asynchronous/test_async_contextvars_reset.py b/test/asynchronous/test_async_contextvars_reset.py index 95ef3fed84..28290be0e0 100644 --- a/test/asynchronous/test_async_contextvars_reset.py +++ b/test/asynchronous/test_async_contextvars_reset.py @@ -32,7 +32,7 @@ async def test_context_vars_are_reset_in_executor(self): if sys.version_info < (3, 12): self.skipTest("Test requires asyncio.Task.get_context (added in Python 3.12)") - await self.client.db.test.insert_one({"x": 1}) + await self.client.db.coll.insert_one({"x": 1}) # Value each contextvar is reset to at the start of the executor task. expected = {"TIMEOUT": None, "RTT": 0.0, "DEADLINE": float("inf"), "OP_ID": None} for server in self.client._topology._servers.values(): diff --git a/test/asynchronous/test_auth.py b/test/asynchronous/test_auth.py index ab96808d26..72085d62dd 100644 --- a/test/asynchronous/test_auth.py +++ b/test/asynchronous/test_auth.py @@ -231,7 +231,7 @@ async def test_gssapi_threaded(self): # collection.find_one with a 1-second delay, forcing it to check out # multiple connections from the pool concurrently, proving that # auto-authentication works with GSSAPI. - collection = db.test + collection = db.coll if not await collection.count_documents({}): try: await collection.drop() @@ -340,7 +340,7 @@ async def test_sasl_plain(self): authSource=SASL_DB, authMechanism="PLAIN", ) - await client.ldap.test.find_one() + await client.ldap.coll.find_one() assert SASL_USER is not None assert SASL_PASS is not None @@ -352,7 +352,7 @@ async def test_sasl_plain(self): SASL_DB, ) client = self.simple_client(uri) - await client.ldap.test.find_one() + await client.ldap.coll.find_one() set_name = async_client_context.replica_set_name if set_name: @@ -365,7 +365,7 @@ async def test_sasl_plain(self): authSource=SASL_DB, authMechanism="PLAIN", ) - await client.ldap.test.find_one() + await client.ldap.coll.find_one() uri = "mongodb://%s:%s@%s:%d/?authMechanism=PLAIN;authSource=%s;replicaSet=%s" % ( quote_plus(SASL_USER), @@ -376,7 +376,7 @@ async def test_sasl_plain(self): str(set_name), ) client = self.simple_client(uri) - await client.ldap.test.find_one() + await client.ldap.coll.find_one() async def test_sasl_plain_bad_credentials(self): def auth_string(user, password): @@ -654,13 +654,13 @@ async def test_cache(self): @async_client_context.require_sync async def test_scram_threaded(self): - coll = async_client_context.client.db.test + coll = async_client_context.client.db.coll await coll.drop() await coll.insert_one({"_id": 1}) # The first thread to call find() will authenticate client = await self.async_rs_or_single_client() - coll = client.db.test + coll = client.db.coll threads = [] for _ in range(4): threads.append(AutoAuthenticateThread(coll)) diff --git a/test/asynchronous/test_auth_oidc.py b/test/asynchronous/test_auth_oidc.py index 669537ab50..4c53c53914 100644 --- a/test/asynchronous/test_auth_oidc.py +++ b/test/asynchronous/test_auth_oidc.py @@ -197,7 +197,7 @@ async def test_1_1_single_principal_implicit_username(self): # Create default OIDC client with authMechanism=MONGODB-OIDC. client = await self.create_client() # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -205,7 +205,7 @@ async def test_1_2_single_principal_explicit_username(self): # Create a client with MONGODB_URI_SINGLE, a username of test_user1, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = await self.create_client(username="test_user1") # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -215,7 +215,7 @@ async def test_1_3_multiple_principal_user_1(self): # Create a client with MONGODB_URI_MULTI, a username of test_user1, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = await self.create_client(self.uri_multiple, username="test_user1") # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -226,7 +226,7 @@ async def test_1_4_multiple_principal_user_2(self): # Create a client with MONGODB_URI_MULTI, a username of test_user2, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = await self.create_client(self.uri_multiple, username="test_user2") # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -237,7 +237,7 @@ async def test_1_5_multiple_principal_no_user(self): client = await self.create_client(self.uri_multiple) # Assert that a find operation fails. with self.assertRaises(OperationFailure): - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -248,7 +248,7 @@ async def test_1_6_allowed_hosts_blocked(self): client = await self.create_client(authmechanismproperties=props) # Assert that a find operation fails with a client-side error. with self.assertRaises(ConfigurationError): - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -267,7 +267,7 @@ async def test_1_6_allowed_hosts_blocked(self): ) # Assert that a find operation fails with a client-side error. with self.assertRaises(ConfigurationError): - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -289,7 +289,7 @@ async def test_1_8_machine_idp_human_callback(self): # Create a client with MONGODB_URI_SINGLE, a username of test_machine, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = await self.create_client(username="test_machine") # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -298,7 +298,7 @@ async def test_2_1_valid_callback_inputs(self): client = await self.create_client() # Perform a find operation that succeeds. Verify that the human callback was called with the appropriate inputs, including the timeout parameter if possible. # Ensure that there are no unexpected fields. - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -311,7 +311,7 @@ def fetch(self, ctx): client = await self.create_client(request_cb=CustomCB()) # Perform a find operation that fails. with self.assertRaises(ValueError): - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -320,7 +320,7 @@ async def test_2_3_refresh_token_is_passed_to_the_callback(self): client = await self.create_client() # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Set a fail point for ``find`` commands. async with self.fail_point( @@ -330,7 +330,7 @@ async def test_2_3_refresh_token_is_passed_to_the_callback(self): } ): # Perform a ``find`` operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the callback has been called twice. self.assertEqual(self.request_called, 2) @@ -351,7 +351,7 @@ async def test_3_1_uses_speculative_authentication_if_there_is_a_cached_token(se ): # Perform a ``find`` operation that fails. with self.assertRaises(AutoReconnect): - await client.test.test.find_one() + await client.test.coll.find_one() # Set a fail point for ``saslStart`` commands. async with self.fail_point( @@ -361,7 +361,7 @@ async def test_3_1_uses_speculative_authentication_if_there_is_a_cached_token(se } ): # Perform a ``find`` operation that succeeds - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -379,7 +379,7 @@ async def test_3_2_does_not_use_speculative_authentication_if_there_is_no_cached ): # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - await client.test.test.find_one() + await client.test.coll.find_one() # Close the client. await client.close() @@ -392,7 +392,7 @@ async def test_4_1_reauthenticate_succeeds(self): client = await self.create_client(event_listeners=[listener]) # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -408,7 +408,7 @@ async def test_4_1_reauthenticate_succeeds(self): } ): # Perform another find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called twice. self.assertEqual(self.request_called, 2) @@ -454,7 +454,7 @@ def fetch(self, *args, **kwargs): client = await self.create_client(request_cb=CustomRequest()) # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -467,7 +467,7 @@ def fetch(self, *args, **kwargs): } ): # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called twice. self.assertEqual(self.request_called, 2) @@ -487,7 +487,7 @@ def fetch(self, *args, **kwargs): client = await self.create_client(request_cb=CustomRequest()) # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -500,7 +500,7 @@ def fetch(self, *args, **kwargs): } ): # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called 2 times. self.assertEqual(self.request_called, 2) @@ -527,7 +527,7 @@ def fetch(self, *args, **kwargs): client = await self.create_client(request_cb=CustomRequest()) # Perform a find operation that succeeds (to force a speculative auth). - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -540,7 +540,7 @@ def fetch(self, *args, **kwargs): ): # Perform a find operation that fails. with self.assertRaises(OperationFailure): - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the human callback has been called three times. self.assertEqual(self.request_called, 3) @@ -555,7 +555,7 @@ def fetch(self, a): client = await self.create_client(request_cb=RequestTokenNull()) with self.assertRaises(ValueError): - await client.test.test.find_one() + await client.test.coll.find_one() await client.close() async def test_request_callback_invalid_result(self): @@ -565,7 +565,7 @@ def fetch(self, a): client = await self.create_client(request_cb=CallbackInvalidToken()) with self.assertRaises(ValueError): - await client.test.test.find_one() + await client.test.coll.find_one() await client.close() async def test_reauthentication_succeeds_multiple_connections(self): @@ -576,8 +576,8 @@ async def test_reauthentication_succeeds_multiple_connections(self): client2 = await self.create_client(request_cb=request_cb) # Perform an insert operation. - await client1.test.test.insert_many([{"a": 1}, {"a": 1}]) - await client2.test.test.find_one() + await client1.test.coll.insert_many([{"a": 1}, {"a": 1}]) + await client2.test.coll.find_one() self.assertEqual(self.request_called, 2) # Use the same authenticator for both clients @@ -588,8 +588,8 @@ async def test_reauthentication_succeeds_multiple_connections(self): client1.options.pool_options._credentials.cache.data ) - await client1.test.test.find_one() - await client2.test.test.find_one() + await client1.test.coll.find_one() + await client2.test.coll.find_one() async with self.fail_point( { @@ -597,7 +597,7 @@ async def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - await client1.test.test.find_one() + await client1.test.coll.find_one() self.assertEqual(self.request_called, 3) @@ -607,7 +607,7 @@ async def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - await client2.test.test.find_one() + await client2.test.coll.find_one() self.assertEqual(self.request_called, 3) await client1.close() @@ -620,7 +620,7 @@ async def test_reauthenticate_succeeds_bulk_write(self): client = await self.create_client() # Perform a find operation. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -632,7 +632,7 @@ async def test_reauthenticate_succeeds_bulk_write(self): } ): # Perform a bulk write operation. - await client.test.test.bulk_write([InsertOne({})]) # type:ignore[type-var] + await client.test.coll.bulk_write([InsertOne({})]) # type:ignore[type-var] # Assert that the request callback has been called twice. self.assertEqual(self.request_called, 2) @@ -643,10 +643,10 @@ async def test_reauthenticate_succeeds_bulk_read(self): client = await self.create_client() # Perform a find operation. - await client.test.test.find_one() + await client.test.coll.find_one() # Perform a bulk write operation. - await client.test.test.bulk_write([InsertOne({})]) # type:ignore[type-var] + await client.test.coll.bulk_write([InsertOne({})]) # type:ignore[type-var] # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -658,7 +658,7 @@ async def test_reauthenticate_succeeds_bulk_read(self): } ): # Perform a bulk read operation. - cursor = client.test.test.find_raw_batches({}) + cursor = client.test.coll.find_raw_batches({}) await cursor.to_list() # Assert that the request callback has been called twice. @@ -670,7 +670,7 @@ async def test_reauthenticate_succeeds_cursor(self): client = await self.create_client() # Perform an insert operation. - await client.test.test.insert_one({"a": 1}) + await client.test.coll.insert_one({"a": 1}) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -682,7 +682,7 @@ async def test_reauthenticate_succeeds_cursor(self): } ): # Perform a find operation. - cursor = client.test.test.find({"a": 1}) + cursor = client.test.coll.find({"a": 1}) self.assertGreaterEqual(len(await cursor.to_list()), 1) # Assert that the request callback has been called twice. @@ -694,7 +694,7 @@ async def test_reauthenticate_succeeds_get_more(self): client = await self.create_client() # Perform an insert operation. - await client.test.test.insert_many([{"a": 1}, {"a": 1}]) + await client.test.coll.insert_many([{"a": 1}, {"a": 1}]) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -706,7 +706,7 @@ async def test_reauthenticate_succeeds_get_more(self): } ): # Perform a find operation. - cursor = client.test.test.find({"a": 1}, batch_size=1) + cursor = client.test.coll.find({"a": 1}, batch_size=1) self.assertGreaterEqual(len(await cursor.to_list()), 1) # Assert that the request callback has been called twice. @@ -724,7 +724,7 @@ async def test_reauthenticate_succeeds_get_more_exhaust(self): client = await self.create_client() # Perform an insert operation. - await client.test.test.insert_many([{"a": 1}, {"a": 1}]) + await client.test.coll.insert_many([{"a": 1}, {"a": 1}]) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -736,7 +736,7 @@ async def test_reauthenticate_succeeds_get_more_exhaust(self): } ): # Perform a find operation. - cursor = client.test.test.find({"a": 1}, batch_size=1, cursor_type=CursorType.EXHAUST) + cursor = client.test.coll.find({"a": 1}, batch_size=1, cursor_type=CursorType.EXHAUST) self.assertGreaterEqual(len(await cursor.to_list()), 1) # Assert that the request callback has been called twice. @@ -748,7 +748,7 @@ async def test_reauthenticate_succeeds_command(self): client = await self.create_client() # Perform an insert operation. - await client.test.test.insert_one({"a": 1}) + await client.test.coll.insert_one({"a": 1}) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -807,7 +807,7 @@ async def test_1_1_callback_is_called_during_reauthentication(self): # implements the provider logic. client = await self.create_client() # Perform a ``find`` operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the callback was called 1 time. self.assertEqual(self.request_called, 1) @@ -820,7 +820,7 @@ async def test_1_2_callback_is_called_once_for_multiple_connections(self): # Start 10 tasks and run 100 find operations that all succeed in each task. async def target(): for _ in range(100): - await client.test.test.find_one() + await client.test.coll.find_one() tasks = [] for i in range(10): @@ -836,7 +836,7 @@ async def test_2_1_valid_callback_inputs(self): # Create a AsyncMongoClient configured with an OIDC callback that validates its inputs and returns a valid access token. client = await self.create_client() # Perform a find operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the OIDC callback was called with the appropriate inputs, including the timeout parameter if possible. Ensure that there are no unexpected fields. self.assertEqual(self.request_called, 1) @@ -849,7 +849,7 @@ def fetch(self, a): client = await self.create_client(request_cb=CallbackNullToken()) # Perform a find operation that fails. with self.assertRaises(ValueError): - await client.test.test.find_one() + await client.test.coll.find_one() async def test_2_3_oidc_callback_returns_missing_data(self): # Create a AsyncMongoClient configured with an OIDC callback that returns data not conforming to the OIDCCredential with missing fields. @@ -863,7 +863,7 @@ def fetch(self, a): client = await self.create_client(request_cb=CustomCallback()) # Perform a find operation that fails. with self.assertRaises(ValueError): - await client.test.test.find_one() + await client.test.coll.find_one() async def test_2_4_invalid_client_configuration_with_callback(self): # Create a AsyncMongoClient configured with an OIDC callback and auth mechanism property ENVIRONMENT:test. @@ -918,13 +918,13 @@ async def test_3_1_authentication_failure_with_cached_tokens_fetch_a_new_token_a # Perform a ``find`` operation that fails. This is to force the ``AsyncMongoClient`` # to cache an access token. with self.assertRaises(AutoReconnect): - await client.test.test.find_one() + await client.test.coll.find_one() # Poison the cache of the client. client.options.pool_options._credentials.cache.data.access_token = "bad" # Reset the request count. self.request_called = 0 # Verify that a find succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Verify that the callback was called 1 time. self.assertEqual(self.request_called, 1) @@ -941,7 +941,7 @@ def fetch(self, a): client = await self.create_client(request_cb=callback) # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - await client.test.test.find_one() + await client.test.coll.find_one() # Verify that the callback was called 1 time. self.assertEqual(callback.count, 1) @@ -958,13 +958,13 @@ async def test_3_3_unexpected_error_code_does_not_clear_cache(self): ): # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the callback has been called once. self.assertEqual(self.request_called, 1) # Perform a ``find`` operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Assert that the callback has been called once. self.assertEqual(self.request_called, 1) @@ -983,7 +983,7 @@ async def test_4_1_reauthentication_succeeds(self): } ): # Perform a ``find`` operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Verify that the callback was called 2 times (once during the connection # handshake, and again during reauthentication). @@ -1009,7 +1009,7 @@ def fetch(self, _): client = await self.create_client(request_cb=callback) # Perform a read operation that succeeds. - await client.test.test.find_one() + await client.test.coll.find_one() # Set a fail point for the find command. async with self.fail_point( @@ -1020,7 +1020,7 @@ def fetch(self, _): ): # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - await client.test.test.find_one() + await client.test.coll.find_one() # Verify that the callback was called 2 times. self.assertEqual(callback.count, 2) @@ -1045,7 +1045,7 @@ def fetch(self, _): client = await self.create_client(request_cb=callback) # Perform an insert operation that succeeds. - await client.test.test.insert_one({}) + await client.test.coll.insert_one({}) # Set a fail point for the find command. async with self.fail_point( @@ -1056,7 +1056,7 @@ def fetch(self, _): ): # Perform a ``insert`` operation that fails. with self.assertRaises(OperationFailure): - await client.test.test.insert_one({}) + await client.test.coll.insert_one({}) # Verify that the callback was called 2 times. self.assertEqual(callback.count, 2) @@ -1069,7 +1069,7 @@ async def test_4_4_speculative_authentication_should_be_ignored_on_reauthenticat # Preload the *Client Cache* with a valid access token to enforce Speculative Authentication. client2 = await self.create_client() - await client2.test.test.find_one() + await client2.test.coll.find_one() client.options.pool_options._credentials.cache.data = ( client2.options.pool_options._credentials.cache.data ) @@ -1077,7 +1077,7 @@ async def test_4_4_speculative_authentication_should_be_ignored_on_reauthenticat self.request_called = 0 # Perform an `insert` operation that succeeds. - await client.test.test.insert_one({}) + await client.test.coll.insert_one({}) # Assert that the callback was not called. self.assertEqual(self.request_called, 0) @@ -1096,7 +1096,7 @@ async def test_4_4_speculative_authentication_should_be_ignored_on_reauthenticat } ): # Perform an `insert` operation that succeeds. - await client.test.test.insert_one({}) + await client.test.coll.insert_one({}) # Assert that the callback was called once. self.assertEqual(self.request_called, 1) @@ -1118,7 +1118,7 @@ async def test_4_5_reauthentication_succeeds_when_a_session_is_involved(self): # Start a new session. async with client.start_session() as session: # In the started session perform a `find` operation that succeeds. - await client.test.test.find_one({}, session=session) + await client.test.coll.find_one({}, session=session) # Assert that the callback was called 2 times (once during the connection handshake, and again during reauthentication). self.assertEqual(self.request_called, 2) @@ -1131,7 +1131,7 @@ async def test_5_1_azure_with_no_username(self): props = dict(TOKEN_RESOURCE=resource, ENVIRONMENT="azure") client = await self.create_client(authMechanismProperties=props) - await client.test.test.find_one() + await client.test.coll.find_one() async def test_5_2_azure_with_bad_username(self): if ENVIRON != "azure": @@ -1143,11 +1143,11 @@ async def test_5_2_azure_with_bad_username(self): props = dict(TOKEN_RESOURCE=token_aud, ENVIRONMENT="azure") client = await self.create_client(username="bad", authmechanismproperties=props) with self.assertRaises(ValueError): - await client.test.test.find_one() + await client.test.coll.find_one() async def test_speculative_auth_success(self): client1 = await self.create_client() - await client1.test.test.find_one() + await client1.test.coll.find_one() client2 = await self.create_client() await client2.aconnect() @@ -1164,15 +1164,15 @@ async def test_speculative_auth_success(self): } ): # Perform a find operation. - await client2.test.test.find_one() + await client2.test.coll.find_one() async def test_reauthentication_succeeds_multiple_connections(self): client1 = await self.create_client() client2 = await self.create_client() # Perform an insert operation. - await client1.test.test.insert_many([{"a": 1}, {"a": 1}]) - await client2.test.test.find_one() + await client1.test.coll.insert_many([{"a": 1}, {"a": 1}]) + await client2.test.coll.find_one() self.assertEqual(self.request_called, 2) # Use the same authenticator for both clients @@ -1183,8 +1183,8 @@ async def test_reauthentication_succeeds_multiple_connections(self): client1.options.pool_options._credentials.cache.data ) - await client1.test.test.find_one() - await client2.test.test.find_one() + await client1.test.coll.find_one() + await client2.test.coll.find_one() async with self.fail_point( { @@ -1192,7 +1192,7 @@ async def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - await client1.test.test.find_one() + await client1.test.coll.find_one() self.assertEqual(self.request_called, 3) @@ -1202,7 +1202,7 @@ async def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - await client2.test.test.find_one() + await client2.test.coll.find_one() self.assertEqual(self.request_called, 3) diff --git a/test/asynchronous/test_bulk.py b/test/asynchronous/test_bulk.py index 0052218bd4..5c6bbc9764 100644 --- a/test/asynchronous/test_bulk.py +++ b/test/asynchronous/test_bulk.py @@ -44,7 +44,7 @@ class AsyncBulkTestBase(AsyncIntegrationTest): async def asyncSetUp(self): await super().asyncSetUp() - self.coll = self.db.test + self.coll = self.db.coll await self.coll.drop() self.coll_w0 = self.coll.with_options(write_concern=WriteConcern(w=0)) @@ -792,7 +792,7 @@ async def asyncSetUp(self): privileges=[ { "actions": ["insert", "update", "find"], - "resource": {"db": "pymongo_test", "collection": "test"}, + "resource": {"db": "pymongo_test", "collection": "coll"}, } ], roles=[], @@ -899,7 +899,7 @@ async def test_readonly(self): cli = await self.async_rs_or_single_client_noauth( username="readonly", password="pw", authSource="pymongo_test" ) - coll = cli.pymongo_test.test + coll = cli.pymongo_test.coll await coll.find_one() with self.assertRaises(OperationFailure): await coll.bulk_write([InsertOne({"x": 1})]) @@ -910,7 +910,7 @@ async def test_no_remove(self): cli = await self.async_rs_or_single_client_noauth( username="noremove", password="pw", authSource="pymongo_test" ) - coll = cli.pymongo_test.test + coll = cli.pymongo_test.coll await coll.find_one() requests = [ InsertOne({"x": 1}), diff --git a/test/asynchronous/test_client.py b/test/asynchronous/test_client.py index 1ad3e66d00..7131382f49 100644 --- a/test/asynchronous/test_client.py +++ b/test/asynchronous/test_client.py @@ -965,13 +965,13 @@ async def test_init_disconnected(self): bad_host = "somedomainthatdoesntexist.org" c = self.simple_client(bad_host, port, connectTimeoutMS=1, serverSelectionTimeoutMS=10) with self.assertRaises(ConnectionFailure): - await c.pymongo_test.test.find_one() + await c.pymongo_test.coll.find_one() async def test_init_disconnected_with_auth(self): uri = "mongodb://user:pass@somedomainthatdoesntexist" c = self.simple_client(uri, connectTimeoutMS=1, serverSelectionTimeoutMS=10) with self.assertRaises(ConnectionFailure): - await c.pymongo_test.test.find_one() + await c.pymongo_test.coll.find_one() @async_client_context.require_replica_set @async_client_context.require_no_load_balancer @@ -1138,7 +1138,7 @@ async def test_list_databases(self): async for doc in await client.list_databases(): self.assertIs(type(doc), dict) - await self.client.pymongo_test.test.insert_one({}) + await self.db.coll.insert_one({}) cursor = await self.client.list_databases(filter={"name": "admin"}) docs = await cursor.to_list() self.assertEqual(1, len(docs)) @@ -1149,8 +1149,8 @@ async def test_list_databases(self): self.assertEqual(["name"], list(doc)) async def test_list_database_names(self): - await self.client.pymongo_test.test.insert_one({"dummy": "object"}) - await self.client.pymongo_test_mike.test.insert_one({"dummy": "object"}) + await self.db.coll.insert_one({"dummy": "object"}) + await self.client.pymongo_test_mike.coll.insert_one({"dummy": "object"}) cmd_docs = (await self.client.admin.command("listDatabases"))["databases"] cmd_names = [doc["name"] for doc in cmd_docs] @@ -1165,8 +1165,8 @@ async def test_drop_database(self): with self.assertRaises(TypeError): await self.client.drop_database(None) # type: ignore[arg-type] - await self.client.pymongo_test.test.insert_one({"dummy": "object"}) - await self.client.pymongo_test2.test.insert_one({"dummy": "object"}) + await self.db.coll.insert_one({"dummy": "object"}) + await self.client.pymongo_test2.coll.insert_one({"dummy": "object"}) dbs = await self.client.list_database_names() self.assertIn("pymongo_test", dbs) self.assertIn("pymongo_test2", dbs) @@ -1224,7 +1224,7 @@ async def test_close_kills_cursors(self): async def test_close_stops_kill_cursors_thread(self): client = await self.async_rs_client() - await client.test.test.find_one() + await client.db.coll.find_one() self.assertFalse(client._kill_cursors_executor._stopped) # Closing the client should stop the thread. @@ -1268,7 +1268,7 @@ async def test_close_does_not_open_servers(self): async def test_close_closes_sockets(self): client = await self.async_rs_client() - await client.test.test.find_one() + await client.db.coll.find_one() topology = client._topology await client.close() for server in topology._servers.values(): @@ -1288,7 +1288,7 @@ async def test_auth_from_uri(self): host, port = await async_client_context.host, await async_client_context.port await async_client_context.create_user("admin", "admin", "pass") self.addAsyncCleanup(async_client_context.drop_user, "admin", "admin") - self.addAsyncCleanup(remove_all_users, self.client.pymongo_test) + self.addAsyncCleanup(remove_all_users, self.db) await async_client_context.create_user( "pymongo_test", "user", "pass", roles=["userAdmin", "readWrite"] @@ -1321,7 +1321,7 @@ async def test_auth_from_uri(self): await self.async_rs_or_single_client_noauth( "mongodb://user:pass@%s:%d/pymongo_test" % (host, port), connect=False ) - ).pymongo_test.test.find_one() + ).pymongo_test.coll.find_one() # Wrong password. bad_client = await self.async_rs_or_single_client_noauth( @@ -1329,7 +1329,7 @@ async def test_auth_from_uri(self): ) with self.assertRaises(OperationFailure): - await bad_client.pymongo_test.test.find_one() + await bad_client.pymongo_test.coll.find_one() @async_client_context.require_auth async def test_username_and_password(self): @@ -1375,7 +1375,7 @@ async def test_unix_socket(self): uri = "mongodb://%s" % encoded_socket # Confirm we can do operations via the socket. client = await self.async_rs_or_single_client(uri) - await client.pymongo_test.test.insert_one({"dummy": "object"}) + await client.pymongo_test.coll.insert_one({"dummy": "object"}) dbs = await client.list_database_names() self.assertIn("pymongo_test", dbs) @@ -1391,18 +1391,18 @@ async def test_unix_socket(self): async def test_document_class(self): c = self.client db = c.pymongo_test - await db.test.insert_one({"x": 1}) + await db.coll.insert_one({"x": 1}) self.assertEqual(dict, c.codec_options.document_class) - self.assertIsInstance(await db.test.find_one(), dict) - self.assertNotIsInstance(await db.test.find_one(), SON) + self.assertIsInstance(await db.coll.find_one(), dict) + self.assertNotIsInstance(await db.coll.find_one(), SON) c = await self.async_rs_or_single_client(document_class=SON) db = c.pymongo_test self.assertEqual(SON, c.codec_options.document_class) - self.assertIsInstance(await db.test.find_one(), SON) + self.assertIsInstance(await db.coll.find_one(), SON) async def test_timeouts(self): client = await self.async_rs_or_single_client( @@ -1444,14 +1444,14 @@ async def test_socket_timeout(self): timeout_sec = 1 timeout = await self.async_rs_or_single_client(socketTimeoutMS=1000 * timeout_sec) - await no_timeout.pymongo_test.drop_collection("test") - await no_timeout.pymongo_test.test.insert_one({"x": 1}) + await no_timeout.pymongo_test.drop_collection("coll") + await no_timeout.pymongo_test.coll.insert_one({"x": 1}) # A $where clause that takes a second longer than the timeout where_func = delay(timeout_sec + 1) async def get_x(db): - doc = await anext(db.test.find().where(where_func)) + doc = await anext(db.coll.find().where(where_func)) return doc["x"] self.assertEqual(1, await get_x(no_timeout.pymongo_test)) @@ -1519,16 +1519,16 @@ async def test_tz_aware(self): aware = await self.async_rs_or_single_client(tz_aware=True) self.addAsyncCleanup(aware.close) naive = self.client - await aware.pymongo_test.drop_collection("test") + await aware.pymongo_test.drop_collection("coll") now = datetime.datetime.now(tz=datetime.timezone.utc) - await aware.pymongo_test.test.insert_one({"x": now}) + await aware.pymongo_test.coll.insert_one({"x": now}) - self.assertEqual(None, (await naive.pymongo_test.test.find_one())["x"].tzinfo) - self.assertEqual(utc, (await aware.pymongo_test.test.find_one())["x"].tzinfo) + self.assertEqual(None, (await naive.pymongo_test.coll.find_one())["x"].tzinfo) + self.assertEqual(utc, (await aware.pymongo_test.coll.find_one())["x"].tzinfo) self.assertEqual( - (await aware.pymongo_test.test.find_one())["x"].replace(tzinfo=None), - (await naive.pymongo_test.test.find_one())["x"], + (await aware.pymongo_test.coll.find_one())["x"].replace(tzinfo=None), + (await naive.pymongo_test.coll.find_one())["x"], ) @async_client_context.require_ipv6 @@ -1547,8 +1547,8 @@ async def test_ipv6(self): uri += "/?replicaSet=" + (async_client_context.replica_set_name or "") client = await self.async_rs_or_single_client_noauth(uri) - await client.pymongo_test.test.insert_one({"dummy": "object"}) - await client.pymongo_test_bernie.test.insert_one({"dummy": "object"}) + await client.pymongo_test.coll.insert_one({"dummy": "object"}) + await client.pymongo_test_bernie.coll.insert_one({"dummy": "object"}) dbs = await client.list_database_names() self.assertIn("pymongo_test", dbs) @@ -1556,8 +1556,8 @@ async def test_ipv6(self): async def test_contextlib(self): client = await self.async_rs_or_single_client() - await client.pymongo_test.drop_collection("test") - await client.pymongo_test.test.insert_one({"foo": "bar"}) + await client.pymongo_test.drop_collection("coll") + await client.pymongo_test.coll.insert_one({"foo": "bar"}) # The socket used for the previous commands has been returned to the # pool @@ -1566,14 +1566,14 @@ async def test_contextlib(self): # contextlib async support was added in Python 3.10 if _IS_SYNC or sys.version_info >= (3, 10): async with contextlib.aclosing(client): - self.assertEqual("bar", (await client.pymongo_test.test.find_one())["foo"]) + self.assertEqual("bar", (await client.pymongo_test.coll.find_one())["foo"]) with self.assertRaises(InvalidOperation): - await client.pymongo_test.test.find_one() + await client.pymongo_test.coll.find_one() client = await self.async_rs_or_single_client() async with client as client: - self.assertEqual("bar", (await client.pymongo_test.test.find_one())["foo"]) + self.assertEqual("bar", (await client.pymongo_test.coll.find_one())["foo"]) with self.assertRaises(InvalidOperation): - await client.pymongo_test.test.find_one() + await client.pymongo_test.coll.find_one() @async_client_context.require_sync def test_interrupt_signal(self): @@ -1582,7 +1582,7 @@ def test_interrupt_signal(self): # Test fix for PYTHON-294 -- make sure AsyncMongoClient closes its # socket if it gets an interrupt while waiting to recv() from it. - db = self.client.pymongo_test + db = self.db # A $where clause which takes 1.5 sec to execute where = delay(1.5) @@ -1642,15 +1642,15 @@ async def test_operation_failure(self): # to avoid race conditions caused by replica set failover or idle # socket reaping. client = await self.async_single_client() - await client.pymongo_test.test.find_one() + await client.pymongo_test.coll.find_one() pool = await async_get_pool(client) socket_count = len(pool.conns) self.assertGreaterEqual(socket_count, 1) old_conn = next(iter(pool.conns)) - await client.pymongo_test.test.drop() - await client.pymongo_test.test.insert_one({"_id": "foo"}) + await client.pymongo_test.coll.drop() + await client.pymongo_test.coll.insert_one({"_id": "foo"}) with self.assertRaises(OperationFailure): - await client.pymongo_test.test.insert_one({"_id": "foo"}) + await client.pymongo_test.coll.insert_one({"_id": "foo"}) self.assertEqual(socket_count, len(pool.conns)) new_con = next(iter(pool.conns)) @@ -1694,7 +1694,7 @@ async def test_exhaust_network_error(self): # When doing an exhaust query, the socket stays checked out on success # but must be checked in on error to avoid semaphore leaks. client = await self.async_rs_or_single_client(maxPoolSize=1, retryReads=False) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll pool = await async_get_pool(client) pool._check_interval_seconds = None # Never check. @@ -1742,7 +1742,7 @@ async def test_auth_network_error(self): async def test_connect_to_standalone_using_replica_set_name(self): client = await self.async_single_client(replicaSet="anything", serverSelectionTimeoutMS=100) with self.assertRaises(AutoReconnect): - await client.test.test.find_one() + await client.db.coll.find_one() @async_client_context.require_replica_set async def test_stale_getmore(self): @@ -1900,7 +1900,7 @@ def compression_settings(client): for level in range(-1, 10): client = await self.async_single_client(zlibcompressionlevel=level) # No error - await client.pymongo_test.test.find_one() + await client.pymongo_test.coll.find_one() async def test_compression_commands(self): # Ensure the compression logic is actually exercised end-to-end by @@ -2109,7 +2109,7 @@ def server_description_count(): ) initial_count = server_description_count() with self.assertRaises(ServerSelectionTimeoutError): - await client.test.test.find_one() + await client.db.coll.find_one() gc.collect() final_count = server_description_count() await client.close() @@ -2128,7 +2128,7 @@ async def test_network_error_message(self): assert await client.address is not None expected = "{}:{}: ".format(*(await client.address)) with self.assertRaisesRegex(AutoReconnect, expected): - await client.pymongo_test.test.find_one({}) + await client.pymongo_test.coll.find_one({}) @unittest.skipIf("PyPy" in sys.version, "PYTHON-2938 could fail on PyPy") async def test_process_periodic_tasks(self): @@ -2330,23 +2330,23 @@ async def test_handshake_09_container_with_provider(self): ) def test_dict_hints(self): - self.db.t.find(hint={"x": 1}) + self.db.coll.find(hint={"x": 1}) def test_dict_hints_sort(self): - result = self.db.t.find() + result = self.db.coll.find() result.sort({"x": 1}) - self.db.t.find(sort={"x": 1}) + self.db.coll.find(sort={"x": 1}) async def test_dict_hints_create_index(self): - await self.db.t.create_index({"x": pymongo.ASCENDING}) + await self.db.coll.create_index({"x": pymongo.ASCENDING}) async def test_legacy_java_uuid_roundtrip(self): data = BinaryData.java_data docs = bson.decode_all(data, CodecOptions(SON[str, Any], False, JAVA_LEGACY)) - await async_client_context.client.pymongo_test.drop_collection("java_uuid") - db = async_client_context.client.pymongo_test + await self.db.drop_collection("java_uuid") + db = self.db coll = db.get_collection("java_uuid", CodecOptions(uuid_representation=JAVA_LEGACY)) await coll.insert_many(docs) @@ -2357,14 +2357,14 @@ async def test_legacy_java_uuid_roundtrip(self): coll = db.get_collection("java_uuid", CodecOptions(uuid_representation=PYTHON_LEGACY)) async for d in coll.find(): self.assertNotEqual(d["newguid"], d["newguidstring"]) - await async_client_context.client.pymongo_test.drop_collection("java_uuid") + await self.db.drop_collection("java_uuid") async def test_legacy_csharp_uuid_roundtrip(self): data = BinaryData.csharp_data docs = bson.decode_all(data, CodecOptions(SON[str, Any], False, CSHARP_LEGACY)) - await async_client_context.client.pymongo_test.drop_collection("csharp_uuid") - db = async_client_context.client.pymongo_test + await self.db.drop_collection("csharp_uuid") + db = self.db coll = db.get_collection("csharp_uuid", CodecOptions(uuid_representation=CSHARP_LEGACY)) await coll.insert_many(docs) @@ -2375,16 +2375,16 @@ async def test_legacy_csharp_uuid_roundtrip(self): coll = db.get_collection("csharp_uuid", CodecOptions(uuid_representation=PYTHON_LEGACY)) async for d in coll.find(): self.assertNotEqual(d["newguid"], d["newguidstring"]) - await async_client_context.client.pymongo_test.drop_collection("csharp_uuid") + await self.db.drop_collection("csharp_uuid") async def test_uri_to_uuid(self): uri = "mongodb://foo/?uuidrepresentation=csharpLegacy" client = await self.async_single_client(uri, connect=False) - self.assertEqual(client.pymongo_test.test.codec_options.uuid_representation, CSHARP_LEGACY) + self.assertEqual(client.pymongo_test.coll.codec_options.uuid_representation, CSHARP_LEGACY) async def test_uuid_queries(self): - db = async_client_context.client.pymongo_test - coll = db.test + db = self.db + coll = db.coll await coll.drop() uu = uuid.uuid4() @@ -2393,7 +2393,7 @@ async def test_uuid_queries(self): # Test regular UUID queries (using subtype 4). coll = db.get_collection( - "test", CodecOptions(uuid_representation=UuidRepresentation.STANDARD) + "coll", CodecOptions(uuid_representation=UuidRepresentation.STANDARD) ) self.assertEqual(0, await coll.count_documents({"uuid": uu})) await coll.insert_one({"uuid": uu}) @@ -2424,7 +2424,7 @@ async def test_exhaust_query_server_error(self): # but must be checked in on error to avoid semaphore leaks. client = await connected(await self.async_rs_or_single_client(maxPoolSize=1)) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll pool = await async_get_pool(client) conn = one(pool.conns) @@ -2446,11 +2446,11 @@ async def test_exhaust_getmore_server_error(self): # When doing a getmore on an exhaust cursor, the socket stays checked # out on success but it's checked in on error to avoid semaphore leaks. client = await self.async_rs_or_single_client(maxPoolSize=1) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll await collection.drop() await collection.insert_many([{} for _ in range(200)]) - self.addAsyncCleanup(async_client_context.client.pymongo_test.test.drop) + self.addAsyncCleanup(self.db.coll.drop) pool = await async_get_pool(client) pool._check_interval_seconds = None # Never check. @@ -2487,7 +2487,7 @@ async def test_exhaust_query_network_error(self): client = await connected( await self.async_rs_or_single_client(maxPoolSize=1, retryReads=False) ) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll pool = await async_get_pool(client) pool._check_interval_seconds = None # Never check. @@ -2508,7 +2508,7 @@ async def test_exhaust_getmore_network_error(self): # When doing a getmore on an exhaust cursor, the socket stays checked # out on success but it's checked in on error to avoid semaphore leaks. client = await self.async_rs_or_single_client(maxPoolSize=1) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll await collection.drop() await collection.insert_many([{} for _ in range(200)]) # More than one batch. pool = await async_get_pool(client) @@ -2544,7 +2544,7 @@ def test_gevent_task(self): def poller(): while True: - async_client_context.client.pymongo_test.test.insert_one({}) + self.db.coll.insert_one({}) task = spawn(poller) task.kill() @@ -2557,7 +2557,7 @@ def test_gevent_timeout(self): from gevent import Timeout, spawn client = self.async_rs_or_single_client(maxPoolSize=1) - coll = client.pymongo_test.test + coll = client.pymongo_test.coll coll.insert_one({}) def contentious_task(): @@ -2590,7 +2590,7 @@ def test_gevent_timeout_when_creating_connection(self): client = self.async_rs_or_single_client() self.addCleanup(client.close) - coll = client.pymongo_test.test + coll = client.pymongo_test.coll pool = async_get_pool(client) # type:ignore # Patch the pool to delay the connect method. diff --git a/test/asynchronous/test_client_backpressure.py b/test/asynchronous/test_client_backpressure.py index 3d5e7bce3f..f5d16701c4 100644 --- a/test/asynchronous/test_client_backpressure.py +++ b/test/asynchronous/test_client_backpressure.py @@ -60,36 +60,36 @@ class TestBackpressure(AsyncIntegrationTest): @async_client_context.require_failCommand_appName async def test_retry_overload_error_command(self): - await self.db.t.insert_one({"x": 1}) + await self.db.coll.insert_one({"x": 1}) # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) async with self.fail_point(fail_many): - await self.db.command("find", "t") + await self.db.command("find", "coll") # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) async with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - await self.db.command("find", "t") + await self.db.command("find", "coll") self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @async_client_context.require_failCommand_appName async def test_retry_overload_error_find(self): - await self.db.t.insert_one({"x": 1}) + await self.db.coll.insert_one({"x": 1}) # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) async with self.fail_point(fail_many): - await self.db.t.find_one() + await self.db.coll.find_one() # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) async with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - await self.db.t.find_one() + await self.db.coll.find_one() self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @@ -99,13 +99,13 @@ async def test_retry_overload_error_insert_one(self): # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) async with self.fail_point(fail_many): - await self.db.t.insert_one({"x": 1}) + await self.db.coll.insert_one({"x": 1}) # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) async with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - await self.db.t.insert_one({"x": 1}) + await self.db.coll.insert_one({"x": 1}) self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @@ -114,25 +114,25 @@ async def test_retry_overload_error_insert_one(self): async def test_retry_overload_error_update_many(self): # Even though update_many is not a retryable write operation, it will # still be retried via the "RetryableError" error label. - await self.db.t.insert_one({"x": 1}) + await self.db.coll.insert_one({"x": 1}) # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) async with self.fail_point(fail_many): - await self.db.t.update_many({}, {"$set": {"x": 2}}) + await self.db.coll.update_many({}, {"$set": {"x": 2}}) # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) async with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - await self.db.t.update_many({}, {"$set": {"x": 2}}) + await self.db.coll.update_many({}, {"$set": {"x": 2}}) self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @async_client_context.require_failCommand_appName async def test_retry_overload_error_getMore(self): - coll = self.db.t + coll = self.db.coll await coll.insert_many([{"x": 1} for _ in range(10)]) # Ensure command is retried on overload error. @@ -189,7 +189,7 @@ async def test_01_operation_retry_uses_exponential_backoff(self, random_func): client = self.client # 2. let `collection` be a collection - collection = client.test.test + collection = client.db.coll # 3. Now, run transactions without backoff: diff --git a/test/asynchronous/test_collation.py b/test/asynchronous/test_collation.py index 72ce70cc78..d1a08f1878 100644 --- a/test/asynchronous/test_collation.py +++ b/test/asynchronous/test_collation.py @@ -121,14 +121,14 @@ def assertCollationInLastCommand(self): self.assertEqual(self.collation.document, self.last_command_started()["collation"]) async def test_create_collection(self): - await self.db.test.drop() - await self.db.create_collection("test", collation=self.collation) + await self.db.coll.drop() + await self.db.create_collection("coll", collation=self.collation) self.assertCollationInLastCommand() # Test passing collation as a dict as well. - await self.db.test.drop() + await self.db.coll.drop() self.listener.reset() - await self.db.create_collection("test", collation=self.collation.document) + await self.db.create_collection("coll", collation=self.collation.document) self.assertCollationInLastCommand() def test_index_model(self): @@ -136,81 +136,81 @@ def test_index_model(self): self.assertEqual(self.collation.document, model.document["collation"]) async def test_create_index(self): - await self.db.test.create_index("foo", collation=self.collation) + await self.db.coll.create_index("foo", collation=self.collation) ci_cmd = self.listener.started_events[0].command self.assertEqual(self.collation.document, ci_cmd["indexes"][0]["collation"]) async def test_aggregate(self): - await self.db.test.aggregate([{"$group": {"_id": 42}}], collation=self.collation) + await self.db.coll.aggregate([{"$group": {"_id": 42}}], collation=self.collation) self.assertCollationInLastCommand() async def test_count_documents(self): - await self.db.test.count_documents({}, collation=self.collation) + await self.db.coll.count_documents({}, collation=self.collation) self.assertCollationInLastCommand() async def test_distinct(self): - await self.db.test.distinct("foo", collation=self.collation) + await self.db.coll.distinct("foo", collation=self.collation) self.assertCollationInLastCommand() self.listener.reset() - await self.db.test.find(collation=self.collation).distinct("foo") + await self.db.coll.find(collation=self.collation).distinct("foo") self.assertCollationInLastCommand() async def test_find_command(self): - await self.db.test.insert_one({"is this thing on?": True}) + await self.db.coll.insert_one({"is this thing on?": True}) self.listener.reset() - await anext(self.db.test.find(collation=self.collation)) + await anext(self.db.coll.find(collation=self.collation)) self.assertCollationInLastCommand() async def test_explain_command(self): self.listener.reset() - await self.db.test.find(collation=self.collation).explain() + await self.db.coll.find(collation=self.collation).explain() # The collation should be part of the explained command. self.assertEqual( self.collation.document, self.last_command_started()["explain"]["collation"] ) async def test_delete(self): - await self.db.test.delete_one({"foo": 42}, collation=self.collation) + await self.db.coll.delete_one({"foo": 42}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["deletes"][0]["collation"]) self.listener.reset() - await self.db.test.delete_many({"foo": 42}, collation=self.collation) + await self.db.coll.delete_many({"foo": 42}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["deletes"][0]["collation"]) async def test_update(self): - await self.db.test.replace_one({"foo": 42}, {"foo": 43}, collation=self.collation) + await self.db.coll.replace_one({"foo": 42}, {"foo": 43}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["updates"][0]["collation"]) self.listener.reset() - await self.db.test.update_one({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) + await self.db.coll.update_one({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["updates"][0]["collation"]) self.listener.reset() - await self.db.test.update_many({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) + await self.db.coll.update_many({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["updates"][0]["collation"]) async def test_find_and(self): - await self.db.test.find_one_and_delete({"foo": 42}, collation=self.collation) + await self.db.coll.find_one_and_delete({"foo": 42}, collation=self.collation) self.assertCollationInLastCommand() self.listener.reset() - await self.db.test.find_one_and_update( + await self.db.coll.find_one_and_update( {"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation ) self.assertCollationInLastCommand() self.listener.reset() - await self.db.test.find_one_and_replace({"foo": 42}, {"foo": 43}, collation=self.collation) + await self.db.coll.find_one_and_replace({"foo": 42}, {"foo": 43}, collation=self.collation) self.assertCollationInLastCommand() async def test_bulk_write(self): - await self.db.test.collection.bulk_write( + await self.db.coll.bulk_write( [ DeleteOne({"noCollation": 42}), DeleteMany({"noCollation": 42}), @@ -241,32 +241,32 @@ def check_ops(ops): check_ops(update_cmd["updates"]) async def test_indexes_same_keys_different_collations(self): - await self.db.test.drop() + await self.db.coll.drop() usa_collation = Collation("en_US") ja_collation = Collation("ja") - await self.db.test.create_indexes( + await self.db.coll.create_indexes( [ IndexModel("fieldname", collation=usa_collation), IndexModel("fieldname", name="japanese_version", collation=ja_collation), IndexModel("fieldname", name="simple"), ] ) - indexes = await self.db.test.index_information() + indexes = await self.db.coll.index_information() self.assertEqual( usa_collation.document["locale"], indexes["fieldname_1"]["collation"]["locale"] ) self.assertEqual( ja_collation.document["locale"], indexes["japanese_version"]["collation"]["locale"] ) - await self.db.test.drop_index("fieldname_1") - indexes = await self.db.test.index_information() + await self.db.coll.drop_index("fieldname_1") + indexes = await self.db.coll.index_information() self.assertIn("japanese_version", indexes) self.assertIn("simple", indexes) self.assertNotIn("fieldname", indexes) async def test_unacknowledged_write(self): unacknowledged = WriteConcern(w=0) - collection = self.db.get_collection("test", write_concern=unacknowledged) + collection = self.db.get_collection("coll", write_concern=unacknowledged) with self.assertRaises(ConfigurationError): await collection.update_one( {"hello": "world"}, {"$set": {"hello": "moon"}}, collation=self.collation @@ -278,6 +278,6 @@ async def test_unacknowledged_write(self): await collection.bulk_write([update_one]) async def test_cursor_collation(self): - await self.db.test.insert_one({"hello": "world"}) - await anext(self.db.test.find().collation(self.collation)) + await self.db.coll.insert_one({"hello": "world"}) + await anext(self.db.coll.find().collation(self.collation)) self.assertCollationInLastCommand() diff --git a/test/asynchronous/test_collection.py b/test/asynchronous/test_collection.py index b3f0391057..63b35a1a4b 100644 --- a/test/asynchronous/test_collection.py +++ b/test/asynchronous/test_collection.py @@ -104,15 +104,15 @@ def make_col(base, name): self.assertRaises(InvalidName, make_col, self.db, ".test") self.assertRaises(InvalidName, make_col, self.db, "test.") self.assertRaises(InvalidName, make_col, self.db, "tes..t") - self.assertRaises(InvalidName, make_col, self.db.test, "") - self.assertRaises(InvalidName, make_col, self.db.test, "te$t") - self.assertRaises(InvalidName, make_col, self.db.test, ".test") - self.assertRaises(InvalidName, make_col, self.db.test, "test.") - self.assertRaises(InvalidName, make_col, self.db.test, "tes..t") - self.assertRaises(InvalidName, make_col, self.db.test, "tes\x00t") + self.assertRaises(InvalidName, make_col, self.db.coll, "") + self.assertRaises(InvalidName, make_col, self.db.coll, "te$t") + self.assertRaises(InvalidName, make_col, self.db.coll, ".test") + self.assertRaises(InvalidName, make_col, self.db.coll, "test.") + self.assertRaises(InvalidName, make_col, self.db.coll, "tes..t") + self.assertRaises(InvalidName, make_col, self.db.coll, "tes\x00t") def test_getattr(self): - coll = self.db.test + coll = self.db.coll self.assertIsInstance(coll["_does_not_exist"], AsyncCollection) with self.assertRaises(AttributeError) as context: @@ -160,7 +160,7 @@ async def asyncSetUp(self): self.w = async_client_context.w # type: ignore async def asyncTearDown(self): - await self.db.test.drop() + await self.db.coll.drop() await self.db.drop_collection("test_large_limit") await super().asyncTearDown() @@ -175,7 +175,7 @@ def write_concern_collection(self): write_concern=WriteConcern(w=len(async_client_context.nodes) + 1), ) else: - yield self.db.test + yield self.db.coll async def test_equality(self): self.assertIsInstance(self.db.test, AsyncCollection) @@ -189,7 +189,7 @@ async def test_hashable(self): async def test_create(self): # No Exception. - db = async_client_context.client.pymongo_test + db = self.db await db.create_test_no_wc.drop() async def lambda_test(): @@ -213,59 +213,59 @@ async def lambda_test_2(): await db.create_collection("create-test-wc", write_concern=IMPOSSIBLE_WRITE_CONCERN) async def test_drop_nonexistent_collection(self): - await self.db.drop_collection("test") - self.assertNotIn("test", await self.db.list_collection_names()) + await self.db.drop_collection("coll") + self.assertNotIn("coll", await self.db.list_collection_names()) # No exception - await self.db.drop_collection("test") + await self.db.drop_collection("coll") async def test_create_indexes(self): db = self.db with self.assertRaises(TypeError): - await db.test.create_indexes("foo") # type: ignore[arg-type] + await db.coll.create_indexes("foo") # type: ignore[arg-type] with self.assertRaises(TypeError): - await db.test.create_indexes(["foo"]) # type: ignore[list-item] + await db.coll.create_indexes(["foo"]) # type: ignore[list-item] self.assertRaises(TypeError, IndexModel, 5) self.assertRaises(ValueError, IndexModel, []) - await db.test.drop_indexes() - await db.create_collection("test") - self.assertEqual(len(await db.test.index_information()), 1) + await db.coll.drop_indexes() + await db.create_collection("coll") + self.assertEqual(len(await db.coll.index_information()), 1) - await db.test.create_indexes([IndexModel("hello")]) - await db.test.create_indexes([IndexModel([("hello", DESCENDING), ("world", ASCENDING)])]) + await db.coll.create_indexes([IndexModel("hello")]) + await db.coll.create_indexes([IndexModel([("hello", DESCENDING), ("world", ASCENDING)])]) # Tuple instead of list. - await db.test.create_indexes([IndexModel((("world", ASCENDING),))]) + await db.coll.create_indexes([IndexModel((("world", ASCENDING),))]) - self.assertEqual(len(await db.test.index_information()), 4) + self.assertEqual(len(await db.coll.index_information()), 4) - await db.test.drop_indexes() - names = await db.test.create_indexes( + await db.coll.drop_indexes() + names = await db.coll.create_indexes( [IndexModel([("hello", DESCENDING), ("world", ASCENDING)], name="hello_world")] ) self.assertEqual(names, ["hello_world"]) - await db.test.drop_indexes() - self.assertEqual(len(await db.test.index_information()), 1) - await db.test.create_indexes([IndexModel("hello")]) - self.assertIn("hello_1", await db.test.index_information()) + await db.coll.drop_indexes() + self.assertEqual(len(await db.coll.index_information()), 1) + await db.coll.create_indexes([IndexModel("hello")]) + self.assertIn("hello_1", await db.coll.index_information()) - await db.test.drop_indexes() - self.assertEqual(len(await db.test.index_information()), 1) - names = await db.test.create_indexes( + await db.coll.drop_indexes() + self.assertEqual(len(await db.coll.index_information()), 1) + names = await db.coll.create_indexes( [IndexModel([("hello", DESCENDING), ("world", ASCENDING)]), IndexModel("hello")] ) - info = await db.test.index_information() + info = await db.coll.index_information() for name in names: self.assertIn(name, info) - await db.test.drop() - await db.test.insert_one({"a": 1}) - await db.test.insert_one({"a": 1}) + await db.coll.drop() + await db.coll.insert_one({"a": 1}) + await db.coll.insert_one({"a": 1}) with self.assertRaises(DuplicateKeyError): - await db.test.create_indexes([IndexModel("a", unique=True)]) + await db.coll.create_indexes([IndexModel("a", unique=True)]) with self.write_concern_collection() as coll: await coll.create_indexes([IndexModel("hello")]) @@ -278,83 +278,83 @@ async def test_create_index(self): db = self.db with self.assertRaises(TypeError): - await db.test.create_index(5) # type: ignore[arg-type] + await db.coll.create_index(5) # type: ignore[arg-type] with self.assertRaises(ValueError): - await db.test.create_index([]) + await db.coll.create_index([]) - await db.test.drop_indexes() - await db.create_collection("test") - self.assertEqual(len(await db.test.index_information()), 1) + await db.coll.drop_indexes() + await db.create_collection("coll") + self.assertEqual(len(await db.coll.index_information()), 1) - await db.test.create_index("hello") - await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)]) + await db.coll.create_index("hello") + await db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)]) # Tuple instead of list. - await db.test.create_index((("world", ASCENDING),)) + await db.coll.create_index((("world", ASCENDING),)) - self.assertEqual(len(await db.test.index_information()), 4) + self.assertEqual(len(await db.coll.index_information()), 4) - await db.test.drop_indexes() - ix = await db.test.create_index( + await db.coll.drop_indexes() + ix = await db.coll.create_index( [("hello", DESCENDING), ("world", ASCENDING)], name="hello_world" ) self.assertEqual(ix, "hello_world") - await db.test.drop_indexes() - self.assertEqual(len(await db.test.index_information()), 1) - await db.test.create_index("hello") - self.assertIn("hello_1", await db.test.index_information()) + await db.coll.drop_indexes() + self.assertEqual(len(await db.coll.index_information()), 1) + await db.coll.create_index("hello") + self.assertIn("hello_1", await db.coll.index_information()) - await db.test.drop_indexes() - self.assertEqual(len(await db.test.index_information()), 1) - await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)]) - self.assertIn("hello_-1_world_1", await db.test.index_information()) + await db.coll.drop_indexes() + self.assertEqual(len(await db.coll.index_information()), 1) + await db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)]) + self.assertIn("hello_-1_world_1", await db.coll.index_information()) - await db.test.drop_indexes() - await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], name=None) - self.assertIn("hello_-1_world_1", await db.test.index_information()) + await db.coll.drop_indexes() + await db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)], name=None) + self.assertIn("hello_-1_world_1", await db.coll.index_information()) - await db.test.drop() - await db.test.insert_one({"a": 1}) - await db.test.insert_one({"a": 1}) + await db.coll.drop() + await db.coll.insert_one({"a": 1}) + await db.coll.insert_one({"a": 1}) with self.assertRaises(DuplicateKeyError): - await db.test.create_index("a", unique=True) + await db.coll.create_index("a", unique=True) with self.write_concern_collection() as coll: await coll.create_index([("hello", DESCENDING)]) - await db.test.create_index(["hello", "world"]) - await db.test.create_index(["hello", ("world", DESCENDING)]) - await db.test.create_index({"hello": 1}.items()) # type:ignore[arg-type] + await db.coll.create_index(["hello", "world"]) + await db.coll.create_index(["hello", ("world", DESCENDING)]) + await db.coll.create_index({"hello": 1}.items()) # type:ignore[arg-type] async def test_drop_index(self): db = self.db - await db.test.drop_indexes() - await db.test.create_index("hello") - name = await db.test.create_index("goodbye") + await db.coll.drop_indexes() + await db.coll.create_index("hello") + name = await db.coll.create_index("goodbye") - self.assertEqual(len(await db.test.index_information()), 3) + self.assertEqual(len(await db.coll.index_information()), 3) self.assertEqual(name, "goodbye_1") - await db.test.drop_index(name) + await db.coll.drop_index(name) # Drop it again. if async_client_context.version < Version(8, 3, -1): with self.assertRaises(OperationFailure): - await db.test.drop_index(name) + await db.coll.drop_index(name) else: - await db.test.drop_index(name) - self.assertEqual(len(await db.test.index_information()), 2) - self.assertIn("hello_1", await db.test.index_information()) + await db.coll.drop_index(name) + self.assertEqual(len(await db.coll.index_information()), 2) + self.assertIn("hello_1", await db.coll.index_information()) - await db.test.drop_indexes() - await db.test.create_index("hello") - name = await db.test.create_index("goodbye") + await db.coll.drop_indexes() + await db.coll.create_index("hello") + name = await db.coll.create_index("goodbye") - self.assertEqual(len(await db.test.index_information()), 3) + self.assertEqual(len(await db.coll.index_information()), 3) self.assertEqual(name, "goodbye_1") - await db.test.drop_index([("goodbye", ASCENDING)]) - self.assertEqual(len(await db.test.index_information()), 2) - self.assertIn("hello_1", await db.test.index_information()) + await db.coll.drop_index([("goodbye", ASCENDING)]) + self.assertEqual(len(await db.coll.index_information()), 2) + self.assertIn("hello_1", await db.coll.index_information()) with self.write_concern_collection() as coll: await coll.drop_index("hello_1") @@ -362,7 +362,7 @@ async def test_drop_index(self): @async_client_context.require_no_mongos @async_client_context.require_test_commands async def test_index_management_max_time_ms(self): - coll = self.db.test + coll = self.db.coll await self.client.admin.command( "configureFailPoint", "maxTimeAlwaysTimeOut", mode="alwaysOn" ) @@ -382,23 +382,23 @@ async def test_index_management_max_time_ms(self): async def test_list_indexes(self): db = self.db - await db.test.drop() - await db.create_collection("test") + await db.coll.drop() + await db.create_collection("coll") def map_indexes(indexes): return {index["name"]: index for index in indexes} - indexes = await (await db.test.list_indexes()).to_list() + indexes = await (await db.coll.list_indexes()).to_list() self.assertEqual(len(indexes), 1) self.assertIn("_id_", map_indexes(indexes)) - await db.test.create_index("hello") - indexes = await (await db.test.list_indexes()).to_list() + await db.coll.create_index("hello") + indexes = await (await db.coll.list_indexes()).to_list() self.assertEqual(len(indexes), 2) self.assertEqual(map_indexes(indexes)["hello_1"]["key"], SON([("hello", ASCENDING)])) - await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) - indexes = await (await db.test.list_indexes()).to_list() + await db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) + indexes = await (await db.coll.list_indexes()).to_list() self.assertEqual(len(indexes), 3) index_map = map_indexes(indexes) self.assertEqual( @@ -416,33 +416,33 @@ def map_indexes(indexes): async def test_index_info(self): db = self.db - await db.test.drop() - await db.create_collection("test") - self.assertEqual(len(await db.test.index_information()), 1) - self.assertIn("_id_", await db.test.index_information()) + await db.coll.drop() + await db.create_collection("coll") + self.assertEqual(len(await db.coll.index_information()), 1) + self.assertIn("_id_", await db.coll.index_information()) - await db.test.create_index("hello") - self.assertEqual(len(await db.test.index_information()), 2) + await db.coll.create_index("hello") + self.assertEqual(len(await db.coll.index_information()), 2) self.assertEqual( - (await db.test.index_information())["hello_1"]["key"], [("hello", ASCENDING)] + (await db.coll.index_information())["hello_1"]["key"], [("hello", ASCENDING)] ) - await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) + await db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) self.assertEqual( - (await db.test.index_information())["hello_1"]["key"], [("hello", ASCENDING)] + (await db.coll.index_information())["hello_1"]["key"], [("hello", ASCENDING)] ) - self.assertEqual(len(await db.test.index_information()), 3) + self.assertEqual(len(await db.coll.index_information()), 3) self.assertEqual( [("hello", DESCENDING), ("world", ASCENDING)], - (await db.test.index_information())["hello_-1_world_1"]["key"], + (await db.coll.index_information())["hello_-1_world_1"]["key"], ) - self.assertEqual(True, (await db.test.index_information())["hello_-1_world_1"]["unique"]) + self.assertEqual(True, (await db.coll.index_information())["hello_-1_world_1"]["unique"]) async def test_index_geo2d(self): db = self.db - await db.test.drop_indexes() - self.assertEqual("loc_2d", await db.test.create_index([("loc", GEO2D)])) - index_info = (await db.test.index_information())["loc_2d"] + await db.coll.drop_indexes() + self.assertEqual("loc_2d", await db.coll.create_index([("loc", GEO2D)])) + index_info = (await db.coll.index_information())["loc_2d"] self.assertEqual([("loc", "2d")], index_info["key"]) # geoSearch was deprecated in 4.4 and removed in 5.0 @@ -450,19 +450,19 @@ async def test_index_geo2d(self): @async_client_context.require_no_mongos async def test_index_haystack(self): db = self.db - await db.test.drop() + await db.coll.drop() _id = ( - await db.test.insert_one({"pos": {"long": 34.2, "lat": 33.3}, "type": "restaurant"}) + await db.coll.insert_one({"pos": {"long": 34.2, "lat": 33.3}, "type": "restaurant"}) ).inserted_id - await db.test.insert_one({"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"}) - await db.test.insert_one({"pos": {"long": 59.1, "lat": 87.2}, "type": "office"}) - await db.test.create_index([("pos", "geoHaystack"), ("type", ASCENDING)], bucketSize=1) + await db.coll.insert_one({"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"}) + await db.coll.insert_one({"pos": {"long": 59.1, "lat": 87.2}, "type": "office"}) + await db.coll.create_index([("pos", "geoHaystack"), ("type", ASCENDING)], bucketSize=1) results = ( await db.command( SON( [ - ("geoSearch", "test"), + ("geoSearch", "coll"), ("near", [33, 33]), ("maxDistance", 6), ("search", {"type": "restaurant"}), @@ -480,31 +480,31 @@ async def test_index_haystack(self): @async_client_context.require_no_mongos async def test_index_text(self): db = self.db - await db.test.drop_indexes() - self.assertEqual("t_text", await db.test.create_index([("t", TEXT)])) - index_info = (await db.test.index_information())["t_text"] + await db.coll.drop_indexes() + self.assertEqual("t_text", await db.coll.create_index([("t", TEXT)])) + index_info = (await db.coll.index_information())["t_text"] self.assertIn("weights", index_info) - await db.test.insert_many( + await db.coll.insert_many( [{"t": "spam eggs and spam"}, {"t": "spam"}, {"t": "egg sausage and bacon"}] ) # MongoDB 2.6 text search. Create 'score' field in projection. - cursor = db.test.find({"$text": {"$search": "spam"}}, {"score": {"$meta": "textScore"}}) + cursor = db.coll.find({"$text": {"$search": "spam"}}, {"score": {"$meta": "textScore"}}) # Sort by 'score' field. cursor.sort([("score", {"$meta": "textScore"})]) results = await cursor.to_list() self.assertGreaterEqual(results[0]["score"], results[1]["score"]) - await db.test.drop_indexes() + await db.coll.drop_indexes() async def test_index_2dsphere(self): db = self.db - await db.test.drop_indexes() - self.assertEqual("geo_2dsphere", await db.test.create_index([("geo", GEOSPHERE)])) + await db.coll.drop_indexes() + self.assertEqual("geo_2dsphere", await db.coll.create_index([("geo", GEOSPHERE)])) - for dummy, info in (await db.test.index_information()).items(): + for dummy, info in (await db.coll.index_information()).items(): field, idx_type = info["key"][0] if field == "geo" and idx_type == "2dsphere": break @@ -515,45 +515,45 @@ async def test_index_2dsphere(self): query = {"geo": {"$within": {"$geometry": poly}}} # This query will error without a 2dsphere index. - db.test.find(query) - await db.test.drop_indexes() + db.coll.find(query) + await db.coll.drop_indexes() async def test_index_hashed(self): db = self.db - await db.test.drop_indexes() - self.assertEqual("a_hashed", await db.test.create_index([("a", HASHED)])) + await db.coll.drop_indexes() + self.assertEqual("a_hashed", await db.coll.create_index([("a", HASHED)])) - for dummy, info in (await db.test.index_information()).items(): + for dummy, info in (await db.coll.index_information()).items(): field, idx_type = info["key"][0] if field == "a" and idx_type == "hashed": break else: self.fail("hashed index not found.") - await db.test.drop_indexes() + await db.coll.drop_indexes() async def test_index_sparse(self): db = self.db - await db.test.drop_indexes() - await db.test.create_index([("key", ASCENDING)], sparse=True) - self.assertTrue((await db.test.index_information())["key_1"]["sparse"]) + await db.coll.drop_indexes() + await db.coll.create_index([("key", ASCENDING)], sparse=True) + self.assertTrue((await db.coll.index_information())["key_1"]["sparse"]) async def test_index_background(self): db = self.db - await db.test.drop_indexes() - await db.test.create_index([("keya", ASCENDING)]) - await db.test.create_index([("keyb", ASCENDING)], background=False) - await db.test.create_index([("keyc", ASCENDING)], background=True) - self.assertNotIn("background", (await db.test.index_information())["keya_1"]) - self.assertFalse((await db.test.index_information())["keyb_1"]["background"]) - self.assertTrue((await db.test.index_information())["keyc_1"]["background"]) + await db.coll.drop_indexes() + await db.coll.create_index([("keya", ASCENDING)]) + await db.coll.create_index([("keyb", ASCENDING)], background=False) + await db.coll.create_index([("keyc", ASCENDING)], background=True) + self.assertNotIn("background", (await db.coll.index_information())["keya_1"]) + self.assertFalse((await db.coll.index_information())["keyb_1"]["background"]) + self.assertTrue((await db.coll.index_information())["keyc_1"]["background"]) async def _drop_dups_setup(self, db): - await db.drop_collection("test") - await db.test.insert_one({"i": 1}) - await db.test.insert_one({"i": 2}) - await db.test.insert_one({"i": 2}) # duplicate - await db.test.insert_one({"i": 3}) + await db.drop_collection("coll") + await db.coll.insert_one({"i": 1}) + await db.coll.insert_one({"i": 2}) + await db.coll.insert_one({"i": 2}) # duplicate + await db.coll.insert_one({"i": 3}) async def test_index_dont_drop_dups(self): # Try *not* dropping duplicates @@ -562,16 +562,16 @@ async def test_index_dont_drop_dups(self): # There's a duplicate async def _test_create(): - await db.test.create_index([("i", ASCENDING)], unique=True, dropDups=False) + await db.coll.create_index([("i", ASCENDING)], unique=True, dropDups=False) with self.assertRaises(DuplicateKeyError): await _test_create() # Duplicate wasn't dropped - self.assertEqual(4, await db.test.count_documents({})) + self.assertEqual(4, await db.coll.count_documents({})) # Index wasn't created, only the default index on _id - self.assertEqual(1, len(await db.test.index_information())) + self.assertEqual(1, len(await db.coll.index_information())) # Get the plan dynamically because the explain format will change. def get_plan_stage(self, root, stage): @@ -596,141 +596,141 @@ def get_plan_stage(self, root, stage): async def test_index_filter(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") # Test bad filter spec on create. with self.assertRaises(OperationFailure): - await db.test.create_index("x", partialFilterExpression=5) + await db.coll.create_index("x", partialFilterExpression=5) with self.assertRaises(OperationFailure): - await db.test.create_index("x", partialFilterExpression={"x": {"$asdasd": 3}}) + await db.coll.create_index("x", partialFilterExpression={"x": {"$asdasd": 3}}) with self.assertRaises(OperationFailure): - await db.test.create_index("x", partialFilterExpression={"$and": 5}) + await db.coll.create_index("x", partialFilterExpression={"$and": 5}) self.assertEqual( "x_1", - await db.test.create_index( + await db.coll.create_index( [("x", ASCENDING)], partialFilterExpression={"a": {"$lte": 1.5}} ), ) - await db.test.insert_one({"x": 5, "a": 2}) - await db.test.insert_one({"x": 6, "a": 1}) + await db.coll.insert_one({"x": 5, "a": 2}) + await db.coll.insert_one({"x": 6, "a": 1}) # Operations that use the partial index. - explain = await db.test.find({"x": 6, "a": 1}).explain() + explain = await db.coll.find({"x": 6, "a": 1}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN") self.assertEqual("x_1", stage.get("indexName")) self.assertTrue(stage.get("isPartial")) - explain = await db.test.find({"x": {"$gt": 1}, "a": 1}).explain() + explain = await db.coll.find({"x": {"$gt": 1}, "a": 1}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN") self.assertEqual("x_1", stage.get("indexName")) self.assertTrue(stage.get("isPartial")) - explain = await db.test.find({"x": 6, "a": {"$lte": 1}}).explain() + explain = await db.coll.find({"x": 6, "a": {"$lte": 1}}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN") self.assertEqual("x_1", stage.get("indexName")) self.assertTrue(stage.get("isPartial")) # Operations that do not use the partial index. - explain = await db.test.find({"x": 6, "a": {"$lte": 1.6}}).explain() + explain = await db.coll.find({"x": 6, "a": {"$lte": 1.6}}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN") self.assertNotEqual({}, stage) - explain = await db.test.find({"x": 6}).explain() + explain = await db.coll.find({"x": 6}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN") self.assertNotEqual({}, stage) # Test drop_indexes. - await db.test.drop_index("x_1") - explain = await db.test.find({"x": 6, "a": 1}).explain() + await db.coll.drop_index("x_1") + explain = await db.coll.find({"x": 6, "a": 1}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN") self.assertNotEqual({}, stage) async def test_field_selection(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") doc = {"a": 1, "b": 5, "c": {"d": 5, "e": 10}} - await db.test.insert_one(doc) + await db.coll.insert_one(doc) # Test field inclusion - doc = await anext(db.test.find({}, ["_id"])) + doc = await anext(db.coll.find({}, ["_id"])) self.assertEqual(list(doc), ["_id"]) - doc = await anext(db.test.find({}, ["a"])) + doc = await anext(db.coll.find({}, ["a"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "a"]) - doc = await anext(db.test.find({}, ["b"])) + doc = await anext(db.coll.find({}, ["b"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "b"]) - doc = await anext(db.test.find({}, ["c"])) + doc = await anext(db.coll.find({}, ["c"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "c"]) - doc = await anext(db.test.find({}, ["a"])) + doc = await anext(db.coll.find({}, ["a"])) self.assertEqual(doc["a"], 1) - doc = await anext(db.test.find({}, ["b"])) + doc = await anext(db.coll.find({}, ["b"])) self.assertEqual(doc["b"], 5) - doc = await anext(db.test.find({}, ["c"])) + doc = await anext(db.coll.find({}, ["c"])) self.assertEqual(doc["c"], {"d": 5, "e": 10}) # Test inclusion of fields with dots - doc = await anext(db.test.find({}, ["c.d"])) + doc = await anext(db.coll.find({}, ["c.d"])) self.assertEqual(doc["c"], {"d": 5}) - doc = await anext(db.test.find({}, ["c.e"])) + doc = await anext(db.coll.find({}, ["c.e"])) self.assertEqual(doc["c"], {"e": 10}) - doc = await anext(db.test.find({}, ["b", "c.e"])) + doc = await anext(db.coll.find({}, ["b", "c.e"])) self.assertEqual(doc["c"], {"e": 10}) - doc = await anext(db.test.find({}, ["b", "c.e"])) + doc = await anext(db.coll.find({}, ["b", "c.e"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "b", "c"]) - doc = await anext(db.test.find({}, ["b", "c.e"])) + doc = await anext(db.coll.find({}, ["b", "c.e"])) self.assertEqual(doc["b"], 5) # Test field exclusion - doc = await anext(db.test.find({}, {"a": False, "b": 0})) + doc = await anext(db.coll.find({}, {"a": False, "b": 0})) l = list(doc) l.sort() self.assertEqual(l, ["_id", "c"]) - doc = await anext(db.test.find({}, {"_id": False})) + doc = await anext(db.coll.find({}, {"_id": False})) l = list(doc) self.assertNotIn("_id", l) async def test_options(self): db = self.db - await db.drop_collection("test") - await db.create_collection("test", capped=True, size=4096) - result = await db.test.options() + await db.drop_collection("coll") + await db.create_collection("coll", capped=True, size=4096) + result = await db.coll.options() self.assertEqual(result, {"capped": True, "size": 4096}) - await db.drop_collection("test") + await db.drop_collection("coll") async def test_insert_one(self): db = self.db - await db.test.drop() + await db.coll.drop() document: dict[str, Any] = {"_id": 1000} - result = await db.test.insert_one(document) + result = await db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertIsInstance(result.inserted_id, int) self.assertEqual(document["_id"], result.inserted_id) self.assertTrue(result.acknowledged) - self.assertIsNotNone(await db.test.find_one({"_id": document["_id"]})) - self.assertEqual(1, await db.test.count_documents({})) + self.assertIsNotNone(await db.coll.find_one({"_id": document["_id"]})) + self.assertEqual(1, await db.coll.count_documents({})) document = {"foo": "bar"} - result = await db.test.insert_one(document) + result = await db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertIsInstance(result.inserted_id, ObjectId) self.assertEqual(document["_id"], result.inserted_id) self.assertTrue(result.acknowledged) - self.assertIsNotNone(await db.test.find_one({"_id": document["_id"]})) - self.assertEqual(2, await db.test.count_documents({})) + self.assertIsNotNone(await db.coll.find_one({"_id": document["_id"]})) + self.assertEqual(2, await db.coll.count_documents({})) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = await db.test.insert_one(document) + result = await db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertIsInstance(result.inserted_id, ObjectId) self.assertEqual(document["_id"], result.inserted_id) @@ -738,21 +738,21 @@ async def test_insert_one(self): # The insert failed duplicate key... async def async_lambda(): - return await db.test.count_documents({}) == 2 + return await db.coll.count_documents({}) == 2 await async_wait_until(async_lambda, "forcing duplicate key error") document = RawBSONDocument(encode({"_id": ObjectId(), "foo": "bar"})) - result = await db.test.insert_one(document) + result = await db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertEqual(result.inserted_id, None) async def test_insert_many(self): db = self.db - await db.test.drop() + await db.coll.drop() docs: list = [{} for _ in range(5)] - result = await db.test.insert_many(docs) + result = await db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertIsInstance(result.inserted_ids, list) self.assertEqual(5, len(result.inserted_ids)) @@ -760,11 +760,11 @@ async def test_insert_many(self): _id = doc["_id"] self.assertIsInstance(_id, ObjectId) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, await db.test.count_documents({"_id": _id})) + self.assertEqual(1, await db.coll.count_documents({"_id": _id})) self.assertTrue(result.acknowledged) docs = [{"_id": i} for i in range(5)] - result = await db.test.insert_many(docs) + result = await db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertIsInstance(result.inserted_ids, list) self.assertEqual(5, len(result.inserted_ids)) @@ -772,24 +772,24 @@ async def test_insert_many(self): _id = doc["_id"] self.assertIsInstance(_id, int) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, await db.test.count_documents({"_id": _id})) + self.assertEqual(1, await db.coll.count_documents({"_id": _id})) self.assertTrue(result.acknowledged) docs = [RawBSONDocument(encode({"_id": i + 5})) for i in range(5)] - result = await db.test.insert_many(docs) + result = await db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertIsInstance(result.inserted_ids, list) self.assertEqual([], result.inserted_ids) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) docs: list = [{} for _ in range(5)] - result = await db.test.insert_many(docs) + result = await db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertFalse(result.acknowledged) - self.assertEqual(20, await db.test.count_documents({})) + self.assertEqual(20, await db.coll.count_documents({})) async def test_insert_many_generator(self): - coll = self.db.test + coll = self.db.coll await coll.delete_many({}) def gen(): @@ -806,75 +806,75 @@ async def test_insert_many_invalid(self): db = self.db with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - await db.test.insert_many({}) + await db.coll.insert_many({}) with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - await db.test.insert_many([]) + await db.coll.insert_many([]) with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - await db.test.insert_many(1) # type: ignore[arg-type] + await db.coll.insert_many(1) # type: ignore[arg-type] with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - await db.test.insert_many(RawBSONDocument(encode({"_id": 2}))) + await db.coll.insert_many(RawBSONDocument(encode({"_id": 2}))) async def test_delete_one(self): - await self.db.test.drop() + await self.db.coll.drop() - await self.db.test.insert_one({"x": 1}) - await self.db.test.insert_one({"y": 1}) - await self.db.test.insert_one({"z": 1}) + await self.db.coll.insert_one({"x": 1}) + await self.db.coll.insert_one({"y": 1}) + await self.db.coll.insert_one({"z": 1}) - result = await self.db.test.delete_one({"x": 1}) + result = await self.db.coll.delete_one({"x": 1}) self.assertIsInstance(result, DeleteResult) self.assertEqual(1, result.deleted_count) self.assertTrue(result.acknowledged) - self.assertEqual(2, await self.db.test.count_documents({})) + self.assertEqual(2, await self.db.coll.count_documents({})) - result = await self.db.test.delete_one({"y": 1}) + result = await self.db.coll.delete_one({"y": 1}) self.assertIsInstance(result, DeleteResult) self.assertEqual(1, result.deleted_count) self.assertTrue(result.acknowledged) - self.assertEqual(1, await self.db.test.count_documents({})) + self.assertEqual(1, await self.db.coll.count_documents({})) db = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) - result = await db.test.delete_one({"z": 1}) + result = await db.coll.delete_one({"z": 1}) self.assertIsInstance(result, DeleteResult) self.assertRaises(InvalidOperation, lambda: result.deleted_count) self.assertFalse(result.acknowledged) async def lambda_async(): - return await db.test.count_documents({}) == 0 + return await db.coll.count_documents({}) == 0 await async_wait_until(lambda_async, "delete 1 documents") async def test_delete_many(self): - await self.db.test.drop() + await self.db.coll.drop() - await self.db.test.insert_one({"x": 1}) - await self.db.test.insert_one({"x": 1}) - await self.db.test.insert_one({"y": 1}) - await self.db.test.insert_one({"y": 1}) + await self.db.coll.insert_one({"x": 1}) + await self.db.coll.insert_one({"x": 1}) + await self.db.coll.insert_one({"y": 1}) + await self.db.coll.insert_one({"y": 1}) - result = await self.db.test.delete_many({"x": 1}) + result = await self.db.coll.delete_many({"x": 1}) self.assertIsInstance(result, DeleteResult) self.assertEqual(2, result.deleted_count) self.assertTrue(result.acknowledged) - self.assertEqual(0, await self.db.test.count_documents({"x": 1})) + self.assertEqual(0, await self.db.coll.count_documents({"x": 1})) db = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) - result = await db.test.delete_many({"y": 1}) + result = await db.coll.delete_many({"y": 1}) self.assertIsInstance(result, DeleteResult) self.assertRaises(InvalidOperation, lambda: result.deleted_count) self.assertFalse(result.acknowledged) async def lambda_async(): - return await db.test.count_documents({}) == 0 + return await db.coll.count_documents({}) == 0 await async_wait_until(lambda_async, "delete 2 documents") async def test_command_document_too_large(self): large = "*" * (await async_client_context.max_bson_size + _COMMAND_OVERHEAD) - coll = self.db.test + coll = self.db.coll with self.assertRaises(DocumentTooLarge): await coll.insert_one({"data": large}) # update_one and update_many are the same @@ -891,200 +891,200 @@ async def test_write_large_document(self): self.assertEqual(max_size, 16777216) with self.assertRaises(OperationFailure): - await self.db.test.insert_one({"foo": max_str}) + await self.db.coll.insert_one({"foo": max_str}) with self.assertRaises(OperationFailure): - await self.db.test.replace_one({}, {"foo": max_str}, upsert=True) + await self.db.coll.replace_one({}, {"foo": max_str}, upsert=True) with self.assertRaises(OperationFailure): - await self.db.test.insert_many([{"x": 1}, {"foo": max_str}]) - await self.db.test.insert_many([{"foo": half_str}, {"foo": half_str}]) + await self.db.coll.insert_many([{"x": 1}, {"foo": max_str}]) + await self.db.coll.insert_many([{"foo": half_str}, {"foo": half_str}]) - await self.db.test.insert_one({"bar": "x"}) + await self.db.coll.insert_one({"bar": "x"}) # Use w=0 here to test legacy doc size checking in all server versions - unack_coll = self.db.test.with_options(write_concern=WriteConcern(w=0)) + unack_coll = self.db.coll.with_options(write_concern=WriteConcern(w=0)) with self.assertRaises(DocumentTooLarge): await unack_coll.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 14)}) - await self.db.test.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 32)}) + await self.db.coll.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 32)}) async def test_insert_bypass_document_validation(self): db = self.db - await db.test.drop() - await db.create_collection("test", validator={"a": {"$exists": True}}) + await db.coll.drop() + await db.create_collection("coll", validator={"a": {"$exists": True}}) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) # Test insert_one with self.assertRaises(OperationFailure): - await db.test.insert_one({"_id": 1, "x": 100}) - result = await db.test.insert_one({"_id": 1, "x": 100}, bypass_document_validation=True) + await db.coll.insert_one({"_id": 1, "x": 100}) + result = await db.coll.insert_one({"_id": 1, "x": 100}, bypass_document_validation=True) self.assertIsInstance(result, InsertOneResult) self.assertEqual(1, result.inserted_id) - result = await db.test.insert_one({"_id": 2, "a": 0}) + result = await db.coll.insert_one({"_id": 2, "a": 0}) self.assertIsInstance(result, InsertOneResult) self.assertEqual(2, result.inserted_id) - await db_w0.test.insert_one({"y": 1}, bypass_document_validation=True) + await db_w0.coll.insert_one({"y": 1}, bypass_document_validation=True) async def async_lambda(): - return await db_w0.test.find_one({"y": 1}) + return await db_w0.coll.find_one({"y": 1}) await async_wait_until(async_lambda, "find w:0 inserted document") # Test insert_many docs = [{"_id": i, "x": 100 - i} for i in range(3, 100)] with self.assertRaises(OperationFailure): - await db.test.insert_many(docs) - result = await db.test.insert_many(docs, bypass_document_validation=True) + await db.coll.insert_many(docs) + result = await db.coll.insert_many(docs, bypass_document_validation=True) self.assertIsInstance(result, InsertManyResult) self.assertTrue(97, len(result.inserted_ids)) for doc in docs: _id = doc["_id"] self.assertIsInstance(_id, int) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, await db.test.count_documents({"x": doc["x"]})) + self.assertEqual(1, await db.coll.count_documents({"x": doc["x"]})) self.assertTrue(result.acknowledged) docs = [{"_id": i, "a": 200 - i} for i in range(100, 200)] - result = await db.test.insert_many(docs) + result = await db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertTrue(97, len(result.inserted_ids)) for doc in docs: _id = doc["_id"] self.assertIsInstance(_id, int) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, await db.test.count_documents({"a": doc["a"]})) + self.assertEqual(1, await db.coll.count_documents({"a": doc["a"]})) self.assertTrue(result.acknowledged) with self.assertRaises(OperationFailure): - await db_w0.test.insert_many( + await db_w0.coll.insert_many( [{"x": 1}, {"x": 2}], bypass_document_validation=True, ) async def test_replace_bypass_document_validation(self): db = self.db - await db.test.drop() - await db.create_collection("test", validator={"a": {"$exists": True}}) + await db.coll.drop() + await db.create_collection("coll", validator={"a": {"$exists": True}}) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) # Test replace_one - await db.test.insert_one({"a": 101}) + await db.coll.insert_one({"a": 101}) with self.assertRaises(OperationFailure): - await db.test.replace_one({"a": 101}, {"y": 1}) - self.assertEqual(0, await db.test.count_documents({"y": 1})) - self.assertEqual(1, await db.test.count_documents({"a": 101})) - await db.test.replace_one({"a": 101}, {"y": 1}, bypass_document_validation=True) - self.assertEqual(0, await db.test.count_documents({"a": 101})) - self.assertEqual(1, await db.test.count_documents({"y": 1})) - await db.test.replace_one({"y": 1}, {"a": 102}) - self.assertEqual(0, await db.test.count_documents({"y": 1})) - self.assertEqual(0, await db.test.count_documents({"a": 101})) - self.assertEqual(1, await db.test.count_documents({"a": 102})) - - await db.test.insert_one({"y": 1}, bypass_document_validation=True) + await db.coll.replace_one({"a": 101}, {"y": 1}) + self.assertEqual(0, await db.coll.count_documents({"y": 1})) + self.assertEqual(1, await db.coll.count_documents({"a": 101})) + await db.coll.replace_one({"a": 101}, {"y": 1}, bypass_document_validation=True) + self.assertEqual(0, await db.coll.count_documents({"a": 101})) + self.assertEqual(1, await db.coll.count_documents({"y": 1})) + await db.coll.replace_one({"y": 1}, {"a": 102}) + self.assertEqual(0, await db.coll.count_documents({"y": 1})) + self.assertEqual(0, await db.coll.count_documents({"a": 101})) + self.assertEqual(1, await db.coll.count_documents({"a": 102})) + + await db.coll.insert_one({"y": 1}, bypass_document_validation=True) with self.assertRaises(OperationFailure): - await db.test.replace_one({"y": 1}, {"x": 101}) - self.assertEqual(0, await db.test.count_documents({"x": 101})) - self.assertEqual(1, await db.test.count_documents({"y": 1})) - await db.test.replace_one({"y": 1}, {"x": 101}, bypass_document_validation=True) - self.assertEqual(0, await db.test.count_documents({"y": 1})) - self.assertEqual(1, await db.test.count_documents({"x": 101})) - await db.test.replace_one({"x": 101}, {"a": 103}, bypass_document_validation=False) - self.assertEqual(0, await db.test.count_documents({"x": 101})) - self.assertEqual(1, await db.test.count_documents({"a": 103})) - - await db.test.insert_one({"y": 1}, bypass_document_validation=True) - await db_w0.test.replace_one({"y": 1}, {"x": 1}, bypass_document_validation=True) + await db.coll.replace_one({"y": 1}, {"x": 101}) + self.assertEqual(0, await db.coll.count_documents({"x": 101})) + self.assertEqual(1, await db.coll.count_documents({"y": 1})) + await db.coll.replace_one({"y": 1}, {"x": 101}, bypass_document_validation=True) + self.assertEqual(0, await db.coll.count_documents({"y": 1})) + self.assertEqual(1, await db.coll.count_documents({"x": 101})) + await db.coll.replace_one({"x": 101}, {"a": 103}, bypass_document_validation=False) + self.assertEqual(0, await db.coll.count_documents({"x": 101})) + self.assertEqual(1, await db.coll.count_documents({"a": 103})) + + await db.coll.insert_one({"y": 1}, bypass_document_validation=True) + await db_w0.coll.replace_one({"y": 1}, {"x": 1}, bypass_document_validation=True) async def predicate(): - return await db_w0.test.find_one({"x": 1}) + return await db_w0.coll.find_one({"x": 1}) await async_wait_until(predicate, "find w:0 replaced document") async def test_update_bypass_document_validation(self): db = self.db - await db.test.drop() - await db.test.insert_one({"z": 5}) - await db.command(SON([("collMod", "test"), ("validator", {"z": {"$gte": 0}})])) + await db.coll.drop() + await db.coll.insert_one({"z": 5}) + await db.command(SON([("collMod", "coll"), ("validator", {"z": {"$gte": 0}})])) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) # Test update_one with self.assertRaises(OperationFailure): - await db.test.update_one({"z": 5}, {"$inc": {"z": -10}}) - self.assertEqual(0, await db.test.count_documents({"z": -5})) - self.assertEqual(1, await db.test.count_documents({"z": 5})) - await db.test.update_one({"z": 5}, {"$inc": {"z": -10}}, bypass_document_validation=True) - self.assertEqual(0, await db.test.count_documents({"z": 5})) - self.assertEqual(1, await db.test.count_documents({"z": -5})) - await db.test.update_one({"z": -5}, {"$inc": {"z": 6}}, bypass_document_validation=False) - self.assertEqual(1, await db.test.count_documents({"z": 1})) - self.assertEqual(0, await db.test.count_documents({"z": -5})) - - await db.test.insert_one({"z": -10}, bypass_document_validation=True) + await db.coll.update_one({"z": 5}, {"$inc": {"z": -10}}) + self.assertEqual(0, await db.coll.count_documents({"z": -5})) + self.assertEqual(1, await db.coll.count_documents({"z": 5})) + await db.coll.update_one({"z": 5}, {"$inc": {"z": -10}}, bypass_document_validation=True) + self.assertEqual(0, await db.coll.count_documents({"z": 5})) + self.assertEqual(1, await db.coll.count_documents({"z": -5})) + await db.coll.update_one({"z": -5}, {"$inc": {"z": 6}}, bypass_document_validation=False) + self.assertEqual(1, await db.coll.count_documents({"z": 1})) + self.assertEqual(0, await db.coll.count_documents({"z": -5})) + + await db.coll.insert_one({"z": -10}, bypass_document_validation=True) with self.assertRaises(OperationFailure): - await db.test.update_one({"z": -10}, {"$inc": {"z": 1}}) - self.assertEqual(0, await db.test.count_documents({"z": -9})) - self.assertEqual(1, await db.test.count_documents({"z": -10})) - await db.test.update_one({"z": -10}, {"$inc": {"z": 1}}, bypass_document_validation=True) - self.assertEqual(1, await db.test.count_documents({"z": -9})) - self.assertEqual(0, await db.test.count_documents({"z": -10})) - await db.test.update_one({"z": -9}, {"$inc": {"z": 9}}, bypass_document_validation=False) - self.assertEqual(0, await db.test.count_documents({"z": -9})) - self.assertEqual(1, await db.test.count_documents({"z": 0})) - - await db.test.insert_one({"y": 1, "x": 0}, bypass_document_validation=True) - await db_w0.test.update_one({"y": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) + await db.coll.update_one({"z": -10}, {"$inc": {"z": 1}}) + self.assertEqual(0, await db.coll.count_documents({"z": -9})) + self.assertEqual(1, await db.coll.count_documents({"z": -10})) + await db.coll.update_one({"z": -10}, {"$inc": {"z": 1}}, bypass_document_validation=True) + self.assertEqual(1, await db.coll.count_documents({"z": -9})) + self.assertEqual(0, await db.coll.count_documents({"z": -10})) + await db.coll.update_one({"z": -9}, {"$inc": {"z": 9}}, bypass_document_validation=False) + self.assertEqual(0, await db.coll.count_documents({"z": -9})) + self.assertEqual(1, await db.coll.count_documents({"z": 0})) + + await db.coll.insert_one({"y": 1, "x": 0}, bypass_document_validation=True) + await db_w0.coll.update_one({"y": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) async def async_lambda(): - return await db_w0.test.find_one({"y": 1, "x": 1}) + return await db_w0.coll.find_one({"y": 1, "x": 1}) await async_wait_until(async_lambda, "find w:0 updated document") # Test update_many - await db.test.insert_many([{"z": i} for i in range(3, 101)]) - await db.test.insert_one({"y": 0}, bypass_document_validation=True) + await db.coll.insert_many([{"z": i} for i in range(3, 101)]) + await db.coll.insert_one({"y": 0}, bypass_document_validation=True) with self.assertRaises(OperationFailure): - await db.test.update_many({}, {"$inc": {"z": -100}}) - self.assertEqual(100, await db.test.count_documents({"z": {"$gte": 0}})) - self.assertEqual(0, await db.test.count_documents({"z": {"$lt": 0}})) - self.assertEqual(0, await db.test.count_documents({"y": 0, "z": -100})) - await db.test.update_many( + await db.coll.update_many({}, {"$inc": {"z": -100}}) + self.assertEqual(100, await db.coll.count_documents({"z": {"$gte": 0}})) + self.assertEqual(0, await db.coll.count_documents({"z": {"$lt": 0}})) + self.assertEqual(0, await db.coll.count_documents({"y": 0, "z": -100})) + await db.coll.update_many( {"z": {"$gte": 0}}, {"$inc": {"z": -100}}, bypass_document_validation=True ) - self.assertEqual(0, await db.test.count_documents({"z": {"$gt": 0}})) - self.assertEqual(100, await db.test.count_documents({"z": {"$lte": 0}})) - await db.test.update_many( + self.assertEqual(0, await db.coll.count_documents({"z": {"$gt": 0}})) + self.assertEqual(100, await db.coll.count_documents({"z": {"$lte": 0}})) + await db.coll.update_many( {"z": {"$gt": -50}}, {"$inc": {"z": 100}}, bypass_document_validation=False ) - self.assertEqual(50, await db.test.count_documents({"z": {"$gt": 0}})) - self.assertEqual(50, await db.test.count_documents({"z": {"$lt": 0}})) + self.assertEqual(50, await db.coll.count_documents({"z": {"$gt": 0}})) + self.assertEqual(50, await db.coll.count_documents({"z": {"$lt": 0}})) - await db.test.insert_many([{"z": -i} for i in range(50)], bypass_document_validation=True) + await db.coll.insert_many([{"z": -i} for i in range(50)], bypass_document_validation=True) with self.assertRaises(OperationFailure): - await db.test.update_many({}, {"$inc": {"z": 1}}) - self.assertEqual(100, await db.test.count_documents({"z": {"$lte": 0}})) - self.assertEqual(50, await db.test.count_documents({"z": {"$gt": 1}})) - await db.test.update_many( + await db.coll.update_many({}, {"$inc": {"z": 1}}) + self.assertEqual(100, await db.coll.count_documents({"z": {"$lte": 0}})) + self.assertEqual(50, await db.coll.count_documents({"z": {"$gt": 1}})) + await db.coll.update_many( {"z": {"$gte": 0}}, {"$inc": {"z": -100}}, bypass_document_validation=True ) - self.assertEqual(0, await db.test.count_documents({"z": {"$gt": 0}})) - self.assertEqual(150, await db.test.count_documents({"z": {"$lte": 0}})) - await db.test.update_many( + self.assertEqual(0, await db.coll.count_documents({"z": {"$gt": 0}})) + self.assertEqual(150, await db.coll.count_documents({"z": {"$lte": 0}})) + await db.coll.update_many( {"z": {"$lte": 0}}, {"$inc": {"z": 100}}, bypass_document_validation=False ) - self.assertEqual(150, await db.test.count_documents({"z": {"$gte": 0}})) - self.assertEqual(0, await db.test.count_documents({"z": {"$lt": 0}})) + self.assertEqual(150, await db.coll.count_documents({"z": {"$gte": 0}})) + self.assertEqual(0, await db.coll.count_documents({"z": {"$lt": 0}})) - await db.test.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) - await db.test.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) - await db_w0.test.update_many({"m": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) + await db.coll.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) + await db.coll.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) + await db_w0.coll.update_many({"m": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) async def async_lambda(): - return await db_w0.test.count_documents({"m": 1, "x": 1}) == 2 + return await db_w0.coll.count_documents({"m": 1, "x": 1}) == 2 await async_wait_until(async_lambda, "find w:0 updated documents") async def test_bypass_document_validation_bulk_write(self): db = self.db - await db.test.drop() - await db.create_collection("test", validator={"a": {"$gte": 0}}) + await db.coll.drop() + await db.create_collection("coll", validator={"a": {"$gte": 0}}) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) ops: list = [ @@ -1095,142 +1095,142 @@ async def test_bypass_document_validation_bulk_write(self): UpdateMany({"a": {"$lte": -10}}, {"$inc": {"a": 1}}), ReplaceOne({"a": {"$lte": -10}}, {"a": -1}), ] - await db.test.bulk_write(ops, bypass_document_validation=True) + await db.coll.bulk_write(ops, bypass_document_validation=True) - self.assertEqual(3, await db.test.count_documents({})) - self.assertEqual(1, await db.test.count_documents({"a": -11})) - self.assertEqual(1, await db.test.count_documents({"a": -1})) - self.assertEqual(1, await db.test.count_documents({"a": -9})) + self.assertEqual(3, await db.coll.count_documents({})) + self.assertEqual(1, await db.coll.count_documents({"a": -11})) + self.assertEqual(1, await db.coll.count_documents({"a": -1})) + self.assertEqual(1, await db.coll.count_documents({"a": -9})) # Assert that the operations would fail without bypass_doc_val for op in ops: with self.assertRaises(BulkWriteError): - await db.test.bulk_write([op]) + await db.coll.bulk_write([op]) with self.assertRaises(OperationFailure): - await db_w0.test.bulk_write(ops, bypass_document_validation=True) + await db_w0.coll.bulk_write(ops, bypass_document_validation=True) async def test_find_by_default_dct(self): db = self.db - await db.test.insert_one({"foo": "bar"}) + await db.coll.insert_one({"foo": "bar"}) dct = defaultdict(dict, [("foo", "bar")]) # type: ignore[arg-type] - self.assertIsNotNone(await db.test.find_one(dct)) + self.assertIsNotNone(await db.coll.find_one(dct)) self.assertEqual(dct, defaultdict(dict, [("foo", "bar")])) async def test_find_w_fields(self): db = self.db - await db.test.delete_many({}) + await db.coll.delete_many({}) - await db.test.insert_one( + await db.coll.insert_one( {"x": 1, "mike": "awesome", "extra thing": "abcdefghijklmnopqrstuvwxyz"} ) - self.assertEqual(1, await db.test.count_documents({})) - doc = await anext(db.test.find({})) + self.assertEqual(1, await db.coll.count_documents({})) + doc = await anext(db.coll.find({})) self.assertIn("x", doc) - doc = await anext(db.test.find({})) + doc = await anext(db.coll.find({})) self.assertIn("mike", doc) - doc = await anext(db.test.find({})) + doc = await anext(db.coll.find({})) self.assertIn("extra thing", doc) - doc = await anext(db.test.find({}, ["x", "mike"])) + doc = await anext(db.coll.find({}, ["x", "mike"])) self.assertIn("x", doc) - doc = await anext(db.test.find({}, ["x", "mike"])) + doc = await anext(db.coll.find({}, ["x", "mike"])) self.assertIn("mike", doc) - doc = await anext(db.test.find({}, ["x", "mike"])) + doc = await anext(db.coll.find({}, ["x", "mike"])) self.assertNotIn("extra thing", doc) - doc = await anext(db.test.find({}, ["mike"])) + doc = await anext(db.coll.find({}, ["mike"])) self.assertNotIn("x", doc) - doc = await anext(db.test.find({}, ["mike"])) + doc = await anext(db.coll.find({}, ["mike"])) self.assertIn("mike", doc) - doc = await anext(db.test.find({}, ["mike"])) + doc = await anext(db.coll.find({}, ["mike"])) self.assertNotIn("extra thing", doc) @no_type_check async def test_fields_specifier_as_dict(self): db = self.db - await db.test.delete_many({}) + await db.coll.delete_many({}) - await db.test.insert_one({"x": [1, 2, 3], "mike": "awesome"}) + await db.coll.insert_one({"x": [1, 2, 3], "mike": "awesome"}) - self.assertEqual([1, 2, 3], (await db.test.find_one())["x"]) - self.assertEqual([2, 3], (await db.test.find_one(projection={"x": {"$slice": -2}}))["x"]) - self.assertNotIn("x", await db.test.find_one(projection={"x": 0})) - self.assertIn("mike", await db.test.find_one(projection={"x": 0})) + self.assertEqual([1, 2, 3], (await db.coll.find_one())["x"]) + self.assertEqual([2, 3], (await db.coll.find_one(projection={"x": {"$slice": -2}}))["x"]) + self.assertNotIn("x", await db.coll.find_one(projection={"x": 0})) + self.assertIn("mike", await db.coll.find_one(projection={"x": 0})) async def test_find_w_regex(self): db = self.db - await db.test.delete_many({}) + await db.coll.delete_many({}) - await db.test.insert_one({"x": "hello_world"}) - await db.test.insert_one({"x": "hello_mike"}) - await db.test.insert_one({"x": "hello_mikey"}) - await db.test.insert_one({"x": "hello_test"}) + await db.coll.insert_one({"x": "hello_world"}) + await db.coll.insert_one({"x": "hello_mike"}) + await db.coll.insert_one({"x": "hello_mikey"}) + await db.coll.insert_one({"x": "hello_test"}) - self.assertEqual(len(await db.test.find().to_list()), 4) - self.assertEqual(len(await db.test.find({"x": re.compile("^hello.*")}).to_list()), 4) - self.assertEqual(len(await db.test.find({"x": re.compile("ello")}).to_list()), 4) - self.assertEqual(len(await db.test.find({"x": re.compile("^hello$")}).to_list()), 0) - self.assertEqual(len(await db.test.find({"x": re.compile("^hello_mi.*$")}).to_list()), 2) + self.assertEqual(len(await db.coll.find().to_list()), 4) + self.assertEqual(len(await db.coll.find({"x": re.compile("^hello.*")}).to_list()), 4) + self.assertEqual(len(await db.coll.find({"x": re.compile("ello")}).to_list()), 4) + self.assertEqual(len(await db.coll.find({"x": re.compile("^hello$")}).to_list()), 0) + self.assertEqual(len(await db.coll.find({"x": re.compile("^hello_mi.*$")}).to_list()), 2) async def test_id_can_be_anything(self): db = self.db - await db.test.delete_many({}) + await db.coll.delete_many({}) auto_id = {"hello": "world"} - await db.test.insert_one(auto_id) + await db.coll.insert_one(auto_id) self.assertIsInstance(auto_id["_id"], ObjectId) numeric = {"_id": 240, "hello": "world"} - await db.test.insert_one(numeric) + await db.coll.insert_one(numeric) self.assertEqual(numeric["_id"], 240) obj = {"_id": numeric, "hello": "world"} - await db.test.insert_one(obj) + await db.coll.insert_one(obj) self.assertEqual(obj["_id"], numeric) - async for x in db.test.find(): + async for x in db.coll.find(): self.assertEqual(x["hello"], "world") self.assertIn("_id", x) async def test_unique_index(self): db = self.db - await db.drop_collection("test") - await db.test.create_index("hello") + await db.drop_collection("coll") + await db.coll.create_index("hello") # No error. - await db.test.insert_one({"hello": "world"}) - await db.test.insert_one({"hello": "world"}) + await db.coll.insert_one({"hello": "world"}) + await db.coll.insert_one({"hello": "world"}) - await db.drop_collection("test") - await db.test.create_index("hello", unique=True) + await db.drop_collection("coll") + await db.coll.create_index("hello", unique=True) with self.assertRaises(DuplicateKeyError): - await db.test.insert_one({"hello": "world"}) - await db.test.insert_one({"hello": "world"}) + await db.coll.insert_one({"hello": "world"}) + await db.coll.insert_one({"hello": "world"}) async def test_duplicate_key_error(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - await db.test.create_index("x", unique=True) + await db.coll.create_index("x", unique=True) - await db.test.insert_one({"_id": 1, "x": 1}) + await db.coll.insert_one({"_id": 1, "x": 1}) with self.assertRaises(DuplicateKeyError) as context: - await db.test.insert_one({"x": 1}) + await db.coll.insert_one({"x": 1}) self.assertIsNotNone(context.exception.details) with self.assertRaises(DuplicateKeyError) as context: - await db.test.insert_one({"x": 1}) + await db.coll.insert_one({"x": 1}) self.assertIsNotNone(context.exception.details) - self.assertEqual(1, await db.test.count_documents({})) + self.assertEqual(1, await db.coll.count_documents({})) async def test_write_error_text_handling(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - await db.test.create_index("text", unique=True) + await db.coll.create_index("text", unique=True) # Test workaround for SERVER-24007 data = ( @@ -1265,21 +1265,21 @@ async def test_write_error_text_handling(self): ) text = utf_8_decode(data, None, True) - await db.test.insert_one({"text": text}) + await db.coll.insert_one({"text": text}) # Should raise DuplicateKeyError, not InvalidBSON with self.assertRaises(DuplicateKeyError): - await db.test.insert_one({"text": text}) + await db.coll.insert_one({"text": text}) with self.assertRaises(DuplicateKeyError): - await db.test.replace_one({"_id": ObjectId()}, {"text": text}, upsert=True) + await db.coll.replace_one({"_id": ObjectId()}, {"text": text}, upsert=True) # Should raise BulkWriteError, not InvalidBSON with self.assertRaises(BulkWriteError): - await db.test.insert_many([{"text": text}]) + await db.coll.insert_many([{"text": text}]) async def test_write_error_unicode(self): - coll = self.db.test + coll = self.db.coll self.addAsyncCleanup(coll.drop) await coll.create_index("a", unique=True) @@ -1293,7 +1293,7 @@ async def test_write_error_unicode(self): async def test_wtimeout(self): # Ensure setting wtimeout doesn't disable write concern altogether. # See SERVER-12596. - collection = self.db.test + collection = self.db.coll await collection.drop() await collection.insert_one({"_id": 1}) @@ -1307,7 +1307,7 @@ async def test_wtimeout(self): async def test_error_code(self): try: - await self.db.test.update_many({}, {"$thismodifierdoesntexist": 1}) + await self.db.coll.update_many({}, {"$thismodifierdoesntexist": 1}) except OperationFailure as exc: self.assertIn(exc.code, (9, 10147, 16840, 17009)) # Just check that we set the error document. Fields @@ -1318,59 +1318,59 @@ async def test_error_code(self): async def test_index_on_subfield(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - await db.test.insert_one({"hello": {"a": 4, "b": 5}}) - await db.test.insert_one({"hello": {"a": 7, "b": 2}}) - await db.test.insert_one({"hello": {"a": 4, "b": 10}}) + await db.coll.insert_one({"hello": {"a": 4, "b": 5}}) + await db.coll.insert_one({"hello": {"a": 7, "b": 2}}) + await db.coll.insert_one({"hello": {"a": 4, "b": 10}}) - await db.drop_collection("test") - await db.test.create_index("hello.a", unique=True) + await db.drop_collection("coll") + await db.coll.create_index("hello.a", unique=True) - await db.test.insert_one({"hello": {"a": 4, "b": 5}}) - await db.test.insert_one({"hello": {"a": 7, "b": 2}}) + await db.coll.insert_one({"hello": {"a": 4, "b": 5}}) + await db.coll.insert_one({"hello": {"a": 7, "b": 2}}) with self.assertRaises(DuplicateKeyError): - await db.test.insert_one({"hello": {"a": 4, "b": 10}}) + await db.coll.insert_one({"hello": {"a": 4, "b": 10}}) async def test_replace_one(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") with self.assertRaises(ValueError): - await db.test.replace_one({}, {"$set": {"x": 1}}) + await db.coll.replace_one({}, {"$set": {"x": 1}}) - id1 = (await db.test.insert_one({"x": 1})).inserted_id - result = await db.test.replace_one({"x": 1}, {"y": 1}) + id1 = (await db.coll.insert_one({"x": 1})).inserted_id + result = await db.coll.replace_one({"x": 1}, {"y": 1}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(1, await db.test.count_documents({"y": 1})) - self.assertEqual(0, await db.test.count_documents({"x": 1})) - self.assertEqual((await db.test.find_one(id1))["y"], 1) # type: ignore + self.assertEqual(1, await db.coll.count_documents({"y": 1})) + self.assertEqual(0, await db.coll.count_documents({"x": 1})) + self.assertEqual((await db.coll.find_one(id1))["y"], 1) # type: ignore replacement = RawBSONDocument(encode({"_id": id1, "z": 1})) - result = await db.test.replace_one({"y": 1}, replacement, True) + result = await db.coll.replace_one({"y": 1}, replacement, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(1, await db.test.count_documents({"z": 1})) - self.assertEqual(0, await db.test.count_documents({"y": 1})) - self.assertEqual((await db.test.find_one(id1))["z"], 1) # type: ignore + self.assertEqual(1, await db.coll.count_documents({"z": 1})) + self.assertEqual(0, await db.coll.count_documents({"y": 1})) + self.assertEqual((await db.coll.find_one(id1))["z"], 1) # type: ignore - result = await db.test.replace_one({"x": 2}, {"y": 2}, True) + result = await db.coll.replace_one({"x": 2}, {"y": 2}, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(0, result.matched_count) self.assertIn(result.modified_count, (None, 0)) self.assertIsInstance(result.upserted_id, ObjectId) self.assertTrue(result.acknowledged) - self.assertEqual(1, await db.test.count_documents({"y": 2})) + self.assertEqual(1, await db.coll.count_documents({"y": 2})) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = await db.test.replace_one({"x": 0}, {"y": 0}) + result = await db.coll.replace_one({"x": 0}, {"y": 0}) self.assertIsInstance(result, UpdateResult) self.assertRaises(InvalidOperation, lambda: result.matched_count) self.assertRaises(InvalidOperation, lambda: result.modified_count) @@ -1379,31 +1379,31 @@ async def test_replace_one(self): async def test_update_one(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") with self.assertRaises(ValueError): - await db.test.update_one({}, {"x": 1}) + await db.coll.update_one({}, {"x": 1}) - id1 = (await db.test.insert_one({"x": 5})).inserted_id - result = await db.test.update_one({}, {"$inc": {"x": 1}}) + id1 = (await db.coll.insert_one({"x": 5})).inserted_id + result = await db.coll.update_one({}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual((await db.test.find_one(id1))["x"], 6) # type: ignore + self.assertEqual((await db.coll.find_one(id1))["x"], 6) # type: ignore - id2 = (await db.test.insert_one({"x": 1})).inserted_id - result = await db.test.update_one({"x": 6}, {"$inc": {"x": 1}}) + id2 = (await db.coll.insert_one({"x": 1})).inserted_id + result = await db.coll.update_one({"x": 6}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual((await db.test.find_one(id1))["x"], 7) # type: ignore - self.assertEqual((await db.test.find_one(id2))["x"], 1) # type: ignore + self.assertEqual((await db.coll.find_one(id1))["x"], 7) # type: ignore + self.assertEqual((await db.coll.find_one(id2))["x"], 1) # type: ignore - result = await db.test.update_one({"x": 2}, {"$set": {"y": 1}}, True) + result = await db.coll.update_one({"x": 2}, {"$set": {"y": 1}}, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(0, result.matched_count) self.assertIn(result.modified_count, (None, 0)) @@ -1411,7 +1411,7 @@ async def test_update_one(self): self.assertTrue(result.acknowledged) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = await db.test.update_one({"x": 0}, {"$inc": {"x": 1}}) + result = await db.coll.update_one({"x": 0}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertRaises(InvalidOperation, lambda: result.matched_count) self.assertRaises(InvalidOperation, lambda: result.modified_count) @@ -1420,45 +1420,45 @@ async def test_update_one(self): async def test_update_result(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - result = await db.test.update_one({"x": 0}, {"$inc": {"x": 1}}, upsert=True) + result = await db.coll.update_one({"x": 0}, {"$inc": {"x": 1}}, upsert=True) self.assertEqual(result.did_upsert, True) - result = await db.test.update_one({"_id": None, "x": 0}, {"$inc": {"x": 1}}, upsert=True) + result = await db.coll.update_one({"_id": None, "x": 0}, {"$inc": {"x": 1}}, upsert=True) self.assertEqual(result.did_upsert, True) - result = await db.test.update_one({"_id": None}, {"$inc": {"x": 1}}) + result = await db.coll.update_one({"_id": None}, {"$inc": {"x": 1}}) self.assertEqual(result.did_upsert, False) async def test_update_many(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") with self.assertRaises(ValueError): - await db.test.update_many({}, {"x": 1}) + await db.coll.update_many({}, {"x": 1}) - await db.test.insert_one({"x": 4, "y": 3}) - await db.test.insert_one({"x": 5, "y": 5}) - await db.test.insert_one({"x": 4, "y": 4}) + await db.coll.insert_one({"x": 4, "y": 3}) + await db.coll.insert_one({"x": 5, "y": 5}) + await db.coll.insert_one({"x": 4, "y": 4}) - result = await db.test.update_many({"x": 4}, {"$set": {"y": 5}}) + result = await db.coll.update_many({"x": 4}, {"$set": {"y": 5}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(2, result.matched_count) self.assertIn(result.modified_count, (None, 2)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(3, await db.test.count_documents({"y": 5})) + self.assertEqual(3, await db.coll.count_documents({"y": 5})) - result = await db.test.update_many({"x": 5}, {"$set": {"y": 6}}) + result = await db.coll.update_many({"x": 5}, {"$set": {"y": 6}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(1, await db.test.count_documents({"y": 6})) + self.assertEqual(1, await db.coll.count_documents({"y": 6})) - result = await db.test.update_many({"x": 2}, {"$set": {"y": 1}}, True) + result = await db.coll.update_many({"x": 2}, {"$set": {"y": 1}}, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(0, result.matched_count) self.assertIn(result.modified_count, (None, 0)) @@ -1466,7 +1466,7 @@ async def test_update_many(self): self.assertTrue(result.acknowledged) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = await db.test.update_many({"x": 0}, {"$inc": {"x": 1}}) + result = await db.coll.update_many({"x": 0}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertRaises(InvalidOperation, lambda: result.matched_count) self.assertRaises(InvalidOperation, lambda: result.modified_count) @@ -1474,12 +1474,12 @@ async def test_update_many(self): self.assertFalse(result.acknowledged) async def test_update_check_keys(self): - await self.db.drop_collection("test") - self.assertTrue(await self.db.test.insert_one({"hello": "world"})) + await self.db.drop_collection("coll") + self.assertTrue(await self.db.coll.insert_one({"hello": "world"})) # Modify shouldn't check keys... self.assertTrue( - await self.db.test.update_one( + await self.db.coll.update_one( {"hello": "world"}, {"$set": {"foo.bar": "baz"}}, upsert=True ) ) @@ -1488,7 +1488,7 @@ async def test_update_check_keys(self): # by CI if the server's behavior changes here. doc = SON([("$set", {"foo.bar": "bim"}), ("hello", "world")]) with self.assertRaises(OperationFailure): - await self.db.test.update_one({"hello": "world"}, doc, upsert=True) + await self.db.coll.update_one({"hello": "world"}, doc, upsert=True) # This is going to cause keys to be checked and raise InvalidDocument. # That's OK assuming the server's behavior in the previous assert @@ -1496,61 +1496,61 @@ async def test_update_check_keys(self): # '$' in update won't be good enough anymore. doc = SON([("hello", "world"), ("$set", {"foo.bar": "bim"})]) with self.assertRaises(OperationFailure): - await self.db.test.replace_one({"hello": "world"}, doc, upsert=True) + await self.db.coll.replace_one({"hello": "world"}, doc, upsert=True) # Replace with empty document self.assertNotEqual( - 0, (await self.db.test.replace_one({"hello": "world"}, {})).matched_count + 0, (await self.db.coll.replace_one({"hello": "world"}, {})).matched_count ) async def test_acknowledged_delete(self): db = self.db - await db.drop_collection("test") - await db.test.insert_many([{"x": 1}, {"x": 1}]) - self.assertEqual(2, (await db.test.delete_many({})).deleted_count) - self.assertEqual(0, (await db.test.delete_many({})).deleted_count) + await db.drop_collection("coll") + await db.coll.insert_many([{"x": 1}, {"x": 1}]) + self.assertEqual(2, (await db.coll.delete_many({})).deleted_count) + self.assertEqual(0, (await db.coll.delete_many({})).deleted_count) @async_client_context.require_version_max(4, 9) async def test_manual_last_error(self): - coll = self.db.get_collection("test", write_concern=WriteConcern(w=0)) + coll = self.db.get_collection("coll", write_concern=WriteConcern(w=0)) await coll.insert_one({"x": 1}) await self.db.command("getlasterror", w=1, wtimeout=1) async def test_count_documents(self): db = self.db - await db.drop_collection("test") - self.addAsyncCleanup(db.drop_collection, "test") + await db.drop_collection("coll") + self.addAsyncCleanup(db.drop_collection, "coll") - self.assertEqual(await db.test.count_documents({}), 0) + self.assertEqual(await db.coll.count_documents({}), 0) await db.wrong.insert_many([{}, {}]) - self.assertEqual(await db.test.count_documents({}), 0) - await db.test.insert_many([{}, {}]) - self.assertEqual(await db.test.count_documents({}), 2) - await db.test.insert_many([{"foo": "bar"}, {"foo": "baz"}]) - self.assertEqual(await db.test.count_documents({"foo": "bar"}), 1) - self.assertEqual(await db.test.count_documents({"foo": re.compile(r"ba.*")}), 2) + self.assertEqual(await db.coll.count_documents({}), 0) + await db.coll.insert_many([{}, {}]) + self.assertEqual(await db.coll.count_documents({}), 2) + await db.coll.insert_many([{"foo": "bar"}, {"foo": "baz"}]) + self.assertEqual(await db.coll.count_documents({"foo": "bar"}), 1) + self.assertEqual(await db.coll.count_documents({"foo": re.compile(r"ba.*")}), 2) async def test_estimated_document_count(self): db = self.db - await db.drop_collection("test") - self.addAsyncCleanup(db.drop_collection, "test") + await db.drop_collection("coll") + self.addAsyncCleanup(db.drop_collection, "coll") - self.assertEqual(await db.test.estimated_document_count(), 0) + self.assertEqual(await db.coll.estimated_document_count(), 0) await db.wrong.insert_many([{}, {}]) - self.assertEqual(await db.test.estimated_document_count(), 0) - await db.test.insert_many([{}, {}]) - self.assertEqual(await db.test.estimated_document_count(), 2) + self.assertEqual(await db.coll.estimated_document_count(), 0) + await db.coll.insert_many([{}, {}]) + self.assertEqual(await db.coll.estimated_document_count(), 2) async def test_aggregate(self): db = self.db - await db.drop_collection("test") - await db.test.insert_one({"foo": [1, 2]}) + await db.drop_collection("coll") + await db.coll.insert_one({"foo": [1, 2]}) with self.assertRaises(TypeError): - await db.test.aggregate("wow") # type: ignore[arg-type] + await db.coll.aggregate("wow") # type: ignore[arg-type] pipeline = {"$project": {"_id": False, "foo": True}} - result = await db.test.aggregate([pipeline]) + result = await db.coll.aggregate([pipeline]) self.assertIsInstance(result, AsyncCommandCursor) self.assertEqual([{"foo": [1, 2]}], await result.to_list()) @@ -1584,14 +1584,14 @@ async def test_aggregate_reserved_options(self): async def test_aggregate_raw_bson(self): db = self.db - await db.drop_collection("test") - await db.test.insert_one({"foo": [1, 2]}) + await db.drop_collection("coll") + await db.coll.insert_one({"foo": [1, 2]}) with self.assertRaises(TypeError): - await db.test.aggregate("wow") # type: ignore[arg-type] + await db.coll.aggregate("wow") # type: ignore[arg-type] pipeline = {"$project": {"_id": False, "foo": True}} - coll = db.get_collection("test", codec_options=CodecOptions(document_class=RawBSONDocument)) + coll = db.get_collection("coll", codec_options=CodecOptions(document_class=RawBSONDocument)) result = await coll.aggregate([pipeline]) self.assertIsInstance(result, AsyncCommandCursor) first_result = await anext(result) @@ -1601,7 +1601,7 @@ async def test_aggregate_raw_bson(self): async def test_aggregation_cursor_validation(self): db = self.db projection = {"$project": {"_id": "$_id"}} - cursor = await db.test.aggregate([projection], cursor={}) + cursor = await db.coll.aggregate([projection], cursor={}) self.assertIsInstance(cursor, AsyncCommandCursor) async def test_aggregation_cursor(self): @@ -1615,16 +1615,16 @@ async def test_aggregation_cursor(self): ) for collection_size in (10, 1000): - await db.drop_collection("test") - await db.test.insert_many([{"_id": i} for i in range(collection_size)]) + await db.drop_collection("coll") + await db.coll.insert_many([{"_id": i} for i in range(collection_size)]) expected_sum = sum(range(collection_size)) # Use batchSize to ensure multiple getMore messages - cursor = await db.test.aggregate([{"$project": {"_id": "$_id"}}], batchSize=5) + cursor = await db.coll.aggregate([{"$project": {"_id": "$_id"}}], batchSize=5) self.assertEqual(expected_sum, sum(doc["_id"] for doc in await cursor.to_list())) # Test that batchSize is handled properly. - cursor = await db.test.aggregate([], batchSize=5) + cursor = await db.coll.aggregate([], batchSize=5) self.assertEqual(5, len(cursor._data)) # Force a getMore cursor._data.clear() @@ -1636,10 +1636,10 @@ async def test_aggregation_cursor(self): pass async def test_aggregation_cursor_alive(self): - await self.db.test.delete_many({}) - await self.db.test.insert_many([{} for _ in range(3)]) - self.addAsyncCleanup(self.db.test.delete_many, {}) - cursor = await self.db.test.aggregate(pipeline=[], cursor={"batchSize": 2}) + await self.db.coll.delete_many({}) + await self.db.coll.insert_many([{} for _ in range(3)]) + self.addAsyncCleanup(self.db.coll.delete_many, {}) + cursor = await self.db.coll.aggregate(pipeline=[], cursor={"batchSize": 2}) n = 0 while True: await cursor.next() @@ -1652,7 +1652,7 @@ async def test_aggregation_cursor_alive(self): async def test_invalid_session_parameter(self): async def try_invalid_session(): - with await self.db.test.aggregate([], {}): # type:ignore + with await self.db.coll.aggregate([], {}): # type:ignore pass with self.assertRaisesRegex(ValueError, "must be an AsyncClientSession"): @@ -1677,45 +1677,45 @@ async def test_large_limit(self): async def test_find_kwargs(self): db = self.db - await db.drop_collection("test") - await db.test.insert_many({"x": i} for i in range(10)) + await db.drop_collection("coll") + await db.coll.insert_many({"x": i} for i in range(10)) - self.assertEqual(10, await db.test.count_documents({})) + self.assertEqual(10, await db.coll.count_documents({})) total = 0 - async for x in db.test.find({}, skip=4, limit=2): + async for x in db.coll.find({}, skip=4, limit=2): total += x["x"] self.assertEqual(9, total) async def test_rename(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") await db.drop_collection("foo") with self.assertRaises(TypeError): - await db.test.rename(5) # type: ignore[arg-type] + await db.coll.rename(5) # type: ignore[arg-type] with self.assertRaises(InvalidName): - await db.test.rename("") + await db.coll.rename("") with self.assertRaises(InvalidName): - await db.test.rename("te$t") + await db.coll.rename("te$t") with self.assertRaises(InvalidName): - await db.test.rename(".test") + await db.coll.rename(".test") with self.assertRaises(InvalidName): - await db.test.rename("test.") + await db.coll.rename("test.") with self.assertRaises(InvalidName): - await db.test.rename("tes..t") + await db.coll.rename("tes..t") - self.assertEqual(0, await db.test.count_documents({})) + self.assertEqual(0, await db.coll.count_documents({})) self.assertEqual(0, await db.foo.count_documents({})) - await db.test.insert_many({"x": i} for i in range(10)) + await db.coll.insert_many({"x": i} for i in range(10)) - self.assertEqual(10, await db.test.count_documents({})) + self.assertEqual(10, await db.coll.count_documents({})) - await db.test.rename("foo") + await db.coll.rename("foo") - self.assertEqual(0, await db.test.count_documents({})) + self.assertEqual(0, await db.coll.count_documents({})) self.assertEqual(10, await db.foo.count_documents({})) x = 0 @@ -1723,10 +1723,10 @@ async def test_rename(self): self.assertEqual(x, doc["x"]) x += 1 - await db.test.insert_one({}) + await db.coll.insert_one({}) with self.assertRaises(OperationFailure): - await db.foo.rename("test") - await db.foo.rename("test", dropTarget=True) + await db.foo.rename("coll") + await db.foo.rename("coll", dropTarget=True) with self.write_concern_collection() as coll: await coll.rename("foo") @@ -1734,81 +1734,81 @@ async def test_rename(self): @no_type_check async def test_find_one(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - _id = (await db.test.insert_one({"hello": "world", "foo": "bar"})).inserted_id + _id = (await db.coll.insert_one({"hello": "world", "foo": "bar"})).inserted_id - self.assertEqual("world", (await db.test.find_one())["hello"]) - self.assertEqual(await db.test.find_one(_id), await db.test.find_one()) - self.assertEqual(await db.test.find_one(None), await db.test.find_one()) - self.assertEqual(await db.test.find_one({}), await db.test.find_one()) - self.assertEqual(await db.test.find_one({"hello": "world"}), await db.test.find_one()) + self.assertEqual("world", (await db.coll.find_one())["hello"]) + self.assertEqual(await db.coll.find_one(_id), await db.coll.find_one()) + self.assertEqual(await db.coll.find_one(None), await db.coll.find_one()) + self.assertEqual(await db.coll.find_one({}), await db.coll.find_one()) + self.assertEqual(await db.coll.find_one({"hello": "world"}), await db.coll.find_one()) - self.assertIn("hello", await db.test.find_one(projection=["hello"])) - self.assertNotIn("hello", await db.test.find_one(projection=["foo"])) + self.assertIn("hello", await db.coll.find_one(projection=["hello"])) + self.assertNotIn("hello", await db.coll.find_one(projection=["foo"])) - self.assertIn("hello", await db.test.find_one(projection=("hello",))) - self.assertNotIn("hello", await db.test.find_one(projection=("foo",))) + self.assertIn("hello", await db.coll.find_one(projection=("hello",))) + self.assertNotIn("hello", await db.coll.find_one(projection=("foo",))) - self.assertIn("hello", await db.test.find_one(projection={"hello"})) - self.assertNotIn("hello", await db.test.find_one(projection={"foo"})) + self.assertIn("hello", await db.coll.find_one(projection={"hello"})) + self.assertNotIn("hello", await db.coll.find_one(projection={"foo"})) - self.assertIn("hello", await db.test.find_one(projection=frozenset(["hello"]))) - self.assertNotIn("hello", await db.test.find_one(projection=frozenset(["foo"]))) + self.assertIn("hello", await db.coll.find_one(projection=frozenset(["hello"]))) + self.assertNotIn("hello", await db.coll.find_one(projection=frozenset(["foo"]))) - self.assertEqual(["_id"], list(await db.test.find_one(projection={"_id": True}))) - self.assertIn("hello", list(await db.test.find_one(projection={}))) - self.assertIn("hello", list(await db.test.find_one(projection=[]))) + self.assertEqual(["_id"], list(await db.coll.find_one(projection={"_id": True}))) + self.assertIn("hello", list(await db.coll.find_one(projection={}))) + self.assertIn("hello", list(await db.coll.find_one(projection=[]))) - self.assertEqual(None, await db.test.find_one({"hello": "foo"})) - self.assertEqual(None, await db.test.find_one(ObjectId())) + self.assertEqual(None, await db.coll.find_one({"hello": "foo"})) + self.assertEqual(None, await db.coll.find_one(ObjectId())) async def test_find_one_non_objectid(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - await db.test.insert_one({"_id": 5}) + await db.coll.insert_one({"_id": 5}) - self.assertTrue(await db.test.find_one(5)) - self.assertFalse(await db.test.find_one(6)) + self.assertTrue(await db.coll.find_one(5)) + self.assertFalse(await db.coll.find_one(6)) async def test_find_one_with_find_args(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - await db.test.insert_many([{"x": i} for i in range(1, 4)]) + await db.coll.insert_many([{"x": i} for i in range(1, 4)]) - self.assertEqual(1, (await db.test.find_one())["x"]) - self.assertEqual(2, (await db.test.find_one(skip=1, limit=2))["x"]) + self.assertEqual(1, (await db.coll.find_one())["x"]) + self.assertEqual(2, (await db.coll.find_one(skip=1, limit=2))["x"]) async def test_find_with_sort(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") - await db.test.insert_many([{"x": 2}, {"x": 1}, {"x": 3}]) + await db.coll.insert_many([{"x": 2}, {"x": 1}, {"x": 3}]) - self.assertEqual(2, (await db.test.find_one())["x"]) - self.assertEqual(1, (await db.test.find_one(sort=[("x", 1)]))["x"]) - self.assertEqual(3, (await db.test.find_one(sort=[("x", -1)]))["x"]) + self.assertEqual(2, (await db.coll.find_one())["x"]) + self.assertEqual(1, (await db.coll.find_one(sort=[("x", 1)]))["x"]) + self.assertEqual(3, (await db.coll.find_one(sort=[("x", -1)]))["x"]) async def to_list(things): return [thing["x"] async for thing in things] - self.assertEqual([2, 1, 3], await to_list(db.test.find())) - self.assertEqual([1, 2, 3], await to_list(db.test.find(sort=[("x", 1)]))) - self.assertEqual([3, 2, 1], await to_list(db.test.find(sort=[("x", -1)]))) + self.assertEqual([2, 1, 3], await to_list(db.coll.find())) + self.assertEqual([1, 2, 3], await to_list(db.coll.find(sort=[("x", 1)]))) + self.assertEqual([3, 2, 1], await to_list(db.coll.find(sort=[("x", -1)]))) with self.assertRaises(TypeError): - await db.test.find(sort=5) + await db.coll.find(sort=5) with self.assertRaises(TypeError): - await db.test.find(sort="hello") + await db.coll.find(sort="hello") with self.assertRaises(TypeError): - await db.test.find(sort=["hello", 1]) + await db.coll.find(sort=["hello", 1]) # TODO doesn't actually test functionality, just that it doesn't blow up async def test_cursor_timeout(self): - await self.db.test.find(no_cursor_timeout=True).to_list() - await self.db.test.find(no_cursor_timeout=False).to_list() + await self.db.coll.find(no_cursor_timeout=True).to_list() + await self.db.coll.find(no_cursor_timeout=False).to_list() async def test_exhaust_limit_raises_without_iterating(self): # The limit conflict is settled at find(); the mongos wire version is not. @@ -1820,33 +1820,33 @@ async def test_exhaust(self): # mongos only serves exhaust cursors from 7.1 onwards (SERVER-57297). if not async_client_context.supports_exhaust_cursors(): with self.assertRaises(InvalidOperation): - await anext(self.db.test.find(cursor_type=CursorType.EXHAUST)) + await anext(self.db.coll.find(cursor_type=CursorType.EXHAUST)) return # Limit is incompatible with exhaust. with self.assertRaises(InvalidOperation): - await anext(self.db.test.find(cursor_type=CursorType.EXHAUST, limit=5)) - cur = self.db.test.find(cursor_type=CursorType.EXHAUST) + await anext(self.db.coll.find(cursor_type=CursorType.EXHAUST, limit=5)) + cur = self.db.coll.find(cursor_type=CursorType.EXHAUST) with self.assertRaises(InvalidOperation): cur.limit(5) await cur.next() - cur = self.db.test.find(limit=5) + cur = self.db.coll.find(limit=5) with self.assertRaises(InvalidOperation): await cur.add_option(64) - cur = self.db.test.find() + cur = self.db.coll.find() await cur.add_option(64) with self.assertRaises(InvalidOperation): cur.limit(5) - await self.db.drop_collection("test") + await self.db.drop_collection("coll") # Insert enough documents to require more than one batch - await self.db.test.insert_many([{"i": i} for i in range(150)]) + await self.db.coll.insert_many([{"i": i} for i in range(150)]) client = await self.async_rs_or_single_client(maxPoolSize=1) pool = await async_get_pool(client) # Make sure the socket is returned after exhaustion. - cur = client[self.db.name].test.find(cursor_type=CursorType.EXHAUST) + cur = client[self.db.name].coll.find(cursor_type=CursorType.EXHAUST) await anext(cur) self.assertEqual(0, len(pool.conns)) async for _ in cur: @@ -1854,14 +1854,14 @@ async def test_exhaust(self): self.assertEqual(1, len(pool.conns)) # Same as previous but don't call next() - async for _ in client[self.db.name].test.find(cursor_type=CursorType.EXHAUST): + async for _ in client[self.db.name].coll.find(cursor_type=CursorType.EXHAUST): pass self.assertEqual(1, len(pool.conns)) # If the Cursor instance is discarded before being completely iterated # and the socket has pending data (more_to_come=True) we have to close # and discard the socket. - cur = client[self.db.name].test.find(cursor_type=CursorType.EXHAUST, batch_size=2) + cur = client[self.db.name].coll.find(cursor_type=CursorType.EXHAUST, batch_size=2) # OP_MSG only sets more_to_come=True after the first getMore. for _ in range(3): await anext(cur) @@ -1876,9 +1876,9 @@ async def test_exhaust(self): self.assertEqual(0, len(pool.conns)) async def test_distinct(self): - await self.db.drop_collection("test") + await self.db.drop_collection("coll") - test = self.db.test + test = self.db.coll await test.insert_many([{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}]) distinct = await test.distinct("a") @@ -1894,7 +1894,7 @@ async def test_distinct(self): distinct.sort() self.assertEqual([2, 3], distinct) - await self.db.drop_collection("test") + await self.db.drop_collection("coll") await test.insert_one({"a": {"b": "a"}, "c": 12}) await test.insert_one({"a": {"b": "b"}, "c": 12}) @@ -1907,19 +1907,19 @@ async def test_distinct(self): self.assertEqual(["a", "b", "c"], distinct) async def test_query_on_query_field(self): - await self.db.drop_collection("test") - await self.db.test.insert_one({"query": "foo"}) - await self.db.test.insert_one({"bar": "foo"}) + await self.db.drop_collection("coll") + await self.db.coll.insert_one({"query": "foo"}) + await self.db.coll.insert_one({"bar": "foo"}) - self.assertEqual(1, await self.db.test.count_documents({"query": {"$ne": None}})) - self.assertEqual(1, len(await self.db.test.find({"query": {"$ne": None}}).to_list())) + self.assertEqual(1, await self.db.coll.count_documents({"query": {"$ne": None}})) + self.assertEqual(1, len(await self.db.coll.find({"query": {"$ne": None}}).to_list())) async def test_min_query(self): - await self.db.drop_collection("test") - await self.db.test.insert_many([{"x": 1}, {"x": 2}]) - await self.db.test.create_index("x") + await self.db.drop_collection("coll") + await self.db.coll.insert_many([{"x": 1}, {"x": 2}]) + await self.db.coll.create_index("x") - cursor = self.db.test.find({"$min": {"x": 2}, "$query": {}}, hint="x_1") + cursor = self.db.coll.find({"$min": {"x": 2}, "$query": {}}, hint="x_1") docs = await cursor.to_list() self.assertEqual(1, len(docs)) @@ -1927,11 +1927,11 @@ async def test_min_query(self): async def test_numerous_inserts(self): # Ensure we don't exceed server's maxWriteBatchSize size limit. - await self.db.test.drop() + await self.db.coll.drop() n_docs = await async_client_context.max_write_batch_size + 100 - await self.db.test.insert_many([{} for _ in range(n_docs)]) - self.assertEqual(n_docs, await self.db.test.count_documents({})) - await self.db.test.drop() + await self.db.coll.insert_many([{} for _ in range(n_docs)]) + self.assertEqual(n_docs, await self.db.coll.count_documents({})) + await self.db.coll.drop() async def test_insert_many_large_batch(self): # Tests legacy insert. @@ -2020,13 +2020,13 @@ async def test_messages_with_unicode_collection_names(self): await db["Employés"].find().to_list() async def test_drop_indexes_non_existent(self): - await self.db.drop_collection("test") - await self.db.test.drop_indexes() + await self.db.drop_collection("coll") + await self.db.coll.drop_indexes() # This is really a bson test but easier to just reproduce it here... # (Shame on me) async def test_bad_encode(self): - c = self.db.test + c = self.db.coll await c.drop() with self.assertRaises(InvalidDocument): await c.insert_one({"x": c}) @@ -2041,7 +2041,7 @@ def __getattr__(self, name): async def test_array_filters_validation(self): # array_filters must be a list. - c = self.db.test + c = self.db.coll with self.assertRaises(TypeError): await c.update_one({}, {"$set": {"a": 1}}, array_filters={}) # type: ignore[arg-type] with self.assertRaises(TypeError): @@ -2051,7 +2051,7 @@ async def test_array_filters_validation(self): await c.find_one_and_update({}, update, array_filters={}) # type: ignore[arg-type] async def test_array_filters_unacknowledged(self): - c_w0 = self.db.test.with_options(write_concern=WriteConcern(w=0)) + c_w0 = self.db.coll.with_options(write_concern=WriteConcern(w=0)) with self.assertRaises(ConfigurationError): await c_w0.update_one({}, {"$set": {"y.$[i].b": 5}}, array_filters=[{"i.b": 1}]) with self.assertRaises(ConfigurationError): @@ -2062,7 +2062,7 @@ async def test_array_filters_unacknowledged(self): ) async def test_find_one_and(self): - c = self.db.test + c = self.db.coll await c.drop() await c.insert_one({"_id": 1, "i": 1}) @@ -2120,9 +2120,9 @@ async def test_find_one_and_write_concern(self): listener = OvertCommandListener() db = (await self.async_single_client(event_listeners=[listener]))[self.db.name] # non-default WriteConcern. - c_w0 = db.get_collection("test", write_concern=WriteConcern(w=0)) + c_w0 = db.get_collection("coll", write_concern=WriteConcern(w=0)) # default WriteConcern. - c_default = db.get_collection("test", write_concern=WriteConcern()) + c_default = db.get_collection("coll", write_concern=WriteConcern()) # Authenticate the client and throw out auth commands from the listener. await db.command("ping") listener.reset() @@ -2168,7 +2168,7 @@ async def test_find_one_and_write_concern(self): listener.reset() async def test_find_with_nested(self): - c = self.db.test + c = self.db.coll await c.drop() await c.insert_many([{"i": i} for i in range(5)]) # [0, 1, 2, 3, 4] self.assertEqual( @@ -2226,7 +2226,7 @@ async def test_find_with_nested(self): ) async def test_find_regex(self): - c = self.db.test + c = self.db.coll await c.drop() await c.insert_one({"r": re.compile(".*")}) @@ -2255,7 +2255,7 @@ def test_bool(self): @async_client_context.require_version_min(5, 0, 0) async def test_helpers_with_let(self): - c = self.db.test + c = self.db.coll async def afind(*args, **kwargs): return c.find(*args, **kwargs) diff --git a/test/asynchronous/test_comment.py b/test/asynchronous/test_comment.py index 09c57891a7..c681170482 100644 --- a/test/asynchronous/test_comment.py +++ b/test/asynchronous/test_comment.py @@ -118,7 +118,7 @@ async def test_client_helpers(self): async def test_collection_helpers(self): listener = OvertCommandListener() db = (await self.async_rs_or_single_client(event_listeners=[listener]))[self.db.name] - coll = db.get_collection("test") + coll = db.get_collection("coll") helpers = [ (coll.list_indexes, []), diff --git a/test/asynchronous/test_common.py b/test/asynchronous/test_common.py index 8440ca98dc..07287dd624 100644 --- a/test/asynchronous/test_common.py +++ b/test/asynchronous/test_common.py @@ -124,11 +124,11 @@ async def test_write_concern(self): db = c.pymongo_test self.assertEqual(wc, db.write_concern) - coll = db.test + coll = db.coll self.assertEqual(wc, coll.write_concern) cwc = WriteConcern(j=True) - coll = db.get_collection("test", write_concern=cwc) + coll = db.get_collection("coll", write_concern=cwc) self.assertEqual(cwc, coll.write_concern) self.assertEqual(wc, db.write_concern) @@ -174,11 +174,12 @@ async def test_mongo_client(self): self.assertFalse(direct != direct2) async def test_validate_boolean(self): - await self.db.test.update_one({}, {"$set": {"total": 1}}, upsert=True) + self.addAsyncCleanup(self.db.coll.drop) + await self.db.coll.update_one({}, {"$set": {"total": 1}}, upsert=True) with self.assertRaisesRegex( TypeError, "upsert must be True or False, was: upsert={'upsert': True}" ): - await self.db.test.update_one({}, {"$set": {"total": 1}}, {"upsert": True}) # type: ignore + await self.db.coll.update_one({}, {"$set": {"total": 1}}, {"upsert": True}) # type: ignore if __name__ == "__main__": diff --git a/test/asynchronous/test_concurrency.py b/test/asynchronous/test_concurrency.py index d2e66762a9..a3588d6848 100644 --- a/test/asynchronous/test_concurrency.py +++ b/test/asynchronous/test_concurrency.py @@ -30,7 +30,7 @@ class TestAsyncConcurrency(AsyncIntegrationTest): async def _task(self, client): - await client.db.test.find_one({"$where": delay(0.20)}) + await client.db.coll.find_one({"$where": delay(0.20)}) @unittest.skipIf( sys.platform == "darwin" and "CI" in os.environ, @@ -41,8 +41,8 @@ async def test_concurrency(self): iterations = 5 client = await self.async_single_client() - await client.db.test.drop() - await client.db.test.insert_one({"x": 1}) + await client.db.coll.drop() + await client.db.coll.insert_one({"x": 1}) start = time.time() diff --git a/test/asynchronous/test_csot.py b/test/asynchronous/test_csot.py index 2566c141fb..065543182f 100644 --- a/test/asynchronous/test_csot.py +++ b/test/asynchronous/test_csot.py @@ -78,7 +78,8 @@ async def test_timeout_nested(self): @async_client_context.require_change_streams @flaky(reason="PYTHON-3522") async def test_change_stream_can_resume_after_timeouts(self): - coll = self.db.test + self.addAsyncCleanup(self.db.coll.drop) + coll = self.db.coll await coll.insert_one({}) async with await coll.watch() as stream: with pymongo.timeout(0.1): diff --git a/test/asynchronous/test_cursor.py b/test/asynchronous/test_cursor.py index f8fbac8032..364f4eb946 100644 --- a/test/asynchronous/test_cursor.py +++ b/test/asynchronous/test_cursor.py @@ -60,7 +60,7 @@ class TestCursor(AsyncIntegrationTest): async def test_deepcopy_cursor_littered_with_regexes(self): - cursor = self.db.test.find( + cursor = self.db.coll.find( { "x": re.compile("^hmmm.*"), "y": [re.compile("^hmm.*")], @@ -73,18 +73,18 @@ async def test_deepcopy_cursor_littered_with_regexes(self): self.assertEqual(cursor._spec, cursor2._spec) async def test_add_remove_option(self): - cursor = self.db.test.find() + cursor = self.db.coll.find() self.assertEqual(0, cursor._query_flags) await cursor.add_option(2) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE) self.assertEqual(2, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) await cursor.add_option(32) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT) self.assertEqual(34, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) await cursor.add_option(128) - cursor2 = await self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT).add_option(128) + cursor2 = await self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT).add_option(128) self.assertEqual(162, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) @@ -93,11 +93,11 @@ async def test_add_remove_option(self): self.assertEqual(162, cursor._query_flags) cursor.remove_option(128) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT) self.assertEqual(34, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(32) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE) self.assertEqual(2, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) @@ -106,25 +106,25 @@ async def test_add_remove_option(self): self.assertEqual(2, cursor._query_flags) # Timeout - cursor = self.db.test.find(no_cursor_timeout=True) + cursor = self.db.coll.find(no_cursor_timeout=True) self.assertEqual(16, cursor._query_flags) - cursor2 = await self.db.test.find().add_option(16) + cursor2 = await self.db.coll.find().add_option(16) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(16) self.assertEqual(0, cursor._query_flags) # Tailable / Await data - cursor = self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT) + cursor = self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT) self.assertEqual(34, cursor._query_flags) - cursor2 = await self.db.test.find().add_option(34) + cursor2 = await self.db.coll.find().add_option(34) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(32) self.assertEqual(2, cursor._query_flags) # Partial - cursor = self.db.test.find(allow_partial_results=True) + cursor = self.db.coll.find(allow_partial_results=True) self.assertEqual(128, cursor._query_flags) - cursor2 = await self.db.test.find().add_option(128) + cursor2 = await self.db.coll.find().add_option(128) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(128) self.assertEqual(0, cursor._query_flags) @@ -133,11 +133,11 @@ async def test_add_remove_option_exhaust(self): # mongos only serves exhaust cursors from 7.1 onwards (SERVER-57297). if not async_client_context.supports_exhaust_cursors(): with self.assertRaises(InvalidOperation): - await anext(self.db.test.find(cursor_type=CursorType.EXHAUST)) + await anext(self.db.coll.find(cursor_type=CursorType.EXHAUST)) else: - cursor = self.db.test.find(cursor_type=CursorType.EXHAUST) + cursor = self.db.coll.find(cursor_type=CursorType.EXHAUST) self.assertEqual(64, cursor._query_flags) - cursor2 = await self.db.test.find().add_option(64) + cursor2 = await self.db.coll.find().add_option(64) self.assertEqual(cursor._query_flags, cursor2._query_flags) self.assertTrue(cursor._exhaust) cursor.remove_option(64) @@ -146,8 +146,8 @@ async def test_add_remove_option_exhaust(self): async def test_allow_disk_use(self): db = self.db - await db.pymongo_test.drop() - coll = db.pymongo_test + await db.coll.drop() + coll = db.coll with self.assertRaises(TypeError): coll.find().allow_disk_use("baz") # type: ignore[arg-type] @@ -159,8 +159,8 @@ async def test_allow_disk_use(self): async def test_max_time_ms(self): db = self.db - await db.pymongo_test.drop() - coll = db.pymongo_test + await db.coll.drop() + coll = db.coll with self.assertRaises(TypeError): coll.find().max_time_ms("foo") # type: ignore[arg-type] await coll.insert_one({"amalia": 1}) @@ -214,17 +214,17 @@ async def test_maxtime_ms_message(self): self.assertIn("(configured timeouts: connectTimeoutMS: 20000.0ms", str(error.exception)) client = await self.async_rs_client(document_class=RawBSONDocument) - await client.db.t.insert_one({"x": 1}) + await client.db.coll.insert_one({"x": 1}) with self.assertRaises(OperationFailure) as error: - await client.db.t.find_one({"$where": delay(2)}, max_time_ms=1) + await client.db.coll.find_one({"$where": delay(2)}, max_time_ms=1) if isinstance(error.exception, ExecutionTimeout): self.assertIn("(configured timeouts: connectTimeoutMS: 20000.0ms", str(error.exception)) async def test_max_await_time_ms(self): db = self.db - await db.pymongo_test.drop() - coll = await db.create_collection("pymongo_test", capped=True, size=4096) + await db.coll.drop() + coll = await db.create_collection("coll", capped=True, size=4096) with self.assertRaises(TypeError): coll.find().max_await_time_ms("foo") # type: ignore[arg-type] @@ -256,9 +256,7 @@ async def test_max_await_time_ms(self): self.assertEqual(90, cursor._max_await_time_ms) listener = AllowListEventListener("find", "getMore") - coll = (await self.async_rs_or_single_client(event_listeners=[listener]))[ - self.db.name - ].pymongo_test + coll = (await self.async_rs_or_single_client(event_listeners=[listener])).pymongo_test.coll # Tailable_await defaults. await coll.find(cursor_type=CursorType.TAILABLE_AWAIT).to_list() @@ -344,7 +342,7 @@ async def test_max_await_time_ms(self): @async_client_context.require_no_mongos async def test_max_time_ms_getmore(self): # Test that Cursor handles server timeout error in response to getmore. - coll = self.db.pymongo_test + coll = self.db.coll await coll.insert_many([{} for _ in range(200)]) cursor = coll.find().max_time_ms(100) @@ -367,7 +365,7 @@ async def test_max_time_ms_getmore(self): ) async def test_explain(self): - a = self.db.test.find() + a = self.db.coll.find() await a.explain() async for _ in a: break @@ -378,7 +376,7 @@ async def test_explain_with_read_concern(self): # Do not add readConcern level to explain. listener = AllowListEventListener("explain") client = await self.async_rs_or_single_client(event_listeners=[listener]) - coll = client.pymongo_test.test.with_options(read_concern=ReadConcern(level="local")) + coll = client.pymongo_test.coll.with_options(read_concern=ReadConcern(level="local")) self.assertTrue(await coll.find().explain()) started = listener.started_events self.assertEqual(len(started), 1) @@ -410,104 +408,104 @@ async def test_explain_csot(self): async def test_hint(self): db = self.db with self.assertRaises(TypeError): - db.test.find().hint(5.5) # type: ignore[arg-type] - await db.test.drop() + db.coll.find().hint(5.5) # type: ignore[arg-type] + await db.coll.drop() - await db.test.insert_many([{"num": i, "foo": i} for i in range(100)]) + await db.coll.insert_many([{"num": i, "foo": i} for i in range(100)]) with self.assertRaises(OperationFailure): - await db.test.find({"num": 17, "foo": 17}).hint([("num", ASCENDING)]).explain() + await db.coll.find({"num": 17, "foo": 17}).hint([("num", ASCENDING)]).explain() with self.assertRaises(OperationFailure): - await db.test.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() + await db.coll.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() spec: list[Any] = [("num", DESCENDING)] - _ = await db.test.create_index(spec) + _ = await db.coll.create_index(spec) - first = await anext(db.test.find()) + first = await anext(db.coll.find()) self.assertEqual(0, first.get("num")) - first = await anext(db.test.find().hint(spec)) + first = await anext(db.coll.find().hint(spec)) self.assertEqual(99, first.get("num")) with self.assertRaises(OperationFailure): - await db.test.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() + await db.coll.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() - a = db.test.find({"num": 17}) + a = db.coll.find({"num": 17}) a.hint(spec) async for _ in a: break self.assertRaises(InvalidOperation, a.hint, spec) - await db.test.drop() - await db.test.insert_many([{"num": i, "foo": i} for i in range(100)]) + await db.coll.drop() + await db.coll.insert_many([{"num": i, "foo": i} for i in range(100)]) spec: _IndexList = ["num", ("foo", DESCENDING)] - await db.test.create_index(spec) - first = await anext(db.test.find().hint(spec)) + await db.coll.create_index(spec) + first = await anext(db.coll.find().hint(spec)) self.assertEqual(0, first.get("num")) self.assertEqual(0, first.get("foo")) - await db.test.drop() - await db.test.insert_many([{"num": i, "foo": i} for i in range(100)]) + await db.coll.drop() + await db.coll.insert_many([{"num": i, "foo": i} for i in range(100)]) spec = ["num"] - await db.test.create_index(spec) - first = await anext(db.test.find().hint(spec)) + await db.coll.create_index(spec) + first = await anext(db.coll.find().hint(spec)) self.assertEqual(0, first.get("num")) async def test_hint_by_name(self): db = self.db - await db.test.drop() + await db.coll.drop() - await db.test.insert_many([{"i": i} for i in range(100)]) + await db.coll.insert_many([{"i": i} for i in range(100)]) - await db.test.create_index([("i", DESCENDING)], name="fooindex") - first = await anext(db.test.find()) + await db.coll.create_index([("i", DESCENDING)], name="fooindex") + first = await anext(db.coll.find()) self.assertEqual(0, first.get("i")) - first = await anext(db.test.find().hint("fooindex")) + first = await anext(db.coll.find().hint("fooindex")) self.assertEqual(99, first.get("i")) async def test_limit(self): db = self.db with self.assertRaises(TypeError): - db.test.find().limit(None) # type: ignore[arg-type] + db.coll.find().limit(None) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().limit("hello") # type: ignore[arg-type] + db.coll.find().limit("hello") # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().limit(5.5) # type: ignore[arg-type] - self.assertTrue((db.test.find()).limit(5)) + db.coll.find().limit(5.5) # type: ignore[arg-type] + self.assertTrue((db.coll.find()).limit(5)) - await db.test.drop() - await db.test.insert_many([{"x": i} for i in range(100)]) + await db.coll.drop() + await db.coll.insert_many([{"x": i} for i in range(100)]) count = 0 - async for _ in db.test.find(): + async for _ in db.coll.find(): count += 1 self.assertEqual(count, 100) count = 0 - async for _ in db.test.find().limit(20): + async for _ in db.coll.find().limit(20): count += 1 self.assertEqual(count, 20) count = 0 - async for _ in db.test.find().limit(99): + async for _ in db.coll.find().limit(99): count += 1 self.assertEqual(count, 99) count = 0 - async for _ in db.test.find().limit(1): + async for _ in db.coll.find().limit(1): count += 1 self.assertEqual(count, 1) count = 0 - async for _ in db.test.find().limit(0): + async for _ in db.coll.find().limit(0): count += 1 self.assertEqual(count, 100) count = 0 - async for _ in db.test.find().limit(0).limit(50).limit(10): + async for _ in db.coll.find().limit(0).limit(50).limit(10): count += 1 self.assertEqual(count, 10) - a = db.test.find() + a = db.coll.find() a.limit(10) async for _ in a: break @@ -516,14 +514,14 @@ async def test_limit(self): async def test_max(self): db = self.db - await db.test.drop() + await db.coll.drop() j_index = [("j", ASCENDING)] - await db.test.create_index(j_index) + await db.coll.create_index(j_index) - await db.test.insert_many([{"j": j, "k": j} for j in range(10)]) + await db.coll.insert_many([{"j": j, "k": j} for j in range(10)]) def find(max_spec, expected_index): - return db.test.find().max(max_spec).hint(expected_index) + return db.coll.find().max(max_spec).hint(expected_index) cursor = find([("j", 3)], j_index) self.assertEqual(len(await cursor.to_list()), 3) @@ -534,7 +532,7 @@ def find(max_spec, expected_index): # Compound index. index_keys = [("j", ASCENDING), ("k", ASCENDING)] - await db.test.create_index(index_keys) + await db.coll.create_index(index_keys) cursor = find([("j", 3), ("k", 3)], index_keys) self.assertEqual(len(await cursor.to_list()), 3) @@ -548,20 +546,20 @@ def find(max_spec, expected_index): with self.assertRaises(OperationFailure): await cursor.to_list() with self.assertRaises(TypeError): - db.test.find().max(10) # type: ignore[arg-type] + db.coll.find().max(10) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().max({"j": 10}) # type: ignore[arg-type] + db.coll.find().max({"j": 10}) # type: ignore[arg-type] async def test_min(self): db = self.db - await db.test.drop() + await db.coll.drop() j_index = [("j", ASCENDING)] - await db.test.create_index(j_index) + await db.coll.create_index(j_index) - await db.test.insert_many([{"j": j, "k": j} for j in range(10)]) + await db.coll.insert_many([{"j": j, "k": j} for j in range(10)]) def find(min_spec, expected_index): - return db.test.find().min(min_spec).hint(expected_index) + return db.coll.find().min(min_spec).hint(expected_index) cursor = find([("j", 3)], j_index) self.assertEqual(len(await cursor.to_list()), 7) @@ -572,7 +570,7 @@ def find(min_spec, expected_index): # Compound index. index_keys = [("j", ASCENDING), ("k", ASCENDING)] - await db.test.create_index(index_keys) + await db.coll.create_index(index_keys) cursor = find([("j", 3), ("k", 3)], index_keys) self.assertEqual(len(await cursor.to_list()), 7) @@ -587,12 +585,12 @@ def find(min_spec, expected_index): await cursor.to_list() with self.assertRaises(TypeError): - db.test.find().min(10) # type: ignore[arg-type] + db.coll.find().min(10) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().min({"j": 10}) # type: ignore[arg-type] + db.coll.find().min({"j": 10}) # type: ignore[arg-type] async def test_min_max_without_hint(self): - coll = self.db.test + coll = self.db.coll j_index = [("j", ASCENDING)] await coll.create_index(j_index) @@ -603,19 +601,19 @@ async def test_min_max_without_hint(self): async def test_batch_size(self): db = self.db - await db.test.drop() - await db.test.insert_many([{"x": x} for x in range(200)]) + await db.coll.drop() + await db.coll.insert_many([{"x": x} for x in range(200)]) with self.assertRaises(TypeError): - db.test.find().batch_size(None) # type: ignore[arg-type] + db.coll.find().batch_size(None) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().batch_size("hello") # type: ignore[arg-type] + db.coll.find().batch_size("hello") # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().batch_size(5.5) # type: ignore[arg-type] + db.coll.find().batch_size(5.5) # type: ignore[arg-type] with self.assertRaises(ValueError): - db.test.find().batch_size(-1) - self.assertTrue((db.test.find()).batch_size(5)) - a = db.test.find() + db.coll.find().batch_size(-1) + self.assertTrue((db.coll.find()).batch_size(5)) + a = db.coll.find() async for _ in a: break self.assertRaises(InvalidOperation, a.batch_size, 5) @@ -626,28 +624,28 @@ async def cursor_count(cursor, expected_count): count += 1 self.assertEqual(expected_count, count) - await cursor_count((db.test.find()).batch_size(0), 200) - await cursor_count((db.test.find()).batch_size(1), 200) - await cursor_count((db.test.find()).batch_size(2), 200) - await cursor_count((db.test.find()).batch_size(5), 200) - await cursor_count((db.test.find()).batch_size(100), 200) - await cursor_count((db.test.find()).batch_size(500), 200) - - await cursor_count((db.test.find()).batch_size(0).limit(1), 1) - await cursor_count((db.test.find()).batch_size(1).limit(1), 1) - await cursor_count((db.test.find()).batch_size(2).limit(1), 1) - await cursor_count((db.test.find()).batch_size(5).limit(1), 1) - await cursor_count((db.test.find()).batch_size(100).limit(1), 1) - await cursor_count((db.test.find()).batch_size(500).limit(1), 1) - - await cursor_count((db.test.find()).batch_size(0).limit(10), 10) - await cursor_count((db.test.find()).batch_size(1).limit(10), 10) - await cursor_count((db.test.find()).batch_size(2).limit(10), 10) - await cursor_count((db.test.find()).batch_size(5).limit(10), 10) - await cursor_count((db.test.find()).batch_size(100).limit(10), 10) - await cursor_count((db.test.find()).batch_size(500).limit(10), 10) - - cur = db.test.find().batch_size(1) + await cursor_count((db.coll.find()).batch_size(0), 200) + await cursor_count((db.coll.find()).batch_size(1), 200) + await cursor_count((db.coll.find()).batch_size(2), 200) + await cursor_count((db.coll.find()).batch_size(5), 200) + await cursor_count((db.coll.find()).batch_size(100), 200) + await cursor_count((db.coll.find()).batch_size(500), 200) + + await cursor_count((db.coll.find()).batch_size(0).limit(1), 1) + await cursor_count((db.coll.find()).batch_size(1).limit(1), 1) + await cursor_count((db.coll.find()).batch_size(2).limit(1), 1) + await cursor_count((db.coll.find()).batch_size(5).limit(1), 1) + await cursor_count((db.coll.find()).batch_size(100).limit(1), 1) + await cursor_count((db.coll.find()).batch_size(500).limit(1), 1) + + await cursor_count((db.coll.find()).batch_size(0).limit(10), 10) + await cursor_count((db.coll.find()).batch_size(1).limit(10), 10) + await cursor_count((db.coll.find()).batch_size(2).limit(10), 10) + await cursor_count((db.coll.find()).batch_size(5).limit(10), 10) + await cursor_count((db.coll.find()).batch_size(100).limit(10), 10) + await cursor_count((db.coll.find()).batch_size(500).limit(10), 10) + + cur = db.coll.find().batch_size(1) await anext(cur) # find command batchSize should be 1 self.assertEqual(0, len(cur._data)) @@ -660,54 +658,54 @@ async def cursor_count(cursor, expected_count): async def test_limit_and_batch_size(self): db = self.db - await db.test.drop() - await db.test.insert_many([{"x": x} for x in range(500)]) + await db.coll.drop() + await db.coll.insert_many([{"x": x} for x in range(500)]) - curs = db.test.find().limit(0).batch_size(10) + curs = db.coll.find().limit(0).batch_size(10) await anext(curs) self.assertEqual(10, curs._retrieved) - curs = db.test.find(limit=0, batch_size=10) + curs = db.coll.find(limit=0, batch_size=10) await anext(curs) self.assertEqual(10, curs._retrieved) - curs = db.test.find().limit(-2).batch_size(0) + curs = db.coll.find().limit(-2).batch_size(0) await anext(curs) self.assertEqual(2, curs._retrieved) - curs = db.test.find(limit=-2, batch_size=0) + curs = db.coll.find(limit=-2, batch_size=0) await anext(curs) self.assertEqual(2, curs._retrieved) - curs = db.test.find().limit(-4).batch_size(5) + curs = db.coll.find().limit(-4).batch_size(5) await anext(curs) self.assertEqual(4, curs._retrieved) - curs = db.test.find(limit=-4, batch_size=5) + curs = db.coll.find(limit=-4, batch_size=5) await anext(curs) self.assertEqual(4, curs._retrieved) - curs = db.test.find().limit(50).batch_size(500) + curs = db.coll.find().limit(50).batch_size(500) await anext(curs) self.assertEqual(50, curs._retrieved) - curs = db.test.find(limit=50, batch_size=500) + curs = db.coll.find(limit=50, batch_size=500) await anext(curs) self.assertEqual(50, curs._retrieved) - curs = db.test.find().batch_size(500) + curs = db.coll.find().batch_size(500) await anext(curs) self.assertEqual(500, curs._retrieved) - curs = db.test.find(batch_size=500) + curs = db.coll.find(batch_size=500) await anext(curs) self.assertEqual(500, curs._retrieved) - curs = db.test.find().limit(50) + curs = db.coll.find().limit(50) await anext(curs) self.assertEqual(50, curs._retrieved) - curs = db.test.find(limit=50) + curs = db.coll.find(limit=50) await anext(curs) self.assertEqual(50, curs._retrieved) @@ -715,15 +713,15 @@ async def test_limit_and_batch_size(self): # is set by the server. as of 2.0.0-rc0, 101 # or 1MB (whichever is smaller) is default # for queries without ntoreturn - curs = db.test.find() + curs = db.coll.find() await anext(curs) self.assertEqual(101, curs._retrieved) - curs = db.test.find().limit(0).batch_size(0) + curs = db.coll.find().limit(0).batch_size(0) await anext(curs) self.assertEqual(101, curs._retrieved) - curs = db.test.find(limit=0, batch_size=0) + curs = db.coll.find(limit=0, batch_size=0) await anext(curs) self.assertEqual(101, curs._retrieved) @@ -731,47 +729,47 @@ async def test_skip(self): db = self.db with self.assertRaises(TypeError): - db.test.find().skip(None) # type: ignore[arg-type] + db.coll.find().skip(None) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().skip("hello") # type: ignore[arg-type] + db.coll.find().skip("hello") # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().skip(5.5) # type: ignore[arg-type] + db.coll.find().skip(5.5) # type: ignore[arg-type] with self.assertRaises(ValueError): - db.test.find().skip(-5) - self.assertTrue((db.test.find()).skip(5)) + db.coll.find().skip(-5) + self.assertTrue((db.coll.find()).skip(5)) - await db.drop_collection("test") + await db.drop_collection("coll") - await db.test.insert_many([{"x": i} for i in range(100)]) + await db.coll.insert_many([{"x": i} for i in range(100)]) - async for i in db.test.find(): + async for i in db.coll.find(): self.assertEqual(i["x"], 0) break - async for i in db.test.find().skip(20): + async for i in db.coll.find().skip(20): self.assertEqual(i["x"], 20) break - async for i in db.test.find().skip(99): + async for i in db.coll.find().skip(99): self.assertEqual(i["x"], 99) break - async for i in db.test.find().skip(1): + async for i in db.coll.find().skip(1): self.assertEqual(i["x"], 1) break - async for i in db.test.find().skip(0): + async for i in db.coll.find().skip(0): self.assertEqual(i["x"], 0) break - async for i in db.test.find().skip(0).skip(50).skip(10): + async for i in db.coll.find().skip(0).skip(50).skip(10): self.assertEqual(i["x"], 10) break - async for _ in db.test.find().skip(1000): + async for _ in db.coll.find().skip(1000): self.fail() - a = db.test.find() + a = db.coll.find() a.skip(10) async for _ in a: break @@ -781,53 +779,53 @@ async def test_sort(self): db = self.db with self.assertRaises(TypeError): - db.test.find().sort(5) # type: ignore[arg-type] + db.coll.find().sort(5) # type: ignore[arg-type] with self.assertRaises(ValueError): - db.test.find().sort([]) # type: ignore[arg-type] + db.coll.find().sort([]) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().sort([], ASCENDING) # type: ignore[arg-type] + db.coll.find().sort([], ASCENDING) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().sort([("hello", DESCENDING)], DESCENDING) # type: ignore[arg-type] + db.coll.find().sort([("hello", DESCENDING)], DESCENDING) # type: ignore[arg-type] - await db.test.drop() + await db.coll.drop() unsort = list(range(10)) random.shuffle(unsort) - await db.test.insert_many([{"x": i} for i in unsort]) + await db.coll.insert_many([{"x": i} for i in unsort]) - asc = [i["x"] async for i in db.test.find().sort("x", ASCENDING)] + asc = [i["x"] async for i in db.coll.find().sort("x", ASCENDING)] self.assertEqual(asc, list(range(10))) - asc = [i["x"] async for i in db.test.find().sort("x")] + asc = [i["x"] async for i in db.coll.find().sort("x")] self.assertEqual(asc, list(range(10))) - asc = [i["x"] async for i in db.test.find().sort([("x", ASCENDING)])] + asc = [i["x"] async for i in db.coll.find().sort([("x", ASCENDING)])] self.assertEqual(asc, list(range(10))) expect = list(reversed(range(10))) - desc = [i["x"] async for i in db.test.find().sort("x", DESCENDING)] + desc = [i["x"] async for i in db.coll.find().sort("x", DESCENDING)] self.assertEqual(desc, expect) - desc = [i["x"] async for i in db.test.find().sort([("x", DESCENDING)])] + desc = [i["x"] async for i in db.coll.find().sort([("x", DESCENDING)])] self.assertEqual(desc, expect) - desc = [i["x"] async for i in db.test.find().sort("x", ASCENDING).sort("x", DESCENDING)] + desc = [i["x"] async for i in db.coll.find().sort("x", ASCENDING).sort("x", DESCENDING)] self.assertEqual(desc, expect) expected = [(1, 5), (2, 5), (0, 3), (7, 3), (9, 2), (2, 1), (3, 1)] shuffled = list(expected) random.shuffle(shuffled) - await db.test.drop() + await db.coll.drop() for a, b in shuffled: - await db.test.insert_one({"a": a, "b": b}) + await db.coll.insert_one({"a": a, "b": b}) result = [ (i["a"], i["b"]) - async for i in db.test.find().sort([("b", DESCENDING), ("a", ASCENDING)]) + async for i in db.coll.find().sort([("b", DESCENDING), ("a", ASCENDING)]) ] self.assertEqual(result, expected) - result = [(i["a"], i["b"]) async for i in db.test.find().sort([("b", DESCENDING), "a"])] + result = [(i["a"], i["b"]) async for i in db.coll.find().sort([("b", DESCENDING), "a"])] self.assertEqual(result, expected) - a = db.test.find() + a = db.coll.find() a.sort("x", ASCENDING) async for _ in a: break @@ -839,9 +837,9 @@ async def test_sort(self): ) async def test_where(self): db = self.db - await db.test.drop() + await db.coll.drop() - a = db.test.find() + a = db.coll.find() with self.assertRaises(TypeError): a.where(5) # type: ignore[arg-type] with self.assertRaises(TypeError): @@ -849,38 +847,38 @@ async def test_where(self): with self.assertRaises(TypeError): a.where({}) # type: ignore[arg-type] - await db.test.insert_many([{"x": i} for i in range(10)]) + await db.coll.insert_many([{"x": i} for i in range(10)]) - self.assertEqual(3, len(await db.test.find().where("this.x < 3").to_list())) - self.assertEqual(3, len(await db.test.find().where(Code("this.x < 3")).to_list())) + self.assertEqual(3, len(await db.coll.find().where("this.x < 3").to_list())) + self.assertEqual(3, len(await db.coll.find().where(Code("this.x < 3")).to_list())) code_with_scope = Code("this.x < i", {"i": 3}) # MongoDB 4.4 removed support for Code with scope. with self.assertRaises(OperationFailure): - await db.test.find().where(code_with_scope).to_list() + await db.coll.find().where(code_with_scope).to_list() code_with_empty_scope = Code("this.x < 3", {}) with self.assertRaises(OperationFailure): - await db.test.find().where(code_with_empty_scope).to_list() + await db.coll.find().where(code_with_empty_scope).to_list() - self.assertEqual(10, len(await db.test.find().to_list())) - self.assertEqual([0, 1, 2], [a["x"] async for a in db.test.find().where("this.x < 3")]) - self.assertEqual([], [a["x"] async for a in db.test.find({"x": 5}).where("this.x < 3")]) - self.assertEqual([5], [a["x"] async for a in db.test.find({"x": 5}).where("this.x > 3")]) + self.assertEqual(10, len(await db.coll.find().to_list())) + self.assertEqual([0, 1, 2], [a["x"] async for a in db.coll.find().where("this.x < 3")]) + self.assertEqual([], [a["x"] async for a in db.coll.find({"x": 5}).where("this.x < 3")]) + self.assertEqual([5], [a["x"] async for a in db.coll.find({"x": 5}).where("this.x > 3")]) - cursor = db.test.find().where("this.x < 3").where("this.x > 7") + cursor = db.coll.find().where("this.x < 3").where("this.x > 7") self.assertEqual([8, 9], [a["x"] async for a in cursor]) - a = db.test.find() + a = db.coll.find() _ = a.where("this.x > 3") async for _ in a: break self.assertRaises(InvalidOperation, a.where, "this.x < 3") async def test_rewind(self): - await self.db.test.insert_many([{"x": i} for i in range(1, 4)]) + await self.db.coll.insert_many([{"x": i} for i in range(1, 4)]) - cursor = self.db.test.find().limit(2) + cursor = self.db.coll.find().limit(2) count = 0 async for _ in cursor: @@ -912,9 +910,9 @@ async def test_rewind(self): # oplog_reply, and snapshot are all deprecated. @ignore_deprecations async def test_clone(self): - await self.db.test.insert_many([{"x": i} for i in range(1, 4)]) + await self.db.coll.insert_many([{"x": i} for i in range(1, 4)]) - cursor = self.db.test.find().limit(2) + cursor = self.db.coll.find().limit(2) count = 0 async for _ in cursor: @@ -949,7 +947,7 @@ async def test_clone(self): # Just test attributes cursor = ( - self.db.test.find( + self.db.coll.find( {"x": re.compile("^hello.*")}, projection={"_id": False}, skip=1, @@ -997,7 +995,7 @@ async def test_clone(self): # Test memo when deepcopying queries query = {"hello": "world"} query["reflexive"] = query - cursor = self.db.test.find(query) + cursor = self.db.coll.find(query) cursor2 = copy.deepcopy(cursor) @@ -1006,7 +1004,7 @@ async def test_clone(self): self.assertEqual(len(cursor2._spec), 2) # Ensure hints are cloned as the correct type - cursor = self.db.test.find().hint([("z", 1), ("a", 1)]) + cursor = self.db.coll.find().hint([("z", 1), ("a", 1)]) cursor2 = copy.deepcopy(cursor) # Internal types are now dict rather than SON by default self.assertIsInstance(cursor2._hint, dict) @@ -1014,9 +1012,9 @@ async def test_clone(self): @async_client_context.require_sync def test_clone_empty(self): - self.db.test.delete_many({}) - self.db.test.insert_many([{"x": i} for i in range(1, 4)]) - cursor = self.db.test.find()[2:2] + self.db.coll.delete_many({}) + self.db.coll.insert_many([{"x": i} for i in range(1, 4)]) + cursor = self.db.coll.find()[2:2] cursor2 = cursor.clone() self.assertRaises(StopIteration, cursor.next) self.assertRaises(StopIteration, cursor2.next) @@ -1024,130 +1022,130 @@ def test_clone_empty(self): # AsyncCursors don't support slicing @async_client_context.require_sync def test_bad_getitem(self): - self.assertRaises(TypeError, lambda x: self.db.test.find()[x], "hello") - self.assertRaises(TypeError, lambda x: self.db.test.find()[x], 5.5) - self.assertRaises(TypeError, lambda x: self.db.test.find()[x], None) + self.assertRaises(TypeError, lambda x: self.db.coll.find()[x], "hello") + self.assertRaises(TypeError, lambda x: self.db.coll.find()[x], 5.5) + self.assertRaises(TypeError, lambda x: self.db.coll.find()[x], None) # AsyncCursors don't support slicing @async_client_context.require_sync def test_getitem_slice_index(self): - self.db.drop_collection("test") - self.db.test.insert_many([{"i": i} for i in range(100)]) + self.db.drop_collection("coll") + self.db.coll.insert_many([{"i": i} for i in range(100)]) count = itertools.count - self.assertRaises(IndexError, lambda: self.db.test.find()[-1:]) - self.assertRaises(IndexError, lambda: self.db.test.find()[1:2:2]) + self.assertRaises(IndexError, lambda: self.db.coll.find()[-1:]) + self.assertRaises(IndexError, lambda: self.db.coll.find()[1:2:2]) - for a, b in zip(count(0), self.db.test.find()): # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find()): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(100, len(list(self.db.test.find()[0:]))) # type: ignore[call-overload] - for a, b in zip(count(0), self.db.test.find()[0:]): # type: ignore[call-overload] + self.assertEqual(100, len(list(self.db.coll.find()[0:]))) # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find()[0:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find()[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[20:]): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[20:]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - for a, b in zip(count(99), self.db.test.find()[99:]): # type: ignore[call-overload] + for a, b in zip(count(99), self.db.coll.find()[99:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - for _i in self.db.test.find()[1000:]: + for _i in self.db.coll.find()[1000:]: self.fail() - self.assertEqual(5, len(list(self.db.test.find()[20:25]))) # type: ignore[call-overload] - self.assertEqual(5, len(list(self.db.test.find()[20:25]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[20:25]): # type: ignore[call-overload] + self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] + self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:25]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find()[40:45][20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[40:45][20:]): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[40:45][20:]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45][20:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find()[40:45].limit(0).skip(20)))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[40:45].limit(0).skip(20)): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[40:45].limit(0).skip(20)))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45].limit(0).skip(20)): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find().limit(10).skip(40)[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find().limit(10).skip(40)[20:]): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find().limit(10).skip(40)[20:]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find().limit(10).skip(40)[20:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(1, len(list(self.db.test.find()[:1]))) # type: ignore[call-overload] - self.assertEqual(5, len(list(self.db.test.find()[:5]))) # type: ignore[call-overload] + self.assertEqual(1, len(list(self.db.coll.find()[:1]))) # type: ignore[call-overload] + self.assertEqual(5, len(list(self.db.coll.find()[:5]))) # type: ignore[call-overload] - self.assertEqual(1, len(list(self.db.test.find()[99:100]))) # type: ignore[call-overload] - self.assertEqual(1, len(list(self.db.test.find()[99:1000]))) # type: ignore[call-overload] - self.assertEqual(0, len(list(self.db.test.find()[10:10]))) # type: ignore[call-overload] - self.assertEqual(0, len(list(self.db.test.find()[:0]))) # type: ignore[call-overload] - self.assertEqual(80, len(list(self.db.test.find()[10:10].limit(0).skip(20)))) # type: ignore[call-overload] + self.assertEqual(1, len(list(self.db.coll.find()[99:100]))) # type: ignore[call-overload] + self.assertEqual(1, len(list(self.db.coll.find()[99:1000]))) # type: ignore[call-overload] + self.assertEqual(0, len(list(self.db.coll.find()[10:10]))) # type: ignore[call-overload] + self.assertEqual(0, len(list(self.db.coll.find()[:0]))) # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[10:10].limit(0).skip(20)))) # type: ignore[call-overload] - self.assertRaises(IndexError, lambda: self.db.test.find()[10:8]) + self.assertRaises(IndexError, lambda: self.db.coll.find()[10:8]) # AsyncCursors don't support slicing @async_client_context.require_sync def test_getitem_numeric_index(self): - self.db.drop_collection("test") - self.db.test.insert_many([{"i": i} for i in range(100)]) + self.db.drop_collection("coll") + self.db.coll.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"]) - self.assertEqual(50, self.db.test.find().skip(50)[0]["i"]) - self.assertEqual(50, self.db.test.find().skip(49)[1]["i"]) - self.assertEqual(50, self.db.test.find()[50]["i"]) - self.assertEqual(99, self.db.test.find()[99]["i"]) + self.assertEqual(0, self.db.coll.find()[0]["i"]) + self.assertEqual(50, self.db.coll.find()[50]["i"]) + self.assertEqual(50, self.db.coll.find().skip(50)[0]["i"]) + self.assertEqual(50, self.db.coll.find().skip(49)[1]["i"]) + self.assertEqual(50, self.db.coll.find()[50]["i"]) + self.assertEqual(99, self.db.coll.find()[99]["i"]) - self.assertRaises(IndexError, lambda x: self.db.test.find()[x], -1) - self.assertRaises(IndexError, lambda x: self.db.test.find()[x], 100) - self.assertRaises(IndexError, lambda x: self.db.test.find().skip(50)[x], 50) + self.assertRaises(IndexError, lambda x: self.db.coll.find()[x], -1) + self.assertRaises(IndexError, lambda x: self.db.coll.find()[x], 100) + self.assertRaises(IndexError, lambda x: self.db.coll.find().skip(50)[x], 50) @async_client_context.require_sync def test_iteration_with_list(self): - self.db.drop_collection("test") - self.db.test.insert_many([{"i": i} for i in range(100)]) + self.db.drop_collection("coll") + self.db.coll.insert_many([{"i": i} for i in range(100)]) - cur = self.db.test.find().batch_size(10) + cur = self.db.coll.find().batch_size(10) self.assertEqual(100, len(list(cur))) # type: ignore[call-overload] def test_len(self): with self.assertRaises(TypeError): - len(self.db.test.find()) # type: ignore[arg-type] + len(self.db.coll.find()) # type: ignore[arg-type] def test_properties(self): - self.assertEqual(self.db.test, self.db.test.find().collection) + self.assertEqual(self.db.coll, self.db.coll.find().collection) with self.assertRaises(AttributeError): - self.db.test.find().collection = "hello" # type: ignore + self.db.coll.find().collection = "hello" # type: ignore async def test_get_more(self): db = self.db - await db.drop_collection("test") - await db.test.insert_many([{"i": i} for i in range(10)]) - self.assertEqual(10, len(await db.test.find().batch_size(5).to_list())) + await db.drop_collection("coll") + await db.coll.insert_many([{"i": i} for i in range(10)]) + self.assertEqual(10, len(await db.coll.find().batch_size(5).to_list())) async def test_tailable(self): db = self.db - await db.drop_collection("test") - await db.create_collection("test", capped=True, size=1000, max=3) - self.addAsyncCleanup(db.drop_collection, "test") - cursor = db.test.find(cursor_type=CursorType.TAILABLE) + await db.drop_collection("coll") + await db.create_collection("coll", capped=True, size=1000, max=3) + self.addAsyncCleanup(db.drop_collection, "coll") + cursor = db.coll.find(cursor_type=CursorType.TAILABLE) - await db.test.insert_one({"x": 1}) + await db.coll.insert_one({"x": 1}) count = 0 async for doc in cursor: count += 1 self.assertEqual(1, doc["x"]) self.assertEqual(1, count) - await db.test.insert_one({"x": 2}) + await db.coll.insert_one({"x": 2}) count = 0 async for doc in cursor: count += 1 self.assertEqual(2, doc["x"]) self.assertEqual(1, count) - await db.test.insert_one({"x": 3}) + await db.coll.insert_one({"x": 3}) count = 0 async for doc in cursor: count += 1 @@ -1157,19 +1155,19 @@ async def test_tailable(self): # Capped rollover - the collection can never # have more than 3 documents. Just make sure # this doesn't raise... - await db.test.insert_many([{"x": i} for i in range(4, 7)]) + await db.coll.insert_many([{"x": i} for i in range(4, 7)]) self.assertEqual(0, len(await cursor.to_list())) # and that the cursor doesn't think it's still alive. self.assertFalse(cursor.alive) - self.assertEqual(3, await db.test.count_documents({})) + self.assertEqual(3, await db.coll.count_documents({})) # __getitem__(index) if _IS_SYNC: for cursor in ( - db.test.find(cursor_type=CursorType.TAILABLE), - db.test.find(cursor_type=CursorType.TAILABLE_AWAIT), + db.coll.find(cursor_type=CursorType.TAILABLE), + db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT), ): self.assertEqual(4, cursor[0]["x"]) self.assertEqual(5, cursor[1]["x"]) @@ -1193,10 +1191,10 @@ async def test_tailable(self): def test_concurrent_close(self): """Ensure a tailable can be closed from another thread.""" db = self.db - db.drop_collection("test") - db.create_collection("test", capped=True, size=1000, max=3) - self.addCleanup(db.drop_collection, "test") - cursor = db.test.find(cursor_type=CursorType.TAILABLE) + db.drop_collection("coll") + db.create_collection("coll", capped=True, size=1000, max=3) + self.addCleanup(db.drop_collection, "coll") + cursor = db.coll.find(cursor_type=CursorType.TAILABLE) def iterate_cursor(): while cursor.alive: @@ -1216,37 +1214,37 @@ def iterate_cursor(): self.assertFalse(t.is_alive()) async def test_distinct(self): - await self.db.drop_collection("test") + await self.db.drop_collection("coll") - await self.db.test.insert_many([{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}]) + await self.db.coll.insert_many([{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}]) - distinct = await self.db.test.find({"a": {"$lt": 3}}).distinct("a") + distinct = await self.db.coll.find({"a": {"$lt": 3}}).distinct("a") distinct.sort() self.assertEqual([1, 2], distinct) - await self.db.drop_collection("test") + await self.db.drop_collection("coll") - await self.db.test.insert_one({"a": {"b": "a"}, "c": 12}) - await self.db.test.insert_one({"a": {"b": "b"}, "c": 8}) - await self.db.test.insert_one({"a": {"b": "c"}, "c": 12}) - await self.db.test.insert_one({"a": {"b": "c"}, "c": 8}) + await self.db.coll.insert_one({"a": {"b": "a"}, "c": 12}) + await self.db.coll.insert_one({"a": {"b": "b"}, "c": 8}) + await self.db.coll.insert_one({"a": {"b": "c"}, "c": 12}) + await self.db.coll.insert_one({"a": {"b": "c"}, "c": 8}) - distinct = await self.db.test.find({"c": 8}).distinct("a.b") + distinct = await self.db.coll.find({"c": 8}).distinct("a.b") distinct.sort() self.assertEqual(["b", "c"], distinct) async def test_with_statement(self): - await self.db.drop_collection("test") - await self.db.test.insert_many([{} for _ in range(100)]) + await self.db.drop_collection("coll") + await self.db.coll.insert_many([{} for _ in range(100)]) - c1 = self.db.test.find() - async with self.db.test.find() as c2: + c1 = self.db.coll.find() + async with self.db.coll.find() as c2: self.assertTrue(c2.alive) self.assertFalse(c2.alive) - async with self.db.test.find() as c2: + async with self.db.coll.find() as c2: self.assertEqual(100, len(await c2.to_list())) self.assertFalse(c2.alive) self.assertTrue(c1.alive) @@ -1256,18 +1254,18 @@ async def test_comment(self): await self.client.drop_database(self.db) await self.db.command("profile", 2) # Profile ALL commands. try: - await self.db.test.find().comment("foo").to_list() + await self.db.coll.find().comment("foo").to_list() count = await self.db.system.profile.count_documents( - {"ns": "pymongo_test.test", "op": "query", "command.comment": "foo"} + {"ns": "pymongo_test.coll", "op": "query", "command.comment": "foo"} ) self.assertEqual(count, 1) - await self.db.test.find().comment("foo").distinct("type") + await self.db.coll.find().comment("foo").distinct("type") count = await self.db.system.profile.count_documents( { - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "op": "command", - "command.distinct": "test", + "command.distinct": "coll", "command.comment": "foo", } ) @@ -1276,16 +1274,16 @@ async def test_comment(self): await self.db.command("profile", 0) # Turn off profiling. await self.db.system.profile.drop() - await self.db.test.insert_many([{}, {}]) - cursor = self.db.test.find() + await self.db.coll.insert_many([{}, {}]) + cursor = self.db.coll.find() await anext(cursor) self.assertRaises(InvalidOperation, cursor.comment, "hello") async def test_alive(self): - await self.db.test.delete_many({}) - await self.db.test.insert_many([{} for _ in range(3)]) - self.addAsyncCleanup(self.db.test.delete_many, {}) - cursor = self.db.test.find().batch_size(2) + await self.db.coll.delete_many({}) + await self.db.coll.insert_many([{} for _ in range(3)]) + self.addAsyncCleanup(self.db.coll.delete_many, {}) + cursor = self.db.coll.find().batch_size(2) n = 0 while True: await cursor.next() @@ -1440,7 +1438,7 @@ async def test_to_list_empty(self): self.assertEqual([], docs) async def test_to_list_length(self): - coll = self.db.test + coll = self.db.coll await coll.insert_many([{} for _ in range(5)]) self.addAsyncCleanup(coll.drop) c = coll.find() @@ -1456,7 +1454,7 @@ async def test_to_list_length(self): @flaky(reason="PYTHON-3522") async def test_to_list_csot_applied(self): client = await self.async_single_client(timeoutMS=500, w=1) - coll = client.pymongo.test + coll = client.pymongo.coll # Initialize the client with a larger timeout to help make test less flaky with pymongo.timeout(10): await coll.insert_many([{} for _ in range(5)]) @@ -1468,7 +1466,7 @@ async def test_to_list_csot_applied(self): @async_client_context.require_change_streams async def test_command_cursor_to_list(self): # Set maxAwaitTimeMS=1 to speed up the test. - c = await self.db.test.aggregate([{"$changeStream": {}}], maxAwaitTimeMS=1) + c = await self.db.coll.aggregate([{"$changeStream": {}}], maxAwaitTimeMS=1) self.addAsyncCleanup(c.close) docs = await c.to_list() self.assertGreaterEqual(len(docs), 0) @@ -1484,21 +1482,21 @@ async def test_command_cursor_to_list_empty(self): @async_client_context.require_change_streams async def test_command_cursor_to_list_length(self): db = self.db - await db.drop_collection("test") - await db.test.insert_many([{"foo": 1}, {"foo": 2}]) + await db.drop_collection("coll") + await db.coll.insert_many([{"foo": 1}, {"foo": 2}]) pipeline = {"$project": {"_id": False, "foo": True}} - result = await db.test.aggregate([pipeline]) + result = await db.coll.aggregate([pipeline]) self.assertEqual(len(await result.to_list()), 2) - result = await db.test.aggregate([pipeline]) + result = await db.coll.aggregate([pipeline]) self.assertEqual(len(await result.to_list(1)), 1) @async_client_context.require_failCommand_blockConnection @flaky(reason="PYTHON-3522") async def test_command_cursor_to_list_csot_applied(self): client = await self.async_single_client(timeoutMS=500, w=1) - coll = client.pymongo.test + coll = client.pymongo.coll # Initialize the client with a larger timeout to help make test less flaky with pymongo.timeout(10): await coll.insert_many([{} for _ in range(5)]) @@ -1517,10 +1515,10 @@ async def test_command_cursor_to_list_csot_applied(self): class TestRawBatchCursor(AsyncIntegrationTest): async def asyncSetUp(self): await super().asyncSetUp() - await self.db.test.drop() + await self.db.coll.drop() async def test_find_raw(self): - c = self.db.test + c = self.db.coll docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) batches = await c.find_raw_batches().sort("_id").to_list() @@ -1529,7 +1527,7 @@ async def test_find_raw(self): @async_client_context.require_transactions async def test_find_raw_transaction(self): - c = self.db.test + c = self.db.coll docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1538,7 +1536,7 @@ async def test_find_raw_transaction(self): async with client.start_session() as session: async with await session.start_transaction(): batches = await ( - client[self.db.name].test.find_raw_batches(session=session).sort("_id") + client[self.db.name].coll.find_raw_batches(session=session).sort("_id") ).to_list() cmd = listener.started_events[0] self.assertEqual(cmd.command_name, "find") @@ -1558,7 +1556,7 @@ async def test_find_raw_transaction(self): @async_client_context.require_sessions @async_client_context.require_failCommand_fail_point async def test_find_raw_retryable_reads(self): - c = self.db.test + c = self.db.coll docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1567,7 +1565,7 @@ async def test_find_raw_retryable_reads(self): async with self.fail_point( {"mode": {"times": 1}, "data": {"failCommands": ["find"], "closeConnection": True}} ): - batches = await client[self.db.name].test.find_raw_batches().sort("_id").to_list() + batches = await client[self.db.name].coll.find_raw_batches().sort("_id").to_list() self.assertEqual(1, len(batches)) self.assertEqual(docs, decode_all(batches[0])) @@ -1578,7 +1576,7 @@ async def test_find_raw_retryable_reads(self): @async_client_context.require_version_min(5, 0, 0) @async_client_context.require_no_standalone async def test_find_raw_snapshot_reads(self): - c = self.db.get_collection("test", write_concern=WriteConcern(w="majority")) + c = self.db.get_collection("coll", write_concern=WriteConcern(w="majority")) docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1586,8 +1584,8 @@ async def test_find_raw_snapshot_reads(self): client = await self.async_rs_or_single_client(event_listeners=[listener], retryReads=True) db = client[self.db.name] async with client.start_session(snapshot=True) as session: - await db.test.distinct("x", {}, session=session) - batches = await db.test.find_raw_batches(session=session).sort("_id").to_list() + await db.coll.distinct("x", {}, session=session) + batches = await db.coll.find_raw_batches(session=session).sort("_id").to_list() self.assertEqual(1, len(batches)) self.assertEqual(docs, decode_all(batches[0])) @@ -1596,55 +1594,55 @@ async def test_find_raw_snapshot_reads(self): self.assertIsNotNone(find_cmd["readConcern"]["atClusterTime"]) async def test_explain(self): - c = self.db.test + c = self.db.coll explanation = await c.find_raw_batches().explain() self.assertIsInstance(explanation, dict) async def test_empty(self): - cursor = self.db.test.find_raw_batches() + cursor = self.db.coll.find_raw_batches() with self.assertRaises(StopAsyncIteration): await anext(cursor) async def test_clone(self): - await self.db.test.insert_one({}) - cursor = self.db.test.find_raw_batches() + await self.db.coll.insert_one({}) + cursor = self.db.coll.find_raw_batches() # Copy of a RawBatchCursor is also a RawBatchCursor, not a Cursor. self.assertIsInstance(await anext(cursor.clone()), bytes) self.assertIsInstance(await anext(copy.copy(cursor)), bytes) @async_client_context.require_exhaust_cursors async def test_exhaust(self): - c = self.db.test + c = self.db.coll await c.insert_many({"_id": i} for i in range(200)) result = b"".join(await c.find_raw_batches(cursor_type=CursorType.EXHAUST).to_list()) self.assertEqual([{"_id": i} for i in range(200)], decode_all(result)) async def test_server_error(self): with self.assertRaises(OperationFailure) as exc: - await anext(self.db.test.find_raw_batches({"x": {"$bad": 1}})) + await anext(self.db.coll.find_raw_batches({"x": {"$bad": 1}})) # The server response was decoded, not left raw. self.assertIsInstance(exc.exception.details, dict) async def test_get_item(self): with self.assertRaises(InvalidOperation): - self.db.test.find_raw_batches()[0] + self.db.coll.find_raw_batches()[0] async def test_collation(self): - await self.db.test.insert_one({}) - await anext(self.db.test.find_raw_batches(collation=Collation("en_US"))) + await self.db.coll.insert_one({}) + await anext(self.db.coll.find_raw_batches(collation=Collation("en_US"))) async def test_read_concern(self): - await self.db.get_collection("test", write_concern=WriteConcern(w="majority")).insert_one( + await self.db.get_collection("coll", write_concern=WriteConcern(w="majority")).insert_one( {} ) - c = self.db.get_collection("test", read_concern=ReadConcern("majority")) + c = self.db.get_collection("coll", read_concern=ReadConcern("majority")) await anext(c.find_raw_batches()) async def test_monitoring(self): listener = OvertCommandListener() client = await self.async_rs_or_single_client(event_listeners=[listener]) - c = client.pymongo_test.test + c = client.pymongo_test.coll await c.insert_many([{"_id": i} for i in range(10)]) listener.reset() @@ -1660,7 +1658,7 @@ async def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("find", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") # The batch is a list of one raw bytes object. self.assertEqual(len(csr["firstBatch"]), 1) @@ -1678,7 +1676,7 @@ async def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("getMore", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(len(csr["nextBatch"]), 1) self.assertEqual(decode_all(csr["nextBatch"][0]), [{"_id": i} for i in range(4, 8)]) finally: @@ -1688,7 +1686,7 @@ async def test_monitoring(self): class TestRawBatchCommandCursor(AsyncIntegrationTest): async def test_aggregate_raw(self): - c = self.db.test + c = self.db.coll await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1698,7 +1696,7 @@ async def test_aggregate_raw(self): @async_client_context.require_transactions async def test_aggregate_raw_transaction(self): - c = self.db.test + c = self.db.coll await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1708,7 +1706,7 @@ async def test_aggregate_raw_transaction(self): async with client.start_session() as session: async with await session.start_transaction(): batches = await ( - await client[self.db.name].test.aggregate_raw_batches( + await client[self.db.name].coll.aggregate_raw_batches( [{"$sort": {"_id": 1}}], session=session ) ).to_list() @@ -1729,7 +1727,7 @@ async def test_aggregate_raw_transaction(self): @async_client_context.require_sessions @async_client_context.require_failCommand_fail_point async def test_aggregate_raw_retryable_reads(self): - c = self.db.test + c = self.db.coll await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1740,7 +1738,7 @@ async def test_aggregate_raw_retryable_reads(self): {"mode": {"times": 1}, "data": {"failCommands": ["aggregate"], "closeConnection": True}} ): batches = await ( - await client[self.db.name].test.aggregate_raw_batches([{"$sort": {"_id": 1}}]) + await client[self.db.name].coll.aggregate_raw_batches([{"$sort": {"_id": 1}}]) ).to_list() self.assertEqual(1, len(batches)) @@ -1753,7 +1751,7 @@ async def test_aggregate_raw_retryable_reads(self): @async_client_context.require_version_min(5, 0, -1) @async_client_context.require_no_standalone async def test_aggregate_raw_snapshot_reads(self): - c = self.db.get_collection("test", write_concern=WriteConcern(w="majority")) + c = self.db.get_collection("coll", write_concern=WriteConcern(w="majority")) await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1762,9 +1760,9 @@ async def test_aggregate_raw_snapshot_reads(self): client = await self.async_rs_or_single_client(event_listeners=[listener], retryReads=True) db = client[self.db.name] async with client.start_session(snapshot=True) as session: - await db.test.distinct("x", {}, session=session) + await db.coll.distinct("x", {}, session=session) batches = await ( - await db.test.aggregate_raw_batches([{"$sort": {"_id": 1}}], session=session) + await db.coll.aggregate_raw_batches([{"$sort": {"_id": 1}}], session=session) ).to_list() self.assertEqual(1, len(batches)) self.assertEqual(docs, decode_all(batches[0])) @@ -1774,7 +1772,7 @@ async def test_aggregate_raw_snapshot_reads(self): self.assertIsNotNone(find_cmd["readConcern"]["atClusterTime"]) async def test_server_error(self): - c = self.db.test + c = self.db.coll await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1782,7 +1780,7 @@ async def test_server_error(self): with self.assertRaises(OperationFailure) as exc: await ( - await self.db.test.aggregate_raw_batches( + await self.db.coll.aggregate_raw_batches( [ { "$sort": {"_id": 1}, @@ -1798,15 +1796,15 @@ async def test_server_error(self): async def test_get_item(self): with self.assertRaises(InvalidOperation): - (await self.db.test.aggregate_raw_batches([]))[0] + (await self.db.coll.aggregate_raw_batches([]))[0] async def test_collation(self): - await anext(await self.db.test.aggregate_raw_batches([], collation=Collation("en_US"))) + await anext(await self.db.coll.aggregate_raw_batches([], collation=Collation("en_US"))) async def test_monitoring(self): listener = OvertCommandListener() client = await self.async_rs_or_single_client(event_listeners=[listener]) - c = client.pymongo_test.test + c = client.pymongo_test.coll await c.drop() await c.insert_many([{"_id": i} for i in range(10)]) @@ -1821,7 +1819,7 @@ async def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("aggregate", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") # First batch is empty. self.assertEqual(len(csr["firstBatch"]), 0) @@ -1837,7 +1835,7 @@ async def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("getMore", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(len(csr["nextBatch"]), 1) self.assertEqual(csr["nextBatch"][0], batch) self.assertEqual(decode_all(batch), [{"_id": i} for i in range(n, min(n + 4, 10))]) @@ -1851,7 +1849,7 @@ async def test_monitoring(self): async def test_exhaust_cursor_db_set(self): listener = OvertCommandListener() client = await self.async_rs_or_single_client(event_listeners=[listener]) - c = client.pymongo_test.test + c = client.pymongo_test.coll await c.delete_many({}) await c.insert_many([{"_id": i} for i in range(3)]) diff --git a/test/asynchronous/test_custom_types.py b/test/asynchronous/test_custom_types.py index c4751f2b13..34c4d05650 100644 --- a/test/asynchronous/test_custom_types.py +++ b/test/asynchronous/test_custom_types.py @@ -632,15 +632,15 @@ class MyType(pytype): # type: ignore class TestCollectionWCustomType(AsyncIntegrationTest): async def asyncSetUp(self): await super().asyncSetUp() - await self.db.test.drop() + await self.db.coll.drop() async def asyncTearDown(self): - await self.db.test.drop() + await self.db.coll.drop() async def test_overflow_int_w_custom_decoder(self): type_registry = TypeRegistry(fallback_encoder=lambda val: str(val)) codec_options = CodecOptions(type_registry=type_registry) - collection = self.db.get_collection("test", codec_options=codec_options) + collection = self.db.get_collection("coll", codec_options=codec_options) await collection.insert_one({"_id": 1, "data": 2**520}) ret = await collection.find_one() @@ -649,7 +649,7 @@ async def test_overflow_int_w_custom_decoder(self): async def test_command_errors_w_custom_type_decoder(self): db = self.db test_doc = {"_id": 1, "data": "a"} - test = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + test = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) result = await test.insert_one(test_doc) self.assertEqual(result.inserted_id, test_doc["_id"]) @@ -660,9 +660,9 @@ async def test_find_w_custom_type_decoder(self): db = self.db input_docs = [{"x": Int64(k)} for k in [1, 2, 3]] for doc in input_docs: - await db.test.insert_one(doc) + await db.coll.insert_one(doc) - test = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + test = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) async for doc in test.find({}, batch_size=1): self.assertIsInstance(doc["x"], UndecipherableInt64Type) @@ -671,10 +671,10 @@ async def run_test(doc_cls): db = self.db input_docs = [{"x": Int64(k)} for k in [1, 2, 3]] for doc in input_docs: - await db.test.insert_one(doc) + await db.coll.insert_one(doc) test = db.get_collection( - "test", + "coll", codec_options=CodecOptions( type_registry=TypeRegistry([UndecipherableIntDecoder()]), document_class=doc_cls ), @@ -688,7 +688,7 @@ async def run_test(doc_cls): async def test_aggregate_w_custom_type_decoder(self): db = self.db - await db.test.insert_many( + await db.coll.insert_many( [ {"status": "in progress", "qty": Int64(1)}, {"status": "complete", "qty": Int64(10)}, @@ -697,7 +697,7 @@ async def test_aggregate_w_custom_type_decoder(self): {"status": "in progress", "qty": Int64(1)}, ] ) - test = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + test = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) pipeline: list = [ {"$match": {"status": "complete"}}, @@ -711,9 +711,9 @@ async def test_aggregate_w_custom_type_decoder(self): self.assertEqual(res["total_qty"].value, 20) async def test_distinct_w_custom_type(self): - await self.db.drop_collection("test") + await self.db.drop_collection("coll") - test = self.db.get_collection("test", codec_options=UNINT_CODECOPTS) + test = self.db.get_collection("coll", codec_options=UNINT_CODECOPTS) values = [ UndecipherableInt64Type(1), UndecipherableInt64Type(2), @@ -726,7 +726,7 @@ async def test_distinct_w_custom_type(self): async def test_find_one_and__w_custom_type_decoder(self): db = self.db - c = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + c = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) await c.insert_one({"_id": 1, "x": Int64(1)}) doc = await c.find_one_and_update( @@ -923,13 +923,13 @@ class TestCollectionChangeStreamsWCustomTypes( @async_client_context.require_change_streams async def asyncSetUp(self): await super().asyncSetUp() - await self.db.test.delete_many({}) + await self.db.coll.delete_many({}) async def asyncTearDown(self): await self.input_target.drop() async def create_targets(self, *args, **kwargs): - self.watched_target = self.db.get_collection("test", *args, **kwargs) + self.watched_target = self.db.get_collection("coll", *args, **kwargs) self.input_target = self.watched_target # Ensure the collection exists and is empty. await self.input_target.insert_one({}) @@ -942,7 +942,7 @@ class TestDatabaseChangeStreamsWCustomTypes( @async_client_context.require_change_streams async def asyncSetUp(self): await super().asyncSetUp() - await self.db.test.delete_many({}) + await self.db.coll.delete_many({}) async def asyncTearDown(self): await self.input_target.drop() @@ -950,7 +950,7 @@ async def asyncTearDown(self): async def create_targets(self, *args, **kwargs): self.watched_target = self.client.get_database(self.db.name, *args, **kwargs) - self.input_target = self.watched_target.test + self.input_target = self.watched_target.coll # Insert a record to ensure db, coll are created. await self.input_target.insert_one({"data": "dummy"}) @@ -961,7 +961,7 @@ class TestClusterChangeStreamsWCustomTypes( @async_client_context.require_change_streams async def asyncSetUp(self): await super().asyncSetUp() - await self.db.test.delete_many({}) + await self.db.coll.delete_many({}) async def asyncTearDown(self): await self.input_target.drop() @@ -973,7 +973,7 @@ async def create_targets(self, *args, **kwargs): kwargs["type_registry"] = codec_options.type_registry kwargs["document_class"] = codec_options.document_class self.watched_target = await self.async_rs_client(*args, **kwargs) - self.input_target = self.watched_target[self.db.name].test + self.input_target = self.watched_target[self.db.name].coll # Insert a record to ensure db, coll are created. await self.input_target.insert_one({"data": "dummy"}) diff --git a/test/asynchronous/test_database.py b/test/asynchronous/test_database.py index 4b9f41c244..22cf4d1332 100644 --- a/test/asynchronous/test_database.py +++ b/test/asynchronous/test_database.py @@ -150,11 +150,11 @@ def test_repr(self): async def test_create_collection(self): db = AsyncDatabase(self.client, "pymongo_test") - await db.test.insert_one({"hello": "world"}) + await db.coll.insert_one({"hello": "world"}) with self.assertRaises(CollectionInvalid): - await db.create_collection("test") + await db.create_collection("coll") - await db.drop_collection("test") + await db.drop_collection("coll") with self.assertRaises(TypeError): await db.create_collection(5) # type: ignore[arg-type] @@ -163,10 +163,10 @@ async def test_create_collection(self): with self.assertRaises(InvalidName): await db.create_collection("coll..ection") # type: ignore[arg-type] - test = await db.create_collection("test") - self.assertIn("test", await db.list_collection_names()) - await test.insert_one({"hello": "world"}) - self.assertEqual((await db.test.find_one())["hello"], "world") + coll_obj = await db.create_collection("coll") + self.assertIn("coll", await db.list_collection_names()) + await coll_obj.insert_one({"hello": "world"}) + self.assertEqual((await db.coll.find_one())["hello"], "world") await db.drop_collection("test.foo") await db.create_collection("test.foo") @@ -176,12 +176,12 @@ async def test_create_collection(self): async def test_list_collection_names(self): db = AsyncDatabase(self.client, "pymongo_test") - await db.test.insert_one({"dummy": "object"}) - await db.test.mike.insert_one({"dummy": "object"}) + await db.coll.insert_one({"dummy": "object"}) + await db.coll.mike.insert_one({"dummy": "object"}) colls = await db.list_collection_names() - self.assertIn("test", colls) - self.assertIn("test.mike", colls) + self.assertIn("coll", colls) + self.assertIn("coll.mike", colls) for coll in colls: self.assertNotIn("$", coll) @@ -246,15 +246,15 @@ async def test_check_exists(self): async def test_list_collections(self): await self.client.drop_database("pymongo_test") db = AsyncDatabase(self.client, "pymongo_test") - await db.test.insert_one({"dummy": "object"}) - await db.test.mike.insert_one({"dummy": "object"}) + await db.coll.insert_one({"dummy": "object"}) + await db.coll.mike.insert_one({"dummy": "object"}) results = await db.list_collections() colls = [result["name"] async for result in results] # All the collections present. - self.assertIn("test", colls) - self.assertIn("test.mike", colls) + self.assertIn("coll", colls) + self.assertIn("coll.mike", colls) # No collection containing a '$'. for coll in colls: @@ -272,25 +272,25 @@ async def test_list_collections(self): coll_cnt: dict = {} # Check if there are any collections which don't exist. - self.assertLessEqual(set(colls), {"test", "test.mike", "system.indexes"}) + self.assertLessEqual(set(colls), {"coll", "coll.mike", "system.indexes"}) - colls = await (await db.list_collections(filter={"name": {"$regex": "^test$"}})).to_list() + colls = await (await db.list_collections(filter={"name": {"$regex": "^coll$"}})).to_list() self.assertEqual(1, len(colls)) colls = await ( - await db.list_collections(filter={"name": {"$regex": "^test.mike$"}}) + await db.list_collections(filter={"name": {"$regex": "^coll.mike$"}}) ).to_list() self.assertEqual(1, len(colls)) - await db.drop_collection("test") + await db.drop_collection("coll") - await db.create_collection("test", capped=True, size=4096) + await db.create_collection("coll", capped=True, size=4096) results = await db.list_collections(filter={"options.capped": True}) colls = [result["name"] async for result in results] # Checking only capped collections are present - self.assertIn("test", colls) - self.assertNotIn("test.mike", colls) + self.assertIn("coll", colls) + self.assertNotIn("coll.mike", colls) # No collection containing a '$'. for coll in colls: @@ -308,7 +308,7 @@ async def test_list_collections(self): coll_cnt = {} # Check if there are any collections which don't exist. - self.assertLessEqual(set(colls), {"test", "system.indexes"}) + self.assertLessEqual(set(colls), {"coll", "system.indexes"}) await self.client.drop_database("pymongo_test") @@ -330,63 +330,63 @@ async def test_drop_collection(self): with self.assertRaises(TypeError): await db.drop_collection(None) # type: ignore[arg-type] - await db.test.insert_one({"dummy": "object"}) - self.assertIn("test", await db.list_collection_names()) - await db.drop_collection("test") - self.assertNotIn("test", await db.list_collection_names()) + await db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", await db.list_collection_names()) + await db.drop_collection("coll") + self.assertNotIn("coll", await db.list_collection_names()) - await db.test.insert_one({"dummy": "object"}) - self.assertIn("test", await db.list_collection_names()) - await db.drop_collection("test") - self.assertNotIn("test", await db.list_collection_names()) + await db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", await db.list_collection_names()) + await db.drop_collection("coll") + self.assertNotIn("coll", await db.list_collection_names()) - await db.test.insert_one({"dummy": "object"}) - self.assertIn("test", await db.list_collection_names()) - await db.drop_collection(db.test) - self.assertNotIn("test", await db.list_collection_names()) + await db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", await db.list_collection_names()) + await db.drop_collection(db.coll) + self.assertNotIn("coll", await db.list_collection_names()) - await db.test.insert_one({"dummy": "object"}) - self.assertIn("test", await db.list_collection_names()) - await db.test.drop() - self.assertNotIn("test", await db.list_collection_names()) - await db.test.drop() + await db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", await db.list_collection_names()) + await db.coll.drop() + self.assertNotIn("coll", await db.list_collection_names()) + await db.coll.drop() - await db.drop_collection(db.test.doesnotexist) + await db.drop_collection(db.coll.doesnotexist) if async_client_context.is_rs: db_wc = AsyncDatabase( self.client, "pymongo_test", write_concern=IMPOSSIBLE_WRITE_CONCERN ) with self.assertRaises(WriteConcernError): - await db_wc.drop_collection("test") + await db_wc.drop_collection("coll") async def test_validate_collection(self): - db = self.client.pymongo_test + db = self.db with self.assertRaises(TypeError): await db.validate_collection(5) # type: ignore[arg-type] with self.assertRaises(TypeError): await db.validate_collection(None) # type: ignore[arg-type] - await db.test.insert_one({"dummy": "object"}) + await db.coll.insert_one({"dummy": "object"}) with self.assertRaises(OperationFailure): - await db.validate_collection("test.doesnotexist") + await db.validate_collection("coll.doesnotexist") with self.assertRaises(OperationFailure): - await db.validate_collection(db.test.doesnotexist) + await db.validate_collection(db.coll.doesnotexist) - self.assertTrue(await db.validate_collection("test")) - self.assertTrue(await db.validate_collection(db.test)) - self.assertTrue(await db.validate_collection(db.test, full=True)) - self.assertTrue(await db.validate_collection(db.test, scandata=True)) - self.assertTrue(await db.validate_collection(db.test, scandata=True, full=True)) - self.assertTrue(await db.validate_collection(db.test, True, True)) + self.assertTrue(await db.validate_collection("coll")) + self.assertTrue(await db.validate_collection(db.coll)) + self.assertTrue(await db.validate_collection(db.coll, full=True)) + self.assertTrue(await db.validate_collection(db.coll, scandata=True)) + self.assertTrue(await db.validate_collection(db.coll, scandata=True, full=True)) + self.assertTrue(await db.validate_collection(db.coll, True, True)) @async_client_context.require_no_standalone async def test_validate_collection_background(self): - db = self.client.pymongo_test.with_options(write_concern=WriteConcern(w="majority")) - await db.test.insert_one({"dummy": "object"}) - coll = db.test + db = self.db.with_options(write_concern=WriteConcern(w="majority")) + await db.coll.insert_one({"dummy": "object"}) + coll = db.coll self.assertTrue(await db.validate_collection(coll, background=False)) # The inMemory storage engine does not support background=True. if async_client_context.storage_engine != "inMemory": @@ -412,12 +412,12 @@ async def test_command(self): # We use 'aggregate' as our example command, since it's an easy way to # retrieve a BSON regex from a collection using a command. async def test_command_with_regex(self): - db = self.client.pymongo_test - await db.test.drop() - await db.test.insert_one({"r": re.compile(".*")}) - await db.test.insert_one({"r": Regex(".*")}) + db = self.db + await db.coll.drop() + await db.coll.insert_one({"r": re.compile(".*")}) + await db.coll.insert_one({"r": Regex(".*")}) - result = await db.command("aggregate", "test", pipeline=[], cursor={}) + result = await db.command("aggregate", "coll", pipeline=[], cursor={}) for doc in result["cursor"]["firstBatch"]: self.assertIsInstance(doc["r"], Regex) @@ -427,23 +427,23 @@ async def test_command_bulkWrite(self): await self.client.admin.command( { "bulkWrite": 1, - "nsInfo": [{"ns": self.db.test.full_name}], + "nsInfo": [{"ns": self.db.coll.full_name}], "ops": [{"insert": 0, "document": {}}], } ) - await self.db.command({"insert": "test", "documents": [{}]}) - await self.db.command({"update": "test", "updates": [{"q": {}, "u": {"$set": {"x": 1}}}]}) - await self.db.command({"delete": "test", "deletes": [{"q": {}, "limit": 1}]}) - await self.db.test.drop() + await self.db.command({"insert": "coll", "documents": [{}]}) + await self.db.command({"update": "coll", "updates": [{"q": {}, "u": {"$set": {"x": 1}}}]}) + await self.db.command({"delete": "coll", "deletes": [{"q": {}, "limit": 1}]}) + await self.db.coll.drop() async def test_cursor_command(self): - db = self.client.pymongo_test - await db.test.drop() + db = self.db + await db.coll.drop() docs = [{"_id": i, "doc": i} for i in range(3)] - await db.test.insert_many(docs) + await db.coll.insert_many(docs) - cursor = await db.cursor_command("find", "test") + cursor = await db.cursor_command("find", "coll") self.assertIsInstance(cursor, AsyncCommandCursor) @@ -452,7 +452,7 @@ async def test_cursor_command(self): async def test_cursor_command_invalid(self): with self.assertRaises(InvalidOperation): - await self.db.cursor_command("usersInfo", "test") + await self.db.cursor_command("usersInfo", "coll") @async_client_context.require_no_fips def test_password_digest(self): @@ -478,22 +478,22 @@ async def test_id_ordering(self): # guarantee any particular order. This will never # work right in any Python or environment # with hash randomization enabled (e.g. tox). - db = self.client.pymongo_test - await db.test.drop() - await db.test.insert_one(SON([("hello", "world"), ("_id", 5)])) + db = self.db + await db.coll.drop() + await db.coll.insert_one(SON([("hello", "world"), ("_id", 5)])) db = self.client.get_database( "pymongo_test", codec_options=CodecOptions(document_class=SON[str, Any]) ) - cursor = db.test.find() + cursor = db.coll.find() async for x in cursor: for k, _v in x.items(): self.assertEqual(k, "_id") break async def test_deref(self): - db = self.client.pymongo_test - await db.test.drop() + db = self.db + await db.coll.drop() with self.assertRaises(TypeError): await db.dereference(5) # type: ignore[arg-type] @@ -502,106 +502,106 @@ async def test_deref(self): with self.assertRaises(TypeError): await db.dereference(None) # type: ignore[arg-type] - self.assertEqual(None, await db.dereference(DBRef("test", ObjectId()))) + self.assertEqual(None, await db.dereference(DBRef("coll", ObjectId()))) obj: dict[str, Any] = {"x": True} - key = (await db.test.insert_one(obj)).inserted_id - self.assertEqual(obj, await db.dereference(DBRef("test", key))) - self.assertEqual(obj, await db.dereference(DBRef("test", key, "pymongo_test"))) + key = (await db.coll.insert_one(obj)).inserted_id + self.assertEqual(obj, await db.dereference(DBRef("coll", key))) + self.assertEqual(obj, await db.dereference(DBRef("coll", key, "pymongo_test"))) with self.assertRaises(ValueError): - await db.dereference(DBRef("test", key, "foo")) + await db.dereference(DBRef("coll", key, "foo")) - self.assertEqual(None, await db.dereference(DBRef("test", 4))) + self.assertEqual(None, await db.dereference(DBRef("coll", 4))) obj = {"_id": 4} - await db.test.insert_one(obj) - self.assertEqual(obj, await db.dereference(DBRef("test", 4))) + await db.coll.insert_one(obj) + self.assertEqual(obj, await db.dereference(DBRef("coll", 4))) async def test_deref_kwargs(self): - db = self.client.pymongo_test - await db.test.drop() + db = self.db + await db.coll.drop() - await db.test.insert_one({"_id": 4, "foo": "bar"}) + await db.coll.insert_one({"_id": 4, "foo": "bar"}) db = self.client.get_database( "pymongo_test", codec_options=CodecOptions(document_class=SON[str, Any]) ) self.assertEqual( - SON([("foo", "bar")]), await db.dereference(DBRef("test", 4), projection={"_id": False}) + SON([("foo", "bar")]), await db.dereference(DBRef("coll", 4), projection={"_id": False}) ) # TODO some of these tests belong in the collection level testing. async def test_insert_find_one(self): - db = self.client.pymongo_test - await db.test.drop() + db = self.db + await db.coll.drop() a_doc = SON({"hello": "world"}) - a_key = (await db.test.insert_one(a_doc)).inserted_id + a_key = (await db.coll.insert_one(a_doc)).inserted_id self.assertIsInstance(a_doc["_id"], ObjectId) self.assertEqual(a_doc["_id"], a_key) - self.assertEqual(a_doc, await db.test.find_one({"_id": a_doc["_id"]})) - self.assertEqual(a_doc, await db.test.find_one(a_key)) - self.assertEqual(None, await db.test.find_one(ObjectId())) - self.assertEqual(a_doc, await db.test.find_one({"hello": "world"})) - self.assertEqual(None, await db.test.find_one({"hello": "test"})) + self.assertEqual(a_doc, await db.coll.find_one({"_id": a_doc["_id"]})) + self.assertEqual(a_doc, await db.coll.find_one(a_key)) + self.assertEqual(None, await db.coll.find_one(ObjectId())) + self.assertEqual(a_doc, await db.coll.find_one({"hello": "world"})) + self.assertEqual(None, await db.coll.find_one({"hello": "test"})) - b = await db.test.find_one() + b = await db.coll.find_one() assert b is not None b["hello"] = "mike" - await db.test.replace_one({"_id": b["_id"]}, b) + await db.coll.replace_one({"_id": b["_id"]}, b) - self.assertNotEqual(a_doc, await db.test.find_one(a_key)) - self.assertEqual(b, await db.test.find_one(a_key)) - self.assertEqual(b, await db.test.find_one()) + self.assertNotEqual(a_doc, await db.coll.find_one(a_key)) + self.assertEqual(b, await db.coll.find_one(a_key)) + self.assertEqual(b, await db.coll.find_one()) count = 0 - async for _ in db.test.find(): + async for _ in db.coll.find(): count += 1 self.assertEqual(count, 1) async def test_long(self): - db = self.client.pymongo_test - await db.test.drop() - await db.test.insert_one({"x": 9223372036854775807}) - retrieved = (await db.test.find_one())["x"] + db = self.db + await db.coll.drop() + await db.coll.insert_one({"x": 9223372036854775807}) + retrieved = (await db.coll.find_one())["x"] self.assertEqual(Int64(9223372036854775807), retrieved) self.assertIsInstance(retrieved, Int64) - await db.test.delete_many({}) - await db.test.insert_one({"x": Int64(1)}) - retrieved = (await db.test.find_one())["x"] + await db.coll.delete_many({}) + await db.coll.insert_one({"x": Int64(1)}) + retrieved = (await db.coll.find_one())["x"] self.assertEqual(Int64(1), retrieved) self.assertIsInstance(retrieved, Int64) async def test_delete(self): - db = self.client.pymongo_test - await db.test.drop() + db = self.db + await db.coll.drop() - await db.test.insert_one({"x": 1}) - await db.test.insert_one({"x": 2}) - await db.test.insert_one({"x": 3}) + await db.coll.insert_one({"x": 1}) + await db.coll.insert_one({"x": 2}) + await db.coll.insert_one({"x": 3}) length = 0 - async for _ in db.test.find(): + async for _ in db.coll.find(): length += 1 self.assertEqual(length, 3) - await db.test.delete_one({"x": 1}) + await db.coll.delete_one({"x": 1}) length = 0 - async for _ in db.test.find(): + async for _ in db.coll.find(): length += 1 self.assertEqual(length, 2) - await db.test.delete_one(await db.test.find_one()) # type: ignore[arg-type] - await db.test.delete_one(await db.test.find_one()) # type: ignore[arg-type] - self.assertEqual(await db.test.find_one(), None) + await db.coll.delete_one(await db.coll.find_one()) # type: ignore[arg-type] + await db.coll.delete_one(await db.coll.find_one()) # type: ignore[arg-type] + self.assertEqual(await db.coll.find_one(), None) - await db.test.insert_one({"x": 1}) - await db.test.insert_one({"x": 2}) - await db.test.insert_one({"x": 3}) + await db.coll.insert_one({"x": 1}) + await db.coll.insert_one({"x": 2}) + await db.coll.insert_one({"x": 3}) - self.assertTrue(await db.test.find_one({"x": 2})) - await db.test.delete_one({"x": 2}) - self.assertFalse(await db.test.find_one({"x": 2})) + self.assertTrue(await db.coll.find_one({"x": 2})) + await db.coll.delete_one({"x": 2}) + self.assertFalse(await db.coll.find_one({"x": 2})) - self.assertTrue(await db.test.find_one()) - await db.test.delete_many({}) - self.assertFalse(await db.test.find_one()) + self.assertTrue(await db.coll.find_one()) + await db.coll.delete_many({}) + self.assertFalse(await db.coll.find_one()) def test_command_response_without_ok(self): # Sometimes (SERVER-10891) the server's response to a badly-formatted @@ -624,25 +624,25 @@ async def test_command_max_time_ms(self): "configureFailPoint", "maxTimeAlwaysTimeOut", mode="alwaysOn" ) try: - db = self.client.pymongo_test - await db.command("count", "test") + db = self.db + await db.command("count", "coll") with self.assertRaises(ExecutionTimeout): - await db.command("count", "test", maxTimeMS=1) + await db.command("count", "coll", maxTimeMS=1) pipeline = [{"$project": {"name": 1, "count": 1}}] # Database command helper. - await db.command("aggregate", "test", pipeline=pipeline, cursor={}) + await db.command("aggregate", "coll", pipeline=pipeline, cursor={}) with self.assertRaises(ExecutionTimeout): await db.command( "aggregate", - "test", + "coll", pipeline=pipeline, cursor={}, maxTimeMS=1, ) # Collection helper. - await db.test.aggregate(pipeline=pipeline) + await db.coll.aggregate(pipeline=pipeline) with self.assertRaises(ExecutionTimeout): - await db.test.aggregate(pipeline, maxTimeMS=1) + await db.coll.aggregate(pipeline, maxTimeMS=1) finally: await self.client.admin.command( "configureFailPoint", "maxTimeAlwaysTimeOut", mode="off" diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 5030f4979d..7552054d14 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -428,7 +428,7 @@ async def test_connection_close_does_not_block_other_operations(self): "pool initialized with 10 connections", ) - await client.db.test.insert_one({"x": 1}) + await client.db.coll.insert_one({"x": 1}) close_delay = 0.1 latencies = [] should_exit = [] @@ -436,7 +436,7 @@ async def test_connection_close_does_not_block_other_operations(self): async def run_task(): while True: start_time = time.monotonic() - await client.db.test.find_one({}) + await client.db.coll.find_one({}) elapsed = time.monotonic() - start_time latencies.append(elapsed) if should_exit: @@ -526,13 +526,13 @@ async def teardown(): ) # Make sure the collection has at least one document. - await client.test.test.delete_many({}) - await client.test.test.insert_one({}) + await client.db.coll.delete_many({}) + await client.db.coll.insert_one({}) # Run a slow operation to tie up the connection. async def target(): try: - await client.test.test.find_one({"$where": delay(0.1)}) + await client.db.coll.find_one({"$where": delay(0.1)}) except ConnectionFailure: pass diff --git a/test/asynchronous/test_encryption.py b/test/asynchronous/test_encryption.py index 0628e736fa..6de4b4ca5b 100644 --- a/test/asynchronous/test_encryption.py +++ b/test/asynchronous/test_encryption.py @@ -381,7 +381,7 @@ async def _test_auto_encrypt(self, opts): {"_id": 4, "ssn": "444"}, {"_id": 5, "ssn": "555"}, ] - encrypted_coll = client.pymongo_test.test + encrypted_coll = client.pymongo_test.coll await encrypted_coll.insert_one(docs[0]) await encrypted_coll.insert_many(docs[1:3]) unack = encrypted_coll.with_options(write_concern=WriteConcern(w=0)) @@ -389,12 +389,12 @@ async def _test_auto_encrypt(self, opts): await unack.insert_many(docs[4:], ordered=False) async def count_documents(): - return await self.db.test.count_documents({}) == len(docs) + return await self.db.coll.count_documents({}) == len(docs) await async_wait_until(count_documents, "insert documents with w=0") # Database.command auto decrypts. - res = await client.pymongo_test.command("find", "test", filter={"ssn": "000"}) + res = await client.pymongo_test.command("find", "coll", filter={"ssn": "000"}) decrypted_docs = res["cursor"]["firstBatch"] self.assertEqual(decrypted_docs, [{"_id": 0, "ssn": "000"}]) @@ -419,7 +419,7 @@ async def count_documents(): self.assertEqual(set(decrypted_ssns), {d["ssn"] for d in docs}) # Make sure the field is actually encrypted. - async for encrypted_doc in self.db.test.find(): + async for encrypted_doc in self.db.coll.find(): self.assertIsInstance(encrypted_doc["_id"], int) self.assertEncrypted(encrypted_doc["ssn"]) @@ -430,15 +430,15 @@ async def count_documents(): async def test_auto_encrypt(self): # Configure the encrypted field via jsonSchema. json_schema = json_data("custom", "schema.json") - await create_with_schema(self.db.test, json_schema) - self.addAsyncCleanup(self.db.test.drop) + await create_with_schema(self.db.coll, json_schema) + self.addAsyncCleanup(self.db.coll.drop) opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys") await self._test_auto_encrypt(opts) async def test_auto_encrypt_local_schema_map(self): # Configure the encrypted field via the local schema_map option. - schemas = {"pymongo_test.test": json_data("custom", "schema.json")} + schemas = {"pymongo_test.coll": json_data("custom", "schema.json")} opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys", schema_map=schemas) await self._test_auto_encrypt(opts) @@ -481,7 +481,7 @@ async def test_upsert_uuid_standard_encrypt(self): client = await self.async_rs_or_single_client(auto_encryption_opts=opts) options = CodecOptions(uuid_representation=UuidRepresentation.STANDARD) - encrypted_coll = client.pymongo_test.test + encrypted_coll = client.pymongo_test.coll coll = encrypted_coll.with_options(codec_options=options) uuids = [uuid.uuid4() for _ in range(3)] result = await coll.bulk_write( @@ -519,17 +519,17 @@ async def test_raise_unsupported_error(self): client = await self.async_rs_or_single_client(auto_encryption_opts=opts) msg = "find_raw_batches does not support auto encryption" with self.assertRaisesRegex(InvalidOperation, msg): - await client.test.test.find_raw_batches({}) + await client.db.coll.find_raw_batches({}) msg = "aggregate_raw_batches does not support auto encryption" with self.assertRaisesRegex(InvalidOperation, msg): - await client.test.test.aggregate_raw_batches([]) + await client.db.coll.aggregate_raw_batches([]) # The auto-encryption guard runs at cursor iteration, before the wire-version # check in _Query.use_command, so it is the error regardless of deployment. msg = "exhaust cursors do not support auto encryption" with self.assertRaisesRegex(InvalidOperation, msg): - await anext(client.test.test.find(cursor_type=CursorType.EXHAUST)) + await anext(client.db.coll.find(cursor_type=CursorType.EXHAUST)) class TestExplicitSimple(AsyncEncryptionIntegrationTest): @@ -3911,12 +3911,12 @@ async def asyncSetUp(self) -> None: async def test_implicit_session_ignored_when_unsupported(self): self.listener.reset() with self.assertRaises(OperationFailure): - await self.mongocryptd_client.db.test.find_one() + await self.mongocryptd_client.db.coll.find_one() self.assertNotIn("lsid", self.listener.started_events[0].command) with self.assertRaises(OperationFailure): - await self.mongocryptd_client.db.test.insert_one({"x": 1}) + await self.mongocryptd_client.db.coll.insert_one({"x": 1}) self.assertNotIn("lsid", self.listener.started_events[1].command) @@ -3928,11 +3928,11 @@ async def test_explicit_session_errors_when_unsupported(self): with self.assertRaisesRegex( ConfigurationError, r"Sessions are not supported by this MongoDB deployment" ): - await self.mongocryptd_client.db.test.find_one(session=s) + await self.mongocryptd_client.db.coll.find_one(session=s) with self.assertRaisesRegex( ConfigurationError, r"Sessions are not supported by this MongoDB deployment" ): - await self.mongocryptd_client.db.test.insert_one({"x": 1}, session=s) + await self.mongocryptd_client.db.coll.insert_one({"x": 1}, session=s) await self.mongocryptd_client.close() diff --git a/test/asynchronous/test_grid_file.py b/test/asynchronous/test_grid_file.py index 32d87bc66f..5319620624 100644 --- a/test/asynchronous/test_grid_file.py +++ b/test/asynchronous/test_grid_file.py @@ -61,7 +61,7 @@ class AsyncTestGridFileNoConnect(AsyncUnitTest): @classmethod def setUpClass(cls): - cls.db = AsyncMongoClient(connect=False).pymongo_test + cls.db = AsyncMongoClient(connect=False)["pymongo_test"] def test_grid_in_custom_opts(self): self.assertRaises(TypeError, AsyncGridIn, "foo") diff --git a/test/asynchronous/test_index_management.py b/test/asynchronous/test_index_management.py index 59ce89e686..0ed5b9f0d6 100644 --- a/test/asynchronous/test_index_management.py +++ b/test/asynchronous/test_index_management.py @@ -49,7 +49,7 @@ class TestCreateSearchIndex(AsyncIntegrationTest): async def test_inputs(self): listener = AllowListEventListener("createSearchIndexes") client = self.simple_client(event_listeners=[listener]) - coll = client.test.test + coll = client.db.coll await coll.drop() definition = dict(mappings=dict(dynamic=True)) model_kwarg_list: list[Mapping[str, Any]] = [ diff --git a/test/asynchronous/test_json_util_integration.py b/test/asynchronous/test_json_util_integration.py index 9d364d06c8..cbc307c0c0 100644 --- a/test/asynchronous/test_json_util_integration.py +++ b/test/asynchronous/test_json_util_integration.py @@ -14,7 +14,8 @@ class TestJsonUtilRoundtrip(AsyncIntegrationTest): async def test_cursor(self): db = self.db - await db.drop_collection("test") + await db.drop_collection("coll") + self.addAsyncCleanup(db.drop_collection, "coll") docs: list[MutableMapping[str, Any]] = [ {"foo": [1, 2]}, {"bar": {"hello": "world"}}, @@ -23,7 +24,7 @@ async def test_cursor(self): {"dbref": {"_ref": DBRef("simple", ObjectId("509b8db456c02c5ab7e63c34"))}}, ] - await db.test.insert_many(docs) - reloaded_docs = json_util.loads(json_util.dumps(await (db.test.find()).to_list())) + await db.coll.insert_many(docs) + reloaded_docs = json_util.loads(json_util.dumps(await (db.coll.find()).to_list())) for doc in docs: self.assertIn(doc, reloaded_docs) diff --git a/test/asynchronous/test_load_balancer.py b/test/asynchronous/test_load_balancer.py index bfc278f152..d25686819e 100644 --- a/test/asynchronous/test_load_balancer.py +++ b/test/asynchronous/test_load_balancer.py @@ -65,12 +65,12 @@ async def test_exhaust_cursor(self): async def test_connections_are_only_returned_once(self): pool = await async_get_pool(self.client) n_conns = len(pool.conns) - await self.db.test.find_one({}) + await self.db.coll.find_one({}) # On PyPy it can take a few rounds to collect the cursor. for _ in range(3): gc.collect() self.assertEqual(len(pool.conns), n_conns) - await (await self.db.test.aggregate([{"$limit": 1}])).to_list() + await (await self.db.coll.aggregate([{"$limit": 1}])).to_list() # On PyPy it can take a few rounds to collect the cursor. for _ in range(3): gc.collect() @@ -80,7 +80,7 @@ async def test_connections_are_only_returned_once(self): async def test_unpin_committed_transaction(self): client = await self.async_rs_client() pool = await async_get_pool(client) - coll = client[self.db.name].test + coll = client[self.db.name].coll async with client.start_session() as session: async with await session.start_transaction(): self.assertEqual(pool.active_sockets, 0) @@ -110,7 +110,7 @@ async def create_resource(coll): async def _test_no_gc_deadlock(self, create_resource): client = await self.async_rs_client() pool = await async_get_pool(client) - coll = client[self.db.name].test + coll = client[self.db.name].coll await coll.insert_many([{} for _ in range(10)]) self.assertEqual(pool.active_sockets, 0) # Cause the initial find attempt to fail to induce a reference cycle. @@ -172,7 +172,7 @@ async def test_session_gc(self): await async_wait_until(lambda: pool.active_sockets == 0, "return socket") # Run another operation to ensure the socket still works. - await client[self.db.name].test.delete_many({}) + await client[self.db.name].coll.delete_many({}) class PoolLocker(ExceptionCatchingTask): diff --git a/test/asynchronous/test_logger.py b/test/asynchronous/test_logger.py index 94a78b5170..c9a80b9eb6 100644 --- a/test/asynchronous/test_logger.py +++ b/test/asynchronous/test_logger.py @@ -27,6 +27,10 @@ # https://github.com/mongodb/specifications/tree/master/source/command-logging-and-monitoring/tests#prose-tests class TestLogger(AsyncIntegrationTest): + async def asyncTearDown(self) -> None: + await self.db.coll.drop() + await super().asyncTearDown() + def _get_command_log(self, records, command_name, status): # PyPy's GC is non-deterministic, so cleanup commands from earlier tests can pollute the logs, # filter for the specific command and status we want @@ -43,7 +47,7 @@ async def test_default_truncation_limit(self): with patch.dict("os.environ"): os.environ.pop("MONGOB_LOG_MAX_DOCUMENT_LENGTH", None) with self.assertLogs("pymongo.command", level="DEBUG") as cm: - await db.test.insert_many(docs) + await db.coll.insert_many(docs) cmd_started_log = self._get_command_log( cm.records, "insert", _CommandStatusMessage.STARTED @@ -56,7 +60,7 @@ async def test_default_truncation_limit(self): self.assertLessEqual(len(cmd_succeeded_log["reply"]), _DEFAULT_DOCUMENT_LENGTH + 3) with self.assertLogs("pymongo.command", level="DEBUG") as cm: - await db.test.find({}).to_list() + await db.coll.find({}).to_list() cmd_succeeded_log = self._get_command_log( cm.records, "find", _CommandStatusMessage.SUCCEEDED ) @@ -97,7 +101,7 @@ async def test_truncation_multi_byte_codepoints(self): for length in document_lengths: with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": length}): with self.assertLogs("pymongo.command", level="DEBUG") as cm: - await self.db.test.insert_one({"x": multi_byte_char_str}) + await self.db.coll.insert_one({"x": multi_byte_char_str}) cmd_started_log = self._get_command_log( cm.records, "insert", _CommandStatusMessage.STARTED )["command"] @@ -111,18 +115,18 @@ async def test_logging_without_listeners(self): c = await self.async_single_client() self.assertEqual(len(c._event_listeners.event_listeners()), 0) with self.assertLogs("pymongo.connection", level="DEBUG") as cm: - await c.db.test.insert_one({"x": "1"}) + await c.db.coll.insert_one({"x": "1"}) self.assertGreater(len(cm.records), 0) with self.assertLogs("pymongo.command", level="DEBUG") as cm: - await c.db.test.insert_one({"x": "1"}) + await c.db.coll.insert_one({"x": "1"}) self.assertGreater(len(cm.records), 0) with self.assertLogs("pymongo.serverSelection", level="DEBUG") as cm: - await c.db.test.insert_one({"x": "1"}) + await c.db.coll.insert_one({"x": "1"}) self.assertGreater(len(cm.records), 0) @async_client_context.require_failCommand_fail_point async def test_logging_retry_read_attempts(self): - await self.db.test.insert_one({"x": "1"}) + await self.db.coll.insert_one({"x": "1"}) async with self.fail_point( { @@ -135,7 +139,7 @@ async def test_logging_retry_read_attempts(self): } ): with self.assertLogs("pymongo.command", level="DEBUG") as cm: - await self.db.test.find_one({"x": "1"}) + await self.db.coll.find_one({"x": "1"}) retry_messages = [ r.getMessage() for r in cm.records if "Retrying read attempt" in r.getMessage() @@ -156,7 +160,7 @@ async def test_logging_retry_write_attempts(self): } ): with self.assertLogs("pymongo.command", level="DEBUG") as cm: - await self.db.test.insert_one({"x": "1"}) + await self.db.coll.insert_one({"x": "1"}) retry_messages = [ r.getMessage() for r in cm.records if "Retrying write attempt" in r.getMessage() diff --git a/test/asynchronous/test_max_staleness.py b/test/asynchronous/test_max_staleness.py index cd6b462fcc..1af7a31d91 100644 --- a/test/asynchronous/test_max_staleness.py +++ b/test/asynchronous/test_max_staleness.py @@ -124,7 +124,8 @@ async def test_max_staleness_zero(self): async def test_last_write_date(self): # From max-staleness-tests.rst, "Parse lastWriteDate". client = await self.async_rs_or_single_client(heartbeatFrequencyMS=500) - await client.pymongo_test.test.insert_one({}) + self.addAsyncCleanup(client.pymongo_test.coll.drop) + await client.pymongo_test.coll.insert_one({}) # Wait for the server description to be updated. await asyncio.sleep(1) server = await client._topology.select_server(writable_server_selector, _Op.TEST) @@ -133,7 +134,7 @@ async def test_last_write_date(self): # The first last_write_date may correspond to a internal server write, # sleep so that the next write does not occur within the same second. await asyncio.sleep(1) - await client.pymongo_test.test.insert_one({}) + await client.pymongo_test.coll.insert_one({}) # Wait for the server description to be updated. await asyncio.sleep(1) server = await client._topology.select_server(writable_server_selector, _Op.TEST) diff --git a/test/asynchronous/test_monitoring.py b/test/asynchronous/test_monitoring.py index c29ab71cc2..e317f65ac3 100644 --- a/test/asynchronous/test_monitoring.py +++ b/test/asynchronous/test_monitoring.py @@ -63,6 +63,7 @@ async def asyncSetUp(self) -> None: self.client = await self.async_rs_or_single_client( event_listeners=[self.listener], retryWrites=False ) + self.addAsyncCleanup(self.client.pymongo_test.coll.drop) async def test_started_simple(self): await self.client.pymongo_test.command("ping") @@ -107,14 +108,14 @@ async def test_failed_simple(self): self.assertIsInstance(failed.duration_micros, int) async def test_find_one(self): - await self.client.pymongo_test.test.find_one() + await self.client.pymongo_test.coll.find_one() started = self.listener.started_events[0] succeeded = self.listener.succeeded_events[0] self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(succeeded, monitoring.CommandSucceededEvent) self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("find", "test"), ("filter", {}), ("limit", 1), ("singleBatch", True)]), + SON([("find", "coll"), ("filter", {}), ("limit", 1), ("singleBatch", True)]), started.command, ) self.assertEqual("find", started.command_name) @@ -123,10 +124,10 @@ async def test_find_one(self): self.assertIsInstance(started.request_id, int) async def test_find_and_get_more(self): - await self.client.pymongo_test.test.drop() - await self.client.pymongo_test.test.insert_many([{} for _ in range(10)]) + await self.client.pymongo_test.coll.drop() + await self.client.pymongo_test.coll.insert_many([{} for _ in range(10)]) self.listener.reset() - cursor = self.client.pymongo_test.test.find(projection={"_id": False}, batch_size=4) + cursor = self.client.pymongo_test.coll.find(projection={"_id": False}, batch_size=4) for _ in range(4): await anext(cursor) cursor_id = cursor.cursor_id @@ -136,7 +137,7 @@ async def test_find_and_get_more(self): self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( SON( - [("find", "test"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 4)] + [("find", "coll"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 4)] ), started.command, ) @@ -151,7 +152,7 @@ async def test_find_and_get_more(self): self.assertEqual(cursor.address, succeeded.connection_id) csr = succeeded.reply["cursor"] self.assertEqual(csr["id"], cursor_id) - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(csr["firstBatch"], [{} for _ in range(4)]) self.listener.reset() @@ -164,7 +165,7 @@ async def test_find_and_get_more(self): self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test"), ("batchSize", 4)]), + SON([("getMore", cursor_id), ("collection", "coll"), ("batchSize", 4)]), started.command, ) self.assertEqual("getMore", started.command_name) @@ -178,18 +179,18 @@ async def test_find_and_get_more(self): self.assertEqual(cursor.address, succeeded.connection_id) csr = succeeded.reply["cursor"] self.assertEqual(csr["id"], cursor_id) - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(csr["nextBatch"], [{} for _ in range(4)]) finally: # Exhaust the cursor to avoid kill cursors. tuple(await cursor.to_list()) async def test_find_with_explain(self): - cmd = SON([("explain", SON([("find", "test"), ("filter", {})]))]) - await self.client.pymongo_test.test.drop() - await self.client.pymongo_test.test.insert_one({}) + cmd = SON([("explain", SON([("find", "coll"), ("filter", {})]))]) + await self.client.pymongo_test.coll.drop() + await self.client.pymongo_test.coll.insert_one({}) self.listener.reset() - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll # Test that we publish the unwrapped command. if await self.client.is_mongos: coll = coll.with_options(read_preference=ReadPreference.PRIMARY_PREFERRED) @@ -211,7 +212,7 @@ async def test_find_with_explain(self): self.assertEqual(res, succeeded.reply) async def _test_find_options(self, query, expected_cmd): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll await coll.drop() await coll.create_index("x") await coll.insert_many([{"x": i} for i in range(5)]) @@ -262,7 +263,7 @@ async def test_find_options(self): } cmd = { - "find": "test", + "find": "coll", "filter": {}, "hint": SON([("x", 1)]), "comment": "this is a test", @@ -282,10 +283,10 @@ async def test_find_options(self): await self._test_find_options(query, cmd) async def test_command_and_get_more(self): - await self.client.pymongo_test.test.drop() - await self.client.pymongo_test.test.insert_many([{"x": 1} for _ in range(10)]) + await self.client.pymongo_test.coll.drop() + await self.client.pymongo_test.coll.insert_many([{"x": 1} for _ in range(10)]) self.listener.reset() - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll # Test that we publish the unwrapped command. if await self.client.is_mongos: coll = coll.with_options(read_preference=ReadPreference.PRIMARY_PREFERRED) @@ -300,7 +301,7 @@ async def test_command_and_get_more(self): self.assertEqualCommand( SON( [ - ("aggregate", "test"), + ("aggregate", "coll"), ("pipeline", [{"$project": {"_id": False, "x": 1}}]), ("cursor", {"batchSize": 4}), ] @@ -318,7 +319,7 @@ async def test_command_and_get_more(self): self.assertEqual(cursor.address, succeeded.connection_id) expected_cursor = { "id": cursor_id, - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "firstBatch": [{"x": 1} for _ in range(4)], } self.assertEqualCommand(expected_cursor, succeeded.reply.get("cursor")) @@ -331,7 +332,7 @@ async def test_command_and_get_more(self): self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test"), ("batchSize", 4)]), + SON([("getMore", cursor_id), ("collection", "coll"), ("batchSize", 4)]), started.command, ) self.assertEqual("getMore", started.command_name) @@ -346,7 +347,7 @@ async def test_command_and_get_more(self): expected_result = { "cursor": { "id": cursor_id, - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "nextBatch": [{"x": 1} for _ in range(4)], }, "ok": 1.0, @@ -358,7 +359,7 @@ async def test_command_and_get_more(self): async def test_get_more_failure(self): address = await self.client.address - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll cursor_id = Int64(12345) cursor_doc = {"id": cursor_id, "firstBatch": [], "ns": coll.full_name} cursor = AsyncCommandCursor(coll, cursor_doc, address) @@ -371,7 +372,7 @@ async def test_get_more_failure(self): failed = self.listener.failed_events[0] self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test")]), started.command + SON([("getMore", cursor_id), ("collection", "coll")]), started.command ) self.assertEqual("getMore", started.command_name) self.assertEqual(await self.client.address, started.connection_id) @@ -394,7 +395,7 @@ async def test_not_primary_error(self): self.listener.reset() error = None try: - await client.pymongo_test.test.find_one_and_delete({}) + await client.pymongo_test.coll.find_one_and_delete({}) except NotPrimaryError as exc: error = exc.errors started = self.listener.started_events[0] @@ -411,10 +412,10 @@ async def test_not_primary_error(self): @async_client_context.require_exhaust_cursors async def test_exhaust(self): - await self.client.pymongo_test.test.drop() - await self.client.pymongo_test.test.insert_many([{} for _ in range(11)]) + await self.client.pymongo_test.coll.drop() + await self.client.pymongo_test.coll.insert_many([{} for _ in range(11)]) self.listener.reset() - cursor = self.client.pymongo_test.test.find( + cursor = self.client.pymongo_test.coll.find( projection={"_id": False}, batch_size=5, cursor_type=CursorType.EXHAUST ) await anext(cursor) @@ -425,7 +426,7 @@ async def test_exhaust(self): self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( SON( - [("find", "test"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 5)] + [("find", "coll"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 5)] ), started.command, ) @@ -441,7 +442,7 @@ async def test_exhaust(self): expected_result = { "cursor": { "id": cursor_id, - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "firstBatch": [{} for _ in range(5)], }, "ok": 1, @@ -454,7 +455,7 @@ async def test_exhaust(self): for event in self.listener.started_events: self.assertIsInstance(event, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test"), ("batchSize", 5)]), + SON([("getMore", cursor_id), ("collection", "coll"), ("batchSize", 5)]), event.command, ) self.assertEqual("getMore", event.command_name) @@ -472,9 +473,9 @@ async def test_exhaust(self): async def test_kill_cursors(self): with client_knobs(kill_cursor_frequency=0.01): - await self.client.pymongo_test.test.drop() - await self.client.pymongo_test.test.insert_many([{} for _ in range(10)]) - cursor = self.client.pymongo_test.test.find().batch_size(5) + await self.client.pymongo_test.coll.drop() + await self.client.pymongo_test.coll.insert_many([{} for _ in range(10)]) + cursor = self.client.pymongo_test.coll.find().batch_size(5) await anext(cursor) cursor_id = cursor.cursor_id self.listener.reset() @@ -505,7 +506,7 @@ async def test_kill_cursors(self): ) async def test_non_bulk_writes(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll await coll.drop() self.listener.reset() @@ -820,7 +821,7 @@ async def test_non_bulk_writes(self): async def test_insert_many(self): # This always uses the bulk API. - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll await coll.drop() self.listener.reset() @@ -859,7 +860,7 @@ async def test_insert_many(self): self.assertEqual(6, count) async def test_insert_many_unacknowledged(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll await coll.drop() unack_coll = coll.with_options(write_concern=WriteConcern(w=0)) self.listener.reset() @@ -902,7 +903,7 @@ async def check(): await async_wait_until(check, "insert documents with w=0") async def test_bulk_write(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll await coll.drop() self.listener.reset() @@ -965,7 +966,7 @@ async def test_bulk_write(self): @async_client_context.require_failCommand_fail_point async def test_bulk_write_command_network_error(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll self.listener.reset() insert_network_error = { @@ -989,7 +990,7 @@ async def test_bulk_write_command_network_error(self): @async_client_context.require_failCommand_fail_point async def test_bulk_write_command_error(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll self.listener.reset() insert_command_error = { @@ -1013,7 +1014,7 @@ async def test_bulk_write_command_error(self): self.assertTrue(event.failure["errmsg"]) async def test_write_errors(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll await coll.drop() self.listener.reset() @@ -1056,15 +1057,17 @@ async def test_write_errors(self): self.assertLessEqual(fields, set(error)) async def test_first_batch_helper(self): + # Ensure the collection exists so listIndexes works on sharded clusters. + await self.client.pymongo_test.coll.insert_one({}) # Regardless of server version and use of helpers._first_batch # this test should still pass. self.listener.reset() - tuple(await (await self.client.pymongo_test.test.list_indexes()).to_list()) + tuple(await (await self.client.pymongo_test.coll.list_indexes()).to_list()) started = self.listener.started_events[0] succeeded = self.listener.succeeded_events[0] self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(started, monitoring.CommandStartedEvent) - expected = SON([("listIndexes", "test"), ("cursor", {})]) + expected = SON([("listIndexes", "coll"), ("cursor", {})]) self.assertEqualCommand(expected, started.command) self.assertEqual("pymongo_test", started.database_name) self.assertEqual("listIndexes", started.command_name) diff --git a/test/asynchronous/test_pooling.py b/test/asynchronous/test_pooling.py index 063f5f06ec..ef670774c8 100644 --- a/test/asynchronous/test_pooling.py +++ b/test/asynchronous/test_pooling.py @@ -170,9 +170,9 @@ async def asyncSetUp(self): self.c = await self.async_rs_or_single_client() db = self.c[DB] await db.unique.drop() - await db.test.drop() + await db.coll.drop() await db.unique.insert_one({"_id": "jesse"}) - await db.test.insert_many([{} for _ in range(10)]) + await db.coll.insert_many([{} for _ in range(10)]) async def create_pool(self, pair=None, *args, **kwargs): if pair is None: @@ -458,14 +458,14 @@ async def test_checkout_more_than_max_pool_size(self): async def test_maxConnecting(self): client = await self.async_rs_or_single_client() - await self.client.test.test.insert_one({}) - self.addAsyncCleanup(self.client.test.test.delete_many, {}) + await self.client.db.coll.insert_one({}) + self.addAsyncCleanup(self.client.db.coll.delete_many, {}) pool = await async_get_pool(client) docs = [] # Run 50 short running operations async def find_one(): - docs.append(await client.test.test.find_one({})) + docs.append(await client.db.coll.find_one({})) tasks = [ConcurrentRunner(target=find_one) for _ in range(50)] for task in tasks: @@ -506,12 +506,12 @@ async def test_csot_timeout_message(self): }, } - await client.db.t.insert_one({"x": 1}) + await client.db.coll.insert_one({"x": 1}) async with self.fail_point(mock_connection_timeout): with self.assertRaises(Exception) as error: with timeout(0.5): - await client.db.t.find_one({"$where": delay(2)}) + await client.db.coll.find_one({"$where": delay(2)}) self.assertIn("(configured timeouts: timeoutMS: 500.0ms", str(error.exception)) @@ -532,11 +532,11 @@ async def test_socket_timeout_message(self): }, } - await client.db.t.insert_one({"x": 1}) + await client.db.coll.insert_one({"x": 1}) async with self.fail_point(mock_connection_timeout): with self.assertRaises(Exception) as error: - await client.db.t.find_one({"$where": delay(2)}) + await client.db.coll.find_one({"$where": delay(2)}) self.assertIn( "(configured timeouts: socketTimeoutMS: 500.0ms, connectTimeoutMS: 20000.0ms)", @@ -617,7 +617,7 @@ class TestPoolMaxSize(_TestPoolingBase): async def test_max_pool_size(self): max_pool_size = 4 c = await self.async_rs_or_single_client(maxPoolSize=max_pool_size) - collection = c[DB].test + collection = c[DB].coll # Need one document. await collection.drop() @@ -656,7 +656,7 @@ async def f(): ) async def test_max_pool_size_none(self): c = await self.async_rs_or_single_client(maxPoolSize=None) - collection = c[DB].test + collection = c[DB].coll # Need one document. await collection.drop() diff --git a/test/asynchronous/test_raw_bson.py b/test/asynchronous/test_raw_bson.py index 6675c30928..5ebcfb350c 100644 --- a/test/asynchronous/test_raw_bson.py +++ b/test/asynchronous/test_raw_bson.py @@ -38,7 +38,7 @@ class TestRawBSONDocument(AsyncIntegrationTest): async def asyncTearDown(self): if async_client_context.connected: - await self.client.pymongo_test.test_raw.drop() + await self.db.test_raw.drop() @async_client_context.require_connection async def test_round_trip_view_backed_document(self): @@ -88,7 +88,7 @@ async def test_round_trip_codec_options(self): "date": datetime.datetime(2015, 6, 3, 18, 40, 50, 826000), "_id": uuid.UUID("026fab8f-975f-4965-9fbf-85ad874c60ff"), } - db = self.client.pymongo_test + db = self.db coll = db.get_collection( "test_raw", codec_options=CodecOptions(uuid_representation=JAVA_LEGACY) ) @@ -104,7 +104,7 @@ async def test_round_trip_codec_options(self): @async_client_context.require_connection async def test_raw_bson_document_embedded(self): doc = {"embedded": self.document} - db = self.client.pymongo_test + db = self.db await db.test_raw.insert_one(doc) result = await db.test_raw.find_one() assert result is not None diff --git a/test/asynchronous/test_read_concern.py b/test/asynchronous/test_read_concern.py index b694d8c0bf..32fde7970a 100644 --- a/test/asynchronous/test_read_concern.py +++ b/test/asynchronous/test_read_concern.py @@ -39,10 +39,11 @@ async def asyncSetUp(self): self.listener = OvertCommandListener() self.client = await self.async_rs_or_single_client(event_listeners=[self.listener]) self.db = self.client.pymongo_test - await async_client_context.client.pymongo_test.create_collection("coll") + await self.db.create_collection("coll") + self.listener.reset() async def asyncTearDown(self): - await async_client_context.client.pymongo_test.drop_collection("coll") + await self.db.drop_collection("coll") def test_read_concern(self): rc = ReadConcern() diff --git a/test/asynchronous/test_read_preferences.py b/test/asynchronous/test_read_preferences.py index 7801926550..fef76a6f27 100644 --- a/test/asynchronous/test_read_preferences.py +++ b/test/asynchronous/test_read_preferences.py @@ -105,16 +105,16 @@ class TestReadPreferencesBase(AsyncIntegrationTest): async def asyncSetUp(self): await super().asyncSetUp() # Insert some data so we can use cursors in read_from_which_host - await self.client.pymongo_test.test.drop() + await self.db.coll.drop() await self.client.get_database( "pymongo_test", write_concern=WriteConcern(w=async_client_context.w) - ).test.insert_many([{"_id": i} for i in range(10)]) + ).coll.insert_many([{"_id": i} for i in range(10)]) - self.addAsyncCleanup(self.client.pymongo_test.test.drop) + self.addAsyncCleanup(self.db.coll.drop) async def read_from_which_host(self, client): """Do a find() on the client and return which host was used""" - cursor = client.pymongo_test.test.find() + cursor = client.pymongo_test.coll.find() await anext(cursor) return cursor.address @@ -158,7 +158,7 @@ async def test_reads_from_secondary(self): self.assertEqual(client.read_preference, ReadPreference.PRIMARY) db = client.pymongo_test - coll = db.test + coll = db.coll # Test find and find_one. self.assertIsNotNone(await coll.find_one()) @@ -166,7 +166,7 @@ async def test_reads_from_secondary(self): # Test some database helpers. self.assertIsNotNone(await db.list_collection_names()) - self.assertIsNotNone(await db.validate_collection("test")) + self.assertIsNotNone(await db.validate_collection("coll")) self.assertIsNotNone(await db.command("ping")) # Test some collection helpers. @@ -444,17 +444,17 @@ async def func(): await self._test_primary_helper(func) async def test_count_documents(self): - await self._test_coll_helper(True, self.c.pymongo_test.test, "count_documents", {}) + await self._test_coll_helper(True, self.c.pymongo_test.coll, "count_documents", {}) async def test_estimated_document_count(self): - await self._test_coll_helper(True, self.c.pymongo_test.test, "estimated_document_count") + await self._test_coll_helper(True, self.c.pymongo_test.coll, "estimated_document_count") async def test_distinct(self): - await self._test_coll_helper(True, self.c.pymongo_test.test, "distinct", "a") + await self._test_coll_helper(True, self.c.pymongo_test.coll, "distinct", "a") async def test_aggregate(self): await self._test_coll_helper( - True, self.c.pymongo_test.test, "aggregate", [{"$project": {"_id": 1}}] + True, self.c.pymongo_test.coll, "aggregate", [{"$project": {"_id": 1}}] ) async def test_aggregate_write(self): @@ -462,7 +462,7 @@ async def test_aggregate_write(self): secondary_ok = async_client_context.version.at_least(5, 0) await self._test_coll_helper( secondary_ok, - self.c.pymongo_test.test, + self.c.pymongo_test.coll, "aggregate", [{"$project": {"_id": 1}}, {"$out": "agg_write_test"}], ) @@ -596,7 +596,7 @@ async def test_send_hedge(self): for _mode, cls in cases.items(): with _ignore_deprecations(): pref = cls(hedge={"enabled": True}) - coll = client.test.get_collection("test", read_preference=pref) + coll = client.test.get_collection("coll", read_preference=pref) listener.reset() await coll.find_one() started = listener.started_events @@ -680,9 +680,7 @@ async def test_mongos(self): num_members = shard.count(",") + 1 if num_members == 1: raise SkipTest("Need a replica set shard to test.") - coll = async_client_context.client.pymongo_test.get_collection( - "test", write_concern=WriteConcern(w=num_members) - ) + coll = self.db.get_collection("test", write_concern=WriteConcern(w=num_members)) await coll.drop() res = await coll.insert_many([{} for _ in range(5)]) first_id = res.inserted_ids[0] @@ -702,15 +700,11 @@ async def test_mongos(self): @async_client_context.require_mongos async def test_mongos_max_staleness(self): # Sanity check that we're sending maxStalenessSeconds - coll = async_client_context.client.pymongo_test.get_collection( - "test", read_preference=SecondaryPreferred(max_staleness=120) - ) + coll = self.db.get_collection("coll", read_preference=SecondaryPreferred(max_staleness=120)) # No error await coll.find_one() - coll = async_client_context.client.pymongo_test.get_collection( - "test", read_preference=SecondaryPreferred(max_staleness=10) - ) + coll = self.db.get_collection("coll", read_preference=SecondaryPreferred(max_staleness=10)) try: await coll.find_one() except OperationFailure as exc: @@ -722,7 +716,7 @@ async def test_mongos_max_staleness(self): await self.async_single_client( readPreference="secondaryPreferred", maxStalenessSeconds=120 ) - ).pymongo_test.test + ).pymongo_test.coll # No error await coll.find_one() @@ -730,7 +724,7 @@ async def test_mongos_max_staleness(self): await self.async_single_client( readPreference="secondaryPreferred", maxStalenessSeconds=10 ) - ).pymongo_test.test + ).pymongo_test.coll try: await coll.find_one() except OperationFailure as exc: diff --git a/test/asynchronous/test_read_write_concern_spec.py b/test/asynchronous/test_read_write_concern_spec.py index f7830fb6b0..c14fc14d1d 100644 --- a/test/asynchronous/test_read_write_concern_spec.py +++ b/test/asynchronous/test_read_write_concern_spec.py @@ -108,7 +108,7 @@ async def assertWriteOpsRaise(self, write_concern, expected_exception): w=wc["w"], wTimeoutMS=wc["wtimeout"], socketTimeoutMS=30000 ) db = client.get_database("pymongo_test") - coll = db.test + coll = db.coll async def insert_command(): await coll.database.command( @@ -194,12 +194,12 @@ async def test_error_includes_errInfo(self): async with self.fail_point(cause_wce): # Write concern error on insert includes errInfo. with self.assertRaises(WriteConcernError) as ctx: - await self.db.test.insert_one({}) + await self.db.coll.insert_one({}) self.assertEqual(ctx.exception.details, expected_wce) # Test bulk_write as well. with self.assertRaises(BulkWriteError) as ctx: - await self.db.test.bulk_write([InsertOne({})]) + await self.db.coll.bulk_write([InsertOne({})]) expected_details = { "writeErrors": [], "writeConcernErrors": [expected_wce], @@ -221,9 +221,9 @@ async def test_write_error_details_exposes_errinfo(self): db = client.errinfotest self.addAsyncCleanup(client.drop_database, "errinfotest") validator = {"x": {"$type": "string"}} - await db.create_collection("test", validator=validator) + await db.create_collection("coll", validator=validator) with self.assertRaises(WriteError) as ctx: - await db.test.insert_one({"x": 1}) + await db.coll.insert_one({"x": 1}) self.assertEqual(ctx.exception.code, 121) self.assertIsNotNone(ctx.exception.details) assert ctx.exception.details is not None diff --git a/test/asynchronous/test_retryable_reads.py b/test/asynchronous/test_retryable_reads.py index ecf621fc7e..eb1b86f849 100644 --- a/test/asynchronous/test_retryable_reads.py +++ b/test/asynchronous/test_retryable_reads.py @@ -97,7 +97,7 @@ async def test_pool_paused_error_is_retryable(self): for _ in range(10): cmap_listener.reset() cmd_listener.reset() - threads = [FindThread(client.pymongo_test.test) for _ in range(2)] + threads = [FindThread(client.pymongo_test.coll) for _ in range(2)] fail_command = { "mode": {"times": 1}, "data": { @@ -183,7 +183,7 @@ async def test_retryable_reads_are_retried_on_a_different_mongos_when_one_is_ava ) with self.assertRaises(OperationFailure): - await client.t.t.find_one({}) + await client.db.coll.find_one({}) # Disable failpoints on each mongos for client in mongos_clients: @@ -219,7 +219,7 @@ async def test_retryable_reads_are_retried_on_the_same_mongos_when_no_others_are retryReads=True, ) - await client.t.t.find_one({}) + await client.db.coll.find_one({}) # Disable failpoint. fail_command["mode"] = "off" @@ -241,17 +241,17 @@ async def test_retryable_reads_are_retried_on_the_same_implicit_session(self): retryReads=True, ) - await client.t.t.insert_one({"x": 1}) + await client.db.coll.insert_one({"x": 1}) commands = [ - ("aggregate", lambda: client.t.t.count_documents({})), - ("aggregate", lambda: client.t.t.aggregate([{"$match": {}}])), - ("count", lambda: client.t.t.estimated_document_count()), - ("distinct", lambda: client.t.t.distinct("x")), - ("find", lambda: client.t.t.find_one({})), + ("aggregate", lambda: client.db.coll.count_documents({})), + ("aggregate", lambda: client.db.coll.aggregate([{"$match": {}}])), + ("count", lambda: client.db.coll.estimated_document_count()), + ("distinct", lambda: client.db.coll.distinct("x")), + ("find", lambda: client.db.coll.find_one({})), ("listDatabases", lambda: client.list_databases()), ("listCollections", lambda: client.t.list_collections()), - ("listIndexes", lambda: client.t.t.list_indexes()), + ("listIndexes", lambda: client.db.coll.list_indexes()), ] for command_name, operation in commands: @@ -310,7 +310,7 @@ async def test_03_01_retryable_reads_caused_by_overload_errors_are_retried_on_a_ listener.reset() # 4. Execute a `find` command with `client`. - await client.t.t.find_one({}) + await client.db.coll.find_one({}) # 5. Assert that one failed command event and one successful command event occurred. self.assertEqual(len(listener.failed_events), 1) @@ -351,7 +351,7 @@ async def test_03_02_retryable_reads_caused_by_non_overload_errors_are_retried_o listener.reset() # 4. Execute a `find` command with `client`. - await client.t.t.find_one({}) + await client.db.coll.find_one({}) # 5. Assert that one failed command event and one successful command event occurred. self.assertEqual(len(listener.failed_events), 1) @@ -394,7 +394,7 @@ async def test_03_03_retryable_reads_caused_by_overload_errors_are_retried_on_th listener.reset() # 4. Execute a `find` command with `client`. - await client.t.t.find_one({}) + await client.db.coll.find_one({}) # 5. Assert that one failed command event and one successful command event occurred. self.assertEqual(len(listener.failed_events), 1) @@ -443,13 +443,13 @@ def failed(event: CommandFailedEvent) -> None: listener.failed = failed client = await self.async_rs_client(event_listeners=[listener]) - await client.test.test.insert_one({}) + await client.db.coll.insert_one({}) self.configure_fail_point_sync(overload_fail_point) self.addCleanup(self.configure_fail_point_sync, {}, off=True) with self.assertRaises(PyMongoError): - await client.test.test.find_one() + await client.db.coll.find_one() started_finds = [e for e in listener.started_events if e.command_name == "find"] self.assertEqual(len(started_finds), MAX_ADAPTIVE_RETRIES + 1) @@ -499,7 +499,7 @@ def failed(event: CommandFailedEvent) -> None: listener.failed = failed client = await self.async_rs_client(event_listeners=[listener]) - await client.test.test.insert_one({}) + await client.db.coll.insert_one({}) self.configure_fail_point_sync(overload_fail_point) self.addCleanup(self.configure_fail_point_sync, {}, off=True) @@ -507,7 +507,7 @@ def failed(event: CommandFailedEvent) -> None: # Perform a findOne operation with coll. Expect the operation to fail. with mock.patch(mock_target, return_value=0) as mock_backoff: with self.assertRaises(PyMongoError): - await client.test.test.find_one() + await client.db.coll.find_one() # Assert that backoff was applied only once for the initial overload error and not for the subsequent non-overload retryable errors. self.assertEqual(mock_backoff.call_count, 1) diff --git a/test/asynchronous/test_retryable_writes.py b/test/asynchronous/test_retryable_writes.py index 90be59016a..f6a0bafbfd 100644 --- a/test/asynchronous/test_retryable_writes.py +++ b/test/asynchronous/test_retryable_writes.py @@ -385,7 +385,7 @@ async def test_retryable_writes_in_sharded_cluster_multiple_available(self): ) with self.assertRaises(AutoReconnect): - await client.t.t.insert_one({"x": 1}) + await client.db.coll.insert_one({"x": 1}) # Disable failpoints on each mongos for client in mongos_clients: @@ -435,7 +435,7 @@ async def test_RetryableWriteError_error_label_RawBSONDocument(self): async with self.fail_point(self.fail_insert): async with self.client.start_session() as s: s._start_retryable_write() - result = await self.client.pymongo_test.command( + result = await self.db.command( "insert", "testcoll", documents=[{"_id": 1}], @@ -480,7 +480,7 @@ async def test_pool_paused_error_is_retryable(self): for _ in range(10): cmap_listener.reset() cmd_listener.reset() - threads = [InsertThread(client.pymongo_test.test) for _ in range(2)] + threads = [InsertThread(client.pymongo_test.coll) for _ in range(2)] fail_command = { "mode": {"times": 1}, "data": { @@ -541,7 +541,7 @@ async def test_returns_original_error_code( client = await self.async_rs_or_single_client( retryWrites=True, event_listeners=[cmd_listener] ) - await client.test.test.drop() + await client.db.coll.drop() cmd_listener.reset() await client.admin.command( { @@ -557,7 +557,7 @@ async def test_returns_original_error_code( } ) with self.assertRaises(WriteConcernError) as exc: - await client.test.test.insert_one({"_id": 1}) + await client.db.coll.insert_one({"_id": 1}) self.assertEqual(exc.exception.code, 91) await client.admin.command( { @@ -671,7 +671,7 @@ def failed(event: CommandFailedEvent) -> None: # Attempt an insertOne operation on any record for any database and collection. # Expect the insertOne to fail with a server error. with self.assertRaises(NotPrimaryError) as exc: - await client.test.test.insert_one({}) + await client.db.coll.insert_one({}) # Assert that the error code of the server error is 10107. assert exc.exception.errors["code"] == 10107 # type:ignore[call-overload] @@ -724,7 +724,7 @@ def failed(event: CommandFailedEvent) -> None: # Attempt an insertOne operation on any record for any database and collection. # Expect the insertOne to fail with a server error. with self.assertRaises(NotPrimaryError) as exc: - await client.test.test.insert_one({}) + await client.db.coll.insert_one({}) # Assert that the error code of the server error is 91. assert exc.exception.errors["code"] == 91 # type:ignore[call-overload] @@ -778,7 +778,7 @@ def failed(event: CommandFailedEvent) -> None: # Attempt an insertOne operation on any record for any database and collection. # Expect the insertOne to fail with a server error. with self.assertRaises(PyMongoError) as exc: - await client.test.test.insert_one({}) + await client.db.coll.insert_one({}) # Assert that the error code of the server error is 91. assert exc.exception.errors["code"] == 91 @@ -829,7 +829,7 @@ def failed(event: CommandFailedEvent) -> None: self.addCleanup(self.configure_fail_point_sync, {}, off=True) with self.assertRaises(PyMongoError): - await client.test.test.insert_one({"x": 1}) + await client.db.coll.insert_one({"x": 1}) started_inserts = [e for e in listener.started_events if e.command_name == "insert"] self.assertEqual(len(started_inserts), MAX_ADAPTIVE_RETRIES + 1) @@ -885,7 +885,7 @@ def failed(event: CommandFailedEvent) -> None: # Perform a findOne operation with coll. Expect the operation to fail. with mock.patch(mock_target, return_value=0) as mock_backoff: with self.assertRaises(PyMongoError): - await client.test.test.insert_one({}) + await client.db.coll.insert_one({}) # Assert that backoff was applied only once for the initial overload error and not for the subsequent non-overload retryable errors. self.assertEqual(mock_backoff.call_count, 1) diff --git a/test/asynchronous/test_sdam_monitoring_spec.py b/test/asynchronous/test_sdam_monitoring_spec.py index 5ffeb81eb9..692625e326 100644 --- a/test/asynchronous/test_sdam_monitoring_spec.py +++ b/test/asynchronous/test_sdam_monitoring_spec.py @@ -295,7 +295,7 @@ async def asyncSetUp(self): self.test_client = await self.async_rs_or_single_client( event_listeners=[self.listener], retryWrites=retry_writes ) - self.coll = self.test_client[self.client.db.name].test + self.coll = self.test_client[self.client.db.name].coll await self.coll.drop() # necessary for first test run await self.coll.database.create_collection(self.coll.name) self.listener.reset() diff --git a/test/asynchronous/test_server_selection.py b/test/asynchronous/test_server_selection.py index b9c84778b2..4a15b7d93a 100644 --- a/test/asynchronous/test_server_selection.py +++ b/test/asynchronous/test_server_selection.py @@ -217,7 +217,7 @@ async def test_server_selection_getMore_blocks(self): client = await self.async_rs_client( event_listeners=[hb_listener], heartbeatFrequencyMS=500, appName="heartbeatFailedClient" ) - coll = client.db.test + coll = client.db.coll await coll.drop() docs = [{"x": 1} for _ in range(5)] await coll.insert_many(docs) diff --git a/test/asynchronous/test_server_selection_in_window.py b/test/asynchronous/test_server_selection_in_window.py index b631cebf68..47d4910fdc 100644 --- a/test/asynchronous/test_server_selection_in_window.py +++ b/test/asynchronous/test_server_selection_in_window.py @@ -118,7 +118,7 @@ async def run(self): class TestProse(AsyncIntegrationTest): async def frequencies(self, client, listener, n_finds=10): - coll = client.test.test + coll = client.db.coll N_TASKS = 10 tasks = [FinderTask(coll, n_finds) for _ in range(N_TASKS)] for task in tasks: @@ -172,7 +172,7 @@ async def test_load_balancing(self): "appName": "loadBalancingTest", }, } - coll = client.test.test + coll = client.db.coll N_TASKS = 10 async with self.fail_point(delay_finds): nodes = async_client_context.client.nodes diff --git a/test/asynchronous/test_session.py b/test/asynchronous/test_session.py index 8bf4b7cc06..0809a23ea8 100644 --- a/test/asynchronous/test_session.py +++ b/test/asynchronous/test_session.py @@ -243,17 +243,17 @@ async def test_implicit_sessions_checkout(self): # Retry up to 10 times because there is a known race condition that can cause multiple # sessions to be used: connection check in happens before session check in for _ in range(10): - cursor = client.db.test.find({}) + cursor = client.db.coll.find({}) ops: list[tuple[Callable, list[Any]]] = [ - (client.db.test.find_one, [{"_id": 1}]), - (client.db.test.delete_one, [{}]), - (client.db.test.update_one, [{}, {"$set": {"x": 2}}]), - (client.db.test.bulk_write, [[UpdateOne({}, {"$set": {"x": 2}})]]), - (client.db.test.find_one_and_delete, [{}]), - (client.db.test.find_one_and_update, [{}, {"$set": {"x": 1}}]), - (client.db.test.find_one_and_replace, [{}, {}]), - (client.db.test.aggregate, [[{"$limit": 1}]]), - (client.db.test.find, []), + (client.db.coll.find_one, [{"_id": 1}]), + (client.db.coll.delete_one, [{}]), + (client.db.coll.update_one, [{}, {"$set": {"x": 2}}]), + (client.db.coll.bulk_write, [[UpdateOne({}, {"$set": {"x": 2}})]]), + (client.db.coll.find_one_and_delete, [{}]), + (client.db.coll.find_one_and_update, [{}, {"$set": {"x": 1}}]), + (client.db.coll.find_one_and_replace, [{}, {}]), + (client.db.coll.aggregate, [[{"$limit": 1}]]), + (client.db.coll.find, []), (client.server_info, []), (client.db.aggregate, [[{"$listLocalSessions": {}}, {"$limit": 1}]]), (cursor.distinct, ["_id"]), @@ -415,7 +415,7 @@ async def test_collection(self): await self._test_ops(client, *ops) async def test_cursor_clone(self): - coll = self.client.pymongo_test.collection + coll = self.db.collection # Ensure some batches. await coll.insert_many({} for _ in range(10)) self.addAsyncCleanup(coll.drop) @@ -689,7 +689,7 @@ async def test_aggregate_error(self): self.assertIn(lsid, session_ids(client)) async def _test_cursor_helper(self, create_cursor, close_cursor): - coll = self.client.pymongo_test.collection + coll = self.db.collection await coll.insert_many([{} for _ in range(1000)]) cursor = await create_cursor(coll, None) @@ -828,7 +828,7 @@ async def _test_unacknowledged_ops(self, client, *ops): async def test_unacknowledged_writes(self): # Ensure the collection exists. - await self.client.pymongo_test.create_collection("test_unacked_writes") + await self.db.create_collection("test_unacked_writes") client = await self.async_rs_or_single_client(w=0, event_listeners=[self.listener]) db = client.pymongo_test coll = db.test_unacked_writes @@ -870,7 +870,7 @@ async def test_session_not_copyable(self): self.assertRaises(TypeError, lambda: copy.copy(s)) async def test_nested_session_binding(self): - coll = self.client.pymongo_test.test + coll = self.db.coll await coll.insert_one({"x": 1}) session1 = self.client.start_session() @@ -921,7 +921,7 @@ async def test_nested_session_binding(self): await session2.end_session() async def test_session_binding_end_session(self): - coll = self.client.pymongo_test.test + coll = self.db.coll await coll.insert_one({"x": 1}) async with self.client.start_session().bind() as s1: @@ -939,7 +939,7 @@ async def test_session_binding_end_session(self): async def test_getmore_preserves_lsid_after_session_support_lost(self): listener = OvertCommandListener() client = await self.async_rs_or_single_client(event_listeners=[listener], maxPoolSize=1) - coll = client.pymongo_test.test + coll = client.pymongo_test.coll await coll.drop() await coll.insert_many([{"x": i} for i in range(10)]) self.addAsyncCleanup(coll.drop) @@ -979,8 +979,8 @@ async def asyncSetUp(self): await super().asyncSetUp() self.listener = SessionTestListener() self.client = await self.async_rs_or_single_client(event_listeners=[self.listener]) - await self.client.pymongo_test.drop_collection("test") - await self.client.pymongo_test.create_collection("test") + await self.client.pymongo_test.drop_collection("coll") + await self.client.pymongo_test.create_collection("coll") @async_client_context.require_no_standalone async def test_core(self): @@ -988,7 +988,7 @@ async def test_core(self): self.assertIsNone(sess.cluster_time) self.assertIsNone(sess.operation_time) self.listener.reset() - await self.client.pymongo_test.test.find_one(session=sess) + await self.client.pymongo_test.coll.find_one(session=sess) started = self.listener.started_events[0] cmd = started.command self.assertIsNone(cmd.get("readConcern")) @@ -999,7 +999,7 @@ async def test_core(self): self.assertEqual(op_time, reply.get("operationTime")) # No explicit session - await self.client.pymongo_test.test.insert_one({}) + await self.client.pymongo_test.coll.insert_one({}) self.assertEqual(sess.operation_time, op_time) self.listener.reset() try: @@ -1031,7 +1031,7 @@ async def test_core(self): self.assertEqual(sess.operation_time, sess2.operation_time) async def _test_reads(self, op, exception=None): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll async with self.client.start_session() as sess: await coll.find_one({}, session=sess) operation_time = sess.operation_time @@ -1074,7 +1074,7 @@ async def find_raw(coll, session): ) async def _test_writes(self, op): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll async with self.client.start_session() as sess: await op(coll, sess) operation_time = sess.operation_time @@ -1127,7 +1127,7 @@ async def test_writes(self): await self._test_writes(lambda coll, session: coll.drop_indexes(session=session)) async def _test_no_read_concern(self, op): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll async with self.client.start_session() as sess: await coll.find_one({}, session=sess) operation_time = sess.operation_time @@ -1145,7 +1145,7 @@ async def test_explain_does_not_include_read_concern(self): @async_client_context.require_no_standalone async def test_get_more_does_not_include_read_concern(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll async with self.client.start_session() as sess: await coll.find_one({}, session=sess) operation_time = sess.operation_time @@ -1161,9 +1161,9 @@ async def test_get_more_does_not_include_read_concern(self): async def test_session_not_causal(self): async with self.client.start_session(causal_consistency=False) as s: - await self.client.pymongo_test.test.insert_one({}, session=s) + await self.client.pymongo_test.coll.insert_one({}, session=s) self.listener.reset() - await self.client.pymongo_test.test.find_one({}, session=s) + await self.client.pymongo_test.coll.find_one({}, session=s) act = ( self.listener.started_events[0] .command.get("readConcern", {}) @@ -1174,9 +1174,9 @@ async def test_session_not_causal(self): @async_client_context.require_standalone async def test_server_not_causal(self): async with self.client.start_session(causal_consistency=True) as s: - await self.client.pymongo_test.test.insert_one({}, session=s) + await self.client.pymongo_test.coll.insert_one({}, session=s) self.listener.reset() - await self.client.pymongo_test.test.find_one({}, session=s) + await self.client.pymongo_test.coll.find_one({}, session=s) act = ( self.listener.started_events[0] .command.get("readConcern", {}) @@ -1187,7 +1187,7 @@ async def test_server_not_causal(self): @async_client_context.require_no_standalone async def test_read_concern(self): async with self.client.start_session(causal_consistency=True) as s: - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll await coll.insert_one({}, session=s) self.listener.reset() await coll.find_one({}, session=s) @@ -1207,14 +1207,14 @@ async def test_read_concern(self): @async_client_context.require_no_standalone async def test_cluster_time_with_server_support(self): self.listener.reset() - await self.client.pymongo_test.test.find_one({}) + await self.client.pymongo_test.coll.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime") self.assertIsNotNone(after_cluster_time) @async_client_context.require_standalone async def test_cluster_time_no_server_support(self): self.listener.reset() - await self.client.pymongo_test.test.find_one({}) + await self.client.pymongo_test.coll.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime") self.assertIsNone(after_cluster_time) @@ -1321,7 +1321,7 @@ async def test_cluster_time_not_used_by_sdam(self): self.assertEqual(c1._topology.max_cluster_time(), cluster_time) # Advance the server's $clusterTime by performing an insert via another client. - await self.db.test.insert_one({"advance": "$clusterTime"}) + await self.db.coll.insert_one({"advance": "$clusterTime"}) # Wait until the client C1 processes the next pair of SDAM heartbeat started + succeeded events. heartbeat_listener.reset() diff --git a/test/asynchronous/test_ssl.py b/test/asynchronous/test_ssl.py index 5944d44ff2..81a7cb9630 100644 --- a/test/asynchronous/test_ssl.py +++ b/test/asynchronous/test_ssl.py @@ -824,7 +824,7 @@ async def test_mongodb_x509_auth(self): ) with self.assertRaises(OperationFailure): - await noauth.pymongo_test.test.find_one() + await noauth.pymongo_test.coll.find_one() listener = EventListener() auth = self.simple_client( @@ -837,7 +837,7 @@ async def test_mongodb_x509_auth(self): ) # No error - await auth.pymongo_test.test.find_one() + await auth.pymongo_test.coll.find_one() names = listener.started_command_names() if async_client_context.version.at_least(4, 4, -1): # Speculative auth skips the authenticate command. @@ -854,14 +854,14 @@ async def test_mongodb_x509_auth(self): uri, ssl=True, tlsAllowInvalidCertificates=True, tlsCertificateKeyFile=CLIENT_PEM ) # No error - await client.pymongo_test.test.find_one() + await client.pymongo_test.coll.find_one() uri = "mongodb://%s:%d/?authMechanism=MONGODB-X509" % (host, port) client = self.simple_client( uri, ssl=True, tlsAllowInvalidCertificates=True, tlsCertificateKeyFile=CLIENT_PEM ) # No error - await client.pymongo_test.test.find_one() + await client.pymongo_test.coll.find_one() # Auth should fail if username and certificate do not match uri = "mongodb://%s@%s:%d/?authMechanism=MONGODB-X509" % ( quote_plus("not the username"), @@ -874,7 +874,7 @@ async def test_mongodb_x509_auth(self): ) with self.assertRaises(OperationFailure): - await bad_client.pymongo_test.test.find_one() + await bad_client.pymongo_test.coll.find_one() bad_client = self.simple_client( await async_client_context.pair, @@ -886,7 +886,7 @@ async def test_mongodb_x509_auth(self): ) with self.assertRaises(OperationFailure): - await bad_client.pymongo_test.test.find_one() + await bad_client.pymongo_test.coll.find_one() # Invalid certificate (using CA certificate as client certificate) uri = "mongodb://%s@%s:%d/?authMechanism=MONGODB-X509" % ( diff --git a/test/asynchronous/test_transactions.py b/test/asynchronous/test_transactions.py index 2891008003..926b19ccd8 100644 --- a/test/asynchronous/test_transactions.py +++ b/test/asynchronous/test_transactions.py @@ -105,7 +105,7 @@ async def test_transaction_write_concern_override(self): """Test txn overrides Client/Database/Collection write_concern.""" client = await self.async_rs_client(w=0) db = client.test - coll = db.test + coll = db.coll await coll.insert_one({}) async with client.start_session() as s: async with await s.start_transaction(write_concern=WriteConcern(w=1)): @@ -156,7 +156,7 @@ async def test_unpin_for_next_transaction(self): async_client_context.mongos_seeds(), localThresholdMS=1000 ) await async_wait_until(lambda: len(client.nodes) > 1, "discover both mongoses") - coll = client.test.test + coll = client.db.coll # Create the collection. await coll.insert_one({}) async with client.start_session() as s: @@ -185,7 +185,7 @@ async def test_unpin_for_non_transaction_operation(self): async_client_context.mongos_seeds(), localThresholdMS=1000 ) await async_wait_until(lambda: len(client.nodes) > 1, "discover both mongoses") - coll = client.test.test + coll = client.db.coll # Create the collection. await coll.insert_one({}) async with client.start_session() as s: @@ -207,7 +207,7 @@ async def test_unpin_for_non_transaction_operation(self): @async_client_context.require_transactions async def test_create_collection(self): client = async_client_context.client - db = client.pymongo_test + db = self.db coll = db.test_create_collection self.addAsyncCleanup(coll.drop) @@ -234,7 +234,7 @@ async def create_and_insert(session): @async_client_context.require_transactions async def test_gridfs_does_not_support_transactions(self): client = async_client_context.client - db = client.pymongo_test + db = self.db gfs = AsyncGridFS(db) bucket = AsyncGridFSBucket(db) @@ -316,7 +316,7 @@ async def test_transaction_starts_with_batched_write(self): # split. listener = OvertCommandListener() client = await self.async_rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll await coll.delete_many({}) listener.reset() self.addAsyncCleanup(coll.drop) @@ -344,7 +344,7 @@ async def test_transaction_starts_with_batched_write(self): @async_client_context.require_transactions async def test_transaction_direct_connection(self): client = await self.async_single_client() - coll = client.pymongo_test.test + coll = client.pymongo_test.coll # Make sure the collection exists. await coll.insert_one({}) @@ -448,10 +448,10 @@ async def callback(_): async with self.client.start_session() as s: self.assertEqual(await s.with_transaction(callback), "Foo") - await self.db.test.insert_one({}) + await self.db.coll.insert_one({}) async def callback2(session): - await self.db.test.insert_one({}, session=session) + await self.db.coll.insert_one({}, session=session) return "Foo" async with self.client.start_session() as s: @@ -472,7 +472,7 @@ def callback(_): async def test_3_1_callback_not_retried_after_timeout(self): listener = OvertCommandListener() client = await self.async_rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll async def callback(session): await coll.insert_one({}, session=session) @@ -502,7 +502,7 @@ async def callback(session): async def test_3_2_callback_not_retried_after_commit_timeout(self): listener = OvertCommandListener() client = await self.async_rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll async def callback(session): await coll.insert_one({}, session=session) @@ -538,7 +538,7 @@ async def callback(session): async def test_3_3_commit_not_retried_after_timeout(self): listener = OvertCommandListener() client = await self.async_rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll async def callback(session): await coll.insert_one({}, session=session) @@ -578,7 +578,7 @@ async def callback(session): async def test_callback_not_retried_after_csot_timeout(self): listener = OvertCommandListener() client = await self.async_rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll async def callback(session): await coll.insert_one({}, session=session) @@ -615,7 +615,7 @@ async def callback(session): @async_client_context.require_transactions async def test_in_transaction_property(self): client = async_client_context.client - coll = client.test.testcollection + coll = client.db.collcollection await coll.insert_one({}) self.addAsyncCleanup(coll.drop) @@ -652,7 +652,7 @@ async def callback(session): @async_client_context.require_transactions async def test_4_retry_backoff_is_enforced(self): client = async_client_context.client - coll = client[self.db.name].test + coll = client[self.db.name].coll end = start = no_backoff_time = 0 # Make random.random always return 0 (no backoff) @@ -715,7 +715,7 @@ async def test_case_1(self): # Write concern not inherited from collection object inside transaction # Create a MongoClient running against a configured sharded/replica set/load balanced cluster. client = async_client_context.client - coll = client[self.db.name].test + coll = client[self.db.name].coll await coll.delete_many({}) # Start a new session on the client. async with client.start_session() as s: diff --git a/test/asynchronous/test_versioned_api_integration.py b/test/asynchronous/test_versioned_api_integration.py index 3e2bbf5f1a..f8adda9896 100644 --- a/test/asynchronous/test_versioned_api_integration.py +++ b/test/asynchronous/test_versioned_api_integration.py @@ -48,7 +48,7 @@ async def test_command_options(self): client = await self.async_rs_or_single_client( server_api=ServerApi("1"), event_listeners=[listener] ) - coll = client.test.test + coll = client.db.coll await coll.insert_many([{} for _ in range(100)]) self.addAsyncCleanup(coll.delete_many, {}) await coll.find(batch_size=25).to_list() @@ -62,7 +62,7 @@ async def test_command_options_txn(self): client = await self.async_rs_or_single_client( server_api=ServerApi("1"), event_listeners=[listener] ) - coll = client.test.test + coll = client.db.coll await coll.insert_many([{} for _ in range(100)]) self.addAsyncCleanup(coll.delete_many, {}) @@ -70,7 +70,7 @@ async def test_command_options_txn(self): async with client.start_session() as s, await s.start_transaction(): await coll.insert_many([{} for _ in range(100)], session=s) await coll.find(batch_size=25, session=s).to_list() - await client.test.command("find", "test", session=s) + await client.db.command("find", "coll", session=s) self.assertServerApiInAllCommands(listener.started_events) diff --git a/test/atlas/test_connection.py b/test/atlas/test_connection.py index 32610b05c1..7424db83e6 100644 --- a/test/atlas/test_connection.py +++ b/test/atlas/test_connection.py @@ -56,7 +56,7 @@ def connect(self, uri): # No TLS error client.admin.command("ping") # No auth error - client.test.test.count_documents({}) + client.db.coll.count_documents({}) @unittest.skipUnless(_has_sni(True), "Free tier requires SNI support") def test_free_tier(self): diff --git a/test/mockupdb/test_cursor_namespace.py b/test/mockupdb/test_cursor_namespace.py index adc73ee4e6..7cf0048bd9 100644 --- a/test/mockupdb/test_cursor_namespace.py +++ b/test/mockupdb/test_cursor_namespace.py @@ -53,7 +53,7 @@ def tearDownClass(cls): def _test_cursor_namespace(self, cursor_op, command): with going(cursor_op) as docs: - request = self.server.receives(**{command: "collection", "namespace": "test"}) + request = self.server.receives(**{command: "coll", "namespace": "test"}) # Respond with a different namespace. request.reply( { @@ -75,19 +75,19 @@ def _test_cursor_namespace(self, cursor_op, command): def test_aggregate_cursor(self): def op(): - return list(self.client.test.collection.aggregate([])) + return list(self.client.test.coll.aggregate([])) self._test_cursor_namespace(op, "aggregate") def test_find_cursor(self): def op(): - return list(self.client.test.collection.find()) + return list(self.client.test.coll.find()) self._test_cursor_namespace(op, "find") def test_list_indexes(self): def op(): - return list(self.client.test.collection.list_indexes()) + return list(self.client.test.coll.list_indexes()) self._test_cursor_namespace(op, "listIndexes") @@ -109,7 +109,7 @@ def tearDownClass(cls): def _test_killCursors_namespace(self, cursor_op, command): with going(cursor_op): - request = self.server.receives(**{command: "collection", "namespace": "test"}) + request = self.server.receives(**{command: "coll", "namespace": "test"}) # Respond with a different namespace. request.reply( { @@ -136,7 +136,7 @@ def _test_killCursors_namespace(self, cursor_op, command): def test_aggregate_killCursor(self): def op(): - cursor = self.client.test.collection.aggregate([], batchSize=1) + cursor = self.client.test.coll.aggregate([], batchSize=1) next(cursor) cursor.close() @@ -144,7 +144,7 @@ def op(): def test_find_killCursor(self): def op(): - cursor = self.client.test.collection.find(batch_size=1) + cursor = self.client.test.coll.find(batch_size=1) next(cursor) cursor.close() diff --git a/test/mypy_fails/insert_many_dict.py b/test/mypy_fails/insert_many_dict.py index 5f9a2d45a9..0a18b0a936 100644 --- a/test/mypy_fails/insert_many_dict.py +++ b/test/mypy_fails/insert_many_dict.py @@ -3,6 +3,6 @@ from pymongo import MongoClient client: MongoClient = MongoClient() -client.test.test.insert_many( +client.db.coll.insert_many( {"a": 1} ) # error: Dict entry 0 has incompatible type "str": "int"; expected "Mapping[str, Any]": "int" diff --git a/test/mypy_fails/insert_one_list.py b/test/mypy_fails/insert_one_list.py index 7c27d5cac9..ffb543ce1c 100644 --- a/test/mypy_fails/insert_one_list.py +++ b/test/mypy_fails/insert_one_list.py @@ -3,6 +3,6 @@ from pymongo import MongoClient client: MongoClient = MongoClient() -client.test.test.insert_one( +client.db.coll.insert_one( [{}] ) # error: Argument 1 to "insert_one" of "Collection" has incompatible type "List[Dict[, ]]"; expected "Mapping[str, Any]" diff --git a/test/mypy_fails/raw_bson_document.py b/test/mypy_fails/raw_bson_document.py index 23424ea89f..4ebec129f4 100644 --- a/test/mypy_fails/raw_bson_document.py +++ b/test/mypy_fails/raw_bson_document.py @@ -4,7 +4,7 @@ from pymongo import MongoClient client = MongoClient(document_class=RawBSONDocument) -coll = client.test.test +coll = client.db.coll doc = {"my": "doc"} coll.insert_one(doc) retrieved = coll.find_one({"_id": doc["_id"]}) diff --git a/test/mypy_fails/typedict_client.py b/test/mypy_fails/typedict_client.py index 37c3f0bfcc..dccb27dd5d 100644 --- a/test/mypy_fails/typedict_client.py +++ b/test/mypy_fails/typedict_client.py @@ -11,7 +11,7 @@ class Movie(TypedDict): client: MongoClient[Movie] = MongoClient() -coll = client.test.test +coll = client.db.coll retrieved = coll.find_one({"_id": "foo"}) assert retrieved is not None assert retrieved["year"] == 1 diff --git a/test/test_auth.py b/test/test_auth.py index 884f888fbf..bf363267dc 100644 --- a/test/test_auth.py +++ b/test/test_auth.py @@ -231,7 +231,7 @@ def test_gssapi_threaded(self): # collection.find_one with a 1-second delay, forcing it to check out # multiple connections from the pool concurrently, proving that # auto-authentication works with GSSAPI. - collection = db.test + collection = db.coll if not collection.count_documents({}): try: collection.drop() @@ -340,7 +340,7 @@ def test_sasl_plain(self): authSource=SASL_DB, authMechanism="PLAIN", ) - client.ldap.test.find_one() + client.ldap.coll.find_one() assert SASL_USER is not None assert SASL_PASS is not None @@ -352,7 +352,7 @@ def test_sasl_plain(self): SASL_DB, ) client = self.simple_client(uri) - client.ldap.test.find_one() + client.ldap.coll.find_one() set_name = client_context.replica_set_name if set_name: @@ -365,7 +365,7 @@ def test_sasl_plain(self): authSource=SASL_DB, authMechanism="PLAIN", ) - client.ldap.test.find_one() + client.ldap.coll.find_one() uri = "mongodb://%s:%s@%s:%d/?authMechanism=PLAIN;authSource=%s;replicaSet=%s" % ( quote_plus(SASL_USER), @@ -376,7 +376,7 @@ def test_sasl_plain(self): str(set_name), ) client = self.simple_client(uri) - client.ldap.test.find_one() + client.ldap.coll.find_one() def test_sasl_plain_bad_credentials(self): def auth_string(user, password): @@ -650,13 +650,13 @@ def test_cache(self): @client_context.require_sync def test_scram_threaded(self): - coll = client_context.client.db.test + coll = client_context.client.db.coll coll.drop() coll.insert_one({"_id": 1}) # The first thread to call find() will authenticate client = self.rs_or_single_client() - coll = client.db.test + coll = client.db.coll threads = [] for _ in range(4): threads.append(AutoAuthenticateThread(coll)) diff --git a/test/test_auth_oidc.py b/test/test_auth_oidc.py index de4076b31a..5250e31da1 100644 --- a/test/test_auth_oidc.py +++ b/test/test_auth_oidc.py @@ -197,7 +197,7 @@ def test_1_1_single_principal_implicit_username(self): # Create default OIDC client with authMechanism=MONGODB-OIDC. client = self.create_client() # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -205,7 +205,7 @@ def test_1_2_single_principal_explicit_username(self): # Create a client with MONGODB_URI_SINGLE, a username of test_user1, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = self.create_client(username="test_user1") # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -215,7 +215,7 @@ def test_1_3_multiple_principal_user_1(self): # Create a client with MONGODB_URI_MULTI, a username of test_user1, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = self.create_client(self.uri_multiple, username="test_user1") # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -226,7 +226,7 @@ def test_1_4_multiple_principal_user_2(self): # Create a client with MONGODB_URI_MULTI, a username of test_user2, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = self.create_client(self.uri_multiple, username="test_user2") # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -237,7 +237,7 @@ def test_1_5_multiple_principal_no_user(self): client = self.create_client(self.uri_multiple) # Assert that a find operation fails. with self.assertRaises(OperationFailure): - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -248,7 +248,7 @@ def test_1_6_allowed_hosts_blocked(self): client = self.create_client(authmechanismproperties=props) # Assert that a find operation fails with a client-side error. with self.assertRaises(ConfigurationError): - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -267,7 +267,7 @@ def test_1_6_allowed_hosts_blocked(self): ) # Assert that a find operation fails with a client-side error. with self.assertRaises(ConfigurationError): - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -289,7 +289,7 @@ def test_1_8_machine_idp_human_callback(self): # Create a client with MONGODB_URI_SINGLE, a username of test_machine, authMechanism=MONGODB-OIDC, and the OIDC human callback. client = self.create_client(username="test_machine") # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -298,7 +298,7 @@ def test_2_1_valid_callback_inputs(self): client = self.create_client() # Perform a find operation that succeeds. Verify that the human callback was called with the appropriate inputs, including the timeout parameter if possible. # Ensure that there are no unexpected fields. - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -311,7 +311,7 @@ def fetch(self, ctx): client = self.create_client(request_cb=CustomCB()) # Perform a find operation that fails. with self.assertRaises(ValueError): - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -320,7 +320,7 @@ def test_2_3_refresh_token_is_passed_to_the_callback(self): client = self.create_client() # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Set a fail point for ``find`` commands. with self.fail_point( @@ -330,7 +330,7 @@ def test_2_3_refresh_token_is_passed_to_the_callback(self): } ): # Perform a ``find`` operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the callback has been called twice. self.assertEqual(self.request_called, 2) @@ -351,7 +351,7 @@ def test_3_1_uses_speculative_authentication_if_there_is_a_cached_token(self): ): # Perform a ``find`` operation that fails. with self.assertRaises(AutoReconnect): - client.test.test.find_one() + client.test.coll.find_one() # Set a fail point for ``saslStart`` commands. with self.fail_point( @@ -361,7 +361,7 @@ def test_3_1_uses_speculative_authentication_if_there_is_a_cached_token(self): } ): # Perform a ``find`` operation that succeeds - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -379,7 +379,7 @@ def test_3_2_does_not_use_speculative_authentication_if_there_is_no_cached_token ): # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - client.test.test.find_one() + client.test.coll.find_one() # Close the client. client.close() @@ -392,7 +392,7 @@ def test_4_1_reauthenticate_succeeds(self): client = self.create_client(event_listeners=[listener]) # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -408,7 +408,7 @@ def test_4_1_reauthenticate_succeeds(self): } ): # Perform another find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called twice. self.assertEqual(self.request_called, 2) @@ -454,7 +454,7 @@ def fetch(self, *args, **kwargs): client = self.create_client(request_cb=CustomRequest()) # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -467,7 +467,7 @@ def fetch(self, *args, **kwargs): } ): # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called twice. self.assertEqual(self.request_called, 2) @@ -487,7 +487,7 @@ def fetch(self, *args, **kwargs): client = self.create_client(request_cb=CustomRequest()) # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -500,7 +500,7 @@ def fetch(self, *args, **kwargs): } ): # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called 2 times. self.assertEqual(self.request_called, 2) @@ -527,7 +527,7 @@ def fetch(self, *args, **kwargs): client = self.create_client(request_cb=CustomRequest()) # Perform a find operation that succeeds (to force a speculative auth). - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called once. self.assertEqual(self.request_called, 1) @@ -540,7 +540,7 @@ def fetch(self, *args, **kwargs): ): # Perform a find operation that fails. with self.assertRaises(OperationFailure): - client.test.test.find_one() + client.test.coll.find_one() # Assert that the human callback has been called three times. self.assertEqual(self.request_called, 3) @@ -555,7 +555,7 @@ def fetch(self, a): client = self.create_client(request_cb=RequestTokenNull()) with self.assertRaises(ValueError): - client.test.test.find_one() + client.test.coll.find_one() client.close() def test_request_callback_invalid_result(self): @@ -565,7 +565,7 @@ def fetch(self, a): client = self.create_client(request_cb=CallbackInvalidToken()) with self.assertRaises(ValueError): - client.test.test.find_one() + client.test.coll.find_one() client.close() def test_reauthentication_succeeds_multiple_connections(self): @@ -576,8 +576,8 @@ def test_reauthentication_succeeds_multiple_connections(self): client2 = self.create_client(request_cb=request_cb) # Perform an insert operation. - client1.test.test.insert_many([{"a": 1}, {"a": 1}]) - client2.test.test.find_one() + client1.test.coll.insert_many([{"a": 1}, {"a": 1}]) + client2.test.coll.find_one() self.assertEqual(self.request_called, 2) # Use the same authenticator for both clients @@ -588,8 +588,8 @@ def test_reauthentication_succeeds_multiple_connections(self): client1.options.pool_options._credentials.cache.data ) - client1.test.test.find_one() - client2.test.test.find_one() + client1.test.coll.find_one() + client2.test.coll.find_one() with self.fail_point( { @@ -597,7 +597,7 @@ def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - client1.test.test.find_one() + client1.test.coll.find_one() self.assertEqual(self.request_called, 3) @@ -607,7 +607,7 @@ def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - client2.test.test.find_one() + client2.test.coll.find_one() self.assertEqual(self.request_called, 3) client1.close() @@ -620,7 +620,7 @@ def test_reauthenticate_succeeds_bulk_write(self): client = self.create_client() # Perform a find operation. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -632,7 +632,7 @@ def test_reauthenticate_succeeds_bulk_write(self): } ): # Perform a bulk write operation. - client.test.test.bulk_write([InsertOne({})]) # type:ignore[type-var] + client.test.coll.bulk_write([InsertOne({})]) # type:ignore[type-var] # Assert that the request callback has been called twice. self.assertEqual(self.request_called, 2) @@ -643,10 +643,10 @@ def test_reauthenticate_succeeds_bulk_read(self): client = self.create_client() # Perform a find operation. - client.test.test.find_one() + client.test.coll.find_one() # Perform a bulk write operation. - client.test.test.bulk_write([InsertOne({})]) # type:ignore[type-var] + client.test.coll.bulk_write([InsertOne({})]) # type:ignore[type-var] # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -658,7 +658,7 @@ def test_reauthenticate_succeeds_bulk_read(self): } ): # Perform a bulk read operation. - cursor = client.test.test.find_raw_batches({}) + cursor = client.test.coll.find_raw_batches({}) cursor.to_list() # Assert that the request callback has been called twice. @@ -670,7 +670,7 @@ def test_reauthenticate_succeeds_cursor(self): client = self.create_client() # Perform an insert operation. - client.test.test.insert_one({"a": 1}) + client.test.coll.insert_one({"a": 1}) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -682,7 +682,7 @@ def test_reauthenticate_succeeds_cursor(self): } ): # Perform a find operation. - cursor = client.test.test.find({"a": 1}) + cursor = client.test.coll.find({"a": 1}) self.assertGreaterEqual(len(cursor.to_list()), 1) # Assert that the request callback has been called twice. @@ -694,7 +694,7 @@ def test_reauthenticate_succeeds_get_more(self): client = self.create_client() # Perform an insert operation. - client.test.test.insert_many([{"a": 1}, {"a": 1}]) + client.test.coll.insert_many([{"a": 1}, {"a": 1}]) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -706,7 +706,7 @@ def test_reauthenticate_succeeds_get_more(self): } ): # Perform a find operation. - cursor = client.test.test.find({"a": 1}, batch_size=1) + cursor = client.test.coll.find({"a": 1}, batch_size=1) self.assertGreaterEqual(len(cursor.to_list()), 1) # Assert that the request callback has been called twice. @@ -724,7 +724,7 @@ def test_reauthenticate_succeeds_get_more_exhaust(self): client = self.create_client() # Perform an insert operation. - client.test.test.insert_many([{"a": 1}, {"a": 1}]) + client.test.coll.insert_many([{"a": 1}, {"a": 1}]) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -736,7 +736,7 @@ def test_reauthenticate_succeeds_get_more_exhaust(self): } ): # Perform a find operation. - cursor = client.test.test.find({"a": 1}, batch_size=1, cursor_type=CursorType.EXHAUST) + cursor = client.test.coll.find({"a": 1}, batch_size=1, cursor_type=CursorType.EXHAUST) self.assertGreaterEqual(len(cursor.to_list()), 1) # Assert that the request callback has been called twice. @@ -748,7 +748,7 @@ def test_reauthenticate_succeeds_command(self): client = self.create_client() # Perform an insert operation. - client.test.test.insert_one({"a": 1}) + client.test.coll.insert_one({"a": 1}) # Assert that the request callback has been called once. self.assertEqual(self.request_called, 1) @@ -807,7 +807,7 @@ def test_1_1_callback_is_called_during_reauthentication(self): # implements the provider logic. client = self.create_client() # Perform a ``find`` operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the callback was called 1 time. self.assertEqual(self.request_called, 1) @@ -820,7 +820,7 @@ def test_1_2_callback_is_called_once_for_multiple_connections(self): # Start 10 tasks and run 100 find operations that all succeed in each task. def target(): for _ in range(100): - client.test.test.find_one() + client.test.coll.find_one() tasks = [] for i in range(10): @@ -836,7 +836,7 @@ def test_2_1_valid_callback_inputs(self): # Create a MongoClient configured with an OIDC callback that validates its inputs and returns a valid access token. client = self.create_client() # Perform a find operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the OIDC callback was called with the appropriate inputs, including the timeout parameter if possible. Ensure that there are no unexpected fields. self.assertEqual(self.request_called, 1) @@ -849,7 +849,7 @@ def fetch(self, a): client = self.create_client(request_cb=CallbackNullToken()) # Perform a find operation that fails. with self.assertRaises(ValueError): - client.test.test.find_one() + client.test.coll.find_one() def test_2_3_oidc_callback_returns_missing_data(self): # Create a MongoClient configured with an OIDC callback that returns data not conforming to the OIDCCredential with missing fields. @@ -863,7 +863,7 @@ def fetch(self, a): client = self.create_client(request_cb=CustomCallback()) # Perform a find operation that fails. with self.assertRaises(ValueError): - client.test.test.find_one() + client.test.coll.find_one() def test_2_4_invalid_client_configuration_with_callback(self): # Create a MongoClient configured with an OIDC callback and auth mechanism property ENVIRONMENT:test. @@ -918,13 +918,13 @@ def test_3_1_authentication_failure_with_cached_tokens_fetch_a_new_token_and_ret # Perform a ``find`` operation that fails. This is to force the ``MongoClient`` # to cache an access token. with self.assertRaises(AutoReconnect): - client.test.test.find_one() + client.test.coll.find_one() # Poison the cache of the client. client.options.pool_options._credentials.cache.data.access_token = "bad" # Reset the request count. self.request_called = 0 # Verify that a find succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Verify that the callback was called 1 time. self.assertEqual(self.request_called, 1) @@ -941,7 +941,7 @@ def fetch(self, a): client = self.create_client(request_cb=callback) # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - client.test.test.find_one() + client.test.coll.find_one() # Verify that the callback was called 1 time. self.assertEqual(callback.count, 1) @@ -958,13 +958,13 @@ def test_3_3_unexpected_error_code_does_not_clear_cache(self): ): # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - client.test.test.find_one() + client.test.coll.find_one() # Assert that the callback has been called once. self.assertEqual(self.request_called, 1) # Perform a ``find`` operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Assert that the callback has been called once. self.assertEqual(self.request_called, 1) @@ -983,7 +983,7 @@ def test_4_1_reauthentication_succeeds(self): } ): # Perform a ``find`` operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Verify that the callback was called 2 times (once during the connection # handshake, and again during reauthentication). @@ -1009,7 +1009,7 @@ def fetch(self, _): client = self.create_client(request_cb=callback) # Perform a read operation that succeeds. - client.test.test.find_one() + client.test.coll.find_one() # Set a fail point for the find command. with self.fail_point( @@ -1020,7 +1020,7 @@ def fetch(self, _): ): # Perform a ``find`` operation that fails. with self.assertRaises(OperationFailure): - client.test.test.find_one() + client.test.coll.find_one() # Verify that the callback was called 2 times. self.assertEqual(callback.count, 2) @@ -1045,7 +1045,7 @@ def fetch(self, _): client = self.create_client(request_cb=callback) # Perform an insert operation that succeeds. - client.test.test.insert_one({}) + client.test.coll.insert_one({}) # Set a fail point for the find command. with self.fail_point( @@ -1056,7 +1056,7 @@ def fetch(self, _): ): # Perform a ``insert`` operation that fails. with self.assertRaises(OperationFailure): - client.test.test.insert_one({}) + client.test.coll.insert_one({}) # Verify that the callback was called 2 times. self.assertEqual(callback.count, 2) @@ -1069,7 +1069,7 @@ def test_4_4_speculative_authentication_should_be_ignored_on_reauthentication(se # Preload the *Client Cache* with a valid access token to enforce Speculative Authentication. client2 = self.create_client() - client2.test.test.find_one() + client2.test.coll.find_one() client.options.pool_options._credentials.cache.data = ( client2.options.pool_options._credentials.cache.data ) @@ -1077,7 +1077,7 @@ def test_4_4_speculative_authentication_should_be_ignored_on_reauthentication(se self.request_called = 0 # Perform an `insert` operation that succeeds. - client.test.test.insert_one({}) + client.test.coll.insert_one({}) # Assert that the callback was not called. self.assertEqual(self.request_called, 0) @@ -1096,7 +1096,7 @@ def test_4_4_speculative_authentication_should_be_ignored_on_reauthentication(se } ): # Perform an `insert` operation that succeeds. - client.test.test.insert_one({}) + client.test.coll.insert_one({}) # Assert that the callback was called once. self.assertEqual(self.request_called, 1) @@ -1118,7 +1118,7 @@ def test_4_5_reauthentication_succeeds_when_a_session_is_involved(self): # Start a new session. with client.start_session() as session: # In the started session perform a `find` operation that succeeds. - client.test.test.find_one({}, session=session) + client.test.coll.find_one({}, session=session) # Assert that the callback was called 2 times (once during the connection handshake, and again during reauthentication). self.assertEqual(self.request_called, 2) @@ -1131,7 +1131,7 @@ def test_5_1_azure_with_no_username(self): props = dict(TOKEN_RESOURCE=resource, ENVIRONMENT="azure") client = self.create_client(authMechanismProperties=props) - client.test.test.find_one() + client.test.coll.find_one() def test_5_2_azure_with_bad_username(self): if ENVIRON != "azure": @@ -1143,11 +1143,11 @@ def test_5_2_azure_with_bad_username(self): props = dict(TOKEN_RESOURCE=token_aud, ENVIRONMENT="azure") client = self.create_client(username="bad", authmechanismproperties=props) with self.assertRaises(ValueError): - client.test.test.find_one() + client.test.coll.find_one() def test_speculative_auth_success(self): client1 = self.create_client() - client1.test.test.find_one() + client1.test.coll.find_one() client2 = self.create_client() client2._connect() @@ -1164,15 +1164,15 @@ def test_speculative_auth_success(self): } ): # Perform a find operation. - client2.test.test.find_one() + client2.test.coll.find_one() def test_reauthentication_succeeds_multiple_connections(self): client1 = self.create_client() client2 = self.create_client() # Perform an insert operation. - client1.test.test.insert_many([{"a": 1}, {"a": 1}]) - client2.test.test.find_one() + client1.test.coll.insert_many([{"a": 1}, {"a": 1}]) + client2.test.coll.find_one() self.assertEqual(self.request_called, 2) # Use the same authenticator for both clients @@ -1183,8 +1183,8 @@ def test_reauthentication_succeeds_multiple_connections(self): client1.options.pool_options._credentials.cache.data ) - client1.test.test.find_one() - client2.test.test.find_one() + client1.test.coll.find_one() + client2.test.coll.find_one() with self.fail_point( { @@ -1192,7 +1192,7 @@ def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - client1.test.test.find_one() + client1.test.coll.find_one() self.assertEqual(self.request_called, 3) @@ -1202,7 +1202,7 @@ def test_reauthentication_succeeds_multiple_connections(self): "data": {"failCommands": ["find"], "errorCode": 391}, } ): - client2.test.test.find_one() + client2.test.coll.find_one() self.assertEqual(self.request_called, 3) diff --git a/test/test_bulk.py b/test/test_bulk.py index 113c905a9b..6c612e0edb 100644 --- a/test/test_bulk.py +++ b/test/test_bulk.py @@ -44,7 +44,7 @@ class BulkTestBase(IntegrationTest): def setUp(self): super().setUp() - self.coll = self.db.test + self.coll = self.db.coll self.coll.drop() self.coll_w0 = self.coll.with_options(write_concern=WriteConcern(w=0)) @@ -790,7 +790,7 @@ def setUp(self): privileges=[ { "actions": ["insert", "update", "find"], - "resource": {"db": "pymongo_test", "collection": "test"}, + "resource": {"db": "pymongo_test", "collection": "coll"}, } ], roles=[], @@ -897,7 +897,7 @@ def test_readonly(self): cli = self.rs_or_single_client_noauth( username="readonly", password="pw", authSource="pymongo_test" ) - coll = cli.pymongo_test.test + coll = cli.pymongo_test.coll coll.find_one() with self.assertRaises(OperationFailure): coll.bulk_write([InsertOne({"x": 1})]) @@ -908,7 +908,7 @@ def test_no_remove(self): cli = self.rs_or_single_client_noauth( username="noremove", password="pw", authSource="pymongo_test" ) - coll = cli.pymongo_test.test + coll = cli.pymongo_test.coll coll.find_one() requests = [ InsertOne({"x": 1}), diff --git a/test/test_client.py b/test/test_client.py index 35eed1f219..79d4268f2e 100644 --- a/test/test_client.py +++ b/test/test_client.py @@ -936,13 +936,13 @@ def test_init_disconnected(self): bad_host = "somedomainthatdoesntexist.org" c = self.simple_client(bad_host, port, connectTimeoutMS=1, serverSelectionTimeoutMS=10) with self.assertRaises(ConnectionFailure): - c.pymongo_test.test.find_one() + c.pymongo_test.coll.find_one() def test_init_disconnected_with_auth(self): uri = "mongodb://user:pass@somedomainthatdoesntexist" c = self.simple_client(uri, connectTimeoutMS=1, serverSelectionTimeoutMS=10) with self.assertRaises(ConnectionFailure): - c.pymongo_test.test.find_one() + c.pymongo_test.coll.find_one() @client_context.require_replica_set @client_context.require_no_load_balancer @@ -1107,7 +1107,7 @@ def test_list_databases(self): for doc in client.list_databases(): self.assertIs(type(doc), dict) - self.client.pymongo_test.test.insert_one({}) + self.db.coll.insert_one({}) cursor = self.client.list_databases(filter={"name": "admin"}) docs = cursor.to_list() self.assertEqual(1, len(docs)) @@ -1118,8 +1118,8 @@ def test_list_databases(self): self.assertEqual(["name"], list(doc)) def test_list_database_names(self): - self.client.pymongo_test.test.insert_one({"dummy": "object"}) - self.client.pymongo_test_mike.test.insert_one({"dummy": "object"}) + self.db.coll.insert_one({"dummy": "object"}) + self.client.pymongo_test_mike.coll.insert_one({"dummy": "object"}) cmd_docs = (self.client.admin.command("listDatabases"))["databases"] cmd_names = [doc["name"] for doc in cmd_docs] @@ -1134,8 +1134,8 @@ def test_drop_database(self): with self.assertRaises(TypeError): self.client.drop_database(None) # type: ignore[arg-type] - self.client.pymongo_test.test.insert_one({"dummy": "object"}) - self.client.pymongo_test2.test.insert_one({"dummy": "object"}) + self.db.coll.insert_one({"dummy": "object"}) + self.client.pymongo_test2.coll.insert_one({"dummy": "object"}) dbs = self.client.list_database_names() self.assertIn("pymongo_test", dbs) self.assertIn("pymongo_test2", dbs) @@ -1193,7 +1193,7 @@ def test_close_kills_cursors(self): def test_close_stops_kill_cursors_thread(self): client = self.rs_client() - client.test.test.find_one() + client.db.coll.find_one() self.assertFalse(client._kill_cursors_executor._stopped) # Closing the client should stop the thread. @@ -1237,7 +1237,7 @@ def test_close_does_not_open_servers(self): def test_close_closes_sockets(self): client = self.rs_client() - client.test.test.find_one() + client.db.coll.find_one() topology = client._topology client.close() for server in topology._servers.values(): @@ -1257,7 +1257,7 @@ def test_auth_from_uri(self): host, port = client_context.host, client_context.port client_context.create_user("admin", "admin", "pass") self.addCleanup(client_context.drop_user, "admin", "admin") - self.addCleanup(remove_all_users, self.client.pymongo_test) + self.addCleanup(remove_all_users, self.db) client_context.create_user("pymongo_test", "user", "pass", roles=["userAdmin", "readWrite"]) @@ -1282,7 +1282,7 @@ def test_auth_from_uri(self): self.rs_or_single_client_noauth( "mongodb://user:pass@%s:%d/pymongo_test" % (host, port), connect=False ) - ).pymongo_test.test.find_one() + ).pymongo_test.coll.find_one() # Wrong password. bad_client = self.rs_or_single_client_noauth( @@ -1290,7 +1290,7 @@ def test_auth_from_uri(self): ) with self.assertRaises(OperationFailure): - bad_client.pymongo_test.test.find_one() + bad_client.pymongo_test.coll.find_one() @client_context.require_auth def test_username_and_password(self): @@ -1334,7 +1334,7 @@ def test_unix_socket(self): uri = "mongodb://%s" % encoded_socket # Confirm we can do operations via the socket. client = self.rs_or_single_client(uri) - client.pymongo_test.test.insert_one({"dummy": "object"}) + client.pymongo_test.coll.insert_one({"dummy": "object"}) dbs = client.list_database_names() self.assertIn("pymongo_test", dbs) @@ -1350,18 +1350,18 @@ def test_unix_socket(self): def test_document_class(self): c = self.client db = c.pymongo_test - db.test.insert_one({"x": 1}) + db.coll.insert_one({"x": 1}) self.assertEqual(dict, c.codec_options.document_class) - self.assertIsInstance(db.test.find_one(), dict) - self.assertNotIsInstance(db.test.find_one(), SON) + self.assertIsInstance(db.coll.find_one(), dict) + self.assertNotIsInstance(db.coll.find_one(), SON) c = self.rs_or_single_client(document_class=SON) db = c.pymongo_test self.assertEqual(SON, c.codec_options.document_class) - self.assertIsInstance(db.test.find_one(), SON) + self.assertIsInstance(db.coll.find_one(), SON) def test_timeouts(self): client = self.rs_or_single_client( @@ -1403,14 +1403,14 @@ def test_socket_timeout(self): timeout_sec = 1 timeout = self.rs_or_single_client(socketTimeoutMS=1000 * timeout_sec) - no_timeout.pymongo_test.drop_collection("test") - no_timeout.pymongo_test.test.insert_one({"x": 1}) + no_timeout.pymongo_test.drop_collection("coll") + no_timeout.pymongo_test.coll.insert_one({"x": 1}) # A $where clause that takes a second longer than the timeout where_func = delay(timeout_sec + 1) def get_x(db): - doc = next(db.test.find().where(where_func)) + doc = next(db.coll.find().where(where_func)) return doc["x"] self.assertEqual(1, get_x(no_timeout.pymongo_test)) @@ -1474,16 +1474,16 @@ def test_tz_aware(self): aware = self.rs_or_single_client(tz_aware=True) self.addCleanup(aware.close) naive = self.client - aware.pymongo_test.drop_collection("test") + aware.pymongo_test.drop_collection("coll") now = datetime.datetime.now(tz=datetime.timezone.utc) - aware.pymongo_test.test.insert_one({"x": now}) + aware.pymongo_test.coll.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) + self.assertEqual(None, (naive.pymongo_test.coll.find_one())["x"].tzinfo) + self.assertEqual(utc, (aware.pymongo_test.coll.find_one())["x"].tzinfo) self.assertEqual( - (aware.pymongo_test.test.find_one())["x"].replace(tzinfo=None), - (naive.pymongo_test.test.find_one())["x"], + (aware.pymongo_test.coll.find_one())["x"].replace(tzinfo=None), + (naive.pymongo_test.coll.find_one())["x"], ) @client_context.require_ipv6 @@ -1502,8 +1502,8 @@ def test_ipv6(self): uri += "/?replicaSet=" + (client_context.replica_set_name or "") client = self.rs_or_single_client_noauth(uri) - client.pymongo_test.test.insert_one({"dummy": "object"}) - client.pymongo_test_bernie.test.insert_one({"dummy": "object"}) + client.pymongo_test.coll.insert_one({"dummy": "object"}) + client.pymongo_test_bernie.coll.insert_one({"dummy": "object"}) dbs = client.list_database_names() self.assertIn("pymongo_test", dbs) @@ -1511,8 +1511,8 @@ def test_ipv6(self): def test_contextlib(self): client = self.rs_or_single_client() - client.pymongo_test.drop_collection("test") - client.pymongo_test.test.insert_one({"foo": "bar"}) + client.pymongo_test.drop_collection("coll") + client.pymongo_test.coll.insert_one({"foo": "bar"}) # The socket used for the previous commands has been returned to the # pool @@ -1521,14 +1521,14 @@ def test_contextlib(self): # contextlib async support was added in Python 3.10 if _IS_SYNC or sys.version_info >= (3, 10): with contextlib.closing(client): - self.assertEqual("bar", (client.pymongo_test.test.find_one())["foo"]) + self.assertEqual("bar", (client.pymongo_test.coll.find_one())["foo"]) with self.assertRaises(InvalidOperation): - client.pymongo_test.test.find_one() + client.pymongo_test.coll.find_one() client = self.rs_or_single_client() with client as client: - self.assertEqual("bar", (client.pymongo_test.test.find_one())["foo"]) + self.assertEqual("bar", (client.pymongo_test.coll.find_one())["foo"]) with self.assertRaises(InvalidOperation): - client.pymongo_test.test.find_one() + client.pymongo_test.coll.find_one() @client_context.require_sync def test_interrupt_signal(self): @@ -1537,7 +1537,7 @@ def test_interrupt_signal(self): # Test fix for PYTHON-294 -- make sure MongoClient closes its # socket if it gets an interrupt while waiting to recv() from it. - db = self.client.pymongo_test + db = self.db # A $where clause which takes 1.5 sec to execute where = delay(1.5) @@ -1597,15 +1597,15 @@ def test_operation_failure(self): # to avoid race conditions caused by replica set failover or idle # socket reaping. client = self.single_client() - client.pymongo_test.test.find_one() + client.pymongo_test.coll.find_one() pool = get_pool(client) socket_count = len(pool.conns) self.assertGreaterEqual(socket_count, 1) old_conn = next(iter(pool.conns)) - client.pymongo_test.test.drop() - client.pymongo_test.test.insert_one({"_id": "foo"}) + client.pymongo_test.coll.drop() + client.pymongo_test.coll.insert_one({"_id": "foo"}) with self.assertRaises(OperationFailure): - client.pymongo_test.test.insert_one({"_id": "foo"}) + client.pymongo_test.coll.insert_one({"_id": "foo"}) self.assertEqual(socket_count, len(pool.conns)) new_con = next(iter(pool.conns)) @@ -1649,7 +1649,7 @@ def test_exhaust_network_error(self): # When doing an exhaust query, the socket stays checked out on success # but must be checked in on error to avoid semaphore leaks. client = self.rs_or_single_client(maxPoolSize=1, retryReads=False) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll pool = get_pool(client) pool._check_interval_seconds = None # Never check. @@ -1695,7 +1695,7 @@ def test_auth_network_error(self): def test_connect_to_standalone_using_replica_set_name(self): client = self.single_client(replicaSet="anything", serverSelectionTimeoutMS=100) with self.assertRaises(AutoReconnect): - client.test.test.find_one() + client.db.coll.find_one() @client_context.require_replica_set def test_stale_getmore(self): @@ -1853,7 +1853,7 @@ def compression_settings(client): for level in range(-1, 10): client = self.single_client(zlibcompressionlevel=level) # No error - client.pymongo_test.test.find_one() + client.pymongo_test.coll.find_one() def test_compression_commands(self): # Ensure the compression logic is actually exercised end-to-end by @@ -2062,7 +2062,7 @@ def server_description_count(): ) initial_count = server_description_count() with self.assertRaises(ServerSelectionTimeoutError): - client.test.test.find_one() + client.db.coll.find_one() gc.collect() final_count = server_description_count() client.close() @@ -2081,7 +2081,7 @@ def test_network_error_message(self): assert client.address is not None expected = "{}:{}: ".format(*(client.address)) with self.assertRaisesRegex(AutoReconnect, expected): - client.pymongo_test.test.find_one({}) + client.pymongo_test.coll.find_one({}) @unittest.skipIf("PyPy" in sys.version, "PYTHON-2938 could fail on PyPy") def test_process_periodic_tasks(self): @@ -2283,23 +2283,23 @@ def test_handshake_09_container_with_provider(self): ) def test_dict_hints(self): - self.db.t.find(hint={"x": 1}) + self.db.coll.find(hint={"x": 1}) def test_dict_hints_sort(self): - result = self.db.t.find() + result = self.db.coll.find() result.sort({"x": 1}) - self.db.t.find(sort={"x": 1}) + self.db.coll.find(sort={"x": 1}) def test_dict_hints_create_index(self): - self.db.t.create_index({"x": pymongo.ASCENDING}) + self.db.coll.create_index({"x": pymongo.ASCENDING}) def test_legacy_java_uuid_roundtrip(self): data = BinaryData.java_data docs = bson.decode_all(data, CodecOptions(SON[str, Any], False, JAVA_LEGACY)) - client_context.client.pymongo_test.drop_collection("java_uuid") - db = client_context.client.pymongo_test + self.db.drop_collection("java_uuid") + db = self.db coll = db.get_collection("java_uuid", CodecOptions(uuid_representation=JAVA_LEGACY)) coll.insert_many(docs) @@ -2310,14 +2310,14 @@ def test_legacy_java_uuid_roundtrip(self): coll = db.get_collection("java_uuid", CodecOptions(uuid_representation=PYTHON_LEGACY)) for d in coll.find(): self.assertNotEqual(d["newguid"], d["newguidstring"]) - client_context.client.pymongo_test.drop_collection("java_uuid") + self.db.drop_collection("java_uuid") def test_legacy_csharp_uuid_roundtrip(self): data = BinaryData.csharp_data docs = bson.decode_all(data, CodecOptions(SON[str, Any], False, CSHARP_LEGACY)) - client_context.client.pymongo_test.drop_collection("csharp_uuid") - db = client_context.client.pymongo_test + self.db.drop_collection("csharp_uuid") + db = self.db coll = db.get_collection("csharp_uuid", CodecOptions(uuid_representation=CSHARP_LEGACY)) coll.insert_many(docs) @@ -2328,16 +2328,16 @@ def test_legacy_csharp_uuid_roundtrip(self): coll = db.get_collection("csharp_uuid", CodecOptions(uuid_representation=PYTHON_LEGACY)) for d in coll.find(): self.assertNotEqual(d["newguid"], d["newguidstring"]) - client_context.client.pymongo_test.drop_collection("csharp_uuid") + self.db.drop_collection("csharp_uuid") def test_uri_to_uuid(self): uri = "mongodb://foo/?uuidrepresentation=csharpLegacy" client = self.single_client(uri, connect=False) - self.assertEqual(client.pymongo_test.test.codec_options.uuid_representation, CSHARP_LEGACY) + self.assertEqual(client.pymongo_test.coll.codec_options.uuid_representation, CSHARP_LEGACY) def test_uuid_queries(self): - db = client_context.client.pymongo_test - coll = db.test + db = self.db + coll = db.coll coll.drop() uu = uuid.uuid4() @@ -2346,7 +2346,7 @@ def test_uuid_queries(self): # Test regular UUID queries (using subtype 4). coll = db.get_collection( - "test", CodecOptions(uuid_representation=UuidRepresentation.STANDARD) + "coll", CodecOptions(uuid_representation=UuidRepresentation.STANDARD) ) self.assertEqual(0, coll.count_documents({"uuid": uu})) coll.insert_one({"uuid": uu}) @@ -2377,7 +2377,7 @@ def test_exhaust_query_server_error(self): # but must be checked in on error to avoid semaphore leaks. client = connected(self.rs_or_single_client(maxPoolSize=1)) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll pool = get_pool(client) conn = one(pool.conns) @@ -2399,11 +2399,11 @@ def test_exhaust_getmore_server_error(self): # When doing a getmore on an exhaust cursor, the socket stays checked # out on success but it's checked in on error to avoid semaphore leaks. client = self.rs_or_single_client(maxPoolSize=1) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll collection.drop() collection.insert_many([{} for _ in range(200)]) - self.addCleanup(client_context.client.pymongo_test.test.drop) + self.addCleanup(self.db.coll.drop) pool = get_pool(client) pool._check_interval_seconds = None # Never check. @@ -2438,7 +2438,7 @@ def test_exhaust_query_network_error(self): # When doing an exhaust query, the socket stays checked out on success # but must be checked in on error to avoid semaphore leaks. client = connected(self.rs_or_single_client(maxPoolSize=1, retryReads=False)) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll pool = get_pool(client) pool._check_interval_seconds = None # Never check. @@ -2459,7 +2459,7 @@ def test_exhaust_getmore_network_error(self): # When doing a getmore on an exhaust cursor, the socket stays checked # out on success but it's checked in on error to avoid semaphore leaks. client = self.rs_or_single_client(maxPoolSize=1) - collection = client.pymongo_test.test + collection = client.pymongo_test.coll collection.drop() collection.insert_many([{} for _ in range(200)]) # More than one batch. pool = get_pool(client) @@ -2495,7 +2495,7 @@ def test_gevent_task(self): def poller(): while True: - client_context.client.pymongo_test.test.insert_one({}) + self.db.coll.insert_one({}) task = spawn(poller) task.kill() @@ -2508,7 +2508,7 @@ def test_gevent_timeout(self): from gevent import Timeout, spawn client = self.rs_or_single_client(maxPoolSize=1) - coll = client.pymongo_test.test + coll = client.pymongo_test.coll coll.insert_one({}) def contentious_task(): @@ -2541,7 +2541,7 @@ def test_gevent_timeout_when_creating_connection(self): client = self.rs_or_single_client() self.addCleanup(client.close) - coll = client.pymongo_test.test + coll = client.pymongo_test.coll pool = get_pool(client) # type:ignore # Patch the pool to delay the connect method. diff --git a/test/test_client_backpressure.py b/test/test_client_backpressure.py index 67e5115e71..a2e9909f5b 100644 --- a/test/test_client_backpressure.py +++ b/test/test_client_backpressure.py @@ -60,36 +60,36 @@ class TestBackpressure(IntegrationTest): @client_context.require_failCommand_appName def test_retry_overload_error_command(self): - self.db.t.insert_one({"x": 1}) + self.db.coll.insert_one({"x": 1}) # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) with self.fail_point(fail_many): - self.db.command("find", "t") + self.db.command("find", "coll") # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - self.db.command("find", "t") + self.db.command("find", "coll") self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @client_context.require_failCommand_appName def test_retry_overload_error_find(self): - self.db.t.insert_one({"x": 1}) + self.db.coll.insert_one({"x": 1}) # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) with self.fail_point(fail_many): - self.db.t.find_one() + self.db.coll.find_one() # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - self.db.t.find_one() + self.db.coll.find_one() self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @@ -99,13 +99,13 @@ def test_retry_overload_error_insert_one(self): # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) with self.fail_point(fail_many): - self.db.t.insert_one({"x": 1}) + self.db.coll.insert_one({"x": 1}) # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - self.db.t.insert_one({"x": 1}) + self.db.coll.insert_one({"x": 1}) self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @@ -114,25 +114,25 @@ def test_retry_overload_error_insert_one(self): def test_retry_overload_error_update_many(self): # Even though update_many is not a retryable write operation, it will # still be retried via the "RetryableError" error label. - self.db.t.insert_one({"x": 1}) + self.db.coll.insert_one({"x": 1}) # Ensure command is retried on overload error. fail_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES) with self.fail_point(fail_many): - self.db.t.update_many({}, {"$set": {"x": 2}}) + self.db.coll.update_many({}, {"$set": {"x": 2}}) # Ensure command stops retrying after MAX_ADAPTIVE_RETRIES. fail_too_many = get_mock_overload_error(MAX_ADAPTIVE_RETRIES + 1) with self.fail_point(fail_too_many): with self.assertRaises(PyMongoError) as error: - self.db.t.update_many({}, {"$set": {"x": 2}}) + self.db.coll.update_many({}, {"$set": {"x": 2}}) self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) @client_context.require_failCommand_appName def test_retry_overload_error_getMore(self): - coll = self.db.t + coll = self.db.coll coll.insert_many([{"x": 1} for _ in range(10)]) # Ensure command is retried on overload error. @@ -189,7 +189,7 @@ def test_01_operation_retry_uses_exponential_backoff(self, random_func): client = self.client # 2. let `collection` be a collection - collection = client.test.test + collection = client.db.coll # 3. Now, run transactions without backoff: diff --git a/test/test_collation.py b/test/test_collation.py index 6bf8975160..0834dd6d7c 100644 --- a/test/test_collation.py +++ b/test/test_collation.py @@ -121,14 +121,14 @@ def assertCollationInLastCommand(self): self.assertEqual(self.collation.document, self.last_command_started()["collation"]) def test_create_collection(self): - self.db.test.drop() - self.db.create_collection("test", collation=self.collation) + self.db.coll.drop() + self.db.create_collection("coll", collation=self.collation) self.assertCollationInLastCommand() # Test passing collation as a dict as well. - self.db.test.drop() + self.db.coll.drop() self.listener.reset() - self.db.create_collection("test", collation=self.collation.document) + self.db.create_collection("coll", collation=self.collation.document) self.assertCollationInLastCommand() def test_index_model(self): @@ -136,81 +136,81 @@ def test_index_model(self): self.assertEqual(self.collation.document, model.document["collation"]) def test_create_index(self): - self.db.test.create_index("foo", collation=self.collation) + self.db.coll.create_index("foo", collation=self.collation) ci_cmd = self.listener.started_events[0].command self.assertEqual(self.collation.document, ci_cmd["indexes"][0]["collation"]) def test_aggregate(self): - self.db.test.aggregate([{"$group": {"_id": 42}}], collation=self.collation) + self.db.coll.aggregate([{"$group": {"_id": 42}}], collation=self.collation) self.assertCollationInLastCommand() def test_count_documents(self): - self.db.test.count_documents({}, collation=self.collation) + self.db.coll.count_documents({}, collation=self.collation) self.assertCollationInLastCommand() def test_distinct(self): - self.db.test.distinct("foo", collation=self.collation) + self.db.coll.distinct("foo", collation=self.collation) self.assertCollationInLastCommand() self.listener.reset() - self.db.test.find(collation=self.collation).distinct("foo") + self.db.coll.find(collation=self.collation).distinct("foo") self.assertCollationInLastCommand() def test_find_command(self): - self.db.test.insert_one({"is this thing on?": True}) + self.db.coll.insert_one({"is this thing on?": True}) self.listener.reset() - next(self.db.test.find(collation=self.collation)) + next(self.db.coll.find(collation=self.collation)) self.assertCollationInLastCommand() def test_explain_command(self): self.listener.reset() - self.db.test.find(collation=self.collation).explain() + self.db.coll.find(collation=self.collation).explain() # The collation should be part of the explained command. self.assertEqual( self.collation.document, self.last_command_started()["explain"]["collation"] ) def test_delete(self): - self.db.test.delete_one({"foo": 42}, collation=self.collation) + self.db.coll.delete_one({"foo": 42}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["deletes"][0]["collation"]) self.listener.reset() - self.db.test.delete_many({"foo": 42}, collation=self.collation) + self.db.coll.delete_many({"foo": 42}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["deletes"][0]["collation"]) def test_update(self): - self.db.test.replace_one({"foo": 42}, {"foo": 43}, collation=self.collation) + self.db.coll.replace_one({"foo": 42}, {"foo": 43}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["updates"][0]["collation"]) self.listener.reset() - self.db.test.update_one({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) + self.db.coll.update_one({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["updates"][0]["collation"]) self.listener.reset() - self.db.test.update_many({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) + self.db.coll.update_many({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation) command = self.listener.started_events[0].command self.assertEqual(self.collation.document, command["updates"][0]["collation"]) def test_find_and(self): - self.db.test.find_one_and_delete({"foo": 42}, collation=self.collation) + self.db.coll.find_one_and_delete({"foo": 42}, collation=self.collation) self.assertCollationInLastCommand() self.listener.reset() - self.db.test.find_one_and_update( + self.db.coll.find_one_and_update( {"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation ) self.assertCollationInLastCommand() self.listener.reset() - self.db.test.find_one_and_replace({"foo": 42}, {"foo": 43}, collation=self.collation) + self.db.coll.find_one_and_replace({"foo": 42}, {"foo": 43}, collation=self.collation) self.assertCollationInLastCommand() def test_bulk_write(self): - self.db.test.collection.bulk_write( + self.db.coll.bulk_write( [ DeleteOne({"noCollation": 42}), DeleteMany({"noCollation": 42}), @@ -241,32 +241,32 @@ def check_ops(ops): check_ops(update_cmd["updates"]) def test_indexes_same_keys_different_collations(self): - self.db.test.drop() + self.db.coll.drop() usa_collation = Collation("en_US") ja_collation = Collation("ja") - self.db.test.create_indexes( + self.db.coll.create_indexes( [ IndexModel("fieldname", collation=usa_collation), IndexModel("fieldname", name="japanese_version", collation=ja_collation), IndexModel("fieldname", name="simple"), ] ) - indexes = self.db.test.index_information() + indexes = self.db.coll.index_information() self.assertEqual( usa_collation.document["locale"], indexes["fieldname_1"]["collation"]["locale"] ) self.assertEqual( ja_collation.document["locale"], indexes["japanese_version"]["collation"]["locale"] ) - self.db.test.drop_index("fieldname_1") - indexes = self.db.test.index_information() + self.db.coll.drop_index("fieldname_1") + indexes = self.db.coll.index_information() self.assertIn("japanese_version", indexes) self.assertIn("simple", indexes) self.assertNotIn("fieldname", indexes) def test_unacknowledged_write(self): unacknowledged = WriteConcern(w=0) - collection = self.db.get_collection("test", write_concern=unacknowledged) + collection = self.db.get_collection("coll", write_concern=unacknowledged) with self.assertRaises(ConfigurationError): collection.update_one( {"hello": "world"}, {"$set": {"hello": "moon"}}, collation=self.collation @@ -278,6 +278,6 @@ def test_unacknowledged_write(self): collection.bulk_write([update_one]) def test_cursor_collation(self): - self.db.test.insert_one({"hello": "world"}) - next(self.db.test.find().collation(self.collation)) + self.db.coll.insert_one({"hello": "world"}) + next(self.db.coll.find().collation(self.collation)) self.assertCollationInLastCommand() diff --git a/test/test_collection.py b/test/test_collection.py index ae389d9166..3958ef1c58 100644 --- a/test/test_collection.py +++ b/test/test_collection.py @@ -104,15 +104,15 @@ def make_col(base, name): self.assertRaises(InvalidName, make_col, self.db, ".test") self.assertRaises(InvalidName, make_col, self.db, "test.") self.assertRaises(InvalidName, make_col, self.db, "tes..t") - self.assertRaises(InvalidName, make_col, self.db.test, "") - self.assertRaises(InvalidName, make_col, self.db.test, "te$t") - self.assertRaises(InvalidName, make_col, self.db.test, ".test") - self.assertRaises(InvalidName, make_col, self.db.test, "test.") - self.assertRaises(InvalidName, make_col, self.db.test, "tes..t") - self.assertRaises(InvalidName, make_col, self.db.test, "tes\x00t") + self.assertRaises(InvalidName, make_col, self.db.coll, "") + self.assertRaises(InvalidName, make_col, self.db.coll, "te$t") + self.assertRaises(InvalidName, make_col, self.db.coll, ".test") + self.assertRaises(InvalidName, make_col, self.db.coll, "test.") + self.assertRaises(InvalidName, make_col, self.db.coll, "tes..t") + self.assertRaises(InvalidName, make_col, self.db.coll, "tes\x00t") def test_getattr(self): - coll = self.db.test + coll = self.db.coll self.assertIsInstance(coll["_does_not_exist"], Collection) with self.assertRaises(AttributeError) as context: @@ -160,7 +160,7 @@ def setUp(self): self.w = client_context.w # type: ignore def tearDown(self): - self.db.test.drop() + self.db.coll.drop() self.db.drop_collection("test_large_limit") super().tearDown() @@ -175,7 +175,7 @@ def write_concern_collection(self): write_concern=WriteConcern(w=len(client_context.nodes) + 1), ) else: - yield self.db.test + yield self.db.coll def test_equality(self): self.assertIsInstance(self.db.test, Collection) @@ -189,7 +189,7 @@ def test_hashable(self): def test_create(self): # No Exception. - db = client_context.client.pymongo_test + db = self.db db.create_test_no_wc.drop() def lambda_test(): @@ -213,59 +213,59 @@ def lambda_test_2(): db.create_collection("create-test-wc", write_concern=IMPOSSIBLE_WRITE_CONCERN) def test_drop_nonexistent_collection(self): - self.db.drop_collection("test") - self.assertNotIn("test", self.db.list_collection_names()) + self.db.drop_collection("coll") + self.assertNotIn("coll", self.db.list_collection_names()) # No exception - self.db.drop_collection("test") + self.db.drop_collection("coll") def test_create_indexes(self): db = self.db with self.assertRaises(TypeError): - db.test.create_indexes("foo") # type: ignore[arg-type] + db.coll.create_indexes("foo") # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.create_indexes(["foo"]) # type: ignore[list-item] + db.coll.create_indexes(["foo"]) # type: ignore[list-item] self.assertRaises(TypeError, IndexModel, 5) self.assertRaises(ValueError, IndexModel, []) - db.test.drop_indexes() - db.create_collection("test") - self.assertEqual(len(db.test.index_information()), 1) + db.coll.drop_indexes() + db.create_collection("coll") + self.assertEqual(len(db.coll.index_information()), 1) - db.test.create_indexes([IndexModel("hello")]) - db.test.create_indexes([IndexModel([("hello", DESCENDING), ("world", ASCENDING)])]) + db.coll.create_indexes([IndexModel("hello")]) + db.coll.create_indexes([IndexModel([("hello", DESCENDING), ("world", ASCENDING)])]) # Tuple instead of list. - db.test.create_indexes([IndexModel((("world", ASCENDING),))]) + db.coll.create_indexes([IndexModel((("world", ASCENDING),))]) - self.assertEqual(len(db.test.index_information()), 4) + self.assertEqual(len(db.coll.index_information()), 4) - db.test.drop_indexes() - names = db.test.create_indexes( + db.coll.drop_indexes() + names = db.coll.create_indexes( [IndexModel([("hello", DESCENDING), ("world", ASCENDING)], name="hello_world")] ) self.assertEqual(names, ["hello_world"]) - db.test.drop_indexes() - self.assertEqual(len(db.test.index_information()), 1) - db.test.create_indexes([IndexModel("hello")]) - self.assertIn("hello_1", db.test.index_information()) + db.coll.drop_indexes() + self.assertEqual(len(db.coll.index_information()), 1) + db.coll.create_indexes([IndexModel("hello")]) + self.assertIn("hello_1", db.coll.index_information()) - db.test.drop_indexes() - self.assertEqual(len(db.test.index_information()), 1) - names = db.test.create_indexes( + db.coll.drop_indexes() + self.assertEqual(len(db.coll.index_information()), 1) + names = db.coll.create_indexes( [IndexModel([("hello", DESCENDING), ("world", ASCENDING)]), IndexModel("hello")] ) - info = db.test.index_information() + info = db.coll.index_information() for name in names: self.assertIn(name, info) - db.test.drop() - db.test.insert_one({"a": 1}) - db.test.insert_one({"a": 1}) + db.coll.drop() + db.coll.insert_one({"a": 1}) + db.coll.insert_one({"a": 1}) with self.assertRaises(DuplicateKeyError): - db.test.create_indexes([IndexModel("a", unique=True)]) + db.coll.create_indexes([IndexModel("a", unique=True)]) with self.write_concern_collection() as coll: coll.create_indexes([IndexModel("hello")]) @@ -278,81 +278,81 @@ def test_create_index(self): db = self.db with self.assertRaises(TypeError): - db.test.create_index(5) # type: ignore[arg-type] + db.coll.create_index(5) # type: ignore[arg-type] with self.assertRaises(ValueError): - db.test.create_index([]) + db.coll.create_index([]) - db.test.drop_indexes() - db.create_collection("test") - self.assertEqual(len(db.test.index_information()), 1) + db.coll.drop_indexes() + db.create_collection("coll") + self.assertEqual(len(db.coll.index_information()), 1) - db.test.create_index("hello") - db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)]) + db.coll.create_index("hello") + db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)]) # Tuple instead of list. - db.test.create_index((("world", ASCENDING),)) + db.coll.create_index((("world", ASCENDING),)) - self.assertEqual(len(db.test.index_information()), 4) + self.assertEqual(len(db.coll.index_information()), 4) - db.test.drop_indexes() - ix = db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], name="hello_world") + db.coll.drop_indexes() + ix = db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)], name="hello_world") self.assertEqual(ix, "hello_world") - db.test.drop_indexes() - self.assertEqual(len(db.test.index_information()), 1) - db.test.create_index("hello") - self.assertIn("hello_1", db.test.index_information()) + db.coll.drop_indexes() + self.assertEqual(len(db.coll.index_information()), 1) + db.coll.create_index("hello") + self.assertIn("hello_1", db.coll.index_information()) - db.test.drop_indexes() - self.assertEqual(len(db.test.index_information()), 1) - db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)]) - self.assertIn("hello_-1_world_1", db.test.index_information()) + db.coll.drop_indexes() + self.assertEqual(len(db.coll.index_information()), 1) + db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)]) + self.assertIn("hello_-1_world_1", db.coll.index_information()) - db.test.drop_indexes() - db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], name=None) - self.assertIn("hello_-1_world_1", db.test.index_information()) + db.coll.drop_indexes() + db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)], name=None) + self.assertIn("hello_-1_world_1", db.coll.index_information()) - db.test.drop() - db.test.insert_one({"a": 1}) - db.test.insert_one({"a": 1}) + db.coll.drop() + db.coll.insert_one({"a": 1}) + db.coll.insert_one({"a": 1}) with self.assertRaises(DuplicateKeyError): - db.test.create_index("a", unique=True) + db.coll.create_index("a", unique=True) with self.write_concern_collection() as coll: coll.create_index([("hello", DESCENDING)]) - db.test.create_index(["hello", "world"]) - db.test.create_index(["hello", ("world", DESCENDING)]) - db.test.create_index({"hello": 1}.items()) # type:ignore[arg-type] + db.coll.create_index(["hello", "world"]) + db.coll.create_index(["hello", ("world", DESCENDING)]) + db.coll.create_index({"hello": 1}.items()) # type:ignore[arg-type] def test_drop_index(self): db = self.db - db.test.drop_indexes() - db.test.create_index("hello") - name = db.test.create_index("goodbye") + db.coll.drop_indexes() + db.coll.create_index("hello") + name = db.coll.create_index("goodbye") - self.assertEqual(len(db.test.index_information()), 3) + self.assertEqual(len(db.coll.index_information()), 3) self.assertEqual(name, "goodbye_1") - db.test.drop_index(name) + db.coll.drop_index(name) # Drop it again. if client_context.version < Version(8, 3, -1): with self.assertRaises(OperationFailure): - db.test.drop_index(name) + db.coll.drop_index(name) else: - db.test.drop_index(name) - self.assertEqual(len(db.test.index_information()), 2) - self.assertIn("hello_1", db.test.index_information()) + db.coll.drop_index(name) + self.assertEqual(len(db.coll.index_information()), 2) + self.assertIn("hello_1", db.coll.index_information()) - db.test.drop_indexes() - db.test.create_index("hello") - name = db.test.create_index("goodbye") + db.coll.drop_indexes() + db.coll.create_index("hello") + name = db.coll.create_index("goodbye") - self.assertEqual(len(db.test.index_information()), 3) + self.assertEqual(len(db.coll.index_information()), 3) self.assertEqual(name, "goodbye_1") - db.test.drop_index([("goodbye", ASCENDING)]) - self.assertEqual(len(db.test.index_information()), 2) - self.assertIn("hello_1", db.test.index_information()) + db.coll.drop_index([("goodbye", ASCENDING)]) + self.assertEqual(len(db.coll.index_information()), 2) + self.assertIn("hello_1", db.coll.index_information()) with self.write_concern_collection() as coll: coll.drop_index("hello_1") @@ -360,7 +360,7 @@ def test_drop_index(self): @client_context.require_no_mongos @client_context.require_test_commands def test_index_management_max_time_ms(self): - coll = self.db.test + coll = self.db.coll self.client.admin.command("configureFailPoint", "maxTimeAlwaysTimeOut", mode="alwaysOn") try: with self.assertRaises(ExecutionTimeout): @@ -376,23 +376,23 @@ def test_index_management_max_time_ms(self): def test_list_indexes(self): db = self.db - db.test.drop() - db.create_collection("test") + db.coll.drop() + db.create_collection("coll") def map_indexes(indexes): return {index["name"]: index for index in indexes} - indexes = (db.test.list_indexes()).to_list() + indexes = (db.coll.list_indexes()).to_list() self.assertEqual(len(indexes), 1) self.assertIn("_id_", map_indexes(indexes)) - db.test.create_index("hello") - indexes = (db.test.list_indexes()).to_list() + db.coll.create_index("hello") + indexes = (db.coll.list_indexes()).to_list() self.assertEqual(len(indexes), 2) self.assertEqual(map_indexes(indexes)["hello_1"]["key"], SON([("hello", ASCENDING)])) - db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) - indexes = (db.test.list_indexes()).to_list() + db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) + indexes = (db.coll.list_indexes()).to_list() self.assertEqual(len(indexes), 3) index_map = map_indexes(indexes) self.assertEqual( @@ -410,29 +410,29 @@ def map_indexes(indexes): def test_index_info(self): db = self.db - db.test.drop() - db.create_collection("test") - self.assertEqual(len(db.test.index_information()), 1) - self.assertIn("_id_", db.test.index_information()) - - db.test.create_index("hello") - self.assertEqual(len(db.test.index_information()), 2) - self.assertEqual((db.test.index_information())["hello_1"]["key"], [("hello", ASCENDING)]) - - db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) - self.assertEqual((db.test.index_information())["hello_1"]["key"], [("hello", ASCENDING)]) - self.assertEqual(len(db.test.index_information()), 3) + db.coll.drop() + db.create_collection("coll") + self.assertEqual(len(db.coll.index_information()), 1) + self.assertIn("_id_", db.coll.index_information()) + + db.coll.create_index("hello") + self.assertEqual(len(db.coll.index_information()), 2) + self.assertEqual((db.coll.index_information())["hello_1"]["key"], [("hello", ASCENDING)]) + + db.coll.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True) + self.assertEqual((db.coll.index_information())["hello_1"]["key"], [("hello", ASCENDING)]) + self.assertEqual(len(db.coll.index_information()), 3) self.assertEqual( [("hello", DESCENDING), ("world", ASCENDING)], - (db.test.index_information())["hello_-1_world_1"]["key"], + (db.coll.index_information())["hello_-1_world_1"]["key"], ) - self.assertEqual(True, (db.test.index_information())["hello_-1_world_1"]["unique"]) + self.assertEqual(True, (db.coll.index_information())["hello_-1_world_1"]["unique"]) def test_index_geo2d(self): db = self.db - db.test.drop_indexes() - self.assertEqual("loc_2d", db.test.create_index([("loc", GEO2D)])) - index_info = (db.test.index_information())["loc_2d"] + db.coll.drop_indexes() + self.assertEqual("loc_2d", db.coll.create_index([("loc", GEO2D)])) + index_info = (db.coll.index_information())["loc_2d"] self.assertEqual([("loc", "2d")], index_info["key"]) # geoSearch was deprecated in 4.4 and removed in 5.0 @@ -440,19 +440,19 @@ def test_index_geo2d(self): @client_context.require_no_mongos def test_index_haystack(self): db = self.db - db.test.drop() + db.coll.drop() _id = ( - db.test.insert_one({"pos": {"long": 34.2, "lat": 33.3}, "type": "restaurant"}) + db.coll.insert_one({"pos": {"long": 34.2, "lat": 33.3}, "type": "restaurant"}) ).inserted_id - db.test.insert_one({"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"}) - db.test.insert_one({"pos": {"long": 59.1, "lat": 87.2}, "type": "office"}) - db.test.create_index([("pos", "geoHaystack"), ("type", ASCENDING)], bucketSize=1) + db.coll.insert_one({"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"}) + db.coll.insert_one({"pos": {"long": 59.1, "lat": 87.2}, "type": "office"}) + db.coll.create_index([("pos", "geoHaystack"), ("type", ASCENDING)], bucketSize=1) results = ( db.command( SON( [ - ("geoSearch", "test"), + ("geoSearch", "coll"), ("near", [33, 33]), ("maxDistance", 6), ("search", {"type": "restaurant"}), @@ -470,31 +470,31 @@ def test_index_haystack(self): @client_context.require_no_mongos def test_index_text(self): db = self.db - db.test.drop_indexes() - self.assertEqual("t_text", db.test.create_index([("t", TEXT)])) - index_info = (db.test.index_information())["t_text"] + db.coll.drop_indexes() + self.assertEqual("t_text", db.coll.create_index([("t", TEXT)])) + index_info = (db.coll.index_information())["t_text"] self.assertIn("weights", index_info) - db.test.insert_many( + db.coll.insert_many( [{"t": "spam eggs and spam"}, {"t": "spam"}, {"t": "egg sausage and bacon"}] ) # MongoDB 2.6 text search. Create 'score' field in projection. - cursor = db.test.find({"$text": {"$search": "spam"}}, {"score": {"$meta": "textScore"}}) + cursor = db.coll.find({"$text": {"$search": "spam"}}, {"score": {"$meta": "textScore"}}) # Sort by 'score' field. cursor.sort([("score", {"$meta": "textScore"})]) results = cursor.to_list() self.assertGreaterEqual(results[0]["score"], results[1]["score"]) - db.test.drop_indexes() + db.coll.drop_indexes() def test_index_2dsphere(self): db = self.db - db.test.drop_indexes() - self.assertEqual("geo_2dsphere", db.test.create_index([("geo", GEOSPHERE)])) + db.coll.drop_indexes() + self.assertEqual("geo_2dsphere", db.coll.create_index([("geo", GEOSPHERE)])) - for dummy, info in (db.test.index_information()).items(): + for dummy, info in (db.coll.index_information()).items(): field, idx_type = info["key"][0] if field == "geo" and idx_type == "2dsphere": break @@ -505,45 +505,45 @@ def test_index_2dsphere(self): query = {"geo": {"$within": {"$geometry": poly}}} # This query will error without a 2dsphere index. - db.test.find(query) - db.test.drop_indexes() + db.coll.find(query) + db.coll.drop_indexes() def test_index_hashed(self): db = self.db - db.test.drop_indexes() - self.assertEqual("a_hashed", db.test.create_index([("a", HASHED)])) + db.coll.drop_indexes() + self.assertEqual("a_hashed", db.coll.create_index([("a", HASHED)])) - for dummy, info in (db.test.index_information()).items(): + for dummy, info in (db.coll.index_information()).items(): field, idx_type = info["key"][0] if field == "a" and idx_type == "hashed": break else: self.fail("hashed index not found.") - db.test.drop_indexes() + db.coll.drop_indexes() def test_index_sparse(self): db = self.db - db.test.drop_indexes() - db.test.create_index([("key", ASCENDING)], sparse=True) - self.assertTrue((db.test.index_information())["key_1"]["sparse"]) + db.coll.drop_indexes() + db.coll.create_index([("key", ASCENDING)], sparse=True) + self.assertTrue((db.coll.index_information())["key_1"]["sparse"]) def test_index_background(self): db = self.db - db.test.drop_indexes() - db.test.create_index([("keya", ASCENDING)]) - db.test.create_index([("keyb", ASCENDING)], background=False) - db.test.create_index([("keyc", ASCENDING)], background=True) - self.assertNotIn("background", (db.test.index_information())["keya_1"]) - self.assertFalse((db.test.index_information())["keyb_1"]["background"]) - self.assertTrue((db.test.index_information())["keyc_1"]["background"]) + db.coll.drop_indexes() + db.coll.create_index([("keya", ASCENDING)]) + db.coll.create_index([("keyb", ASCENDING)], background=False) + db.coll.create_index([("keyc", ASCENDING)], background=True) + self.assertNotIn("background", (db.coll.index_information())["keya_1"]) + self.assertFalse((db.coll.index_information())["keyb_1"]["background"]) + self.assertTrue((db.coll.index_information())["keyc_1"]["background"]) def _drop_dups_setup(self, db): - db.drop_collection("test") - 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}) + db.drop_collection("coll") + db.coll.insert_one({"i": 1}) + db.coll.insert_one({"i": 2}) + db.coll.insert_one({"i": 2}) # duplicate + db.coll.insert_one({"i": 3}) def test_index_dont_drop_dups(self): # Try *not* dropping duplicates @@ -552,16 +552,16 @@ def test_index_dont_drop_dups(self): # There's a duplicate def _test_create(): - db.test.create_index([("i", ASCENDING)], unique=True, dropDups=False) + db.coll.create_index([("i", ASCENDING)], unique=True, dropDups=False) with self.assertRaises(DuplicateKeyError): _test_create() # Duplicate wasn't dropped - self.assertEqual(4, db.test.count_documents({})) + self.assertEqual(4, db.coll.count_documents({})) # Index wasn't created, only the default index on _id - self.assertEqual(1, len(db.test.index_information())) + self.assertEqual(1, len(db.coll.index_information())) # Get the plan dynamically because the explain format will change. def get_plan_stage(self, root, stage): @@ -586,139 +586,139 @@ def get_plan_stage(self, root, stage): def test_index_filter(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") # Test bad filter spec on create. with self.assertRaises(OperationFailure): - db.test.create_index("x", partialFilterExpression=5) + db.coll.create_index("x", partialFilterExpression=5) with self.assertRaises(OperationFailure): - db.test.create_index("x", partialFilterExpression={"x": {"$asdasd": 3}}) + db.coll.create_index("x", partialFilterExpression={"x": {"$asdasd": 3}}) with self.assertRaises(OperationFailure): - db.test.create_index("x", partialFilterExpression={"$and": 5}) + db.coll.create_index("x", partialFilterExpression={"$and": 5}) self.assertEqual( "x_1", - db.test.create_index([("x", ASCENDING)], partialFilterExpression={"a": {"$lte": 1.5}}), + db.coll.create_index([("x", ASCENDING)], partialFilterExpression={"a": {"$lte": 1.5}}), ) - db.test.insert_one({"x": 5, "a": 2}) - db.test.insert_one({"x": 6, "a": 1}) + db.coll.insert_one({"x": 5, "a": 2}) + db.coll.insert_one({"x": 6, "a": 1}) # Operations that use the partial index. - explain = db.test.find({"x": 6, "a": 1}).explain() + explain = db.coll.find({"x": 6, "a": 1}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN") self.assertEqual("x_1", stage.get("indexName")) self.assertTrue(stage.get("isPartial")) - explain = db.test.find({"x": {"$gt": 1}, "a": 1}).explain() + explain = db.coll.find({"x": {"$gt": 1}, "a": 1}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN") self.assertEqual("x_1", stage.get("indexName")) self.assertTrue(stage.get("isPartial")) - explain = db.test.find({"x": 6, "a": {"$lte": 1}}).explain() + explain = db.coll.find({"x": 6, "a": {"$lte": 1}}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN") self.assertEqual("x_1", stage.get("indexName")) self.assertTrue(stage.get("isPartial")) # Operations that do not use the partial index. - explain = db.test.find({"x": 6, "a": {"$lte": 1.6}}).explain() + explain = db.coll.find({"x": 6, "a": {"$lte": 1.6}}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN") self.assertNotEqual({}, stage) - explain = db.test.find({"x": 6}).explain() + explain = db.coll.find({"x": 6}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN") self.assertNotEqual({}, stage) # Test drop_indexes. - db.test.drop_index("x_1") - explain = db.test.find({"x": 6, "a": 1}).explain() + db.coll.drop_index("x_1") + explain = db.coll.find({"x": 6, "a": 1}).explain() stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN") self.assertNotEqual({}, stage) def test_field_selection(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") doc = {"a": 1, "b": 5, "c": {"d": 5, "e": 10}} - db.test.insert_one(doc) + db.coll.insert_one(doc) # Test field inclusion - doc = next(db.test.find({}, ["_id"])) + doc = next(db.coll.find({}, ["_id"])) self.assertEqual(list(doc), ["_id"]) - doc = next(db.test.find({}, ["a"])) + doc = next(db.coll.find({}, ["a"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "a"]) - doc = next(db.test.find({}, ["b"])) + doc = next(db.coll.find({}, ["b"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "b"]) - doc = next(db.test.find({}, ["c"])) + doc = next(db.coll.find({}, ["c"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "c"]) - doc = next(db.test.find({}, ["a"])) + doc = next(db.coll.find({}, ["a"])) self.assertEqual(doc["a"], 1) - doc = next(db.test.find({}, ["b"])) + doc = next(db.coll.find({}, ["b"])) self.assertEqual(doc["b"], 5) - doc = next(db.test.find({}, ["c"])) + doc = next(db.coll.find({}, ["c"])) self.assertEqual(doc["c"], {"d": 5, "e": 10}) # Test inclusion of fields with dots - doc = next(db.test.find({}, ["c.d"])) + doc = next(db.coll.find({}, ["c.d"])) self.assertEqual(doc["c"], {"d": 5}) - doc = next(db.test.find({}, ["c.e"])) + doc = next(db.coll.find({}, ["c.e"])) self.assertEqual(doc["c"], {"e": 10}) - doc = next(db.test.find({}, ["b", "c.e"])) + doc = next(db.coll.find({}, ["b", "c.e"])) self.assertEqual(doc["c"], {"e": 10}) - doc = next(db.test.find({}, ["b", "c.e"])) + doc = next(db.coll.find({}, ["b", "c.e"])) l = list(doc) l.sort() self.assertEqual(l, ["_id", "b", "c"]) - doc = next(db.test.find({}, ["b", "c.e"])) + doc = next(db.coll.find({}, ["b", "c.e"])) self.assertEqual(doc["b"], 5) # Test field exclusion - doc = next(db.test.find({}, {"a": False, "b": 0})) + doc = next(db.coll.find({}, {"a": False, "b": 0})) l = list(doc) l.sort() self.assertEqual(l, ["_id", "c"]) - doc = next(db.test.find({}, {"_id": False})) + doc = next(db.coll.find({}, {"_id": False})) l = list(doc) self.assertNotIn("_id", l) def test_options(self): db = self.db - db.drop_collection("test") - db.create_collection("test", capped=True, size=4096) - result = db.test.options() + db.drop_collection("coll") + db.create_collection("coll", capped=True, size=4096) + result = db.coll.options() self.assertEqual(result, {"capped": True, "size": 4096}) - db.drop_collection("test") + db.drop_collection("coll") def test_insert_one(self): db = self.db - db.test.drop() + db.coll.drop() document: dict[str, Any] = {"_id": 1000} - result = db.test.insert_one(document) + result = db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertIsInstance(result.inserted_id, int) self.assertEqual(document["_id"], result.inserted_id) self.assertTrue(result.acknowledged) - self.assertIsNotNone(db.test.find_one({"_id": document["_id"]})) - self.assertEqual(1, db.test.count_documents({})) + self.assertIsNotNone(db.coll.find_one({"_id": document["_id"]})) + self.assertEqual(1, db.coll.count_documents({})) document = {"foo": "bar"} - result = db.test.insert_one(document) + result = db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertIsInstance(result.inserted_id, ObjectId) self.assertEqual(document["_id"], result.inserted_id) self.assertTrue(result.acknowledged) - self.assertIsNotNone(db.test.find_one({"_id": document["_id"]})) - self.assertEqual(2, db.test.count_documents({})) + self.assertIsNotNone(db.coll.find_one({"_id": document["_id"]})) + self.assertEqual(2, db.coll.count_documents({})) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = db.test.insert_one(document) + result = db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertIsInstance(result.inserted_id, ObjectId) self.assertEqual(document["_id"], result.inserted_id) @@ -726,21 +726,21 @@ def test_insert_one(self): # The insert failed duplicate key... def async_lambda(): - return db.test.count_documents({}) == 2 + return db.coll.count_documents({}) == 2 wait_until(async_lambda, "forcing duplicate key error") document = RawBSONDocument(encode({"_id": ObjectId(), "foo": "bar"})) - result = db.test.insert_one(document) + result = db.coll.insert_one(document) self.assertIsInstance(result, InsertOneResult) self.assertEqual(result.inserted_id, None) def test_insert_many(self): db = self.db - db.test.drop() + db.coll.drop() docs: list = [{} for _ in range(5)] - result = db.test.insert_many(docs) + result = db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertIsInstance(result.inserted_ids, list) self.assertEqual(5, len(result.inserted_ids)) @@ -748,11 +748,11 @@ def test_insert_many(self): _id = doc["_id"] self.assertIsInstance(_id, ObjectId) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, db.test.count_documents({"_id": _id})) + self.assertEqual(1, db.coll.count_documents({"_id": _id})) self.assertTrue(result.acknowledged) docs = [{"_id": i} for i in range(5)] - result = db.test.insert_many(docs) + result = db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertIsInstance(result.inserted_ids, list) self.assertEqual(5, len(result.inserted_ids)) @@ -760,24 +760,24 @@ def test_insert_many(self): _id = doc["_id"] self.assertIsInstance(_id, int) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, db.test.count_documents({"_id": _id})) + self.assertEqual(1, db.coll.count_documents({"_id": _id})) self.assertTrue(result.acknowledged) docs = [RawBSONDocument(encode({"_id": i + 5})) for i in range(5)] - result = db.test.insert_many(docs) + result = db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertIsInstance(result.inserted_ids, list) self.assertEqual([], result.inserted_ids) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) docs: list = [{} for _ in range(5)] - result = db.test.insert_many(docs) + result = db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertFalse(result.acknowledged) - self.assertEqual(20, db.test.count_documents({})) + self.assertEqual(20, db.coll.count_documents({})) def test_insert_many_generator(self): - coll = self.db.test + coll = self.db.coll coll.delete_many({}) def gen(): @@ -794,75 +794,75 @@ def test_insert_many_invalid(self): db = self.db with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - db.test.insert_many({}) + db.coll.insert_many({}) with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - db.test.insert_many([]) + db.coll.insert_many([]) with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - db.test.insert_many(1) # type: ignore[arg-type] + db.coll.insert_many(1) # type: ignore[arg-type] with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"): - db.test.insert_many(RawBSONDocument(encode({"_id": 2}))) + db.coll.insert_many(RawBSONDocument(encode({"_id": 2}))) def test_delete_one(self): - self.db.test.drop() + self.db.coll.drop() - self.db.test.insert_one({"x": 1}) - self.db.test.insert_one({"y": 1}) - self.db.test.insert_one({"z": 1}) + self.db.coll.insert_one({"x": 1}) + self.db.coll.insert_one({"y": 1}) + self.db.coll.insert_one({"z": 1}) - result = self.db.test.delete_one({"x": 1}) + result = self.db.coll.delete_one({"x": 1}) self.assertIsInstance(result, DeleteResult) self.assertEqual(1, result.deleted_count) self.assertTrue(result.acknowledged) - self.assertEqual(2, self.db.test.count_documents({})) + self.assertEqual(2, self.db.coll.count_documents({})) - result = self.db.test.delete_one({"y": 1}) + result = self.db.coll.delete_one({"y": 1}) self.assertIsInstance(result, DeleteResult) self.assertEqual(1, result.deleted_count) self.assertTrue(result.acknowledged) - self.assertEqual(1, self.db.test.count_documents({})) + self.assertEqual(1, self.db.coll.count_documents({})) db = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) - result = db.test.delete_one({"z": 1}) + result = db.coll.delete_one({"z": 1}) self.assertIsInstance(result, DeleteResult) self.assertRaises(InvalidOperation, lambda: result.deleted_count) self.assertFalse(result.acknowledged) def lambda_async(): - return db.test.count_documents({}) == 0 + return db.coll.count_documents({}) == 0 wait_until(lambda_async, "delete 1 documents") def test_delete_many(self): - self.db.test.drop() + self.db.coll.drop() - self.db.test.insert_one({"x": 1}) - self.db.test.insert_one({"x": 1}) - self.db.test.insert_one({"y": 1}) - self.db.test.insert_one({"y": 1}) + self.db.coll.insert_one({"x": 1}) + self.db.coll.insert_one({"x": 1}) + self.db.coll.insert_one({"y": 1}) + self.db.coll.insert_one({"y": 1}) - result = self.db.test.delete_many({"x": 1}) + result = self.db.coll.delete_many({"x": 1}) self.assertIsInstance(result, DeleteResult) self.assertEqual(2, result.deleted_count) self.assertTrue(result.acknowledged) - self.assertEqual(0, self.db.test.count_documents({"x": 1})) + self.assertEqual(0, self.db.coll.count_documents({"x": 1})) db = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) - result = db.test.delete_many({"y": 1}) + result = db.coll.delete_many({"y": 1}) self.assertIsInstance(result, DeleteResult) self.assertRaises(InvalidOperation, lambda: result.deleted_count) self.assertFalse(result.acknowledged) def lambda_async(): - return db.test.count_documents({}) == 0 + return db.coll.count_documents({}) == 0 wait_until(lambda_async, "delete 2 documents") def test_command_document_too_large(self): large = "*" * (client_context.max_bson_size + _COMMAND_OVERHEAD) - coll = self.db.test + coll = self.db.coll with self.assertRaises(DocumentTooLarge): coll.insert_one({"data": large}) # update_one and update_many are the same @@ -879,200 +879,200 @@ def test_write_large_document(self): self.assertEqual(max_size, 16777216) with self.assertRaises(OperationFailure): - self.db.test.insert_one({"foo": max_str}) + self.db.coll.insert_one({"foo": max_str}) with self.assertRaises(OperationFailure): - self.db.test.replace_one({}, {"foo": max_str}, upsert=True) + self.db.coll.replace_one({}, {"foo": max_str}, upsert=True) with self.assertRaises(OperationFailure): - self.db.test.insert_many([{"x": 1}, {"foo": max_str}]) - self.db.test.insert_many([{"foo": half_str}, {"foo": half_str}]) + self.db.coll.insert_many([{"x": 1}, {"foo": max_str}]) + self.db.coll.insert_many([{"foo": half_str}, {"foo": half_str}]) - self.db.test.insert_one({"bar": "x"}) + self.db.coll.insert_one({"bar": "x"}) # Use w=0 here to test legacy doc size checking in all server versions - unack_coll = self.db.test.with_options(write_concern=WriteConcern(w=0)) + unack_coll = self.db.coll.with_options(write_concern=WriteConcern(w=0)) with self.assertRaises(DocumentTooLarge): unack_coll.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 14)}) - self.db.test.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 32)}) + self.db.coll.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 32)}) def test_insert_bypass_document_validation(self): db = self.db - db.test.drop() - db.create_collection("test", validator={"a": {"$exists": True}}) + db.coll.drop() + db.create_collection("coll", validator={"a": {"$exists": True}}) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) # Test insert_one with self.assertRaises(OperationFailure): - db.test.insert_one({"_id": 1, "x": 100}) - result = db.test.insert_one({"_id": 1, "x": 100}, bypass_document_validation=True) + db.coll.insert_one({"_id": 1, "x": 100}) + result = db.coll.insert_one({"_id": 1, "x": 100}, bypass_document_validation=True) self.assertIsInstance(result, InsertOneResult) self.assertEqual(1, result.inserted_id) - result = db.test.insert_one({"_id": 2, "a": 0}) + result = db.coll.insert_one({"_id": 2, "a": 0}) self.assertIsInstance(result, InsertOneResult) self.assertEqual(2, result.inserted_id) - db_w0.test.insert_one({"y": 1}, bypass_document_validation=True) + db_w0.coll.insert_one({"y": 1}, bypass_document_validation=True) def async_lambda(): - return db_w0.test.find_one({"y": 1}) + return db_w0.coll.find_one({"y": 1}) wait_until(async_lambda, "find w:0 inserted document") # Test insert_many docs = [{"_id": i, "x": 100 - i} for i in range(3, 100)] with self.assertRaises(OperationFailure): - db.test.insert_many(docs) - result = db.test.insert_many(docs, bypass_document_validation=True) + db.coll.insert_many(docs) + result = db.coll.insert_many(docs, bypass_document_validation=True) self.assertIsInstance(result, InsertManyResult) self.assertTrue(97, len(result.inserted_ids)) for doc in docs: _id = doc["_id"] self.assertIsInstance(_id, int) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, db.test.count_documents({"x": doc["x"]})) + self.assertEqual(1, db.coll.count_documents({"x": doc["x"]})) self.assertTrue(result.acknowledged) docs = [{"_id": i, "a": 200 - i} for i in range(100, 200)] - result = db.test.insert_many(docs) + result = db.coll.insert_many(docs) self.assertIsInstance(result, InsertManyResult) self.assertTrue(97, len(result.inserted_ids)) for doc in docs: _id = doc["_id"] self.assertIsInstance(_id, int) self.assertIn(_id, result.inserted_ids) - self.assertEqual(1, db.test.count_documents({"a": doc["a"]})) + self.assertEqual(1, db.coll.count_documents({"a": doc["a"]})) self.assertTrue(result.acknowledged) with self.assertRaises(OperationFailure): - db_w0.test.insert_many( + db_w0.coll.insert_many( [{"x": 1}, {"x": 2}], bypass_document_validation=True, ) def test_replace_bypass_document_validation(self): db = self.db - db.test.drop() - db.create_collection("test", validator={"a": {"$exists": True}}) + db.coll.drop() + db.create_collection("coll", validator={"a": {"$exists": True}}) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) # Test replace_one - db.test.insert_one({"a": 101}) + db.coll.insert_one({"a": 101}) with self.assertRaises(OperationFailure): - db.test.replace_one({"a": 101}, {"y": 1}) - self.assertEqual(0, db.test.count_documents({"y": 1})) - self.assertEqual(1, db.test.count_documents({"a": 101})) - db.test.replace_one({"a": 101}, {"y": 1}, bypass_document_validation=True) - self.assertEqual(0, db.test.count_documents({"a": 101})) - self.assertEqual(1, db.test.count_documents({"y": 1})) - db.test.replace_one({"y": 1}, {"a": 102}) - self.assertEqual(0, db.test.count_documents({"y": 1})) - self.assertEqual(0, db.test.count_documents({"a": 101})) - self.assertEqual(1, db.test.count_documents({"a": 102})) - - db.test.insert_one({"y": 1}, bypass_document_validation=True) + db.coll.replace_one({"a": 101}, {"y": 1}) + self.assertEqual(0, db.coll.count_documents({"y": 1})) + self.assertEqual(1, db.coll.count_documents({"a": 101})) + db.coll.replace_one({"a": 101}, {"y": 1}, bypass_document_validation=True) + self.assertEqual(0, db.coll.count_documents({"a": 101})) + self.assertEqual(1, db.coll.count_documents({"y": 1})) + db.coll.replace_one({"y": 1}, {"a": 102}) + self.assertEqual(0, db.coll.count_documents({"y": 1})) + self.assertEqual(0, db.coll.count_documents({"a": 101})) + self.assertEqual(1, db.coll.count_documents({"a": 102})) + + db.coll.insert_one({"y": 1}, bypass_document_validation=True) with self.assertRaises(OperationFailure): - db.test.replace_one({"y": 1}, {"x": 101}) - self.assertEqual(0, db.test.count_documents({"x": 101})) - self.assertEqual(1, db.test.count_documents({"y": 1})) - db.test.replace_one({"y": 1}, {"x": 101}, bypass_document_validation=True) - self.assertEqual(0, db.test.count_documents({"y": 1})) - self.assertEqual(1, db.test.count_documents({"x": 101})) - db.test.replace_one({"x": 101}, {"a": 103}, bypass_document_validation=False) - self.assertEqual(0, db.test.count_documents({"x": 101})) - self.assertEqual(1, db.test.count_documents({"a": 103})) - - db.test.insert_one({"y": 1}, bypass_document_validation=True) - db_w0.test.replace_one({"y": 1}, {"x": 1}, bypass_document_validation=True) + db.coll.replace_one({"y": 1}, {"x": 101}) + self.assertEqual(0, db.coll.count_documents({"x": 101})) + self.assertEqual(1, db.coll.count_documents({"y": 1})) + db.coll.replace_one({"y": 1}, {"x": 101}, bypass_document_validation=True) + self.assertEqual(0, db.coll.count_documents({"y": 1})) + self.assertEqual(1, db.coll.count_documents({"x": 101})) + db.coll.replace_one({"x": 101}, {"a": 103}, bypass_document_validation=False) + self.assertEqual(0, db.coll.count_documents({"x": 101})) + self.assertEqual(1, db.coll.count_documents({"a": 103})) + + db.coll.insert_one({"y": 1}, bypass_document_validation=True) + db_w0.coll.replace_one({"y": 1}, {"x": 1}, bypass_document_validation=True) def predicate(): - return db_w0.test.find_one({"x": 1}) + return db_w0.coll.find_one({"x": 1}) wait_until(predicate, "find w:0 replaced document") def test_update_bypass_document_validation(self): db = self.db - db.test.drop() - db.test.insert_one({"z": 5}) - db.command(SON([("collMod", "test"), ("validator", {"z": {"$gte": 0}})])) + db.coll.drop() + db.coll.insert_one({"z": 5}) + db.command(SON([("collMod", "coll"), ("validator", {"z": {"$gte": 0}})])) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) # Test update_one with self.assertRaises(OperationFailure): - db.test.update_one({"z": 5}, {"$inc": {"z": -10}}) - self.assertEqual(0, db.test.count_documents({"z": -5})) - self.assertEqual(1, db.test.count_documents({"z": 5})) - db.test.update_one({"z": 5}, {"$inc": {"z": -10}}, bypass_document_validation=True) - self.assertEqual(0, db.test.count_documents({"z": 5})) - self.assertEqual(1, db.test.count_documents({"z": -5})) - db.test.update_one({"z": -5}, {"$inc": {"z": 6}}, bypass_document_validation=False) - self.assertEqual(1, db.test.count_documents({"z": 1})) - self.assertEqual(0, db.test.count_documents({"z": -5})) - - db.test.insert_one({"z": -10}, bypass_document_validation=True) + db.coll.update_one({"z": 5}, {"$inc": {"z": -10}}) + self.assertEqual(0, db.coll.count_documents({"z": -5})) + self.assertEqual(1, db.coll.count_documents({"z": 5})) + db.coll.update_one({"z": 5}, {"$inc": {"z": -10}}, bypass_document_validation=True) + self.assertEqual(0, db.coll.count_documents({"z": 5})) + self.assertEqual(1, db.coll.count_documents({"z": -5})) + db.coll.update_one({"z": -5}, {"$inc": {"z": 6}}, bypass_document_validation=False) + self.assertEqual(1, db.coll.count_documents({"z": 1})) + self.assertEqual(0, db.coll.count_documents({"z": -5})) + + db.coll.insert_one({"z": -10}, bypass_document_validation=True) with self.assertRaises(OperationFailure): - db.test.update_one({"z": -10}, {"$inc": {"z": 1}}) - self.assertEqual(0, db.test.count_documents({"z": -9})) - self.assertEqual(1, db.test.count_documents({"z": -10})) - db.test.update_one({"z": -10}, {"$inc": {"z": 1}}, bypass_document_validation=True) - self.assertEqual(1, db.test.count_documents({"z": -9})) - self.assertEqual(0, db.test.count_documents({"z": -10})) - db.test.update_one({"z": -9}, {"$inc": {"z": 9}}, bypass_document_validation=False) - self.assertEqual(0, db.test.count_documents({"z": -9})) - self.assertEqual(1, db.test.count_documents({"z": 0})) - - db.test.insert_one({"y": 1, "x": 0}, bypass_document_validation=True) - db_w0.test.update_one({"y": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) + db.coll.update_one({"z": -10}, {"$inc": {"z": 1}}) + self.assertEqual(0, db.coll.count_documents({"z": -9})) + self.assertEqual(1, db.coll.count_documents({"z": -10})) + db.coll.update_one({"z": -10}, {"$inc": {"z": 1}}, bypass_document_validation=True) + self.assertEqual(1, db.coll.count_documents({"z": -9})) + self.assertEqual(0, db.coll.count_documents({"z": -10})) + db.coll.update_one({"z": -9}, {"$inc": {"z": 9}}, bypass_document_validation=False) + self.assertEqual(0, db.coll.count_documents({"z": -9})) + self.assertEqual(1, db.coll.count_documents({"z": 0})) + + db.coll.insert_one({"y": 1, "x": 0}, bypass_document_validation=True) + db_w0.coll.update_one({"y": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) def async_lambda(): - return db_w0.test.find_one({"y": 1, "x": 1}) + return db_w0.coll.find_one({"y": 1, "x": 1}) wait_until(async_lambda, "find w:0 updated document") # Test update_many - db.test.insert_many([{"z": i} for i in range(3, 101)]) - db.test.insert_one({"y": 0}, bypass_document_validation=True) + db.coll.insert_many([{"z": i} for i in range(3, 101)]) + db.coll.insert_one({"y": 0}, bypass_document_validation=True) with self.assertRaises(OperationFailure): - db.test.update_many({}, {"$inc": {"z": -100}}) - self.assertEqual(100, db.test.count_documents({"z": {"$gte": 0}})) - self.assertEqual(0, db.test.count_documents({"z": {"$lt": 0}})) - self.assertEqual(0, db.test.count_documents({"y": 0, "z": -100})) - db.test.update_many( + db.coll.update_many({}, {"$inc": {"z": -100}}) + self.assertEqual(100, db.coll.count_documents({"z": {"$gte": 0}})) + self.assertEqual(0, db.coll.count_documents({"z": {"$lt": 0}})) + self.assertEqual(0, db.coll.count_documents({"y": 0, "z": -100})) + db.coll.update_many( {"z": {"$gte": 0}}, {"$inc": {"z": -100}}, bypass_document_validation=True ) - self.assertEqual(0, db.test.count_documents({"z": {"$gt": 0}})) - self.assertEqual(100, db.test.count_documents({"z": {"$lte": 0}})) - db.test.update_many( + self.assertEqual(0, db.coll.count_documents({"z": {"$gt": 0}})) + self.assertEqual(100, db.coll.count_documents({"z": {"$lte": 0}})) + db.coll.update_many( {"z": {"$gt": -50}}, {"$inc": {"z": 100}}, bypass_document_validation=False ) - self.assertEqual(50, db.test.count_documents({"z": {"$gt": 0}})) - self.assertEqual(50, db.test.count_documents({"z": {"$lt": 0}})) + self.assertEqual(50, db.coll.count_documents({"z": {"$gt": 0}})) + self.assertEqual(50, db.coll.count_documents({"z": {"$lt": 0}})) - db.test.insert_many([{"z": -i} for i in range(50)], bypass_document_validation=True) + db.coll.insert_many([{"z": -i} for i in range(50)], bypass_document_validation=True) with self.assertRaises(OperationFailure): - db.test.update_many({}, {"$inc": {"z": 1}}) - self.assertEqual(100, db.test.count_documents({"z": {"$lte": 0}})) - self.assertEqual(50, db.test.count_documents({"z": {"$gt": 1}})) - db.test.update_many( + db.coll.update_many({}, {"$inc": {"z": 1}}) + self.assertEqual(100, db.coll.count_documents({"z": {"$lte": 0}})) + self.assertEqual(50, db.coll.count_documents({"z": {"$gt": 1}})) + db.coll.update_many( {"z": {"$gte": 0}}, {"$inc": {"z": -100}}, bypass_document_validation=True ) - self.assertEqual(0, db.test.count_documents({"z": {"$gt": 0}})) - self.assertEqual(150, db.test.count_documents({"z": {"$lte": 0}})) - db.test.update_many( + self.assertEqual(0, db.coll.count_documents({"z": {"$gt": 0}})) + self.assertEqual(150, db.coll.count_documents({"z": {"$lte": 0}})) + db.coll.update_many( {"z": {"$lte": 0}}, {"$inc": {"z": 100}}, bypass_document_validation=False ) - self.assertEqual(150, db.test.count_documents({"z": {"$gte": 0}})) - self.assertEqual(0, db.test.count_documents({"z": {"$lt": 0}})) + self.assertEqual(150, db.coll.count_documents({"z": {"$gte": 0}})) + self.assertEqual(0, db.coll.count_documents({"z": {"$lt": 0}})) - db.test.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) - db.test.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) - db_w0.test.update_many({"m": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) + db.coll.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) + db.coll.insert_one({"m": 1, "x": 0}, bypass_document_validation=True) + db_w0.coll.update_many({"m": 1}, {"$inc": {"x": 1}}, bypass_document_validation=True) def async_lambda(): - return db_w0.test.count_documents({"m": 1, "x": 1}) == 2 + return db_w0.coll.count_documents({"m": 1, "x": 1}) == 2 wait_until(async_lambda, "find w:0 updated documents") def test_bypass_document_validation_bulk_write(self): db = self.db - db.test.drop() - db.create_collection("test", validator={"a": {"$gte": 0}}) + db.coll.drop() + db.create_collection("coll", validator={"a": {"$gte": 0}}) db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0)) ops: list = [ @@ -1083,140 +1083,140 @@ def test_bypass_document_validation_bulk_write(self): UpdateMany({"a": {"$lte": -10}}, {"$inc": {"a": 1}}), ReplaceOne({"a": {"$lte": -10}}, {"a": -1}), ] - db.test.bulk_write(ops, bypass_document_validation=True) + db.coll.bulk_write(ops, bypass_document_validation=True) - self.assertEqual(3, db.test.count_documents({})) - self.assertEqual(1, db.test.count_documents({"a": -11})) - self.assertEqual(1, db.test.count_documents({"a": -1})) - self.assertEqual(1, db.test.count_documents({"a": -9})) + self.assertEqual(3, db.coll.count_documents({})) + self.assertEqual(1, db.coll.count_documents({"a": -11})) + self.assertEqual(1, db.coll.count_documents({"a": -1})) + self.assertEqual(1, db.coll.count_documents({"a": -9})) # Assert that the operations would fail without bypass_doc_val for op in ops: with self.assertRaises(BulkWriteError): - db.test.bulk_write([op]) + db.coll.bulk_write([op]) with self.assertRaises(OperationFailure): - db_w0.test.bulk_write(ops, bypass_document_validation=True) + db_w0.coll.bulk_write(ops, bypass_document_validation=True) def test_find_by_default_dct(self): db = self.db - db.test.insert_one({"foo": "bar"}) + db.coll.insert_one({"foo": "bar"}) dct = defaultdict(dict, [("foo", "bar")]) # type: ignore[arg-type] - self.assertIsNotNone(db.test.find_one(dct)) + self.assertIsNotNone(db.coll.find_one(dct)) self.assertEqual(dct, defaultdict(dict, [("foo", "bar")])) def test_find_w_fields(self): db = self.db - db.test.delete_many({}) + db.coll.delete_many({}) - db.test.insert_one({"x": 1, "mike": "awesome", "extra thing": "abcdefghijklmnopqrstuvwxyz"}) - self.assertEqual(1, db.test.count_documents({})) - doc = next(db.test.find({})) + db.coll.insert_one({"x": 1, "mike": "awesome", "extra thing": "abcdefghijklmnopqrstuvwxyz"}) + self.assertEqual(1, db.coll.count_documents({})) + doc = next(db.coll.find({})) self.assertIn("x", doc) - doc = next(db.test.find({})) + doc = next(db.coll.find({})) self.assertIn("mike", doc) - doc = next(db.test.find({})) + doc = next(db.coll.find({})) self.assertIn("extra thing", doc) - doc = next(db.test.find({}, ["x", "mike"])) + doc = next(db.coll.find({}, ["x", "mike"])) self.assertIn("x", doc) - doc = next(db.test.find({}, ["x", "mike"])) + doc = next(db.coll.find({}, ["x", "mike"])) self.assertIn("mike", doc) - doc = next(db.test.find({}, ["x", "mike"])) + doc = next(db.coll.find({}, ["x", "mike"])) self.assertNotIn("extra thing", doc) - doc = next(db.test.find({}, ["mike"])) + doc = next(db.coll.find({}, ["mike"])) self.assertNotIn("x", doc) - doc = next(db.test.find({}, ["mike"])) + doc = next(db.coll.find({}, ["mike"])) self.assertIn("mike", doc) - doc = next(db.test.find({}, ["mike"])) + doc = next(db.coll.find({}, ["mike"])) self.assertNotIn("extra thing", doc) @no_type_check def test_fields_specifier_as_dict(self): db = self.db - db.test.delete_many({}) + db.coll.delete_many({}) - db.test.insert_one({"x": [1, 2, 3], "mike": "awesome"}) + db.coll.insert_one({"x": [1, 2, 3], "mike": "awesome"}) - self.assertEqual([1, 2, 3], (db.test.find_one())["x"]) - self.assertEqual([2, 3], (db.test.find_one(projection={"x": {"$slice": -2}}))["x"]) - self.assertNotIn("x", db.test.find_one(projection={"x": 0})) - self.assertIn("mike", db.test.find_one(projection={"x": 0})) + self.assertEqual([1, 2, 3], (db.coll.find_one())["x"]) + self.assertEqual([2, 3], (db.coll.find_one(projection={"x": {"$slice": -2}}))["x"]) + self.assertNotIn("x", db.coll.find_one(projection={"x": 0})) + self.assertIn("mike", db.coll.find_one(projection={"x": 0})) def test_find_w_regex(self): db = self.db - db.test.delete_many({}) + db.coll.delete_many({}) - 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"}) + db.coll.insert_one({"x": "hello_world"}) + db.coll.insert_one({"x": "hello_mike"}) + db.coll.insert_one({"x": "hello_mikey"}) + db.coll.insert_one({"x": "hello_test"}) - self.assertEqual(len(db.test.find().to_list()), 4) - self.assertEqual(len(db.test.find({"x": re.compile("^hello.*")}).to_list()), 4) - self.assertEqual(len(db.test.find({"x": re.compile("ello")}).to_list()), 4) - self.assertEqual(len(db.test.find({"x": re.compile("^hello$")}).to_list()), 0) - self.assertEqual(len(db.test.find({"x": re.compile("^hello_mi.*$")}).to_list()), 2) + self.assertEqual(len(db.coll.find().to_list()), 4) + self.assertEqual(len(db.coll.find({"x": re.compile("^hello.*")}).to_list()), 4) + self.assertEqual(len(db.coll.find({"x": re.compile("ello")}).to_list()), 4) + self.assertEqual(len(db.coll.find({"x": re.compile("^hello$")}).to_list()), 0) + self.assertEqual(len(db.coll.find({"x": re.compile("^hello_mi.*$")}).to_list()), 2) def test_id_can_be_anything(self): db = self.db - db.test.delete_many({}) + db.coll.delete_many({}) auto_id = {"hello": "world"} - db.test.insert_one(auto_id) + db.coll.insert_one(auto_id) self.assertIsInstance(auto_id["_id"], ObjectId) numeric = {"_id": 240, "hello": "world"} - db.test.insert_one(numeric) + db.coll.insert_one(numeric) self.assertEqual(numeric["_id"], 240) obj = {"_id": numeric, "hello": "world"} - db.test.insert_one(obj) + db.coll.insert_one(obj) self.assertEqual(obj["_id"], numeric) - for x in db.test.find(): + for x in db.coll.find(): self.assertEqual(x["hello"], "world") self.assertIn("_id", x) def test_unique_index(self): db = self.db - db.drop_collection("test") - db.test.create_index("hello") + db.drop_collection("coll") + db.coll.create_index("hello") # No error. - db.test.insert_one({"hello": "world"}) - db.test.insert_one({"hello": "world"}) + db.coll.insert_one({"hello": "world"}) + db.coll.insert_one({"hello": "world"}) - db.drop_collection("test") - db.test.create_index("hello", unique=True) + db.drop_collection("coll") + db.coll.create_index("hello", unique=True) with self.assertRaises(DuplicateKeyError): - db.test.insert_one({"hello": "world"}) - db.test.insert_one({"hello": "world"}) + db.coll.insert_one({"hello": "world"}) + db.coll.insert_one({"hello": "world"}) def test_duplicate_key_error(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - db.test.create_index("x", unique=True) + db.coll.create_index("x", unique=True) - db.test.insert_one({"_id": 1, "x": 1}) + db.coll.insert_one({"_id": 1, "x": 1}) with self.assertRaises(DuplicateKeyError) as context: - db.test.insert_one({"x": 1}) + db.coll.insert_one({"x": 1}) self.assertIsNotNone(context.exception.details) with self.assertRaises(DuplicateKeyError) as context: - db.test.insert_one({"x": 1}) + db.coll.insert_one({"x": 1}) self.assertIsNotNone(context.exception.details) - self.assertEqual(1, db.test.count_documents({})) + self.assertEqual(1, db.coll.count_documents({})) def test_write_error_text_handling(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - db.test.create_index("text", unique=True) + db.coll.create_index("text", unique=True) # Test workaround for SERVER-24007 data = ( @@ -1251,21 +1251,21 @@ def test_write_error_text_handling(self): ) text = utf_8_decode(data, None, True) - db.test.insert_one({"text": text}) + db.coll.insert_one({"text": text}) # Should raise DuplicateKeyError, not InvalidBSON with self.assertRaises(DuplicateKeyError): - db.test.insert_one({"text": text}) + db.coll.insert_one({"text": text}) with self.assertRaises(DuplicateKeyError): - db.test.replace_one({"_id": ObjectId()}, {"text": text}, upsert=True) + db.coll.replace_one({"_id": ObjectId()}, {"text": text}, upsert=True) # Should raise BulkWriteError, not InvalidBSON with self.assertRaises(BulkWriteError): - db.test.insert_many([{"text": text}]) + db.coll.insert_many([{"text": text}]) def test_write_error_unicode(self): - coll = self.db.test + coll = self.db.coll self.addCleanup(coll.drop) coll.create_index("a", unique=True) @@ -1279,7 +1279,7 @@ def test_write_error_unicode(self): def test_wtimeout(self): # Ensure setting wtimeout doesn't disable write concern altogether. # See SERVER-12596. - collection = self.db.test + collection = self.db.coll collection.drop() collection.insert_one({"_id": 1}) @@ -1293,7 +1293,7 @@ def test_wtimeout(self): def test_error_code(self): try: - self.db.test.update_many({}, {"$thismodifierdoesntexist": 1}) + self.db.coll.update_many({}, {"$thismodifierdoesntexist": 1}) except OperationFailure as exc: self.assertIn(exc.code, (9, 10147, 16840, 17009)) # Just check that we set the error document. Fields @@ -1304,59 +1304,59 @@ def test_error_code(self): def test_index_on_subfield(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - 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.coll.insert_one({"hello": {"a": 4, "b": 5}}) + db.coll.insert_one({"hello": {"a": 7, "b": 2}}) + db.coll.insert_one({"hello": {"a": 4, "b": 10}}) - db.drop_collection("test") - db.test.create_index("hello.a", unique=True) + db.drop_collection("coll") + db.coll.create_index("hello.a", unique=True) - db.test.insert_one({"hello": {"a": 4, "b": 5}}) - db.test.insert_one({"hello": {"a": 7, "b": 2}}) + db.coll.insert_one({"hello": {"a": 4, "b": 5}}) + db.coll.insert_one({"hello": {"a": 7, "b": 2}}) with self.assertRaises(DuplicateKeyError): - db.test.insert_one({"hello": {"a": 4, "b": 10}}) + db.coll.insert_one({"hello": {"a": 4, "b": 10}}) def test_replace_one(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") with self.assertRaises(ValueError): - db.test.replace_one({}, {"$set": {"x": 1}}) + db.coll.replace_one({}, {"$set": {"x": 1}}) - id1 = (db.test.insert_one({"x": 1})).inserted_id - result = db.test.replace_one({"x": 1}, {"y": 1}) + id1 = (db.coll.insert_one({"x": 1})).inserted_id + result = db.coll.replace_one({"x": 1}, {"y": 1}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(1, db.test.count_documents({"y": 1})) - self.assertEqual(0, db.test.count_documents({"x": 1})) - self.assertEqual((db.test.find_one(id1))["y"], 1) # type: ignore + self.assertEqual(1, db.coll.count_documents({"y": 1})) + self.assertEqual(0, db.coll.count_documents({"x": 1})) + self.assertEqual((db.coll.find_one(id1))["y"], 1) # type: ignore replacement = RawBSONDocument(encode({"_id": id1, "z": 1})) - result = db.test.replace_one({"y": 1}, replacement, True) + result = db.coll.replace_one({"y": 1}, replacement, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(1, db.test.count_documents({"z": 1})) - self.assertEqual(0, db.test.count_documents({"y": 1})) - self.assertEqual((db.test.find_one(id1))["z"], 1) # type: ignore + self.assertEqual(1, db.coll.count_documents({"z": 1})) + self.assertEqual(0, db.coll.count_documents({"y": 1})) + self.assertEqual((db.coll.find_one(id1))["z"], 1) # type: ignore - result = db.test.replace_one({"x": 2}, {"y": 2}, True) + result = db.coll.replace_one({"x": 2}, {"y": 2}, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(0, result.matched_count) self.assertIn(result.modified_count, (None, 0)) self.assertIsInstance(result.upserted_id, ObjectId) self.assertTrue(result.acknowledged) - self.assertEqual(1, db.test.count_documents({"y": 2})) + self.assertEqual(1, db.coll.count_documents({"y": 2})) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = db.test.replace_one({"x": 0}, {"y": 0}) + result = db.coll.replace_one({"x": 0}, {"y": 0}) self.assertIsInstance(result, UpdateResult) self.assertRaises(InvalidOperation, lambda: result.matched_count) self.assertRaises(InvalidOperation, lambda: result.modified_count) @@ -1365,31 +1365,31 @@ def test_replace_one(self): def test_update_one(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") with self.assertRaises(ValueError): - db.test.update_one({}, {"x": 1}) + db.coll.update_one({}, {"x": 1}) - id1 = (db.test.insert_one({"x": 5})).inserted_id - result = db.test.update_one({}, {"$inc": {"x": 1}}) + id1 = (db.coll.insert_one({"x": 5})).inserted_id + result = db.coll.update_one({}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual((db.test.find_one(id1))["x"], 6) # type: ignore + self.assertEqual((db.coll.find_one(id1))["x"], 6) # type: ignore - id2 = (db.test.insert_one({"x": 1})).inserted_id - result = db.test.update_one({"x": 6}, {"$inc": {"x": 1}}) + id2 = (db.coll.insert_one({"x": 1})).inserted_id + result = db.coll.update_one({"x": 6}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual((db.test.find_one(id1))["x"], 7) # type: ignore - self.assertEqual((db.test.find_one(id2))["x"], 1) # type: ignore + self.assertEqual((db.coll.find_one(id1))["x"], 7) # type: ignore + self.assertEqual((db.coll.find_one(id2))["x"], 1) # type: ignore - result = db.test.update_one({"x": 2}, {"$set": {"y": 1}}, True) + result = db.coll.update_one({"x": 2}, {"$set": {"y": 1}}, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(0, result.matched_count) self.assertIn(result.modified_count, (None, 0)) @@ -1397,7 +1397,7 @@ def test_update_one(self): self.assertTrue(result.acknowledged) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = db.test.update_one({"x": 0}, {"$inc": {"x": 1}}) + result = db.coll.update_one({"x": 0}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertRaises(InvalidOperation, lambda: result.matched_count) self.assertRaises(InvalidOperation, lambda: result.modified_count) @@ -1406,45 +1406,45 @@ def test_update_one(self): def test_update_result(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - result = db.test.update_one({"x": 0}, {"$inc": {"x": 1}}, upsert=True) + result = db.coll.update_one({"x": 0}, {"$inc": {"x": 1}}, upsert=True) self.assertEqual(result.did_upsert, True) - result = db.test.update_one({"_id": None, "x": 0}, {"$inc": {"x": 1}}, upsert=True) + result = db.coll.update_one({"_id": None, "x": 0}, {"$inc": {"x": 1}}, upsert=True) self.assertEqual(result.did_upsert, True) - result = db.test.update_one({"_id": None}, {"$inc": {"x": 1}}) + result = db.coll.update_one({"_id": None}, {"$inc": {"x": 1}}) self.assertEqual(result.did_upsert, False) def test_update_many(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") with self.assertRaises(ValueError): - db.test.update_many({}, {"x": 1}) + db.coll.update_many({}, {"x": 1}) - db.test.insert_one({"x": 4, "y": 3}) - db.test.insert_one({"x": 5, "y": 5}) - db.test.insert_one({"x": 4, "y": 4}) + db.coll.insert_one({"x": 4, "y": 3}) + db.coll.insert_one({"x": 5, "y": 5}) + db.coll.insert_one({"x": 4, "y": 4}) - result = db.test.update_many({"x": 4}, {"$set": {"y": 5}}) + result = db.coll.update_many({"x": 4}, {"$set": {"y": 5}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(2, result.matched_count) self.assertIn(result.modified_count, (None, 2)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(3, db.test.count_documents({"y": 5})) + self.assertEqual(3, db.coll.count_documents({"y": 5})) - result = db.test.update_many({"x": 5}, {"$set": {"y": 6}}) + result = db.coll.update_many({"x": 5}, {"$set": {"y": 6}}) self.assertIsInstance(result, UpdateResult) self.assertEqual(1, result.matched_count) self.assertIn(result.modified_count, (None, 1)) self.assertIsNone(result.upserted_id) self.assertTrue(result.acknowledged) - self.assertEqual(1, db.test.count_documents({"y": 6})) + self.assertEqual(1, db.coll.count_documents({"y": 6})) - result = db.test.update_many({"x": 2}, {"$set": {"y": 1}}, True) + result = db.coll.update_many({"x": 2}, {"$set": {"y": 1}}, True) self.assertIsInstance(result, UpdateResult) self.assertEqual(0, result.matched_count) self.assertIn(result.modified_count, (None, 0)) @@ -1452,7 +1452,7 @@ def test_update_many(self): self.assertTrue(result.acknowledged) db = db.client.get_database(db.name, write_concern=WriteConcern(w=0)) - result = db.test.update_many({"x": 0}, {"$inc": {"x": 1}}) + result = db.coll.update_many({"x": 0}, {"$inc": {"x": 1}}) self.assertIsInstance(result, UpdateResult) self.assertRaises(InvalidOperation, lambda: result.matched_count) self.assertRaises(InvalidOperation, lambda: result.modified_count) @@ -1460,19 +1460,19 @@ def test_update_many(self): self.assertFalse(result.acknowledged) def test_update_check_keys(self): - self.db.drop_collection("test") - self.assertTrue(self.db.test.insert_one({"hello": "world"})) + self.db.drop_collection("coll") + self.assertTrue(self.db.coll.insert_one({"hello": "world"})) # Modify shouldn't check keys... self.assertTrue( - self.db.test.update_one({"hello": "world"}, {"$set": {"foo.bar": "baz"}}, upsert=True) + self.db.coll.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")]) with self.assertRaises(OperationFailure): - self.db.test.update_one({"hello": "world"}, doc, upsert=True) + self.db.coll.update_one({"hello": "world"}, doc, upsert=True) # This is going to cause keys to be checked and raise InvalidDocument. # That's OK assuming the server's behavior in the previous assert @@ -1480,59 +1480,59 @@ def test_update_check_keys(self): # '$' in update won't be good enough anymore. doc = SON([("hello", "world"), ("$set", {"foo.bar": "bim"})]) with self.assertRaises(OperationFailure): - self.db.test.replace_one({"hello": "world"}, doc, upsert=True) + self.db.coll.replace_one({"hello": "world"}, doc, upsert=True) # Replace with empty document - self.assertNotEqual(0, (self.db.test.replace_one({"hello": "world"}, {})).matched_count) + self.assertNotEqual(0, (self.db.coll.replace_one({"hello": "world"}, {})).matched_count) def test_acknowledged_delete(self): db = self.db - db.drop_collection("test") - db.test.insert_many([{"x": 1}, {"x": 1}]) - self.assertEqual(2, (db.test.delete_many({})).deleted_count) - self.assertEqual(0, (db.test.delete_many({})).deleted_count) + db.drop_collection("coll") + db.coll.insert_many([{"x": 1}, {"x": 1}]) + self.assertEqual(2, (db.coll.delete_many({})).deleted_count) + self.assertEqual(0, (db.coll.delete_many({})).deleted_count) @client_context.require_version_max(4, 9) def test_manual_last_error(self): - coll = self.db.get_collection("test", write_concern=WriteConcern(w=0)) + coll = self.db.get_collection("coll", write_concern=WriteConcern(w=0)) coll.insert_one({"x": 1}) self.db.command("getlasterror", w=1, wtimeout=1) def test_count_documents(self): db = self.db - db.drop_collection("test") - self.addCleanup(db.drop_collection, "test") + db.drop_collection("coll") + self.addCleanup(db.drop_collection, "coll") - self.assertEqual(db.test.count_documents({}), 0) + self.assertEqual(db.coll.count_documents({}), 0) db.wrong.insert_many([{}, {}]) - self.assertEqual(db.test.count_documents({}), 0) - db.test.insert_many([{}, {}]) - self.assertEqual(db.test.count_documents({}), 2) - db.test.insert_many([{"foo": "bar"}, {"foo": "baz"}]) - self.assertEqual(db.test.count_documents({"foo": "bar"}), 1) - self.assertEqual(db.test.count_documents({"foo": re.compile(r"ba.*")}), 2) + self.assertEqual(db.coll.count_documents({}), 0) + db.coll.insert_many([{}, {}]) + self.assertEqual(db.coll.count_documents({}), 2) + db.coll.insert_many([{"foo": "bar"}, {"foo": "baz"}]) + self.assertEqual(db.coll.count_documents({"foo": "bar"}), 1) + self.assertEqual(db.coll.count_documents({"foo": re.compile(r"ba.*")}), 2) def test_estimated_document_count(self): db = self.db - db.drop_collection("test") - self.addCleanup(db.drop_collection, "test") + db.drop_collection("coll") + self.addCleanup(db.drop_collection, "coll") - self.assertEqual(db.test.estimated_document_count(), 0) + self.assertEqual(db.coll.estimated_document_count(), 0) db.wrong.insert_many([{}, {}]) - self.assertEqual(db.test.estimated_document_count(), 0) - db.test.insert_many([{}, {}]) - self.assertEqual(db.test.estimated_document_count(), 2) + self.assertEqual(db.coll.estimated_document_count(), 0) + db.coll.insert_many([{}, {}]) + self.assertEqual(db.coll.estimated_document_count(), 2) def test_aggregate(self): db = self.db - db.drop_collection("test") - db.test.insert_one({"foo": [1, 2]}) + db.drop_collection("coll") + db.coll.insert_one({"foo": [1, 2]}) with self.assertRaises(TypeError): - db.test.aggregate("wow") # type: ignore[arg-type] + db.coll.aggregate("wow") # type: ignore[arg-type] pipeline = {"$project": {"_id": False, "foo": True}} - result = db.test.aggregate([pipeline]) + result = db.coll.aggregate([pipeline]) self.assertIsInstance(result, CommandCursor) self.assertEqual([{"foo": [1, 2]}], result.to_list()) @@ -1566,14 +1566,14 @@ def test_aggregate_reserved_options(self): def test_aggregate_raw_bson(self): db = self.db - db.drop_collection("test") - db.test.insert_one({"foo": [1, 2]}) + db.drop_collection("coll") + db.coll.insert_one({"foo": [1, 2]}) with self.assertRaises(TypeError): - db.test.aggregate("wow") # type: ignore[arg-type] + db.coll.aggregate("wow") # type: ignore[arg-type] pipeline = {"$project": {"_id": False, "foo": True}} - coll = db.get_collection("test", codec_options=CodecOptions(document_class=RawBSONDocument)) + coll = db.get_collection("coll", codec_options=CodecOptions(document_class=RawBSONDocument)) result = coll.aggregate([pipeline]) self.assertIsInstance(result, CommandCursor) first_result = next(result) @@ -1583,7 +1583,7 @@ def test_aggregate_raw_bson(self): def test_aggregation_cursor_validation(self): db = self.db projection = {"$project": {"_id": "$_id"}} - cursor = db.test.aggregate([projection], cursor={}) + cursor = db.coll.aggregate([projection], cursor={}) self.assertIsInstance(cursor, CommandCursor) def test_aggregation_cursor(self): @@ -1597,16 +1597,16 @@ def test_aggregation_cursor(self): ) for collection_size in (10, 1000): - db.drop_collection("test") - db.test.insert_many([{"_id": i} for i in range(collection_size)]) + db.drop_collection("coll") + db.coll.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([{"$project": {"_id": "$_id"}}], batchSize=5) + cursor = db.coll.aggregate([{"$project": {"_id": "$_id"}}], batchSize=5) self.assertEqual(expected_sum, sum(doc["_id"] for doc in cursor.to_list())) # Test that batchSize is handled properly. - cursor = db.test.aggregate([], batchSize=5) + cursor = db.coll.aggregate([], batchSize=5) self.assertEqual(5, len(cursor._data)) # Force a getMore cursor._data.clear() @@ -1618,10 +1618,10 @@ def test_aggregation_cursor(self): pass def test_aggregation_cursor_alive(self): - self.db.test.delete_many({}) - self.db.test.insert_many([{} for _ in range(3)]) - self.addCleanup(self.db.test.delete_many, {}) - cursor = self.db.test.aggregate(pipeline=[], cursor={"batchSize": 2}) + self.db.coll.delete_many({}) + self.db.coll.insert_many([{} for _ in range(3)]) + self.addCleanup(self.db.coll.delete_many, {}) + cursor = self.db.coll.aggregate(pipeline=[], cursor={"batchSize": 2}) n = 0 while True: cursor.next() @@ -1634,7 +1634,7 @@ def test_aggregation_cursor_alive(self): def test_invalid_session_parameter(self): def try_invalid_session(): - with self.db.test.aggregate([], {}): # type:ignore + with self.db.coll.aggregate([], {}): # type:ignore pass with self.assertRaisesRegex(ValueError, "must be a ClientSession"): @@ -1659,45 +1659,45 @@ def test_large_limit(self): def test_find_kwargs(self): db = self.db - db.drop_collection("test") - db.test.insert_many({"x": i} for i in range(10)) + db.drop_collection("coll") + db.coll.insert_many({"x": i} for i in range(10)) - self.assertEqual(10, db.test.count_documents({})) + self.assertEqual(10, db.coll.count_documents({})) total = 0 - for x in db.test.find({}, skip=4, limit=2): + for x in db.coll.find({}, skip=4, limit=2): total += x["x"] self.assertEqual(9, total) def test_rename(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") db.drop_collection("foo") with self.assertRaises(TypeError): - db.test.rename(5) # type: ignore[arg-type] + db.coll.rename(5) # type: ignore[arg-type] with self.assertRaises(InvalidName): - db.test.rename("") + db.coll.rename("") with self.assertRaises(InvalidName): - db.test.rename("te$t") + db.coll.rename("te$t") with self.assertRaises(InvalidName): - db.test.rename(".test") + db.coll.rename(".test") with self.assertRaises(InvalidName): - db.test.rename("test.") + db.coll.rename("test.") with self.assertRaises(InvalidName): - db.test.rename("tes..t") + db.coll.rename("tes..t") - self.assertEqual(0, db.test.count_documents({})) + self.assertEqual(0, db.coll.count_documents({})) self.assertEqual(0, db.foo.count_documents({})) - db.test.insert_many({"x": i} for i in range(10)) + db.coll.insert_many({"x": i} for i in range(10)) - self.assertEqual(10, db.test.count_documents({})) + self.assertEqual(10, db.coll.count_documents({})) - db.test.rename("foo") + db.coll.rename("foo") - self.assertEqual(0, db.test.count_documents({})) + self.assertEqual(0, db.coll.count_documents({})) self.assertEqual(10, db.foo.count_documents({})) x = 0 @@ -1705,10 +1705,10 @@ def test_rename(self): self.assertEqual(x, doc["x"]) x += 1 - db.test.insert_one({}) + db.coll.insert_one({}) with self.assertRaises(OperationFailure): - db.foo.rename("test") - db.foo.rename("test", dropTarget=True) + db.foo.rename("coll") + db.foo.rename("coll", dropTarget=True) with self.write_concern_collection() as coll: coll.rename("foo") @@ -1716,81 +1716,81 @@ def test_rename(self): @no_type_check def test_find_one(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - _id = (db.test.insert_one({"hello": "world", "foo": "bar"})).inserted_id + _id = (db.coll.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()) - self.assertEqual(db.test.find_one(None), db.test.find_one()) - self.assertEqual(db.test.find_one({}), db.test.find_one()) - self.assertEqual(db.test.find_one({"hello": "world"}), db.test.find_one()) + self.assertEqual("world", (db.coll.find_one())["hello"]) + self.assertEqual(db.coll.find_one(_id), db.coll.find_one()) + self.assertEqual(db.coll.find_one(None), db.coll.find_one()) + self.assertEqual(db.coll.find_one({}), db.coll.find_one()) + self.assertEqual(db.coll.find_one({"hello": "world"}), db.coll.find_one()) - self.assertIn("hello", db.test.find_one(projection=["hello"])) - self.assertNotIn("hello", db.test.find_one(projection=["foo"])) + self.assertIn("hello", db.coll.find_one(projection=["hello"])) + self.assertNotIn("hello", db.coll.find_one(projection=["foo"])) - self.assertIn("hello", db.test.find_one(projection=("hello",))) - self.assertNotIn("hello", db.test.find_one(projection=("foo",))) + self.assertIn("hello", db.coll.find_one(projection=("hello",))) + self.assertNotIn("hello", db.coll.find_one(projection=("foo",))) - self.assertIn("hello", db.test.find_one(projection={"hello"})) - self.assertNotIn("hello", db.test.find_one(projection={"foo"})) + self.assertIn("hello", db.coll.find_one(projection={"hello"})) + self.assertNotIn("hello", db.coll.find_one(projection={"foo"})) - self.assertIn("hello", db.test.find_one(projection=frozenset(["hello"]))) - self.assertNotIn("hello", db.test.find_one(projection=frozenset(["foo"]))) + self.assertIn("hello", db.coll.find_one(projection=frozenset(["hello"]))) + self.assertNotIn("hello", db.coll.find_one(projection=frozenset(["foo"]))) - self.assertEqual(["_id"], list(db.test.find_one(projection={"_id": True}))) - self.assertIn("hello", list(db.test.find_one(projection={}))) - self.assertIn("hello", list(db.test.find_one(projection=[]))) + self.assertEqual(["_id"], list(db.coll.find_one(projection={"_id": True}))) + self.assertIn("hello", list(db.coll.find_one(projection={}))) + self.assertIn("hello", list(db.coll.find_one(projection=[]))) - self.assertEqual(None, db.test.find_one({"hello": "foo"})) - self.assertEqual(None, db.test.find_one(ObjectId())) + self.assertEqual(None, db.coll.find_one({"hello": "foo"})) + self.assertEqual(None, db.coll.find_one(ObjectId())) def test_find_one_non_objectid(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - db.test.insert_one({"_id": 5}) + db.coll.insert_one({"_id": 5}) - self.assertTrue(db.test.find_one(5)) - self.assertFalse(db.test.find_one(6)) + self.assertTrue(db.coll.find_one(5)) + self.assertFalse(db.coll.find_one(6)) def test_find_one_with_find_args(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - db.test.insert_many([{"x": i} for i in range(1, 4)]) + db.coll.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"]) + self.assertEqual(1, (db.coll.find_one())["x"]) + self.assertEqual(2, (db.coll.find_one(skip=1, limit=2))["x"]) def test_find_with_sort(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") - db.test.insert_many([{"x": 2}, {"x": 1}, {"x": 3}]) + db.coll.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"]) - self.assertEqual(3, (db.test.find_one(sort=[("x", -1)]))["x"]) + self.assertEqual(2, (db.coll.find_one())["x"]) + self.assertEqual(1, (db.coll.find_one(sort=[("x", 1)]))["x"]) + self.assertEqual(3, (db.coll.find_one(sort=[("x", -1)]))["x"]) def to_list(things): return [thing["x"] for thing in things] - self.assertEqual([2, 1, 3], to_list(db.test.find())) - self.assertEqual([1, 2, 3], to_list(db.test.find(sort=[("x", 1)]))) - self.assertEqual([3, 2, 1], to_list(db.test.find(sort=[("x", -1)]))) + self.assertEqual([2, 1, 3], to_list(db.coll.find())) + self.assertEqual([1, 2, 3], to_list(db.coll.find(sort=[("x", 1)]))) + self.assertEqual([3, 2, 1], to_list(db.coll.find(sort=[("x", -1)]))) with self.assertRaises(TypeError): - db.test.find(sort=5) + db.coll.find(sort=5) with self.assertRaises(TypeError): - db.test.find(sort="hello") + db.coll.find(sort="hello") with self.assertRaises(TypeError): - db.test.find(sort=["hello", 1]) + db.coll.find(sort=["hello", 1]) # TODO doesn't actually test functionality, just that it doesn't blow up def test_cursor_timeout(self): - self.db.test.find(no_cursor_timeout=True).to_list() - self.db.test.find(no_cursor_timeout=False).to_list() + self.db.coll.find(no_cursor_timeout=True).to_list() + self.db.coll.find(no_cursor_timeout=False).to_list() def test_exhaust_limit_raises_without_iterating(self): # The limit conflict is settled at find(); the mongos wire version is not. @@ -1802,33 +1802,33 @@ def test_exhaust(self): # mongos only serves exhaust cursors from 7.1 onwards (SERVER-57297). if not client_context.supports_exhaust_cursors(): with self.assertRaises(InvalidOperation): - next(self.db.test.find(cursor_type=CursorType.EXHAUST)) + next(self.db.coll.find(cursor_type=CursorType.EXHAUST)) return # Limit is incompatible with exhaust. with self.assertRaises(InvalidOperation): - next(self.db.test.find(cursor_type=CursorType.EXHAUST, limit=5)) - cur = self.db.test.find(cursor_type=CursorType.EXHAUST) + next(self.db.coll.find(cursor_type=CursorType.EXHAUST, limit=5)) + cur = self.db.coll.find(cursor_type=CursorType.EXHAUST) with self.assertRaises(InvalidOperation): cur.limit(5) cur.next() - cur = self.db.test.find(limit=5) + cur = self.db.coll.find(limit=5) with self.assertRaises(InvalidOperation): cur.add_option(64) - cur = self.db.test.find() + cur = self.db.coll.find() cur.add_option(64) with self.assertRaises(InvalidOperation): cur.limit(5) - self.db.drop_collection("test") + self.db.drop_collection("coll") # Insert enough documents to require more than one batch - self.db.test.insert_many([{"i": i} for i in range(150)]) + self.db.coll.insert_many([{"i": i} for i in range(150)]) client = self.rs_or_single_client(maxPoolSize=1) pool = get_pool(client) # Make sure the socket is returned after exhaustion. - cur = client[self.db.name].test.find(cursor_type=CursorType.EXHAUST) + cur = client[self.db.name].coll.find(cursor_type=CursorType.EXHAUST) next(cur) self.assertEqual(0, len(pool.conns)) for _ in cur: @@ -1836,14 +1836,14 @@ def test_exhaust(self): self.assertEqual(1, len(pool.conns)) # Same as previous but don't call next() - for _ in client[self.db.name].test.find(cursor_type=CursorType.EXHAUST): + for _ in client[self.db.name].coll.find(cursor_type=CursorType.EXHAUST): pass self.assertEqual(1, len(pool.conns)) # If the Cursor instance is discarded before being completely iterated # and the socket has pending data (more_to_come=True) we have to close # and discard the socket. - cur = client[self.db.name].test.find(cursor_type=CursorType.EXHAUST, batch_size=2) + cur = client[self.db.name].coll.find(cursor_type=CursorType.EXHAUST, batch_size=2) # OP_MSG only sets more_to_come=True after the first getMore. for _ in range(3): next(cur) @@ -1858,9 +1858,9 @@ def test_exhaust(self): self.assertEqual(0, len(pool.conns)) def test_distinct(self): - self.db.drop_collection("test") + self.db.drop_collection("coll") - test = self.db.test + test = self.db.coll test.insert_many([{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}]) distinct = test.distinct("a") @@ -1876,7 +1876,7 @@ def test_distinct(self): distinct.sort() self.assertEqual([2, 3], distinct) - self.db.drop_collection("test") + self.db.drop_collection("coll") test.insert_one({"a": {"b": "a"}, "c": 12}) test.insert_one({"a": {"b": "b"}, "c": 12}) @@ -1889,19 +1889,19 @@ def test_distinct(self): self.assertEqual(["a", "b", "c"], distinct) def test_query_on_query_field(self): - self.db.drop_collection("test") - self.db.test.insert_one({"query": "foo"}) - self.db.test.insert_one({"bar": "foo"}) + self.db.drop_collection("coll") + self.db.coll.insert_one({"query": "foo"}) + self.db.coll.insert_one({"bar": "foo"}) - self.assertEqual(1, self.db.test.count_documents({"query": {"$ne": None}})) - self.assertEqual(1, len(self.db.test.find({"query": {"$ne": None}}).to_list())) + self.assertEqual(1, self.db.coll.count_documents({"query": {"$ne": None}})) + self.assertEqual(1, len(self.db.coll.find({"query": {"$ne": None}}).to_list())) def test_min_query(self): - self.db.drop_collection("test") - self.db.test.insert_many([{"x": 1}, {"x": 2}]) - self.db.test.create_index("x") + self.db.drop_collection("coll") + self.db.coll.insert_many([{"x": 1}, {"x": 2}]) + self.db.coll.create_index("x") - cursor = self.db.test.find({"$min": {"x": 2}, "$query": {}}, hint="x_1") + cursor = self.db.coll.find({"$min": {"x": 2}, "$query": {}}, hint="x_1") docs = cursor.to_list() self.assertEqual(1, len(docs)) @@ -1909,11 +1909,11 @@ def test_min_query(self): def test_numerous_inserts(self): # Ensure we don't exceed server's maxWriteBatchSize size limit. - self.db.test.drop() + self.db.coll.drop() n_docs = client_context.max_write_batch_size + 100 - self.db.test.insert_many([{} for _ in range(n_docs)]) - self.assertEqual(n_docs, self.db.test.count_documents({})) - self.db.test.drop() + self.db.coll.insert_many([{} for _ in range(n_docs)]) + self.assertEqual(n_docs, self.db.coll.count_documents({})) + self.db.coll.drop() def test_insert_many_large_batch(self): # Tests legacy insert. @@ -2002,13 +2002,13 @@ def test_messages_with_unicode_collection_names(self): db["Employés"].find().to_list() def test_drop_indexes_non_existent(self): - self.db.drop_collection("test") - self.db.test.drop_indexes() + self.db.drop_collection("coll") + self.db.coll.drop_indexes() # This is really a bson test but easier to just reproduce it here... # (Shame on me) def test_bad_encode(self): - c = self.db.test + c = self.db.coll c.drop() with self.assertRaises(InvalidDocument): c.insert_one({"x": c}) @@ -2023,7 +2023,7 @@ def __getattr__(self, name): def test_array_filters_validation(self): # array_filters must be a list. - c = self.db.test + c = self.db.coll with self.assertRaises(TypeError): c.update_one({}, {"$set": {"a": 1}}, array_filters={}) # type: ignore[arg-type] with self.assertRaises(TypeError): @@ -2033,7 +2033,7 @@ def test_array_filters_validation(self): c.find_one_and_update({}, update, array_filters={}) # type: ignore[arg-type] def test_array_filters_unacknowledged(self): - c_w0 = self.db.test.with_options(write_concern=WriteConcern(w=0)) + c_w0 = self.db.coll.with_options(write_concern=WriteConcern(w=0)) with self.assertRaises(ConfigurationError): c_w0.update_one({}, {"$set": {"y.$[i].b": 5}}, array_filters=[{"i.b": 1}]) with self.assertRaises(ConfigurationError): @@ -2042,7 +2042,7 @@ def test_array_filters_unacknowledged(self): c_w0.find_one_and_update({}, {"$set": {"y.$[i].b": 5}}, array_filters=[{"i.b": 1}]) def test_find_one_and(self): - c = self.db.test + c = self.db.coll c.drop() c.insert_one({"_id": 1, "i": 1}) @@ -2098,9 +2098,9 @@ def test_find_one_and_write_concern(self): listener = OvertCommandListener() db = (self.single_client(event_listeners=[listener]))[self.db.name] # non-default WriteConcern. - c_w0 = db.get_collection("test", write_concern=WriteConcern(w=0)) + c_w0 = db.get_collection("coll", write_concern=WriteConcern(w=0)) # default WriteConcern. - c_default = db.get_collection("test", write_concern=WriteConcern()) + c_default = db.get_collection("coll", write_concern=WriteConcern()) # Authenticate the client and throw out auth commands from the listener. db.command("ping") listener.reset() @@ -2146,7 +2146,7 @@ def test_find_one_and_write_concern(self): listener.reset() def test_find_with_nested(self): - c = self.db.test + c = self.db.coll c.drop() c.insert_many([{"i": i} for i in range(5)]) # [0, 1, 2, 3, 4] self.assertEqual( @@ -2204,7 +2204,7 @@ def test_find_with_nested(self): ) def test_find_regex(self): - c = self.db.test + c = self.db.coll c.drop() c.insert_one({"r": re.compile(".*")}) @@ -2233,7 +2233,7 @@ def test_bool(self): @client_context.require_version_min(5, 0, 0) def test_helpers_with_let(self): - c = self.db.test + c = self.db.coll def afind(*args, **kwargs): return c.find(*args, **kwargs) diff --git a/test/test_comment.py b/test/test_comment.py index 9200abd511..07a10b02ca 100644 --- a/test/test_comment.py +++ b/test/test_comment.py @@ -118,7 +118,7 @@ def test_client_helpers(self): def test_collection_helpers(self): listener = OvertCommandListener() db = (self.rs_or_single_client(event_listeners=[listener]))[self.db.name] - coll = db.get_collection("test") + coll = db.get_collection("coll") helpers = [ (coll.list_indexes, []), diff --git a/test/test_common.py b/test/test_common.py index b0c706b9f2..cc9a565d6d 100644 --- a/test/test_common.py +++ b/test/test_common.py @@ -124,11 +124,11 @@ def test_write_concern(self): db = c.pymongo_test self.assertEqual(wc, db.write_concern) - coll = db.test + coll = db.coll self.assertEqual(wc, coll.write_concern) cwc = WriteConcern(j=True) - coll = db.get_collection("test", write_concern=cwc) + coll = db.get_collection("coll", write_concern=cwc) self.assertEqual(cwc, coll.write_concern) self.assertEqual(wc, db.write_concern) @@ -172,11 +172,12 @@ def test_mongo_client(self): self.assertFalse(direct != direct2) def test_validate_boolean(self): - self.db.test.update_one({}, {"$set": {"total": 1}}, upsert=True) + self.addCleanup(self.db.coll.drop) + self.db.coll.update_one({}, {"$set": {"total": 1}}, upsert=True) with self.assertRaisesRegex( TypeError, "upsert must be True or False, was: upsert={'upsert': True}" ): - self.db.test.update_one({}, {"$set": {"total": 1}}, {"upsert": True}) # type: ignore + self.db.coll.update_one({}, {"$set": {"total": 1}}, {"upsert": True}) # type: ignore if __name__ == "__main__": diff --git a/test/test_csot.py b/test/test_csot.py index 2b1997c945..77d080e2a1 100644 --- a/test/test_csot.py +++ b/test/test_csot.py @@ -78,7 +78,8 @@ def test_timeout_nested(self): @client_context.require_change_streams @flaky(reason="PYTHON-3522") def test_change_stream_can_resume_after_timeouts(self): - coll = self.db.test + self.addCleanup(self.db.coll.drop) + coll = self.db.coll coll.insert_one({}) with coll.watch() as stream: with pymongo.timeout(0.1): diff --git a/test/test_cursor.py b/test/test_cursor.py index 806dba45c9..5ce277e8a9 100644 --- a/test/test_cursor.py +++ b/test/test_cursor.py @@ -60,7 +60,7 @@ class TestCursor(IntegrationTest): def test_deepcopy_cursor_littered_with_regexes(self): - cursor = self.db.test.find( + cursor = self.db.coll.find( { "x": re.compile("^hmmm.*"), "y": [re.compile("^hmm.*")], @@ -73,18 +73,18 @@ def test_deepcopy_cursor_littered_with_regexes(self): self.assertEqual(cursor._spec, cursor2._spec) def test_add_remove_option(self): - cursor = self.db.test.find() + cursor = self.db.coll.find() self.assertEqual(0, cursor._query_flags) cursor.add_option(2) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE) self.assertEqual(2, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.add_option(32) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT) self.assertEqual(34, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.add_option(128) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT).add_option(128) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT).add_option(128) self.assertEqual(162, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) @@ -93,11 +93,11 @@ def test_add_remove_option(self): self.assertEqual(162, cursor._query_flags) cursor.remove_option(128) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT) self.assertEqual(34, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(32) - cursor2 = self.db.test.find(cursor_type=CursorType.TAILABLE) + cursor2 = self.db.coll.find(cursor_type=CursorType.TAILABLE) self.assertEqual(2, cursor2._query_flags) self.assertEqual(cursor._query_flags, cursor2._query_flags) @@ -106,25 +106,25 @@ def test_add_remove_option(self): self.assertEqual(2, cursor._query_flags) # Timeout - cursor = self.db.test.find(no_cursor_timeout=True) + cursor = self.db.coll.find(no_cursor_timeout=True) self.assertEqual(16, cursor._query_flags) - cursor2 = self.db.test.find().add_option(16) + cursor2 = self.db.coll.find().add_option(16) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(16) self.assertEqual(0, cursor._query_flags) # Tailable / Await data - cursor = self.db.test.find(cursor_type=CursorType.TAILABLE_AWAIT) + cursor = self.db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT) self.assertEqual(34, cursor._query_flags) - cursor2 = self.db.test.find().add_option(34) + cursor2 = self.db.coll.find().add_option(34) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(32) self.assertEqual(2, cursor._query_flags) # Partial - cursor = self.db.test.find(allow_partial_results=True) + cursor = self.db.coll.find(allow_partial_results=True) self.assertEqual(128, cursor._query_flags) - cursor2 = self.db.test.find().add_option(128) + cursor2 = self.db.coll.find().add_option(128) self.assertEqual(cursor._query_flags, cursor2._query_flags) cursor.remove_option(128) self.assertEqual(0, cursor._query_flags) @@ -133,11 +133,11 @@ def test_add_remove_option_exhaust(self): # mongos only serves exhaust cursors from 7.1 onwards (SERVER-57297). if not client_context.supports_exhaust_cursors(): with self.assertRaises(InvalidOperation): - next(self.db.test.find(cursor_type=CursorType.EXHAUST)) + next(self.db.coll.find(cursor_type=CursorType.EXHAUST)) else: - cursor = self.db.test.find(cursor_type=CursorType.EXHAUST) + cursor = self.db.coll.find(cursor_type=CursorType.EXHAUST) self.assertEqual(64, cursor._query_flags) - cursor2 = self.db.test.find().add_option(64) + cursor2 = self.db.coll.find().add_option(64) self.assertEqual(cursor._query_flags, cursor2._query_flags) self.assertTrue(cursor._exhaust) cursor.remove_option(64) @@ -146,8 +146,8 @@ def test_add_remove_option_exhaust(self): def test_allow_disk_use(self): db = self.db - db.pymongo_test.drop() - coll = db.pymongo_test + db.coll.drop() + coll = db.coll with self.assertRaises(TypeError): coll.find().allow_disk_use("baz") # type: ignore[arg-type] @@ -159,8 +159,8 @@ def test_allow_disk_use(self): def test_max_time_ms(self): db = self.db - db.pymongo_test.drop() - coll = db.pymongo_test + db.coll.drop() + coll = db.coll with self.assertRaises(TypeError): coll.find().max_time_ms("foo") # type: ignore[arg-type] coll.insert_one({"amalia": 1}) @@ -212,17 +212,17 @@ def test_maxtime_ms_message(self): self.assertIn("(configured timeouts: connectTimeoutMS: 20000.0ms", str(error.exception)) client = self.rs_client(document_class=RawBSONDocument) - client.db.t.insert_one({"x": 1}) + client.db.coll.insert_one({"x": 1}) with self.assertRaises(OperationFailure) as error: - client.db.t.find_one({"$where": delay(2)}, max_time_ms=1) + client.db.coll.find_one({"$where": delay(2)}, max_time_ms=1) if isinstance(error.exception, ExecutionTimeout): self.assertIn("(configured timeouts: connectTimeoutMS: 20000.0ms", str(error.exception)) def test_max_await_time_ms(self): db = self.db - db.pymongo_test.drop() - coll = db.create_collection("pymongo_test", capped=True, size=4096) + db.coll.drop() + coll = db.create_collection("coll", capped=True, size=4096) with self.assertRaises(TypeError): coll.find().max_await_time_ms("foo") # type: ignore[arg-type] @@ -254,7 +254,7 @@ def test_max_await_time_ms(self): self.assertEqual(90, cursor._max_await_time_ms) listener = AllowListEventListener("find", "getMore") - coll = (self.rs_or_single_client(event_listeners=[listener]))[self.db.name].pymongo_test + coll = (self.rs_or_single_client(event_listeners=[listener])).pymongo_test.coll # Tailable_defaults. coll.find(cursor_type=CursorType.TAILABLE_AWAIT).to_list() @@ -340,7 +340,7 @@ def test_max_await_time_ms(self): @client_context.require_no_mongos def test_max_time_ms_getmore(self): # Test that Cursor handles server timeout error in response to getmore. - coll = self.db.pymongo_test + coll = self.db.coll coll.insert_many([{} for _ in range(200)]) cursor = coll.find().max_time_ms(100) @@ -359,7 +359,7 @@ def test_max_time_ms_getmore(self): self.client.admin.command("configureFailPoint", "maxTimeAlwaysTimeOut", mode="off") def test_explain(self): - a = self.db.test.find() + a = self.db.coll.find() a.explain() for _ in a: break @@ -370,7 +370,7 @@ def test_explain_with_read_concern(self): # Do not add readConcern level to explain. listener = AllowListEventListener("explain") client = self.rs_or_single_client(event_listeners=[listener]) - coll = client.pymongo_test.test.with_options(read_concern=ReadConcern(level="local")) + coll = client.pymongo_test.coll.with_options(read_concern=ReadConcern(level="local")) self.assertTrue(coll.find().explain()) started = listener.started_events self.assertEqual(len(started), 1) @@ -402,104 +402,104 @@ def test_explain_csot(self): def test_hint(self): db = self.db with self.assertRaises(TypeError): - db.test.find().hint(5.5) # type: ignore[arg-type] - db.test.drop() + db.coll.find().hint(5.5) # type: ignore[arg-type] + db.coll.drop() - db.test.insert_many([{"num": i, "foo": i} for i in range(100)]) + db.coll.insert_many([{"num": i, "foo": i} for i in range(100)]) with self.assertRaises(OperationFailure): - db.test.find({"num": 17, "foo": 17}).hint([("num", ASCENDING)]).explain() + db.coll.find({"num": 17, "foo": 17}).hint([("num", ASCENDING)]).explain() with self.assertRaises(OperationFailure): - db.test.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() + db.coll.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() spec: list[Any] = [("num", DESCENDING)] - _ = db.test.create_index(spec) + _ = db.coll.create_index(spec) - first = next(db.test.find()) + first = next(db.coll.find()) self.assertEqual(0, first.get("num")) - first = next(db.test.find().hint(spec)) + first = next(db.coll.find().hint(spec)) self.assertEqual(99, first.get("num")) with self.assertRaises(OperationFailure): - db.test.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() + db.coll.find({"num": 17, "foo": 17}).hint([("foo", ASCENDING)]).explain() - a = db.test.find({"num": 17}) + a = db.coll.find({"num": 17}) a.hint(spec) for _ in a: break self.assertRaises(InvalidOperation, a.hint, spec) - db.test.drop() - db.test.insert_many([{"num": i, "foo": i} for i in range(100)]) + db.coll.drop() + db.coll.insert_many([{"num": i, "foo": i} for i in range(100)]) spec: _IndexList = ["num", ("foo", DESCENDING)] - db.test.create_index(spec) - first = next(db.test.find().hint(spec)) + db.coll.create_index(spec) + first = next(db.coll.find().hint(spec)) self.assertEqual(0, first.get("num")) self.assertEqual(0, first.get("foo")) - db.test.drop() - db.test.insert_many([{"num": i, "foo": i} for i in range(100)]) + db.coll.drop() + db.coll.insert_many([{"num": i, "foo": i} for i in range(100)]) spec = ["num"] - db.test.create_index(spec) - first = next(db.test.find().hint(spec)) + db.coll.create_index(spec) + first = next(db.coll.find().hint(spec)) self.assertEqual(0, first.get("num")) def test_hint_by_name(self): db = self.db - db.test.drop() + db.coll.drop() - db.test.insert_many([{"i": i} for i in range(100)]) + db.coll.insert_many([{"i": i} for i in range(100)]) - db.test.create_index([("i", DESCENDING)], name="fooindex") - first = next(db.test.find()) + db.coll.create_index([("i", DESCENDING)], name="fooindex") + first = next(db.coll.find()) self.assertEqual(0, first.get("i")) - first = next(db.test.find().hint("fooindex")) + first = next(db.coll.find().hint("fooindex")) self.assertEqual(99, first.get("i")) def test_limit(self): db = self.db with self.assertRaises(TypeError): - db.test.find().limit(None) # type: ignore[arg-type] + db.coll.find().limit(None) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().limit("hello") # type: ignore[arg-type] + db.coll.find().limit("hello") # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().limit(5.5) # type: ignore[arg-type] - self.assertTrue((db.test.find()).limit(5)) + db.coll.find().limit(5.5) # type: ignore[arg-type] + self.assertTrue((db.coll.find()).limit(5)) - db.test.drop() - db.test.insert_many([{"x": i} for i in range(100)]) + db.coll.drop() + db.coll.insert_many([{"x": i} for i in range(100)]) count = 0 - for _ in db.test.find(): + for _ in db.coll.find(): count += 1 self.assertEqual(count, 100) count = 0 - for _ in db.test.find().limit(20): + for _ in db.coll.find().limit(20): count += 1 self.assertEqual(count, 20) count = 0 - for _ in db.test.find().limit(99): + for _ in db.coll.find().limit(99): count += 1 self.assertEqual(count, 99) count = 0 - for _ in db.test.find().limit(1): + for _ in db.coll.find().limit(1): count += 1 self.assertEqual(count, 1) count = 0 - for _ in db.test.find().limit(0): + for _ in db.coll.find().limit(0): count += 1 self.assertEqual(count, 100) count = 0 - for _ in db.test.find().limit(0).limit(50).limit(10): + for _ in db.coll.find().limit(0).limit(50).limit(10): count += 1 self.assertEqual(count, 10) - a = db.test.find() + a = db.coll.find() a.limit(10) for _ in a: break @@ -508,14 +508,14 @@ def test_limit(self): def test_max(self): db = self.db - db.test.drop() + db.coll.drop() j_index = [("j", ASCENDING)] - db.test.create_index(j_index) + db.coll.create_index(j_index) - db.test.insert_many([{"j": j, "k": j} for j in range(10)]) + db.coll.insert_many([{"j": j, "k": j} for j in range(10)]) def find(max_spec, expected_index): - return db.test.find().max(max_spec).hint(expected_index) + return db.coll.find().max(max_spec).hint(expected_index) cursor = find([("j", 3)], j_index) self.assertEqual(len(cursor.to_list()), 3) @@ -526,7 +526,7 @@ def find(max_spec, expected_index): # Compound index. index_keys = [("j", ASCENDING), ("k", ASCENDING)] - db.test.create_index(index_keys) + db.coll.create_index(index_keys) cursor = find([("j", 3), ("k", 3)], index_keys) self.assertEqual(len(cursor.to_list()), 3) @@ -540,20 +540,20 @@ def find(max_spec, expected_index): with self.assertRaises(OperationFailure): cursor.to_list() with self.assertRaises(TypeError): - db.test.find().max(10) # type: ignore[arg-type] + db.coll.find().max(10) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().max({"j": 10}) # type: ignore[arg-type] + db.coll.find().max({"j": 10}) # type: ignore[arg-type] def test_min(self): db = self.db - db.test.drop() + db.coll.drop() j_index = [("j", ASCENDING)] - db.test.create_index(j_index) + db.coll.create_index(j_index) - db.test.insert_many([{"j": j, "k": j} for j in range(10)]) + db.coll.insert_many([{"j": j, "k": j} for j in range(10)]) def find(min_spec, expected_index): - return db.test.find().min(min_spec).hint(expected_index) + return db.coll.find().min(min_spec).hint(expected_index) cursor = find([("j", 3)], j_index) self.assertEqual(len(cursor.to_list()), 7) @@ -564,7 +564,7 @@ def find(min_spec, expected_index): # Compound index. index_keys = [("j", ASCENDING), ("k", ASCENDING)] - db.test.create_index(index_keys) + db.coll.create_index(index_keys) cursor = find([("j", 3), ("k", 3)], index_keys) self.assertEqual(len(cursor.to_list()), 7) @@ -579,12 +579,12 @@ def find(min_spec, expected_index): cursor.to_list() with self.assertRaises(TypeError): - db.test.find().min(10) # type: ignore[arg-type] + db.coll.find().min(10) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().min({"j": 10}) # type: ignore[arg-type] + db.coll.find().min({"j": 10}) # type: ignore[arg-type] def test_min_max_without_hint(self): - coll = self.db.test + coll = self.db.coll j_index = [("j", ASCENDING)] coll.create_index(j_index) @@ -595,19 +595,19 @@ def test_min_max_without_hint(self): def test_batch_size(self): db = self.db - db.test.drop() - db.test.insert_many([{"x": x} for x in range(200)]) + db.coll.drop() + db.coll.insert_many([{"x": x} for x in range(200)]) with self.assertRaises(TypeError): - db.test.find().batch_size(None) # type: ignore[arg-type] + db.coll.find().batch_size(None) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().batch_size("hello") # type: ignore[arg-type] + db.coll.find().batch_size("hello") # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().batch_size(5.5) # type: ignore[arg-type] + db.coll.find().batch_size(5.5) # type: ignore[arg-type] with self.assertRaises(ValueError): - db.test.find().batch_size(-1) - self.assertTrue((db.test.find()).batch_size(5)) - a = db.test.find() + db.coll.find().batch_size(-1) + self.assertTrue((db.coll.find()).batch_size(5)) + a = db.coll.find() for _ in a: break self.assertRaises(InvalidOperation, a.batch_size, 5) @@ -618,28 +618,28 @@ def cursor_count(cursor, expected_count): count += 1 self.assertEqual(expected_count, count) - cursor_count((db.test.find()).batch_size(0), 200) - cursor_count((db.test.find()).batch_size(1), 200) - cursor_count((db.test.find()).batch_size(2), 200) - cursor_count((db.test.find()).batch_size(5), 200) - cursor_count((db.test.find()).batch_size(100), 200) - cursor_count((db.test.find()).batch_size(500), 200) - - cursor_count((db.test.find()).batch_size(0).limit(1), 1) - cursor_count((db.test.find()).batch_size(1).limit(1), 1) - cursor_count((db.test.find()).batch_size(2).limit(1), 1) - cursor_count((db.test.find()).batch_size(5).limit(1), 1) - cursor_count((db.test.find()).batch_size(100).limit(1), 1) - cursor_count((db.test.find()).batch_size(500).limit(1), 1) - - cursor_count((db.test.find()).batch_size(0).limit(10), 10) - cursor_count((db.test.find()).batch_size(1).limit(10), 10) - cursor_count((db.test.find()).batch_size(2).limit(10), 10) - cursor_count((db.test.find()).batch_size(5).limit(10), 10) - cursor_count((db.test.find()).batch_size(100).limit(10), 10) - cursor_count((db.test.find()).batch_size(500).limit(10), 10) - - cur = db.test.find().batch_size(1) + cursor_count((db.coll.find()).batch_size(0), 200) + cursor_count((db.coll.find()).batch_size(1), 200) + cursor_count((db.coll.find()).batch_size(2), 200) + cursor_count((db.coll.find()).batch_size(5), 200) + cursor_count((db.coll.find()).batch_size(100), 200) + cursor_count((db.coll.find()).batch_size(500), 200) + + cursor_count((db.coll.find()).batch_size(0).limit(1), 1) + cursor_count((db.coll.find()).batch_size(1).limit(1), 1) + cursor_count((db.coll.find()).batch_size(2).limit(1), 1) + cursor_count((db.coll.find()).batch_size(5).limit(1), 1) + cursor_count((db.coll.find()).batch_size(100).limit(1), 1) + cursor_count((db.coll.find()).batch_size(500).limit(1), 1) + + cursor_count((db.coll.find()).batch_size(0).limit(10), 10) + cursor_count((db.coll.find()).batch_size(1).limit(10), 10) + cursor_count((db.coll.find()).batch_size(2).limit(10), 10) + cursor_count((db.coll.find()).batch_size(5).limit(10), 10) + cursor_count((db.coll.find()).batch_size(100).limit(10), 10) + cursor_count((db.coll.find()).batch_size(500).limit(10), 10) + + cur = db.coll.find().batch_size(1) next(cur) # find command batchSize should be 1 self.assertEqual(0, len(cur._data)) @@ -652,54 +652,54 @@ def cursor_count(cursor, expected_count): def test_limit_and_batch_size(self): db = self.db - db.test.drop() - db.test.insert_many([{"x": x} for x in range(500)]) + db.coll.drop() + db.coll.insert_many([{"x": x} for x in range(500)]) - curs = db.test.find().limit(0).batch_size(10) + curs = db.coll.find().limit(0).batch_size(10) next(curs) self.assertEqual(10, curs._retrieved) - curs = db.test.find(limit=0, batch_size=10) + curs = db.coll.find(limit=0, batch_size=10) next(curs) self.assertEqual(10, curs._retrieved) - curs = db.test.find().limit(-2).batch_size(0) + curs = db.coll.find().limit(-2).batch_size(0) next(curs) self.assertEqual(2, curs._retrieved) - curs = db.test.find(limit=-2, batch_size=0) + curs = db.coll.find(limit=-2, batch_size=0) next(curs) self.assertEqual(2, curs._retrieved) - curs = db.test.find().limit(-4).batch_size(5) + curs = db.coll.find().limit(-4).batch_size(5) next(curs) self.assertEqual(4, curs._retrieved) - curs = db.test.find(limit=-4, batch_size=5) + curs = db.coll.find(limit=-4, batch_size=5) next(curs) self.assertEqual(4, curs._retrieved) - curs = db.test.find().limit(50).batch_size(500) + curs = db.coll.find().limit(50).batch_size(500) next(curs) self.assertEqual(50, curs._retrieved) - curs = db.test.find(limit=50, batch_size=500) + curs = db.coll.find(limit=50, batch_size=500) next(curs) self.assertEqual(50, curs._retrieved) - curs = db.test.find().batch_size(500) + curs = db.coll.find().batch_size(500) next(curs) self.assertEqual(500, curs._retrieved) - curs = db.test.find(batch_size=500) + curs = db.coll.find(batch_size=500) next(curs) self.assertEqual(500, curs._retrieved) - curs = db.test.find().limit(50) + curs = db.coll.find().limit(50) next(curs) self.assertEqual(50, curs._retrieved) - curs = db.test.find(limit=50) + curs = db.coll.find(limit=50) next(curs) self.assertEqual(50, curs._retrieved) @@ -707,15 +707,15 @@ def test_limit_and_batch_size(self): # is set by the server. as of 2.0.0-rc0, 101 # or 1MB (whichever is smaller) is default # for queries without ntoreturn - curs = db.test.find() + curs = db.coll.find() next(curs) self.assertEqual(101, curs._retrieved) - curs = db.test.find().limit(0).batch_size(0) + curs = db.coll.find().limit(0).batch_size(0) next(curs) self.assertEqual(101, curs._retrieved) - curs = db.test.find(limit=0, batch_size=0) + curs = db.coll.find(limit=0, batch_size=0) next(curs) self.assertEqual(101, curs._retrieved) @@ -723,47 +723,47 @@ def test_skip(self): db = self.db with self.assertRaises(TypeError): - db.test.find().skip(None) # type: ignore[arg-type] + db.coll.find().skip(None) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().skip("hello") # type: ignore[arg-type] + db.coll.find().skip("hello") # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().skip(5.5) # type: ignore[arg-type] + db.coll.find().skip(5.5) # type: ignore[arg-type] with self.assertRaises(ValueError): - db.test.find().skip(-5) - self.assertTrue((db.test.find()).skip(5)) + db.coll.find().skip(-5) + self.assertTrue((db.coll.find()).skip(5)) - db.drop_collection("test") + db.drop_collection("coll") - db.test.insert_many([{"x": i} for i in range(100)]) + db.coll.insert_many([{"x": i} for i in range(100)]) - for i in db.test.find(): + for i in db.coll.find(): self.assertEqual(i["x"], 0) break - for i in db.test.find().skip(20): + for i in db.coll.find().skip(20): self.assertEqual(i["x"], 20) break - for i in db.test.find().skip(99): + for i in db.coll.find().skip(99): self.assertEqual(i["x"], 99) break - for i in db.test.find().skip(1): + for i in db.coll.find().skip(1): self.assertEqual(i["x"], 1) break - for i in db.test.find().skip(0): + for i in db.coll.find().skip(0): self.assertEqual(i["x"], 0) break - for i in db.test.find().skip(0).skip(50).skip(10): + for i in db.coll.find().skip(0).skip(50).skip(10): self.assertEqual(i["x"], 10) break - for _ in db.test.find().skip(1000): + for _ in db.coll.find().skip(1000): self.fail() - a = db.test.find() + a = db.coll.find() a.skip(10) for _ in a: break @@ -773,52 +773,52 @@ def test_sort(self): db = self.db with self.assertRaises(TypeError): - db.test.find().sort(5) # type: ignore[arg-type] + db.coll.find().sort(5) # type: ignore[arg-type] with self.assertRaises(ValueError): - db.test.find().sort([]) # type: ignore[arg-type] + db.coll.find().sort([]) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().sort([], ASCENDING) # type: ignore[arg-type] + db.coll.find().sort([], ASCENDING) # type: ignore[arg-type] with self.assertRaises(TypeError): - db.test.find().sort([("hello", DESCENDING)], DESCENDING) # type: ignore[arg-type] + db.coll.find().sort([("hello", DESCENDING)], DESCENDING) # type: ignore[arg-type] - db.test.drop() + db.coll.drop() unsort = list(range(10)) random.shuffle(unsort) - db.test.insert_many([{"x": i} for i in unsort]) + db.coll.insert_many([{"x": i} for i in unsort]) - asc = [i["x"] for i in db.test.find().sort("x", ASCENDING)] + asc = [i["x"] for i in db.coll.find().sort("x", ASCENDING)] self.assertEqual(asc, list(range(10))) - asc = [i["x"] for i in db.test.find().sort("x")] + asc = [i["x"] for i in db.coll.find().sort("x")] self.assertEqual(asc, list(range(10))) - asc = [i["x"] for i in db.test.find().sort([("x", ASCENDING)])] + asc = [i["x"] for i in db.coll.find().sort([("x", ASCENDING)])] self.assertEqual(asc, list(range(10))) expect = list(reversed(range(10))) - desc = [i["x"] for i in db.test.find().sort("x", DESCENDING)] + desc = [i["x"] for i in db.coll.find().sort("x", DESCENDING)] self.assertEqual(desc, expect) - desc = [i["x"] for i in db.test.find().sort([("x", DESCENDING)])] + desc = [i["x"] for i in db.coll.find().sort([("x", DESCENDING)])] self.assertEqual(desc, expect) - desc = [i["x"] for i in db.test.find().sort("x", ASCENDING).sort("x", DESCENDING)] + desc = [i["x"] for i in db.coll.find().sort("x", ASCENDING).sort("x", DESCENDING)] self.assertEqual(desc, expect) expected = [(1, 5), (2, 5), (0, 3), (7, 3), (9, 2), (2, 1), (3, 1)] shuffled = list(expected) random.shuffle(shuffled) - db.test.drop() + db.coll.drop() for a, b in shuffled: - db.test.insert_one({"a": a, "b": b}) + db.coll.insert_one({"a": a, "b": b}) result = [ - (i["a"], i["b"]) for i in db.test.find().sort([("b", DESCENDING), ("a", ASCENDING)]) + (i["a"], i["b"]) for i in db.coll.find().sort([("b", DESCENDING), ("a", ASCENDING)]) ] self.assertEqual(result, expected) - result = [(i["a"], i["b"]) for i in db.test.find().sort([("b", DESCENDING), "a"])] + result = [(i["a"], i["b"]) for i in db.coll.find().sort([("b", DESCENDING), "a"])] self.assertEqual(result, expected) - a = db.test.find() + a = db.coll.find() a.sort("x", ASCENDING) for _ in a: break @@ -830,9 +830,9 @@ def test_sort(self): ) def test_where(self): db = self.db - db.test.drop() + db.coll.drop() - a = db.test.find() + a = db.coll.find() with self.assertRaises(TypeError): a.where(5) # type: ignore[arg-type] with self.assertRaises(TypeError): @@ -840,38 +840,38 @@ def test_where(self): with self.assertRaises(TypeError): a.where({}) # type: ignore[arg-type] - db.test.insert_many([{"x": i} for i in range(10)]) + db.coll.insert_many([{"x": i} for i in range(10)]) - self.assertEqual(3, len(db.test.find().where("this.x < 3").to_list())) - self.assertEqual(3, len(db.test.find().where(Code("this.x < 3")).to_list())) + self.assertEqual(3, len(db.coll.find().where("this.x < 3").to_list())) + self.assertEqual(3, len(db.coll.find().where(Code("this.x < 3")).to_list())) code_with_scope = Code("this.x < i", {"i": 3}) # MongoDB 4.4 removed support for Code with scope. with self.assertRaises(OperationFailure): - db.test.find().where(code_with_scope).to_list() + db.coll.find().where(code_with_scope).to_list() code_with_empty_scope = Code("this.x < 3", {}) with self.assertRaises(OperationFailure): - db.test.find().where(code_with_empty_scope).to_list() + db.coll.find().where(code_with_empty_scope).to_list() - self.assertEqual(10, len(db.test.find().to_list())) - self.assertEqual([0, 1, 2], [a["x"] for a in db.test.find().where("this.x < 3")]) - self.assertEqual([], [a["x"] for a in db.test.find({"x": 5}).where("this.x < 3")]) - self.assertEqual([5], [a["x"] for a in db.test.find({"x": 5}).where("this.x > 3")]) + self.assertEqual(10, len(db.coll.find().to_list())) + self.assertEqual([0, 1, 2], [a["x"] for a in db.coll.find().where("this.x < 3")]) + self.assertEqual([], [a["x"] for a in db.coll.find({"x": 5}).where("this.x < 3")]) + self.assertEqual([5], [a["x"] for a in db.coll.find({"x": 5}).where("this.x > 3")]) - cursor = db.test.find().where("this.x < 3").where("this.x > 7") + cursor = db.coll.find().where("this.x < 3").where("this.x > 7") self.assertEqual([8, 9], [a["x"] for a in cursor]) - a = db.test.find() + a = db.coll.find() _ = a.where("this.x > 3") for _ in a: break self.assertRaises(InvalidOperation, a.where, "this.x < 3") def test_rewind(self): - self.db.test.insert_many([{"x": i} for i in range(1, 4)]) + self.db.coll.insert_many([{"x": i} for i in range(1, 4)]) - cursor = self.db.test.find().limit(2) + cursor = self.db.coll.find().limit(2) count = 0 for _ in cursor: @@ -903,9 +903,9 @@ def test_rewind(self): # oplog_reply, and snapshot are all deprecated. @ignore_deprecations def test_clone(self): - self.db.test.insert_many([{"x": i} for i in range(1, 4)]) + self.db.coll.insert_many([{"x": i} for i in range(1, 4)]) - cursor = self.db.test.find().limit(2) + cursor = self.db.coll.find().limit(2) count = 0 for _ in cursor: @@ -940,7 +940,7 @@ def test_clone(self): # Just test attributes cursor = ( - self.db.test.find( + self.db.coll.find( {"x": re.compile("^hello.*")}, projection={"_id": False}, skip=1, @@ -988,7 +988,7 @@ def test_clone(self): # Test memo when deepcopying queries query = {"hello": "world"} query["reflexive"] = query - cursor = self.db.test.find(query) + cursor = self.db.coll.find(query) cursor2 = copy.deepcopy(cursor) @@ -997,7 +997,7 @@ def test_clone(self): self.assertEqual(len(cursor2._spec), 2) # Ensure hints are cloned as the correct type - cursor = self.db.test.find().hint([("z", 1), ("a", 1)]) + cursor = self.db.coll.find().hint([("z", 1), ("a", 1)]) cursor2 = copy.deepcopy(cursor) # Internal types are now dict rather than SON by default self.assertIsInstance(cursor2._hint, dict) @@ -1005,9 +1005,9 @@ def test_clone(self): @client_context.require_sync def test_clone_empty(self): - self.db.test.delete_many({}) - self.db.test.insert_many([{"x": i} for i in range(1, 4)]) - cursor = self.db.test.find()[2:2] + self.db.coll.delete_many({}) + self.db.coll.insert_many([{"x": i} for i in range(1, 4)]) + cursor = self.db.coll.find()[2:2] cursor2 = cursor.clone() self.assertRaises(StopIteration, cursor.next) self.assertRaises(StopIteration, cursor2.next) @@ -1015,130 +1015,130 @@ def test_clone_empty(self): # Cursors don't support slicing @client_context.require_sync def test_bad_getitem(self): - self.assertRaises(TypeError, lambda x: self.db.test.find()[x], "hello") - self.assertRaises(TypeError, lambda x: self.db.test.find()[x], 5.5) - self.assertRaises(TypeError, lambda x: self.db.test.find()[x], None) + self.assertRaises(TypeError, lambda x: self.db.coll.find()[x], "hello") + self.assertRaises(TypeError, lambda x: self.db.coll.find()[x], 5.5) + self.assertRaises(TypeError, lambda x: self.db.coll.find()[x], None) # Cursors don't support slicing @client_context.require_sync def test_getitem_slice_index(self): - self.db.drop_collection("test") - self.db.test.insert_many([{"i": i} for i in range(100)]) + self.db.drop_collection("coll") + self.db.coll.insert_many([{"i": i} for i in range(100)]) count = itertools.count - self.assertRaises(IndexError, lambda: self.db.test.find()[-1:]) - self.assertRaises(IndexError, lambda: self.db.test.find()[1:2:2]) + self.assertRaises(IndexError, lambda: self.db.coll.find()[-1:]) + self.assertRaises(IndexError, lambda: self.db.coll.find()[1:2:2]) - for a, b in zip(count(0), self.db.test.find()): # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find()): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(100, len(list(self.db.test.find()[0:]))) # type: ignore[call-overload] - for a, b in zip(count(0), self.db.test.find()[0:]): # type: ignore[call-overload] + self.assertEqual(100, len(list(self.db.coll.find()[0:]))) # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find()[0:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find()[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[20:]): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[20:]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - for a, b in zip(count(99), self.db.test.find()[99:]): # type: ignore[call-overload] + for a, b in zip(count(99), self.db.coll.find()[99:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - for _i in self.db.test.find()[1000:]: + for _i in self.db.coll.find()[1000:]: self.fail() - self.assertEqual(5, len(list(self.db.test.find()[20:25]))) # type: ignore[call-overload] - self.assertEqual(5, len(list(self.db.test.find()[20:25]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[20:25]): # type: ignore[call-overload] + self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] + self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:25]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find()[40:45][20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[40:45][20:]): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[40:45][20:]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45][20:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find()[40:45].limit(0).skip(20)))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find()[40:45].limit(0).skip(20)): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[40:45].limit(0).skip(20)))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45].limit(0).skip(20)): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(80, len(list(self.db.test.find().limit(10).skip(40)[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.test.find().limit(10).skip(40)[20:]): # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find().limit(10).skip(40)[20:]))) # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find().limit(10).skip(40)[20:]): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - self.assertEqual(1, len(list(self.db.test.find()[:1]))) # type: ignore[call-overload] - self.assertEqual(5, len(list(self.db.test.find()[:5]))) # type: ignore[call-overload] + self.assertEqual(1, len(list(self.db.coll.find()[:1]))) # type: ignore[call-overload] + self.assertEqual(5, len(list(self.db.coll.find()[:5]))) # type: ignore[call-overload] - self.assertEqual(1, len(list(self.db.test.find()[99:100]))) # type: ignore[call-overload] - self.assertEqual(1, len(list(self.db.test.find()[99:1000]))) # type: ignore[call-overload] - self.assertEqual(0, len(list(self.db.test.find()[10:10]))) # type: ignore[call-overload] - self.assertEqual(0, len(list(self.db.test.find()[:0]))) # type: ignore[call-overload] - self.assertEqual(80, len(list(self.db.test.find()[10:10].limit(0).skip(20)))) # type: ignore[call-overload] + self.assertEqual(1, len(list(self.db.coll.find()[99:100]))) # type: ignore[call-overload] + self.assertEqual(1, len(list(self.db.coll.find()[99:1000]))) # type: ignore[call-overload] + self.assertEqual(0, len(list(self.db.coll.find()[10:10]))) # type: ignore[call-overload] + self.assertEqual(0, len(list(self.db.coll.find()[:0]))) # type: ignore[call-overload] + self.assertEqual(80, len(list(self.db.coll.find()[10:10].limit(0).skip(20)))) # type: ignore[call-overload] - self.assertRaises(IndexError, lambda: self.db.test.find()[10:8]) + self.assertRaises(IndexError, lambda: self.db.coll.find()[10:8]) # Cursors don't support slicing @client_context.require_sync def test_getitem_numeric_index(self): - self.db.drop_collection("test") - self.db.test.insert_many([{"i": i} for i in range(100)]) + self.db.drop_collection("coll") + self.db.coll.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"]) - self.assertEqual(50, self.db.test.find().skip(50)[0]["i"]) - self.assertEqual(50, self.db.test.find().skip(49)[1]["i"]) - self.assertEqual(50, self.db.test.find()[50]["i"]) - self.assertEqual(99, self.db.test.find()[99]["i"]) + self.assertEqual(0, self.db.coll.find()[0]["i"]) + self.assertEqual(50, self.db.coll.find()[50]["i"]) + self.assertEqual(50, self.db.coll.find().skip(50)[0]["i"]) + self.assertEqual(50, self.db.coll.find().skip(49)[1]["i"]) + self.assertEqual(50, self.db.coll.find()[50]["i"]) + self.assertEqual(99, self.db.coll.find()[99]["i"]) - self.assertRaises(IndexError, lambda x: self.db.test.find()[x], -1) - self.assertRaises(IndexError, lambda x: self.db.test.find()[x], 100) - self.assertRaises(IndexError, lambda x: self.db.test.find().skip(50)[x], 50) + self.assertRaises(IndexError, lambda x: self.db.coll.find()[x], -1) + self.assertRaises(IndexError, lambda x: self.db.coll.find()[x], 100) + self.assertRaises(IndexError, lambda x: self.db.coll.find().skip(50)[x], 50) @client_context.require_sync def test_iteration_with_list(self): - self.db.drop_collection("test") - self.db.test.insert_many([{"i": i} for i in range(100)]) + self.db.drop_collection("coll") + self.db.coll.insert_many([{"i": i} for i in range(100)]) - cur = self.db.test.find().batch_size(10) + cur = self.db.coll.find().batch_size(10) self.assertEqual(100, len(list(cur))) # type: ignore[call-overload] def test_len(self): with self.assertRaises(TypeError): - len(self.db.test.find()) # type: ignore[arg-type] + len(self.db.coll.find()) # type: ignore[arg-type] def test_properties(self): - self.assertEqual(self.db.test, self.db.test.find().collection) + self.assertEqual(self.db.coll, self.db.coll.find().collection) with self.assertRaises(AttributeError): - self.db.test.find().collection = "hello" # type: ignore + self.db.coll.find().collection = "hello" # type: ignore def test_get_more(self): db = self.db - db.drop_collection("test") - db.test.insert_many([{"i": i} for i in range(10)]) - self.assertEqual(10, len(db.test.find().batch_size(5).to_list())) + db.drop_collection("coll") + db.coll.insert_many([{"i": i} for i in range(10)]) + self.assertEqual(10, len(db.coll.find().batch_size(5).to_list())) def test_tailable(self): db = self.db - db.drop_collection("test") - db.create_collection("test", capped=True, size=1000, max=3) - self.addCleanup(db.drop_collection, "test") - cursor = db.test.find(cursor_type=CursorType.TAILABLE) + db.drop_collection("coll") + db.create_collection("coll", capped=True, size=1000, max=3) + self.addCleanup(db.drop_collection, "coll") + cursor = db.coll.find(cursor_type=CursorType.TAILABLE) - db.test.insert_one({"x": 1}) + db.coll.insert_one({"x": 1}) count = 0 for doc in cursor: count += 1 self.assertEqual(1, doc["x"]) self.assertEqual(1, count) - db.test.insert_one({"x": 2}) + db.coll.insert_one({"x": 2}) count = 0 for doc in cursor: count += 1 self.assertEqual(2, doc["x"]) self.assertEqual(1, count) - db.test.insert_one({"x": 3}) + db.coll.insert_one({"x": 3}) count = 0 for doc in cursor: count += 1 @@ -1148,19 +1148,19 @@ def test_tailable(self): # Capped rollover - the collection can never # have more than 3 documents. Just make sure # this doesn't raise... - db.test.insert_many([{"x": i} for i in range(4, 7)]) + db.coll.insert_many([{"x": i} for i in range(4, 7)]) self.assertEqual(0, len(cursor.to_list())) # and that the cursor doesn't think it's still alive. self.assertFalse(cursor.alive) - self.assertEqual(3, db.test.count_documents({})) + self.assertEqual(3, db.coll.count_documents({})) # __getitem__(index) if _IS_SYNC: for cursor in ( - db.test.find(cursor_type=CursorType.TAILABLE), - db.test.find(cursor_type=CursorType.TAILABLE_AWAIT), + db.coll.find(cursor_type=CursorType.TAILABLE), + db.coll.find(cursor_type=CursorType.TAILABLE_AWAIT), ): self.assertEqual(4, cursor[0]["x"]) self.assertEqual(5, cursor[1]["x"]) @@ -1184,10 +1184,10 @@ def test_tailable(self): def test_concurrent_close(self): """Ensure a tailable can be closed from another thread.""" db = self.db - db.drop_collection("test") - db.create_collection("test", capped=True, size=1000, max=3) - self.addCleanup(db.drop_collection, "test") - cursor = db.test.find(cursor_type=CursorType.TAILABLE) + db.drop_collection("coll") + db.create_collection("coll", capped=True, size=1000, max=3) + self.addCleanup(db.drop_collection, "coll") + cursor = db.coll.find(cursor_type=CursorType.TAILABLE) def iterate_cursor(): while cursor.alive: @@ -1207,37 +1207,37 @@ def iterate_cursor(): self.assertFalse(t.is_alive()) def test_distinct(self): - self.db.drop_collection("test") + self.db.drop_collection("coll") - self.db.test.insert_many([{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}]) + self.db.coll.insert_many([{"a": 1}, {"a": 2}, {"a": 2}, {"a": 2}, {"a": 3}]) - distinct = self.db.test.find({"a": {"$lt": 3}}).distinct("a") + distinct = self.db.coll.find({"a": {"$lt": 3}}).distinct("a") distinct.sort() self.assertEqual([1, 2], distinct) - self.db.drop_collection("test") + self.db.drop_collection("coll") - 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}) + self.db.coll.insert_one({"a": {"b": "a"}, "c": 12}) + self.db.coll.insert_one({"a": {"b": "b"}, "c": 8}) + self.db.coll.insert_one({"a": {"b": "c"}, "c": 12}) + self.db.coll.insert_one({"a": {"b": "c"}, "c": 8}) - distinct = self.db.test.find({"c": 8}).distinct("a.b") + distinct = self.db.coll.find({"c": 8}).distinct("a.b") distinct.sort() self.assertEqual(["b", "c"], distinct) def test_with_statement(self): - self.db.drop_collection("test") - self.db.test.insert_many([{} for _ in range(100)]) + self.db.drop_collection("coll") + self.db.coll.insert_many([{} for _ in range(100)]) - c1 = self.db.test.find() - with self.db.test.find() as c2: + c1 = self.db.coll.find() + with self.db.coll.find() as c2: self.assertTrue(c2.alive) self.assertFalse(c2.alive) - with self.db.test.find() as c2: + with self.db.coll.find() as c2: self.assertEqual(100, len(c2.to_list())) self.assertFalse(c2.alive) self.assertTrue(c1.alive) @@ -1247,18 +1247,18 @@ def test_comment(self): self.client.drop_database(self.db) self.db.command("profile", 2) # Profile ALL commands. try: - self.db.test.find().comment("foo").to_list() + self.db.coll.find().comment("foo").to_list() count = self.db.system.profile.count_documents( - {"ns": "pymongo_test.test", "op": "query", "command.comment": "foo"} + {"ns": "pymongo_test.coll", "op": "query", "command.comment": "foo"} ) self.assertEqual(count, 1) - self.db.test.find().comment("foo").distinct("type") + self.db.coll.find().comment("foo").distinct("type") count = self.db.system.profile.count_documents( { - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "op": "command", - "command.distinct": "test", + "command.distinct": "coll", "command.comment": "foo", } ) @@ -1267,16 +1267,16 @@ def test_comment(self): self.db.command("profile", 0) # Turn off profiling. self.db.system.profile.drop() - self.db.test.insert_many([{}, {}]) - cursor = self.db.test.find() + self.db.coll.insert_many([{}, {}]) + cursor = self.db.coll.find() next(cursor) self.assertRaises(InvalidOperation, cursor.comment, "hello") def test_alive(self): - self.db.test.delete_many({}) - self.db.test.insert_many([{} for _ in range(3)]) - self.addCleanup(self.db.test.delete_many, {}) - cursor = self.db.test.find().batch_size(2) + self.db.coll.delete_many({}) + self.db.coll.insert_many([{} for _ in range(3)]) + self.addCleanup(self.db.coll.delete_many, {}) + cursor = self.db.coll.find().batch_size(2) n = 0 while True: cursor.next() @@ -1431,7 +1431,7 @@ def test_to_list_empty(self): self.assertEqual([], docs) def test_to_list_length(self): - coll = self.db.test + coll = self.db.coll coll.insert_many([{} for _ in range(5)]) self.addCleanup(coll.drop) c = coll.find() @@ -1447,7 +1447,7 @@ def test_to_list_length(self): @flaky(reason="PYTHON-3522") def test_to_list_csot_applied(self): client = self.single_client(timeoutMS=500, w=1) - coll = client.pymongo.test + coll = client.pymongo.coll # Initialize the client with a larger timeout to help make test less flaky with pymongo.timeout(10): coll.insert_many([{} for _ in range(5)]) @@ -1459,7 +1459,7 @@ def test_to_list_csot_applied(self): @client_context.require_change_streams def test_command_cursor_to_list(self): # Set maxAwaitTimeMS=1 to speed up the test. - c = self.db.test.aggregate([{"$changeStream": {}}], maxAwaitTimeMS=1) + c = self.db.coll.aggregate([{"$changeStream": {}}], maxAwaitTimeMS=1) self.addCleanup(c.close) docs = c.to_list() self.assertGreaterEqual(len(docs), 0) @@ -1475,21 +1475,21 @@ def test_command_cursor_to_list_empty(self): @client_context.require_change_streams def test_command_cursor_to_list_length(self): db = self.db - db.drop_collection("test") - db.test.insert_many([{"foo": 1}, {"foo": 2}]) + db.drop_collection("coll") + db.coll.insert_many([{"foo": 1}, {"foo": 2}]) pipeline = {"$project": {"_id": False, "foo": True}} - result = db.test.aggregate([pipeline]) + result = db.coll.aggregate([pipeline]) self.assertEqual(len(result.to_list()), 2) - result = db.test.aggregate([pipeline]) + result = db.coll.aggregate([pipeline]) self.assertEqual(len(result.to_list(1)), 1) @client_context.require_failCommand_blockConnection @flaky(reason="PYTHON-3522") def test_command_cursor_to_list_csot_applied(self): client = self.single_client(timeoutMS=500, w=1) - coll = client.pymongo.test + coll = client.pymongo.coll # Initialize the client with a larger timeout to help make test less flaky with pymongo.timeout(10): coll.insert_many([{} for _ in range(5)]) @@ -1508,10 +1508,10 @@ def test_command_cursor_to_list_csot_applied(self): class TestRawBatchCursor(IntegrationTest): def setUp(self): super().setUp() - self.db.test.drop() + self.db.coll.drop() def test_find_raw(self): - c = self.db.test + c = self.db.coll docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) batches = c.find_raw_batches().sort("_id").to_list() @@ -1520,7 +1520,7 @@ def test_find_raw(self): @client_context.require_transactions def test_find_raw_transaction(self): - c = self.db.test + c = self.db.coll docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1529,7 +1529,7 @@ def test_find_raw_transaction(self): with client.start_session() as session: with session.start_transaction(): batches = ( - client[self.db.name].test.find_raw_batches(session=session).sort("_id") + client[self.db.name].coll.find_raw_batches(session=session).sort("_id") ).to_list() cmd = listener.started_events[0] self.assertEqual(cmd.command_name, "find") @@ -1549,7 +1549,7 @@ def test_find_raw_transaction(self): @client_context.require_sessions @client_context.require_failCommand_fail_point def test_find_raw_retryable_reads(self): - c = self.db.test + c = self.db.coll docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1558,7 +1558,7 @@ def test_find_raw_retryable_reads(self): with self.fail_point( {"mode": {"times": 1}, "data": {"failCommands": ["find"], "closeConnection": True}} ): - batches = client[self.db.name].test.find_raw_batches().sort("_id").to_list() + batches = client[self.db.name].coll.find_raw_batches().sort("_id").to_list() self.assertEqual(1, len(batches)) self.assertEqual(docs, decode_all(batches[0])) @@ -1569,7 +1569,7 @@ def test_find_raw_retryable_reads(self): @client_context.require_version_min(5, 0, 0) @client_context.require_no_standalone def test_find_raw_snapshot_reads(self): - c = self.db.get_collection("test", write_concern=WriteConcern(w="majority")) + c = self.db.get_collection("coll", write_concern=WriteConcern(w="majority")) docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1577,8 +1577,8 @@ def test_find_raw_snapshot_reads(self): client = self.rs_or_single_client(event_listeners=[listener], retryReads=True) db = client[self.db.name] with client.start_session(snapshot=True) as session: - db.test.distinct("x", {}, session=session) - batches = db.test.find_raw_batches(session=session).sort("_id").to_list() + db.coll.distinct("x", {}, session=session) + batches = db.coll.find_raw_batches(session=session).sort("_id").to_list() self.assertEqual(1, len(batches)) self.assertEqual(docs, decode_all(batches[0])) @@ -1587,53 +1587,53 @@ def test_find_raw_snapshot_reads(self): self.assertIsNotNone(find_cmd["readConcern"]["atClusterTime"]) def test_explain(self): - c = self.db.test + c = self.db.coll explanation = c.find_raw_batches().explain() self.assertIsInstance(explanation, dict) def test_empty(self): - cursor = self.db.test.find_raw_batches() + cursor = self.db.coll.find_raw_batches() with self.assertRaises(StopIteration): next(cursor) def test_clone(self): - self.db.test.insert_one({}) - cursor = self.db.test.find_raw_batches() + self.db.coll.insert_one({}) + cursor = self.db.coll.find_raw_batches() # Copy of a RawBatchCursor is also a RawBatchCursor, not a Cursor. self.assertIsInstance(next(cursor.clone()), bytes) self.assertIsInstance(next(copy.copy(cursor)), bytes) @client_context.require_exhaust_cursors def test_exhaust(self): - c = self.db.test + c = self.db.coll c.insert_many({"_id": i} for i in range(200)) result = b"".join(c.find_raw_batches(cursor_type=CursorType.EXHAUST).to_list()) self.assertEqual([{"_id": i} for i in range(200)], decode_all(result)) def test_server_error(self): with self.assertRaises(OperationFailure) as exc: - next(self.db.test.find_raw_batches({"x": {"$bad": 1}})) + next(self.db.coll.find_raw_batches({"x": {"$bad": 1}})) # The server response was decoded, not left raw. self.assertIsInstance(exc.exception.details, dict) def test_get_item(self): with self.assertRaises(InvalidOperation): - self.db.test.find_raw_batches()[0] + self.db.coll.find_raw_batches()[0] def test_collation(self): - self.db.test.insert_one({}) - next(self.db.test.find_raw_batches(collation=Collation("en_US"))) + self.db.coll.insert_one({}) + next(self.db.coll.find_raw_batches(collation=Collation("en_US"))) def test_read_concern(self): - self.db.get_collection("test", write_concern=WriteConcern(w="majority")).insert_one({}) - c = self.db.get_collection("test", read_concern=ReadConcern("majority")) + self.db.get_collection("coll", write_concern=WriteConcern(w="majority")).insert_one({}) + c = self.db.get_collection("coll", read_concern=ReadConcern("majority")) next(c.find_raw_batches()) def test_monitoring(self): listener = OvertCommandListener() client = self.rs_or_single_client(event_listeners=[listener]) - c = client.pymongo_test.test + c = client.pymongo_test.coll c.insert_many([{"_id": i} for i in range(10)]) listener.reset() @@ -1649,7 +1649,7 @@ def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("find", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") # The batch is a list of one raw bytes object. self.assertEqual(len(csr["firstBatch"]), 1) @@ -1667,7 +1667,7 @@ def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("getMore", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(len(csr["nextBatch"]), 1) self.assertEqual(decode_all(csr["nextBatch"][0]), [{"_id": i} for i in range(4, 8)]) finally: @@ -1677,7 +1677,7 @@ def test_monitoring(self): class TestRawBatchCommandCursor(IntegrationTest): def test_aggregate_raw(self): - c = self.db.test + c = self.db.coll c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1687,7 +1687,7 @@ def test_aggregate_raw(self): @client_context.require_transactions def test_aggregate_raw_transaction(self): - c = self.db.test + c = self.db.coll c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1697,7 +1697,7 @@ def test_aggregate_raw_transaction(self): with client.start_session() as session: with session.start_transaction(): batches = ( - client[self.db.name].test.aggregate_raw_batches( + client[self.db.name].coll.aggregate_raw_batches( [{"$sort": {"_id": 1}}], session=session ) ).to_list() @@ -1718,7 +1718,7 @@ def test_aggregate_raw_transaction(self): @client_context.require_sessions @client_context.require_failCommand_fail_point def test_aggregate_raw_retryable_reads(self): - c = self.db.test + c = self.db.coll c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1729,7 +1729,7 @@ def test_aggregate_raw_retryable_reads(self): {"mode": {"times": 1}, "data": {"failCommands": ["aggregate"], "closeConnection": True}} ): batches = ( - client[self.db.name].test.aggregate_raw_batches([{"$sort": {"_id": 1}}]) + client[self.db.name].coll.aggregate_raw_batches([{"$sort": {"_id": 1}}]) ).to_list() self.assertEqual(1, len(batches)) @@ -1742,7 +1742,7 @@ def test_aggregate_raw_retryable_reads(self): @client_context.require_version_min(5, 0, -1) @client_context.require_no_standalone def test_aggregate_raw_snapshot_reads(self): - c = self.db.get_collection("test", write_concern=WriteConcern(w="majority")) + c = self.db.get_collection("coll", write_concern=WriteConcern(w="majority")) c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1751,9 +1751,9 @@ def test_aggregate_raw_snapshot_reads(self): client = self.rs_or_single_client(event_listeners=[listener], retryReads=True) db = client[self.db.name] with client.start_session(snapshot=True) as session: - db.test.distinct("x", {}, session=session) + db.coll.distinct("x", {}, session=session) batches = ( - db.test.aggregate_raw_batches([{"$sort": {"_id": 1}}], session=session) + db.coll.aggregate_raw_batches([{"$sort": {"_id": 1}}], session=session) ).to_list() self.assertEqual(1, len(batches)) self.assertEqual(docs, decode_all(batches[0])) @@ -1763,7 +1763,7 @@ def test_aggregate_raw_snapshot_reads(self): self.assertIsNotNone(find_cmd["readConcern"]["atClusterTime"]) def test_server_error(self): - c = self.db.test + c = self.db.coll c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1771,7 +1771,7 @@ def test_server_error(self): with self.assertRaises(OperationFailure) as exc: ( - self.db.test.aggregate_raw_batches( + self.db.coll.aggregate_raw_batches( [ { "$sort": {"_id": 1}, @@ -1787,15 +1787,15 @@ def test_server_error(self): def test_get_item(self): with self.assertRaises(InvalidOperation): - (self.db.test.aggregate_raw_batches([]))[0] + (self.db.coll.aggregate_raw_batches([]))[0] def test_collation(self): - next(self.db.test.aggregate_raw_batches([], collation=Collation("en_US"))) + next(self.db.coll.aggregate_raw_batches([], collation=Collation("en_US"))) def test_monitoring(self): listener = OvertCommandListener() client = self.rs_or_single_client(event_listeners=[listener]) - c = client.pymongo_test.test + c = client.pymongo_test.coll c.drop() c.insert_many([{"_id": i} for i in range(10)]) @@ -1810,7 +1810,7 @@ def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("aggregate", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") # First batch is empty. self.assertEqual(len(csr["firstBatch"]), 0) @@ -1826,7 +1826,7 @@ def test_monitoring(self): self.assertEqual("pymongo_test", started.database_name) self.assertEqual("getMore", succeeded.command_name) csr = succeeded.reply["cursor"] - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(len(csr["nextBatch"]), 1) self.assertEqual(csr["nextBatch"][0], batch) self.assertEqual(decode_all(batch), [{"_id": i} for i in range(n, min(n + 4, 10))]) @@ -1840,7 +1840,7 @@ def test_monitoring(self): def test_exhaust_cursor_db_set(self): listener = OvertCommandListener() client = self.rs_or_single_client(event_listeners=[listener]) - c = client.pymongo_test.test + c = client.pymongo_test.coll c.delete_many({}) c.insert_many([{"_id": i} for i in range(3)]) diff --git a/test/test_custom_types.py b/test/test_custom_types.py index 4d825b9086..34f0fb31bc 100644 --- a/test/test_custom_types.py +++ b/test/test_custom_types.py @@ -632,15 +632,15 @@ class MyType(pytype): # type: ignore class TestCollectionWCustomType(IntegrationTest): def setUp(self): super().setUp() - self.db.test.drop() + self.db.coll.drop() def tearDown(self): - self.db.test.drop() + self.db.coll.drop() def test_overflow_int_w_custom_decoder(self): type_registry = TypeRegistry(fallback_encoder=lambda val: str(val)) codec_options = CodecOptions(type_registry=type_registry) - collection = self.db.get_collection("test", codec_options=codec_options) + collection = self.db.get_collection("coll", codec_options=codec_options) collection.insert_one({"_id": 1, "data": 2**520}) ret = collection.find_one() @@ -649,7 +649,7 @@ def test_overflow_int_w_custom_decoder(self): def test_command_errors_w_custom_type_decoder(self): db = self.db test_doc = {"_id": 1, "data": "a"} - test = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + test = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) result = test.insert_one(test_doc) self.assertEqual(result.inserted_id, test_doc["_id"]) @@ -660,9 +660,9 @@ def test_find_w_custom_type_decoder(self): db = self.db input_docs = [{"x": Int64(k)} for k in [1, 2, 3]] for doc in input_docs: - db.test.insert_one(doc) + db.coll.insert_one(doc) - test = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + test = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) for doc in test.find({}, batch_size=1): self.assertIsInstance(doc["x"], UndecipherableInt64Type) @@ -671,10 +671,10 @@ def run_test(doc_cls): db = self.db input_docs = [{"x": Int64(k)} for k in [1, 2, 3]] for doc in input_docs: - db.test.insert_one(doc) + db.coll.insert_one(doc) test = db.get_collection( - "test", + "coll", codec_options=CodecOptions( type_registry=TypeRegistry([UndecipherableIntDecoder()]), document_class=doc_cls ), @@ -688,7 +688,7 @@ def run_test(doc_cls): def test_aggregate_w_custom_type_decoder(self): db = self.db - db.test.insert_many( + db.coll.insert_many( [ {"status": "in progress", "qty": Int64(1)}, {"status": "complete", "qty": Int64(10)}, @@ -697,7 +697,7 @@ def test_aggregate_w_custom_type_decoder(self): {"status": "in progress", "qty": Int64(1)}, ] ) - test = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + test = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) pipeline: list = [ {"$match": {"status": "complete"}}, @@ -711,9 +711,9 @@ def test_aggregate_w_custom_type_decoder(self): self.assertEqual(res["total_qty"].value, 20) def test_distinct_w_custom_type(self): - self.db.drop_collection("test") + self.db.drop_collection("coll") - test = self.db.get_collection("test", codec_options=UNINT_CODECOPTS) + test = self.db.get_collection("coll", codec_options=UNINT_CODECOPTS) values = [ UndecipherableInt64Type(1), UndecipherableInt64Type(2), @@ -726,7 +726,7 @@ def test_distinct_w_custom_type(self): def test_find_one_and__w_custom_type_decoder(self): db = self.db - c = db.get_collection("test", codec_options=UNINT_DECODER_CODECOPTS) + c = db.get_collection("coll", codec_options=UNINT_DECODER_CODECOPTS) c.insert_one({"_id": 1, "x": Int64(1)}) doc = c.find_one_and_update( @@ -921,13 +921,13 @@ class TestCollectionChangeStreamsWCustomTypes(IntegrationTest, ChangeStreamsWCus @client_context.require_change_streams def setUp(self): super().setUp() - self.db.test.delete_many({}) + self.db.coll.delete_many({}) def tearDown(self): self.input_target.drop() def create_targets(self, *args, **kwargs): - self.watched_target = self.db.get_collection("test", *args, **kwargs) + self.watched_target = self.db.get_collection("coll", *args, **kwargs) self.input_target = self.watched_target # Ensure the collection exists and is empty. self.input_target.insert_one({}) @@ -938,7 +938,7 @@ class TestDatabaseChangeStreamsWCustomTypes(IntegrationTest, ChangeStreamsWCusto @client_context.require_change_streams def setUp(self): super().setUp() - self.db.test.delete_many({}) + self.db.coll.delete_many({}) def tearDown(self): self.input_target.drop() @@ -946,7 +946,7 @@ def tearDown(self): def create_targets(self, *args, **kwargs): self.watched_target = self.client.get_database(self.db.name, *args, **kwargs) - self.input_target = self.watched_target.test + self.input_target = self.watched_target.coll # Insert a record to ensure db, coll are created. self.input_target.insert_one({"data": "dummy"}) @@ -955,7 +955,7 @@ class TestClusterChangeStreamsWCustomTypes(IntegrationTest, ChangeStreamsWCustom @client_context.require_change_streams def setUp(self): super().setUp() - self.db.test.delete_many({}) + self.db.coll.delete_many({}) def tearDown(self): self.input_target.drop() @@ -967,7 +967,7 @@ def create_targets(self, *args, **kwargs): kwargs["type_registry"] = codec_options.type_registry kwargs["document_class"] = codec_options.document_class self.watched_target = self.rs_client(*args, **kwargs) - self.input_target = self.watched_target[self.db.name].test + self.input_target = self.watched_target[self.db.name].coll # Insert a record to ensure db, coll are created. self.input_target.insert_one({"data": "dummy"}) diff --git a/test/test_database.py b/test/test_database.py index f1932c86fa..312297b2c9 100644 --- a/test/test_database.py +++ b/test/test_database.py @@ -149,11 +149,11 @@ def test_repr(self): def test_create_collection(self): db = Database(self.client, "pymongo_test") - db.test.insert_one({"hello": "world"}) + db.coll.insert_one({"hello": "world"}) with self.assertRaises(CollectionInvalid): - db.create_collection("test") + db.create_collection("coll") - db.drop_collection("test") + db.drop_collection("coll") with self.assertRaises(TypeError): db.create_collection(5) # type: ignore[arg-type] @@ -162,10 +162,10 @@ def test_create_collection(self): with self.assertRaises(InvalidName): db.create_collection("coll..ection") # type: ignore[arg-type] - test = db.create_collection("test") - self.assertIn("test", db.list_collection_names()) - test.insert_one({"hello": "world"}) - self.assertEqual((db.test.find_one())["hello"], "world") + coll_obj = db.create_collection("coll") + self.assertIn("coll", db.list_collection_names()) + coll_obj.insert_one({"hello": "world"}) + self.assertEqual((db.coll.find_one())["hello"], "world") db.drop_collection("test.foo") db.create_collection("test.foo") @@ -175,12 +175,12 @@ def test_create_collection(self): def test_list_collection_names(self): db = Database(self.client, "pymongo_test") - db.test.insert_one({"dummy": "object"}) - db.test.mike.insert_one({"dummy": "object"}) + db.coll.insert_one({"dummy": "object"}) + db.coll.mike.insert_one({"dummy": "object"}) colls = db.list_collection_names() - self.assertIn("test", colls) - self.assertIn("test.mike", colls) + self.assertIn("coll", colls) + self.assertIn("coll.mike", colls) for coll in colls: self.assertNotIn("$", coll) @@ -245,15 +245,15 @@ def test_check_exists(self): def test_list_collections(self): self.client.drop_database("pymongo_test") db = Database(self.client, "pymongo_test") - db.test.insert_one({"dummy": "object"}) - db.test.mike.insert_one({"dummy": "object"}) + db.coll.insert_one({"dummy": "object"}) + db.coll.mike.insert_one({"dummy": "object"}) results = db.list_collections() colls = [result["name"] for result in results] # All the collections present. - self.assertIn("test", colls) - self.assertIn("test.mike", colls) + self.assertIn("coll", colls) + self.assertIn("coll.mike", colls) # No collection containing a '$'. for coll in colls: @@ -271,23 +271,23 @@ def test_list_collections(self): coll_cnt: dict = {} # Check if there are any collections which don't exist. - self.assertLessEqual(set(colls), {"test", "test.mike", "system.indexes"}) + self.assertLessEqual(set(colls), {"coll", "coll.mike", "system.indexes"}) - colls = (db.list_collections(filter={"name": {"$regex": "^test$"}})).to_list() + colls = (db.list_collections(filter={"name": {"$regex": "^coll$"}})).to_list() self.assertEqual(1, len(colls)) - colls = (db.list_collections(filter={"name": {"$regex": "^test.mike$"}})).to_list() + colls = (db.list_collections(filter={"name": {"$regex": "^coll.mike$"}})).to_list() self.assertEqual(1, len(colls)) - db.drop_collection("test") + db.drop_collection("coll") - db.create_collection("test", capped=True, size=4096) + db.create_collection("coll", capped=True, size=4096) results = db.list_collections(filter={"options.capped": True}) colls = [result["name"] for result in results] # Checking only capped collections are present - self.assertIn("test", colls) - self.assertNotIn("test.mike", colls) + self.assertIn("coll", colls) + self.assertNotIn("coll.mike", colls) # No collection containing a '$'. for coll in colls: @@ -305,7 +305,7 @@ def test_list_collections(self): coll_cnt = {} # Check if there are any collections which don't exist. - self.assertLessEqual(set(colls), {"test", "system.indexes"}) + self.assertLessEqual(set(colls), {"coll", "system.indexes"}) self.client.drop_database("pymongo_test") @@ -327,61 +327,61 @@ def test_drop_collection(self): with self.assertRaises(TypeError): db.drop_collection(None) # type: ignore[arg-type] - db.test.insert_one({"dummy": "object"}) - self.assertIn("test", db.list_collection_names()) - db.drop_collection("test") - self.assertNotIn("test", db.list_collection_names()) + db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", db.list_collection_names()) + db.drop_collection("coll") + self.assertNotIn("coll", db.list_collection_names()) - db.test.insert_one({"dummy": "object"}) - self.assertIn("test", db.list_collection_names()) - db.drop_collection("test") - self.assertNotIn("test", db.list_collection_names()) + db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", db.list_collection_names()) + db.drop_collection("coll") + self.assertNotIn("coll", db.list_collection_names()) - db.test.insert_one({"dummy": "object"}) - self.assertIn("test", db.list_collection_names()) - db.drop_collection(db.test) - self.assertNotIn("test", db.list_collection_names()) + db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", db.list_collection_names()) + db.drop_collection(db.coll) + self.assertNotIn("coll", db.list_collection_names()) - db.test.insert_one({"dummy": "object"}) - self.assertIn("test", db.list_collection_names()) - db.test.drop() - self.assertNotIn("test", db.list_collection_names()) - db.test.drop() + db.coll.insert_one({"dummy": "object"}) + self.assertIn("coll", db.list_collection_names()) + db.coll.drop() + self.assertNotIn("coll", db.list_collection_names()) + db.coll.drop() - db.drop_collection(db.test.doesnotexist) + db.drop_collection(db.coll.doesnotexist) if client_context.is_rs: db_wc = Database(self.client, "pymongo_test", write_concern=IMPOSSIBLE_WRITE_CONCERN) with self.assertRaises(WriteConcernError): - db_wc.drop_collection("test") + db_wc.drop_collection("coll") def test_validate_collection(self): - db = self.client.pymongo_test + db = self.db with self.assertRaises(TypeError): db.validate_collection(5) # type: ignore[arg-type] with self.assertRaises(TypeError): db.validate_collection(None) # type: ignore[arg-type] - db.test.insert_one({"dummy": "object"}) + db.coll.insert_one({"dummy": "object"}) with self.assertRaises(OperationFailure): - db.validate_collection("test.doesnotexist") + db.validate_collection("coll.doesnotexist") with self.assertRaises(OperationFailure): - db.validate_collection(db.test.doesnotexist) + db.validate_collection(db.coll.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)) + self.assertTrue(db.validate_collection("coll")) + self.assertTrue(db.validate_collection(db.coll)) + self.assertTrue(db.validate_collection(db.coll, full=True)) + self.assertTrue(db.validate_collection(db.coll, scandata=True)) + self.assertTrue(db.validate_collection(db.coll, scandata=True, full=True)) + self.assertTrue(db.validate_collection(db.coll, True, True)) @client_context.require_no_standalone def test_validate_collection_background(self): - db = self.client.pymongo_test.with_options(write_concern=WriteConcern(w="majority")) - db.test.insert_one({"dummy": "object"}) - coll = db.test + db = self.db.with_options(write_concern=WriteConcern(w="majority")) + db.coll.insert_one({"dummy": "object"}) + coll = db.coll self.assertTrue(db.validate_collection(coll, background=False)) # The inMemory storage engine does not support background=True. if client_context.storage_engine != "inMemory": @@ -407,12 +407,12 @@ def test_command(self): # We use 'aggregate' as our example command, since it's an easy way to # retrieve a BSON regex from a collection using a command. def test_command_with_regex(self): - db = self.client.pymongo_test - db.test.drop() - db.test.insert_one({"r": re.compile(".*")}) - db.test.insert_one({"r": Regex(".*")}) + db = self.db + db.coll.drop() + db.coll.insert_one({"r": re.compile(".*")}) + db.coll.insert_one({"r": Regex(".*")}) - result = db.command("aggregate", "test", pipeline=[], cursor={}) + result = db.command("aggregate", "coll", pipeline=[], cursor={}) for doc in result["cursor"]["firstBatch"]: self.assertIsInstance(doc["r"], Regex) @@ -422,23 +422,23 @@ def test_command_bulkWrite(self): self.client.admin.command( { "bulkWrite": 1, - "nsInfo": [{"ns": self.db.test.full_name}], + "nsInfo": [{"ns": self.db.coll.full_name}], "ops": [{"insert": 0, "document": {}}], } ) - self.db.command({"insert": "test", "documents": [{}]}) - self.db.command({"update": "test", "updates": [{"q": {}, "u": {"$set": {"x": 1}}}]}) - self.db.command({"delete": "test", "deletes": [{"q": {}, "limit": 1}]}) - self.db.test.drop() + self.db.command({"insert": "coll", "documents": [{}]}) + self.db.command({"update": "coll", "updates": [{"q": {}, "u": {"$set": {"x": 1}}}]}) + self.db.command({"delete": "coll", "deletes": [{"q": {}, "limit": 1}]}) + self.db.coll.drop() def test_cursor_command(self): - db = self.client.pymongo_test - db.test.drop() + db = self.db + db.coll.drop() docs = [{"_id": i, "doc": i} for i in range(3)] - db.test.insert_many(docs) + db.coll.insert_many(docs) - cursor = db.cursor_command("find", "test") + cursor = db.cursor_command("find", "coll") self.assertIsInstance(cursor, CommandCursor) @@ -447,7 +447,7 @@ def test_cursor_command(self): def test_cursor_command_invalid(self): with self.assertRaises(InvalidOperation): - self.db.cursor_command("usersInfo", "test") + self.db.cursor_command("usersInfo", "coll") @client_context.require_no_fips def test_password_digest(self): @@ -473,22 +473,22 @@ def test_id_ordering(self): # guarantee any particular order. This will never # work right in any Python or environment # with hash randomization enabled (e.g. tox). - db = self.client.pymongo_test - db.test.drop() - db.test.insert_one(SON([("hello", "world"), ("_id", 5)])) + db = self.db + db.coll.drop() + db.coll.insert_one(SON([("hello", "world"), ("_id", 5)])) db = self.client.get_database( "pymongo_test", codec_options=CodecOptions(document_class=SON[str, Any]) ) - cursor = db.test.find() + cursor = db.coll.find() for x in cursor: for k, _v in x.items(): self.assertEqual(k, "_id") break def test_deref(self): - db = self.client.pymongo_test - db.test.drop() + db = self.db + db.coll.drop() with self.assertRaises(TypeError): db.dereference(5) # type: ignore[arg-type] @@ -497,106 +497,106 @@ def test_deref(self): with self.assertRaises(TypeError): db.dereference(None) # type: ignore[arg-type] - self.assertEqual(None, db.dereference(DBRef("test", ObjectId()))) + self.assertEqual(None, db.dereference(DBRef("coll", ObjectId()))) obj: dict[str, Any] = {"x": True} - 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"))) + key = (db.coll.insert_one(obj)).inserted_id + self.assertEqual(obj, db.dereference(DBRef("coll", key))) + self.assertEqual(obj, db.dereference(DBRef("coll", key, "pymongo_test"))) with self.assertRaises(ValueError): - db.dereference(DBRef("test", key, "foo")) + db.dereference(DBRef("coll", key, "foo")) - self.assertEqual(None, db.dereference(DBRef("test", 4))) + self.assertEqual(None, db.dereference(DBRef("coll", 4))) obj = {"_id": 4} - db.test.insert_one(obj) - self.assertEqual(obj, db.dereference(DBRef("test", 4))) + db.coll.insert_one(obj) + self.assertEqual(obj, db.dereference(DBRef("coll", 4))) def test_deref_kwargs(self): - db = self.client.pymongo_test - db.test.drop() + db = self.db + db.coll.drop() - db.test.insert_one({"_id": 4, "foo": "bar"}) + db.coll.insert_one({"_id": 4, "foo": "bar"}) db = self.client.get_database( "pymongo_test", codec_options=CodecOptions(document_class=SON[str, Any]) ) self.assertEqual( - SON([("foo", "bar")]), db.dereference(DBRef("test", 4), projection={"_id": False}) + SON([("foo", "bar")]), db.dereference(DBRef("coll", 4), projection={"_id": False}) ) # TODO some of these tests belong in the collection level testing. def test_insert_find_one(self): - db = self.client.pymongo_test - db.test.drop() + db = self.db + db.coll.drop() a_doc = SON({"hello": "world"}) - a_key = (db.test.insert_one(a_doc)).inserted_id + a_key = (db.coll.insert_one(a_doc)).inserted_id self.assertIsInstance(a_doc["_id"], ObjectId) self.assertEqual(a_doc["_id"], a_key) - self.assertEqual(a_doc, db.test.find_one({"_id": a_doc["_id"]})) - self.assertEqual(a_doc, db.test.find_one(a_key)) - self.assertEqual(None, db.test.find_one(ObjectId())) - self.assertEqual(a_doc, db.test.find_one({"hello": "world"})) - self.assertEqual(None, db.test.find_one({"hello": "test"})) + self.assertEqual(a_doc, db.coll.find_one({"_id": a_doc["_id"]})) + self.assertEqual(a_doc, db.coll.find_one(a_key)) + self.assertEqual(None, db.coll.find_one(ObjectId())) + self.assertEqual(a_doc, db.coll.find_one({"hello": "world"})) + self.assertEqual(None, db.coll.find_one({"hello": "test"})) - b = db.test.find_one() + b = db.coll.find_one() assert b is not None b["hello"] = "mike" - db.test.replace_one({"_id": b["_id"]}, b) + db.coll.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)) - self.assertEqual(b, db.test.find_one()) + self.assertNotEqual(a_doc, db.coll.find_one(a_key)) + self.assertEqual(b, db.coll.find_one(a_key)) + self.assertEqual(b, db.coll.find_one()) count = 0 - for _ in db.test.find(): + for _ in db.coll.find(): count += 1 self.assertEqual(count, 1) def test_long(self): - db = self.client.pymongo_test - db.test.drop() - db.test.insert_one({"x": 9223372036854775807}) - retrieved = (db.test.find_one())["x"] + db = self.db + db.coll.drop() + db.coll.insert_one({"x": 9223372036854775807}) + retrieved = (db.coll.find_one())["x"] self.assertEqual(Int64(9223372036854775807), retrieved) self.assertIsInstance(retrieved, Int64) - db.test.delete_many({}) - db.test.insert_one({"x": Int64(1)}) - retrieved = (db.test.find_one())["x"] + db.coll.delete_many({}) + db.coll.insert_one({"x": Int64(1)}) + retrieved = (db.coll.find_one())["x"] self.assertEqual(Int64(1), retrieved) self.assertIsInstance(retrieved, Int64) def test_delete(self): - db = self.client.pymongo_test - db.test.drop() + db = self.db + db.coll.drop() - db.test.insert_one({"x": 1}) - db.test.insert_one({"x": 2}) - db.test.insert_one({"x": 3}) + db.coll.insert_one({"x": 1}) + db.coll.insert_one({"x": 2}) + db.coll.insert_one({"x": 3}) length = 0 - for _ in db.test.find(): + for _ in db.coll.find(): length += 1 self.assertEqual(length, 3) - db.test.delete_one({"x": 1}) + db.coll.delete_one({"x": 1}) length = 0 - for _ in db.test.find(): + for _ in db.coll.find(): length += 1 self.assertEqual(length, 2) - db.test.delete_one(db.test.find_one()) # type: ignore[arg-type] - db.test.delete_one(db.test.find_one()) # type: ignore[arg-type] - self.assertEqual(db.test.find_one(), None) + db.coll.delete_one(db.coll.find_one()) # type: ignore[arg-type] + db.coll.delete_one(db.coll.find_one()) # type: ignore[arg-type] + self.assertEqual(db.coll.find_one(), None) - db.test.insert_one({"x": 1}) - db.test.insert_one({"x": 2}) - db.test.insert_one({"x": 3}) + db.coll.insert_one({"x": 1}) + db.coll.insert_one({"x": 2}) + db.coll.insert_one({"x": 3}) - self.assertTrue(db.test.find_one({"x": 2})) - db.test.delete_one({"x": 2}) - self.assertFalse(db.test.find_one({"x": 2})) + self.assertTrue(db.coll.find_one({"x": 2})) + db.coll.delete_one({"x": 2}) + self.assertFalse(db.coll.find_one({"x": 2})) - self.assertTrue(db.test.find_one()) - db.test.delete_many({}) - self.assertFalse(db.test.find_one()) + self.assertTrue(db.coll.find_one()) + db.coll.delete_many({}) + self.assertFalse(db.coll.find_one()) def test_command_response_without_ok(self): # Sometimes (SERVER-10891) the server's response to a badly-formatted @@ -617,25 +617,25 @@ def test_command_response_without_ok(self): def test_command_max_time_ms(self): self.client.admin.command("configureFailPoint", "maxTimeAlwaysTimeOut", mode="alwaysOn") try: - db = self.client.pymongo_test - db.command("count", "test") + db = self.db + db.command("count", "coll") with self.assertRaises(ExecutionTimeout): - db.command("count", "test", maxTimeMS=1) + db.command("count", "coll", maxTimeMS=1) pipeline = [{"$project": {"name": 1, "count": 1}}] # Database command helper. - db.command("aggregate", "test", pipeline=pipeline, cursor={}) + db.command("aggregate", "coll", pipeline=pipeline, cursor={}) with self.assertRaises(ExecutionTimeout): db.command( "aggregate", - "test", + "coll", pipeline=pipeline, cursor={}, maxTimeMS=1, ) # Collection helper. - db.test.aggregate(pipeline=pipeline) + db.coll.aggregate(pipeline=pipeline) with self.assertRaises(ExecutionTimeout): - db.test.aggregate(pipeline, maxTimeMS=1) + db.coll.aggregate(pipeline, maxTimeMS=1) finally: self.client.admin.command("configureFailPoint", "maxTimeAlwaysTimeOut", mode="off") diff --git a/test/test_decimal128.py b/test/test_decimal128.py index 5727dc5233..9ea20ed84f 100644 --- a/test/test_decimal128.py +++ b/test/test_decimal128.py @@ -29,7 +29,7 @@ class TestDecimal128(unittest.TestCase): @client_context.require_connection def test_round_trip(self): - coll = client_context.client.pymongo_test.test + coll = client_context.client.pymongo_test.coll coll.drop() dec128 = Decimal128.from_bid(b"\x00@cR\xbf\xc6\x01\x00\x00\x00\x00\x00\x00\x00\x1c0") diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 10f6224e85..2086f56a2b 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -426,7 +426,7 @@ def test_connection_close_does_not_block_other_operations(self): "pool initialized with 10 connections", ) - client.db.test.insert_one({"x": 1}) + client.db.coll.insert_one({"x": 1}) close_delay = 0.1 latencies = [] should_exit = [] @@ -434,7 +434,7 @@ def test_connection_close_does_not_block_other_operations(self): def run_task(): while True: start_time = time.monotonic() - client.db.test.find_one({}) + client.db.coll.find_one({}) elapsed = time.monotonic() - start_time latencies.append(elapsed) if should_exit: @@ -523,13 +523,13 @@ def teardown(): ) # Make sure the collection has at least one document. - client.test.test.delete_many({}) - client.test.test.insert_one({}) + client.db.coll.delete_many({}) + client.db.coll.insert_one({}) # Run a slow operation to tie up the connection. def target(): try: - client.test.test.find_one({"$where": delay(0.1)}) + client.db.coll.find_one({"$where": delay(0.1)}) except ConnectionFailure: pass diff --git a/test/test_encryption.py b/test/test_encryption.py index 036d394a1a..1e14d1c1ad 100644 --- a/test/test_encryption.py +++ b/test/test_encryption.py @@ -381,7 +381,7 @@ def _test_auto_encrypt(self, opts): {"_id": 4, "ssn": "444"}, {"_id": 5, "ssn": "555"}, ] - encrypted_coll = client.pymongo_test.test + encrypted_coll = client.pymongo_test.coll encrypted_coll.insert_one(docs[0]) encrypted_coll.insert_many(docs[1:3]) unack = encrypted_coll.with_options(write_concern=WriteConcern(w=0)) @@ -389,12 +389,12 @@ def _test_auto_encrypt(self, opts): unack.insert_many(docs[4:], ordered=False) def count_documents(): - return self.db.test.count_documents({}) == len(docs) + return self.db.coll.count_documents({}) == len(docs) wait_until(count_documents, "insert documents with w=0") # Database.command auto decrypts. - res = client.pymongo_test.command("find", "test", filter={"ssn": "000"}) + res = client.pymongo_test.command("find", "coll", filter={"ssn": "000"}) decrypted_docs = res["cursor"]["firstBatch"] self.assertEqual(decrypted_docs, [{"_id": 0, "ssn": "000"}]) @@ -419,7 +419,7 @@ def count_documents(): self.assertEqual(set(decrypted_ssns), {d["ssn"] for d in docs}) # Make sure the field is actually encrypted. - for encrypted_doc in self.db.test.find(): + for encrypted_doc in self.db.coll.find(): self.assertIsInstance(encrypted_doc["_id"], int) self.assertEncrypted(encrypted_doc["ssn"]) @@ -430,15 +430,15 @@ def count_documents(): def test_auto_encrypt(self): # Configure the encrypted field via jsonSchema. json_schema = json_data("custom", "schema.json") - create_with_schema(self.db.test, json_schema) - self.addCleanup(self.db.test.drop) + create_with_schema(self.db.coll, json_schema) + self.addCleanup(self.db.coll.drop) opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys") self._test_auto_encrypt(opts) def test_auto_encrypt_local_schema_map(self): # Configure the encrypted field via the local schema_map option. - schemas = {"pymongo_test.test": json_data("custom", "schema.json")} + schemas = {"pymongo_test.coll": json_data("custom", "schema.json")} opts = AutoEncryptionOpts(KMS_PROVIDERS, "keyvault.datakeys", schema_map=schemas) self._test_auto_encrypt(opts) @@ -481,7 +481,7 @@ def test_upsert_uuid_standard_encrypt(self): client = self.rs_or_single_client(auto_encryption_opts=opts) options = CodecOptions(uuid_representation=UuidRepresentation.STANDARD) - encrypted_coll = client.pymongo_test.test + encrypted_coll = client.pymongo_test.coll coll = encrypted_coll.with_options(codec_options=options) uuids = [uuid.uuid4() for _ in range(3)] result = coll.bulk_write( @@ -519,17 +519,17 @@ def test_raise_unsupported_error(self): client = self.rs_or_single_client(auto_encryption_opts=opts) msg = "find_raw_batches does not support auto encryption" with self.assertRaisesRegex(InvalidOperation, msg): - client.test.test.find_raw_batches({}) + client.db.coll.find_raw_batches({}) msg = "aggregate_raw_batches does not support auto encryption" with self.assertRaisesRegex(InvalidOperation, msg): - client.test.test.aggregate_raw_batches([]) + client.db.coll.aggregate_raw_batches([]) # The auto-encryption guard runs at cursor iteration, before the wire-version # check in _Query.use_command, so it is the error regardless of deployment. msg = "exhaust cursors do not support auto encryption" with self.assertRaisesRegex(InvalidOperation, msg): - next(client.test.test.find(cursor_type=CursorType.EXHAUST)) + next(client.db.coll.find(cursor_type=CursorType.EXHAUST)) class TestExplicitSimple(EncryptionIntegrationTest): @@ -3889,12 +3889,12 @@ def setUp(self) -> None: def test_implicit_session_ignored_when_unsupported(self): self.listener.reset() with self.assertRaises(OperationFailure): - self.mongocryptd_client.db.test.find_one() + self.mongocryptd_client.db.coll.find_one() self.assertNotIn("lsid", self.listener.started_events[0].command) with self.assertRaises(OperationFailure): - self.mongocryptd_client.db.test.insert_one({"x": 1}) + self.mongocryptd_client.db.coll.insert_one({"x": 1}) self.assertNotIn("lsid", self.listener.started_events[1].command) @@ -3906,11 +3906,11 @@ def test_explicit_session_errors_when_unsupported(self): with self.assertRaisesRegex( ConfigurationError, r"Sessions are not supported by this MongoDB deployment" ): - self.mongocryptd_client.db.test.find_one(session=s) + self.mongocryptd_client.db.coll.find_one(session=s) with self.assertRaisesRegex( ConfigurationError, r"Sessions are not supported by this MongoDB deployment" ): - self.mongocryptd_client.db.test.insert_one({"x": 1}, session=s) + self.mongocryptd_client.db.coll.insert_one({"x": 1}, session=s) self.mongocryptd_client.close() diff --git a/test/test_grid_file.py b/test/test_grid_file.py index dcd186361c..21c2c29d74 100644 --- a/test/test_grid_file.py +++ b/test/test_grid_file.py @@ -61,7 +61,7 @@ class TestGridFileNoConnect(UnitTest): @classmethod def setUpClass(cls): - cls.db = MongoClient(connect=False).pymongo_test + cls.db = MongoClient(connect=False)["pymongo_test"] def test_grid_in_custom_opts(self): self.assertRaises(TypeError, GridIn, "foo") diff --git a/test/test_index_management.py b/test/test_index_management.py index 557f9ab93d..a603fd3258 100644 --- a/test/test_index_management.py +++ b/test/test_index_management.py @@ -49,7 +49,7 @@ class TestCreateSearchIndex(IntegrationTest): def test_inputs(self): listener = AllowListEventListener("createSearchIndexes") client = self.simple_client(event_listeners=[listener]) - coll = client.test.test + coll = client.db.coll coll.drop() definition = dict(mappings=dict(dynamic=True)) model_kwarg_list: list[Mapping[str, Any]] = [ diff --git a/test/test_json_util_integration.py b/test/test_json_util_integration.py index 129f28c2ef..5772309842 100644 --- a/test/test_json_util_integration.py +++ b/test/test_json_util_integration.py @@ -14,7 +14,8 @@ class TestJsonUtilRoundtrip(IntegrationTest): def test_cursor(self): db = self.db - db.drop_collection("test") + db.drop_collection("coll") + self.addCleanup(db.drop_collection, "coll") docs: list[MutableMapping[str, Any]] = [ {"foo": [1, 2]}, {"bar": {"hello": "world"}}, @@ -23,7 +24,7 @@ def test_cursor(self): {"dbref": {"_ref": DBRef("simple", ObjectId("509b8db456c02c5ab7e63c34"))}}, ] - db.test.insert_many(docs) - reloaded_docs = json_util.loads(json_util.dumps((db.test.find()).to_list())) + db.coll.insert_many(docs) + reloaded_docs = json_util.loads(json_util.dumps((db.coll.find()).to_list())) for doc in docs: self.assertIn(doc, reloaded_docs) diff --git a/test/test_load_balancer.py b/test/test_load_balancer.py index ab549f2288..3d6606e66e 100644 --- a/test/test_load_balancer.py +++ b/test/test_load_balancer.py @@ -65,12 +65,12 @@ def test_exhaust_cursor(self): def test_connections_are_only_returned_once(self): pool = get_pool(self.client) n_conns = len(pool.conns) - self.db.test.find_one({}) + self.db.coll.find_one({}) # On PyPy it can take a few rounds to collect the cursor. for _ in range(3): gc.collect() self.assertEqual(len(pool.conns), n_conns) - (self.db.test.aggregate([{"$limit": 1}])).to_list() + (self.db.coll.aggregate([{"$limit": 1}])).to_list() # On PyPy it can take a few rounds to collect the cursor. for _ in range(3): gc.collect() @@ -80,7 +80,7 @@ def test_connections_are_only_returned_once(self): def test_unpin_committed_transaction(self): client = self.rs_client() pool = get_pool(client) - coll = client[self.db.name].test + coll = client[self.db.name].coll with client.start_session() as session: with session.start_transaction(): self.assertEqual(pool.active_sockets, 0) @@ -110,7 +110,7 @@ def create_resource(coll): def _test_no_gc_deadlock(self, create_resource): client = self.rs_client() pool = get_pool(client) - coll = client[self.db.name].test + coll = client[self.db.name].coll coll.insert_many([{} for _ in range(10)]) self.assertEqual(pool.active_sockets, 0) # Cause the initial find attempt to fail to induce a reference cycle. @@ -172,7 +172,7 @@ def test_session_gc(self): wait_until(lambda: pool.active_sockets == 0, "return socket") # Run another operation to ensure the socket still works. - client[self.db.name].test.delete_many({}) + client[self.db.name].coll.delete_many({}) class PoolLocker(ExceptionCatchingTask): diff --git a/test/test_logger.py b/test/test_logger.py index c7a4058d7b..781b7b5f11 100644 --- a/test/test_logger.py +++ b/test/test_logger.py @@ -26,6 +26,10 @@ # https://github.com/mongodb/specifications/tree/master/source/command-logging-and-monitoring/tests#prose-tests class TestLogger(IntegrationTest): + def tearDown(self) -> None: + self.db.coll.drop() + super().tearDown() + def _get_command_log(self, records, command_name, status): # PyPy's GC is non-deterministic, so cleanup commands from earlier tests can pollute the logs, # filter for the specific command and status we want @@ -42,7 +46,7 @@ def test_default_truncation_limit(self): with patch.dict("os.environ"): os.environ.pop("MONGOB_LOG_MAX_DOCUMENT_LENGTH", None) with self.assertLogs("pymongo.command", level="DEBUG") as cm: - db.test.insert_many(docs) + db.coll.insert_many(docs) cmd_started_log = self._get_command_log( cm.records, "insert", _CommandStatusMessage.STARTED @@ -55,7 +59,7 @@ def test_default_truncation_limit(self): self.assertLessEqual(len(cmd_succeeded_log["reply"]), _DEFAULT_DOCUMENT_LENGTH + 3) with self.assertLogs("pymongo.command", level="DEBUG") as cm: - db.test.find({}).to_list() + db.coll.find({}).to_list() cmd_succeeded_log = self._get_command_log( cm.records, "find", _CommandStatusMessage.SUCCEEDED ) @@ -96,7 +100,7 @@ def test_truncation_multi_byte_codepoints(self): for length in document_lengths: with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": length}): with self.assertLogs("pymongo.command", level="DEBUG") as cm: - self.db.test.insert_one({"x": multi_byte_char_str}) + self.db.coll.insert_one({"x": multi_byte_char_str}) cmd_started_log = self._get_command_log( cm.records, "insert", _CommandStatusMessage.STARTED )["command"] @@ -110,18 +114,18 @@ def test_logging_without_listeners(self): c = self.single_client() self.assertEqual(len(c._event_listeners.event_listeners()), 0) with self.assertLogs("pymongo.connection", level="DEBUG") as cm: - c.db.test.insert_one({"x": "1"}) + c.db.coll.insert_one({"x": "1"}) self.assertGreater(len(cm.records), 0) with self.assertLogs("pymongo.command", level="DEBUG") as cm: - c.db.test.insert_one({"x": "1"}) + c.db.coll.insert_one({"x": "1"}) self.assertGreater(len(cm.records), 0) with self.assertLogs("pymongo.serverSelection", level="DEBUG") as cm: - c.db.test.insert_one({"x": "1"}) + c.db.coll.insert_one({"x": "1"}) self.assertGreater(len(cm.records), 0) @client_context.require_failCommand_fail_point def test_logging_retry_read_attempts(self): - self.db.test.insert_one({"x": "1"}) + self.db.coll.insert_one({"x": "1"}) with self.fail_point( { @@ -134,7 +138,7 @@ def test_logging_retry_read_attempts(self): } ): with self.assertLogs("pymongo.command", level="DEBUG") as cm: - self.db.test.find_one({"x": "1"}) + self.db.coll.find_one({"x": "1"}) retry_messages = [ r.getMessage() for r in cm.records if "Retrying read attempt" in r.getMessage() @@ -155,7 +159,7 @@ def test_logging_retry_write_attempts(self): } ): with self.assertLogs("pymongo.command", level="DEBUG") as cm: - self.db.test.insert_one({"x": "1"}) + self.db.coll.insert_one({"x": "1"}) retry_messages = [ r.getMessage() for r in cm.records if "Retrying write attempt" in r.getMessage() diff --git a/test/test_max_staleness.py b/test/test_max_staleness.py index a5a5561096..a695e2d208 100644 --- a/test/test_max_staleness.py +++ b/test/test_max_staleness.py @@ -124,7 +124,8 @@ def test_max_staleness_zero(self): def test_last_write_date(self): # From max-staleness-tests.rst, "Parse lastWriteDate". client = self.rs_or_single_client(heartbeatFrequencyMS=500) - client.pymongo_test.test.insert_one({}) + self.addCleanup(client.pymongo_test.coll.drop) + client.pymongo_test.coll.insert_one({}) # Wait for the server description to be updated. time.sleep(1) server = client._topology.select_server(writable_server_selector, _Op.TEST) @@ -133,7 +134,7 @@ def test_last_write_date(self): # The first last_write_date may correspond to a internal server write, # sleep so that the next write does not occur within the same second. time.sleep(1) - client.pymongo_test.test.insert_one({}) + client.pymongo_test.coll.insert_one({}) # Wait for the server description to be updated. time.sleep(1) server = client._topology.select_server(writable_server_selector, _Op.TEST) diff --git a/test/test_monitoring.py b/test/test_monitoring.py index fde78a7c1e..4b28687f4b 100644 --- a/test/test_monitoring.py +++ b/test/test_monitoring.py @@ -61,6 +61,7 @@ def setUp(self) -> None: super().setUp() self.listener.reset() self.client = self.rs_or_single_client(event_listeners=[self.listener], retryWrites=False) + self.addCleanup(self.client.pymongo_test.coll.drop) def test_started_simple(self): self.client.pymongo_test.command("ping") @@ -105,14 +106,14 @@ def test_failed_simple(self): self.assertIsInstance(failed.duration_micros, int) def test_find_one(self): - self.client.pymongo_test.test.find_one() + self.client.pymongo_test.coll.find_one() started = self.listener.started_events[0] succeeded = self.listener.succeeded_events[0] self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(succeeded, monitoring.CommandSucceededEvent) self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("find", "test"), ("filter", {}), ("limit", 1), ("singleBatch", True)]), + SON([("find", "coll"), ("filter", {}), ("limit", 1), ("singleBatch", True)]), started.command, ) self.assertEqual("find", started.command_name) @@ -121,10 +122,10 @@ def test_find_one(self): self.assertIsInstance(started.request_id, int) def test_find_and_get_more(self): - self.client.pymongo_test.test.drop() - self.client.pymongo_test.test.insert_many([{} for _ in range(10)]) + self.client.pymongo_test.coll.drop() + self.client.pymongo_test.coll.insert_many([{} for _ in range(10)]) self.listener.reset() - cursor = self.client.pymongo_test.test.find(projection={"_id": False}, batch_size=4) + cursor = self.client.pymongo_test.coll.find(projection={"_id": False}, batch_size=4) for _ in range(4): next(cursor) cursor_id = cursor.cursor_id @@ -134,7 +135,7 @@ def test_find_and_get_more(self): self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( SON( - [("find", "test"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 4)] + [("find", "coll"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 4)] ), started.command, ) @@ -149,7 +150,7 @@ def test_find_and_get_more(self): self.assertEqual(cursor.address, succeeded.connection_id) csr = succeeded.reply["cursor"] self.assertEqual(csr["id"], cursor_id) - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(csr["firstBatch"], [{} for _ in range(4)]) self.listener.reset() @@ -162,7 +163,7 @@ def test_find_and_get_more(self): self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test"), ("batchSize", 4)]), + SON([("getMore", cursor_id), ("collection", "coll"), ("batchSize", 4)]), started.command, ) self.assertEqual("getMore", started.command_name) @@ -176,18 +177,18 @@ def test_find_and_get_more(self): self.assertEqual(cursor.address, succeeded.connection_id) csr = succeeded.reply["cursor"] self.assertEqual(csr["id"], cursor_id) - self.assertEqual(csr["ns"], "pymongo_test.test") + self.assertEqual(csr["ns"], "pymongo_test.coll") self.assertEqual(csr["nextBatch"], [{} for _ in range(4)]) finally: # Exhaust the cursor to avoid kill cursors. tuple(cursor.to_list()) def test_find_with_explain(self): - cmd = SON([("explain", SON([("find", "test"), ("filter", {})]))]) - self.client.pymongo_test.test.drop() - self.client.pymongo_test.test.insert_one({}) + cmd = SON([("explain", SON([("find", "coll"), ("filter", {})]))]) + self.client.pymongo_test.coll.drop() + self.client.pymongo_test.coll.insert_one({}) self.listener.reset() - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll # Test that we publish the unwrapped command. if self.client.is_mongos: coll = coll.with_options(read_preference=ReadPreference.PRIMARY_PREFERRED) @@ -209,7 +210,7 @@ def test_find_with_explain(self): self.assertEqual(res, succeeded.reply) def _test_find_options(self, query, expected_cmd): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll coll.drop() coll.create_index("x") coll.insert_many([{"x": i} for i in range(5)]) @@ -260,7 +261,7 @@ def test_find_options(self): } cmd = { - "find": "test", + "find": "coll", "filter": {}, "hint": SON([("x", 1)]), "comment": "this is a test", @@ -280,10 +281,10 @@ def test_find_options(self): self._test_find_options(query, cmd) def test_command_and_get_more(self): - self.client.pymongo_test.test.drop() - self.client.pymongo_test.test.insert_many([{"x": 1} for _ in range(10)]) + self.client.pymongo_test.coll.drop() + self.client.pymongo_test.coll.insert_many([{"x": 1} for _ in range(10)]) self.listener.reset() - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll # Test that we publish the unwrapped command. if self.client.is_mongos: coll = coll.with_options(read_preference=ReadPreference.PRIMARY_PREFERRED) @@ -298,7 +299,7 @@ def test_command_and_get_more(self): self.assertEqualCommand( SON( [ - ("aggregate", "test"), + ("aggregate", "coll"), ("pipeline", [{"$project": {"_id": False, "x": 1}}]), ("cursor", {"batchSize": 4}), ] @@ -316,7 +317,7 @@ def test_command_and_get_more(self): self.assertEqual(cursor.address, succeeded.connection_id) expected_cursor = { "id": cursor_id, - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "firstBatch": [{"x": 1} for _ in range(4)], } self.assertEqualCommand(expected_cursor, succeeded.reply.get("cursor")) @@ -329,7 +330,7 @@ def test_command_and_get_more(self): self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test"), ("batchSize", 4)]), + SON([("getMore", cursor_id), ("collection", "coll"), ("batchSize", 4)]), started.command, ) self.assertEqual("getMore", started.command_name) @@ -344,7 +345,7 @@ def test_command_and_get_more(self): expected_result = { "cursor": { "id": cursor_id, - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "nextBatch": [{"x": 1} for _ in range(4)], }, "ok": 1.0, @@ -356,7 +357,7 @@ def test_command_and_get_more(self): def test_get_more_failure(self): address = self.client.address - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll cursor_id = Int64(12345) cursor_doc = {"id": cursor_id, "firstBatch": [], "ns": coll.full_name} cursor = CommandCursor(coll, cursor_doc, address) @@ -369,7 +370,7 @@ def test_get_more_failure(self): failed = self.listener.failed_events[0] self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test")]), started.command + SON([("getMore", cursor_id), ("collection", "coll")]), started.command ) self.assertEqual("getMore", started.command_name) self.assertEqual(self.client.address, started.connection_id) @@ -392,7 +393,7 @@ def test_not_primary_error(self): self.listener.reset() error = None try: - client.pymongo_test.test.find_one_and_delete({}) + client.pymongo_test.coll.find_one_and_delete({}) except NotPrimaryError as exc: error = exc.errors started = self.listener.started_events[0] @@ -409,10 +410,10 @@ def test_not_primary_error(self): @client_context.require_exhaust_cursors def test_exhaust(self): - self.client.pymongo_test.test.drop() - self.client.pymongo_test.test.insert_many([{} for _ in range(11)]) + self.client.pymongo_test.coll.drop() + self.client.pymongo_test.coll.insert_many([{} for _ in range(11)]) self.listener.reset() - cursor = self.client.pymongo_test.test.find( + cursor = self.client.pymongo_test.coll.find( projection={"_id": False}, batch_size=5, cursor_type=CursorType.EXHAUST ) next(cursor) @@ -423,7 +424,7 @@ def test_exhaust(self): self.assertIsInstance(started, monitoring.CommandStartedEvent) self.assertEqualCommand( SON( - [("find", "test"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 5)] + [("find", "coll"), ("filter", {}), ("projection", {"_id": False}), ("batchSize", 5)] ), started.command, ) @@ -439,7 +440,7 @@ def test_exhaust(self): expected_result = { "cursor": { "id": cursor_id, - "ns": "pymongo_test.test", + "ns": "pymongo_test.coll", "firstBatch": [{} for _ in range(5)], }, "ok": 1, @@ -452,7 +453,7 @@ def test_exhaust(self): for event in self.listener.started_events: self.assertIsInstance(event, monitoring.CommandStartedEvent) self.assertEqualCommand( - SON([("getMore", cursor_id), ("collection", "test"), ("batchSize", 5)]), + SON([("getMore", cursor_id), ("collection", "coll"), ("batchSize", 5)]), event.command, ) self.assertEqual("getMore", event.command_name) @@ -470,9 +471,9 @@ def test_exhaust(self): def test_kill_cursors(self): with client_knobs(kill_cursor_frequency=0.01): - self.client.pymongo_test.test.drop() - self.client.pymongo_test.test.insert_many([{} for _ in range(10)]) - cursor = self.client.pymongo_test.test.find().batch_size(5) + self.client.pymongo_test.coll.drop() + self.client.pymongo_test.coll.insert_many([{} for _ in range(10)]) + cursor = self.client.pymongo_test.coll.find().batch_size(5) next(cursor) cursor_id = cursor.cursor_id self.listener.reset() @@ -503,7 +504,7 @@ def test_kill_cursors(self): ) def test_non_bulk_writes(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll coll.drop() self.listener.reset() @@ -818,7 +819,7 @@ def test_non_bulk_writes(self): def test_insert_many(self): # This always uses the bulk API. - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll coll.drop() self.listener.reset() @@ -857,7 +858,7 @@ def test_insert_many(self): self.assertEqual(6, count) def test_insert_many_unacknowledged(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll coll.drop() unack_coll = coll.with_options(write_concern=WriteConcern(w=0)) self.listener.reset() @@ -900,7 +901,7 @@ def check(): wait_until(check, "insert documents with w=0") def test_bulk_write(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll coll.drop() self.listener.reset() @@ -963,7 +964,7 @@ def test_bulk_write(self): @client_context.require_failCommand_fail_point def test_bulk_write_command_network_error(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll self.listener.reset() insert_network_error = { @@ -987,7 +988,7 @@ def test_bulk_write_command_network_error(self): @client_context.require_failCommand_fail_point def test_bulk_write_command_error(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll self.listener.reset() insert_command_error = { @@ -1011,7 +1012,7 @@ def test_bulk_write_command_error(self): self.assertTrue(event.failure["errmsg"]) def test_write_errors(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll coll.drop() self.listener.reset() @@ -1054,15 +1055,17 @@ def test_write_errors(self): self.assertLessEqual(fields, set(error)) def test_first_batch_helper(self): + # Ensure the collection exists so listIndexes works on sharded clusters. + self.client.pymongo_test.coll.insert_one({}) # Regardless of server version and use of helpers._first_batch # this test should still pass. self.listener.reset() - tuple((self.client.pymongo_test.test.list_indexes()).to_list()) + tuple((self.client.pymongo_test.coll.list_indexes()).to_list()) started = self.listener.started_events[0] succeeded = self.listener.succeeded_events[0] self.assertEqual(0, len(self.listener.failed_events)) self.assertIsInstance(started, monitoring.CommandStartedEvent) - expected = SON([("listIndexes", "test"), ("cursor", {})]) + expected = SON([("listIndexes", "coll"), ("cursor", {})]) self.assertEqualCommand(expected, started.command) self.assertEqual("pymongo_test", started.database_name) self.assertEqual("listIndexes", started.command_name) diff --git a/test/test_pooling.py b/test/test_pooling.py index 64146a0e13..64e6aa931f 100644 --- a/test/test_pooling.py +++ b/test/test_pooling.py @@ -170,9 +170,9 @@ def setUp(self): self.c = self.rs_or_single_client() db = self.c[DB] db.unique.drop() - db.test.drop() + db.coll.drop() db.unique.insert_one({"_id": "jesse"}) - db.test.insert_many([{} for _ in range(10)]) + db.coll.insert_many([{} for _ in range(10)]) def create_pool(self, pair=None, *args, **kwargs): if pair is None: @@ -458,14 +458,14 @@ def test_checkout_more_than_max_pool_size(self): def test_maxConnecting(self): client = self.rs_or_single_client() - self.client.test.test.insert_one({}) - self.addCleanup(self.client.test.test.delete_many, {}) + self.client.db.coll.insert_one({}) + self.addCleanup(self.client.db.coll.delete_many, {}) pool = get_pool(client) docs = [] # Run 50 short running operations def find_one(): - docs.append(client.test.test.find_one({})) + docs.append(client.db.coll.find_one({})) tasks = [ConcurrentRunner(target=find_one) for _ in range(50)] for task in tasks: @@ -506,12 +506,12 @@ def test_csot_timeout_message(self): }, } - client.db.t.insert_one({"x": 1}) + client.db.coll.insert_one({"x": 1}) with self.fail_point(mock_connection_timeout): with self.assertRaises(Exception) as error: with timeout(0.5): - client.db.t.find_one({"$where": delay(2)}) + client.db.coll.find_one({"$where": delay(2)}) self.assertIn("(configured timeouts: timeoutMS: 500.0ms", str(error.exception)) @@ -530,11 +530,11 @@ def test_socket_timeout_message(self): }, } - client.db.t.insert_one({"x": 1}) + client.db.coll.insert_one({"x": 1}) with self.fail_point(mock_connection_timeout): with self.assertRaises(Exception) as error: - client.db.t.find_one({"$where": delay(2)}) + client.db.coll.find_one({"$where": delay(2)}) self.assertIn( "(configured timeouts: socketTimeoutMS: 500.0ms, connectTimeoutMS: 20000.0ms)", @@ -615,7 +615,7 @@ class TestPoolMaxSize(_TestPoolingBase): def test_max_pool_size(self): max_pool_size = 4 c = self.rs_or_single_client(maxPoolSize=max_pool_size) - collection = c[DB].test + collection = c[DB].coll # Need one document. collection.drop() @@ -654,7 +654,7 @@ def f(): ) def test_max_pool_size_none(self): c = self.rs_or_single_client(maxPoolSize=None) - collection = c[DB].test + collection = c[DB].coll # Need one document. collection.drop() diff --git a/test/test_raw_bson.py b/test/test_raw_bson.py index b9f0d6239c..5e213cccd8 100644 --- a/test/test_raw_bson.py +++ b/test/test_raw_bson.py @@ -38,7 +38,7 @@ class TestRawBSONDocument(IntegrationTest): def tearDown(self): if client_context.connected: - self.client.pymongo_test.test_raw.drop() + self.db.test_raw.drop() @client_context.require_connection def test_round_trip_view_backed_document(self): @@ -88,7 +88,7 @@ def test_round_trip_codec_options(self): "date": datetime.datetime(2015, 6, 3, 18, 40, 50, 826000), "_id": uuid.UUID("026fab8f-975f-4965-9fbf-85ad874c60ff"), } - db = self.client.pymongo_test + db = self.db coll = db.get_collection( "test_raw", codec_options=CodecOptions(uuid_representation=JAVA_LEGACY) ) @@ -104,7 +104,7 @@ def test_round_trip_codec_options(self): @client_context.require_connection def test_raw_bson_document_embedded(self): doc = {"embedded": self.document} - db = self.client.pymongo_test + db = self.db db.test_raw.insert_one(doc) result = db.test_raw.find_one() assert result is not None diff --git a/test/test_read_concern.py b/test/test_read_concern.py index f9b2faf67f..5283ad9015 100644 --- a/test/test_read_concern.py +++ b/test/test_read_concern.py @@ -39,10 +39,11 @@ def setUp(self): self.listener = OvertCommandListener() self.client = self.rs_or_single_client(event_listeners=[self.listener]) self.db = self.client.pymongo_test - client_context.client.pymongo_test.create_collection("coll") + self.db.create_collection("coll") + self.listener.reset() def tearDown(self): - client_context.client.pymongo_test.drop_collection("coll") + self.db.drop_collection("coll") def test_read_concern(self): rc = ReadConcern() diff --git a/test/test_read_preferences.py b/test/test_read_preferences.py index 65c25735f5..2904fb2e7a 100644 --- a/test/test_read_preferences.py +++ b/test/test_read_preferences.py @@ -105,16 +105,16 @@ class TestReadPreferencesBase(IntegrationTest): def setUp(self): super().setUp() # Insert some data so we can use cursors in read_from_which_host - self.client.pymongo_test.test.drop() + self.db.coll.drop() self.client.get_database( "pymongo_test", write_concern=WriteConcern(w=client_context.w) - ).test.insert_many([{"_id": i} for i in range(10)]) + ).coll.insert_many([{"_id": i} for i in range(10)]) - self.addCleanup(self.client.pymongo_test.test.drop) + self.addCleanup(self.db.coll.drop) def read_from_which_host(self, client): """Do a find() on the client and return which host was used""" - cursor = client.pymongo_test.test.find() + cursor = client.pymongo_test.coll.find() next(cursor) return cursor.address @@ -158,7 +158,7 @@ def test_reads_from_secondary(self): self.assertEqual(client.read_preference, ReadPreference.PRIMARY) db = client.pymongo_test - coll = db.test + coll = db.coll # Test find and find_one. self.assertIsNotNone(coll.find_one()) @@ -166,7 +166,7 @@ def test_reads_from_secondary(self): # Test some database helpers. self.assertIsNotNone(db.list_collection_names()) - self.assertIsNotNone(db.validate_collection("test")) + self.assertIsNotNone(db.validate_collection("coll")) self.assertIsNotNone(db.command("ping")) # Test some collection helpers. @@ -424,17 +424,17 @@ def func(): self._test_primary_helper(func) def test_count_documents(self): - self._test_coll_helper(True, self.c.pymongo_test.test, "count_documents", {}) + self._test_coll_helper(True, self.c.pymongo_test.coll, "count_documents", {}) def test_estimated_document_count(self): - self._test_coll_helper(True, self.c.pymongo_test.test, "estimated_document_count") + self._test_coll_helper(True, self.c.pymongo_test.coll, "estimated_document_count") def test_distinct(self): - self._test_coll_helper(True, self.c.pymongo_test.test, "distinct", "a") + self._test_coll_helper(True, self.c.pymongo_test.coll, "distinct", "a") def test_aggregate(self): self._test_coll_helper( - True, self.c.pymongo_test.test, "aggregate", [{"$project": {"_id": 1}}] + True, self.c.pymongo_test.coll, "aggregate", [{"$project": {"_id": 1}}] ) def test_aggregate_write(self): @@ -442,7 +442,7 @@ def test_aggregate_write(self): secondary_ok = client_context.version.at_least(5, 0) self._test_coll_helper( secondary_ok, - self.c.pymongo_test.test, + self.c.pymongo_test.coll, "aggregate", [{"$project": {"_id": 1}}, {"$out": "agg_write_test"}], ) @@ -576,7 +576,7 @@ def test_send_hedge(self): for _mode, cls in cases.items(): with _ignore_deprecations(): pref = cls(hedge={"enabled": True}) - coll = client.test.get_collection("test", read_preference=pref) + coll = client.test.get_collection("coll", read_preference=pref) listener.reset() coll.find_one() started = listener.started_events @@ -660,9 +660,7 @@ def test_mongos(self): num_members = shard.count(",") + 1 if num_members == 1: raise SkipTest("Need a replica set shard to test.") - coll = client_context.client.pymongo_test.get_collection( - "test", write_concern=WriteConcern(w=num_members) - ) + coll = self.db.get_collection("test", write_concern=WriteConcern(w=num_members)) coll.drop() res = coll.insert_many([{} for _ in range(5)]) first_id = res.inserted_ids[0] @@ -682,15 +680,11 @@ def test_mongos(self): @client_context.require_mongos def test_mongos_max_staleness(self): # Sanity check that we're sending maxStalenessSeconds - coll = client_context.client.pymongo_test.get_collection( - "test", read_preference=SecondaryPreferred(max_staleness=120) - ) + coll = self.db.get_collection("coll", read_preference=SecondaryPreferred(max_staleness=120)) # No error coll.find_one() - coll = client_context.client.pymongo_test.get_collection( - "test", read_preference=SecondaryPreferred(max_staleness=10) - ) + coll = self.db.get_collection("coll", read_preference=SecondaryPreferred(max_staleness=10)) try: coll.find_one() except OperationFailure as exc: @@ -700,13 +694,13 @@ def test_mongos_max_staleness(self): coll = ( self.single_client(readPreference="secondaryPreferred", maxStalenessSeconds=120) - ).pymongo_test.test + ).pymongo_test.coll # No error coll.find_one() coll = ( self.single_client(readPreference="secondaryPreferred", maxStalenessSeconds=10) - ).pymongo_test.test + ).pymongo_test.coll try: coll.find_one() except OperationFailure as exc: diff --git a/test/test_read_write_concern_spec.py b/test/test_read_write_concern_spec.py index d1afe3e2b0..fd6f161346 100644 --- a/test/test_read_write_concern_spec.py +++ b/test/test_read_write_concern_spec.py @@ -108,7 +108,7 @@ def assertWriteOpsRaise(self, write_concern, expected_exception): w=wc["w"], wTimeoutMS=wc["wtimeout"], socketTimeoutMS=30000 ) db = client.get_database("pymongo_test") - coll = db.test + coll = db.coll def insert_command(): coll.database.command( @@ -192,12 +192,12 @@ def test_error_includes_errInfo(self): with self.fail_point(cause_wce): # Write concern error on insert includes errInfo. with self.assertRaises(WriteConcernError) as ctx: - self.db.test.insert_one({}) + self.db.coll.insert_one({}) self.assertEqual(ctx.exception.details, expected_wce) # Test bulk_write as well. with self.assertRaises(BulkWriteError) as ctx: - self.db.test.bulk_write([InsertOne({})]) + self.db.coll.bulk_write([InsertOne({})]) expected_details = { "writeErrors": [], "writeConcernErrors": [expected_wce], @@ -219,9 +219,9 @@ def test_write_error_details_exposes_errinfo(self): db = client.errinfotest self.addCleanup(client.drop_database, "errinfotest") validator = {"x": {"$type": "string"}} - db.create_collection("test", validator=validator) + db.create_collection("coll", validator=validator) with self.assertRaises(WriteError) as ctx: - db.test.insert_one({"x": 1}) + db.coll.insert_one({"x": 1}) self.assertEqual(ctx.exception.code, 121) self.assertIsNotNone(ctx.exception.details) assert ctx.exception.details is not None diff --git a/test/test_retryable_reads.py b/test/test_retryable_reads.py index bf0650393b..1097e051d2 100644 --- a/test/test_retryable_reads.py +++ b/test/test_retryable_reads.py @@ -97,7 +97,7 @@ def test_pool_paused_error_is_retryable(self): for _ in range(10): cmap_listener.reset() cmd_listener.reset() - threads = [FindThread(client.pymongo_test.test) for _ in range(2)] + threads = [FindThread(client.pymongo_test.coll) for _ in range(2)] fail_command = { "mode": {"times": 1}, "data": { @@ -183,7 +183,7 @@ def test_retryable_reads_are_retried_on_a_different_mongos_when_one_is_available ) with self.assertRaises(OperationFailure): - client.t.t.find_one({}) + client.db.coll.find_one({}) # Disable failpoints on each mongos for client in mongos_clients: @@ -219,7 +219,7 @@ def test_retryable_reads_are_retried_on_the_same_mongos_when_no_others_are_avail retryReads=True, ) - client.t.t.find_one({}) + client.db.coll.find_one({}) # Disable failpoint. fail_command["mode"] = "off" @@ -241,17 +241,17 @@ def test_retryable_reads_are_retried_on_the_same_implicit_session(self): retryReads=True, ) - client.t.t.insert_one({"x": 1}) + client.db.coll.insert_one({"x": 1}) commands = [ - ("aggregate", lambda: client.t.t.count_documents({})), - ("aggregate", lambda: client.t.t.aggregate([{"$match": {}}])), - ("count", lambda: client.t.t.estimated_document_count()), - ("distinct", lambda: client.t.t.distinct("x")), - ("find", lambda: client.t.t.find_one({})), + ("aggregate", lambda: client.db.coll.count_documents({})), + ("aggregate", lambda: client.db.coll.aggregate([{"$match": {}}])), + ("count", lambda: client.db.coll.estimated_document_count()), + ("distinct", lambda: client.db.coll.distinct("x")), + ("find", lambda: client.db.coll.find_one({})), ("listDatabases", lambda: client.list_databases()), ("listCollections", lambda: client.t.list_collections()), - ("listIndexes", lambda: client.t.t.list_indexes()), + ("listIndexes", lambda: client.db.coll.list_indexes()), ] for command_name, operation in commands: @@ -310,7 +310,7 @@ def test_03_01_retryable_reads_caused_by_overload_errors_are_retried_on_a_differ listener.reset() # 4. Execute a `find` command with `client`. - client.t.t.find_one({}) + client.db.coll.find_one({}) # 5. Assert that one failed command event and one successful command event occurred. self.assertEqual(len(listener.failed_events), 1) @@ -351,7 +351,7 @@ def test_03_02_retryable_reads_caused_by_non_overload_errors_are_retried_on_the_ listener.reset() # 4. Execute a `find` command with `client`. - client.t.t.find_one({}) + client.db.coll.find_one({}) # 5. Assert that one failed command event and one successful command event occurred. self.assertEqual(len(listener.failed_events), 1) @@ -394,7 +394,7 @@ def test_03_03_retryable_reads_caused_by_overload_errors_are_retried_on_the_same listener.reset() # 4. Execute a `find` command with `client`. - client.t.t.find_one({}) + client.db.coll.find_one({}) # 5. Assert that one failed command event and one successful command event occurred. self.assertEqual(len(listener.failed_events), 1) @@ -443,13 +443,13 @@ def failed(event: CommandFailedEvent) -> None: listener.failed = failed client = self.rs_client(event_listeners=[listener]) - client.test.test.insert_one({}) + client.db.coll.insert_one({}) self.configure_fail_point_sync(overload_fail_point) self.addCleanup(self.configure_fail_point_sync, {}, off=True) with self.assertRaises(PyMongoError): - client.test.test.find_one() + client.db.coll.find_one() started_finds = [e for e in listener.started_events if e.command_name == "find"] self.assertEqual(len(started_finds), MAX_ADAPTIVE_RETRIES + 1) @@ -499,7 +499,7 @@ def failed(event: CommandFailedEvent) -> None: listener.failed = failed client = self.rs_client(event_listeners=[listener]) - client.test.test.insert_one({}) + client.db.coll.insert_one({}) self.configure_fail_point_sync(overload_fail_point) self.addCleanup(self.configure_fail_point_sync, {}, off=True) @@ -507,7 +507,7 @@ def failed(event: CommandFailedEvent) -> None: # Perform a findOne operation with coll. Expect the operation to fail. with mock.patch(mock_target, return_value=0) as mock_backoff: with self.assertRaises(PyMongoError): - client.test.test.find_one() + client.db.coll.find_one() # Assert that backoff was applied only once for the initial overload error and not for the subsequent non-overload retryable errors. self.assertEqual(mock_backoff.call_count, 1) diff --git a/test/test_retryable_writes.py b/test/test_retryable_writes.py index 71552b208e..222d59695c 100644 --- a/test/test_retryable_writes.py +++ b/test/test_retryable_writes.py @@ -383,7 +383,7 @@ def test_retryable_writes_in_sharded_cluster_multiple_available(self): ) with self.assertRaises(AutoReconnect): - client.t.t.insert_one({"x": 1}) + client.db.coll.insert_one({"x": 1}) # Disable failpoints on each mongos for client in mongos_clients: @@ -433,7 +433,7 @@ def test_RetryableWriteError_error_label_RawBSONDocument(self): with self.fail_point(self.fail_insert): with self.client.start_session() as s: s._start_retryable_write() - result = self.client.pymongo_test.command( + result = self.db.command( "insert", "testcoll", documents=[{"_id": 1}], @@ -478,7 +478,7 @@ def test_pool_paused_error_is_retryable(self): for _ in range(10): cmap_listener.reset() cmd_listener.reset() - threads = [InsertThread(client.pymongo_test.test) for _ in range(2)] + threads = [InsertThread(client.pymongo_test.coll) for _ in range(2)] fail_command = { "mode": {"times": 1}, "data": { @@ -537,7 +537,7 @@ def test_returns_original_error_code( ): cmd_listener = InsertEventListener() client = self.rs_or_single_client(retryWrites=True, event_listeners=[cmd_listener]) - client.test.test.drop() + client.db.coll.drop() cmd_listener.reset() client.admin.command( { @@ -553,7 +553,7 @@ def test_returns_original_error_code( } ) with self.assertRaises(WriteConcernError) as exc: - client.test.test.insert_one({"_id": 1}) + client.db.coll.insert_one({"_id": 1}) self.assertEqual(exc.exception.code, 91) client.admin.command( { @@ -667,7 +667,7 @@ def failed(event: CommandFailedEvent) -> None: # Attempt an insertOne operation on any record for any database and collection. # Expect the insertOne to fail with a server error. with self.assertRaises(NotPrimaryError) as exc: - client.test.test.insert_one({}) + client.db.coll.insert_one({}) # Assert that the error code of the server error is 10107. assert exc.exception.errors["code"] == 10107 # type:ignore[call-overload] @@ -720,7 +720,7 @@ def failed(event: CommandFailedEvent) -> None: # Attempt an insertOne operation on any record for any database and collection. # Expect the insertOne to fail with a server error. with self.assertRaises(NotPrimaryError) as exc: - client.test.test.insert_one({}) + client.db.coll.insert_one({}) # Assert that the error code of the server error is 91. assert exc.exception.errors["code"] == 91 # type:ignore[call-overload] @@ -774,7 +774,7 @@ def failed(event: CommandFailedEvent) -> None: # Attempt an insertOne operation on any record for any database and collection. # Expect the insertOne to fail with a server error. with self.assertRaises(PyMongoError) as exc: - client.test.test.insert_one({}) + client.db.coll.insert_one({}) # Assert that the error code of the server error is 91. assert exc.exception.errors["code"] == 91 @@ -825,7 +825,7 @@ def failed(event: CommandFailedEvent) -> None: self.addCleanup(self.configure_fail_point_sync, {}, off=True) with self.assertRaises(PyMongoError): - client.test.test.insert_one({"x": 1}) + client.db.coll.insert_one({"x": 1}) started_inserts = [e for e in listener.started_events if e.command_name == "insert"] self.assertEqual(len(started_inserts), MAX_ADAPTIVE_RETRIES + 1) @@ -881,7 +881,7 @@ def failed(event: CommandFailedEvent) -> None: # Perform a findOne operation with coll. Expect the operation to fail. with mock.patch(mock_target, return_value=0) as mock_backoff: with self.assertRaises(PyMongoError): - client.test.test.insert_one({}) + client.db.coll.insert_one({}) # Assert that backoff was applied only once for the initial overload error and not for the subsequent non-overload retryable errors. self.assertEqual(mock_backoff.call_count, 1) diff --git a/test/test_sdam_monitoring_spec.py b/test/test_sdam_monitoring_spec.py index 437516999e..6e63f94ea3 100644 --- a/test/test_sdam_monitoring_spec.py +++ b/test/test_sdam_monitoring_spec.py @@ -295,7 +295,7 @@ def setUp(self): self.test_client = self.rs_or_single_client( event_listeners=[self.listener], retryWrites=retry_writes ) - self.coll = self.test_client[self.client.db.name].test + self.coll = self.test_client[self.client.db.name].coll self.coll.drop() # necessary for first test run self.coll.database.create_collection(self.coll.name) self.listener.reset() diff --git a/test/test_server_selection.py b/test/test_server_selection.py index 50076a8024..d877392aaf 100644 --- a/test/test_server_selection.py +++ b/test/test_server_selection.py @@ -215,7 +215,7 @@ def test_server_selection_getMore_blocks(self): client = self.rs_client( event_listeners=[hb_listener], heartbeatFrequencyMS=500, appName="heartbeatFailedClient" ) - coll = client.db.test + coll = client.db.coll coll.drop() docs = [{"x": 1} for _ in range(5)] coll.insert_many(docs) diff --git a/test/test_server_selection_in_window.py b/test/test_server_selection_in_window.py index 7b561d93db..771a0b3b5f 100644 --- a/test/test_server_selection_in_window.py +++ b/test/test_server_selection_in_window.py @@ -118,7 +118,7 @@ def run(self): class TestProse(IntegrationTest): def frequencies(self, client, listener, n_finds=10): - coll = client.test.test + coll = client.db.coll N_TASKS = 10 tasks = [FinderTask(coll, n_finds) for _ in range(N_TASKS)] for task in tasks: @@ -172,7 +172,7 @@ def test_load_balancing(self): "appName": "loadBalancingTest", }, } - coll = client.test.test + coll = client.db.coll N_TASKS = 10 with self.fail_point(delay_finds): nodes = client_context.client.nodes diff --git a/test/test_session.py b/test/test_session.py index c929a87fcd..2d4427960e 100644 --- a/test/test_session.py +++ b/test/test_session.py @@ -243,17 +243,17 @@ def test_implicit_sessions_checkout(self): # Retry up to 10 times because there is a known race condition that can cause multiple # sessions to be used: connection check in happens before session check in for _ in range(10): - cursor = client.db.test.find({}) + cursor = client.db.coll.find({}) ops: list[tuple[Callable, list[Any]]] = [ - (client.db.test.find_one, [{"_id": 1}]), - (client.db.test.delete_one, [{}]), - (client.db.test.update_one, [{}, {"$set": {"x": 2}}]), - (client.db.test.bulk_write, [[UpdateOne({}, {"$set": {"x": 2}})]]), - (client.db.test.find_one_and_delete, [{}]), - (client.db.test.find_one_and_update, [{}, {"$set": {"x": 1}}]), - (client.db.test.find_one_and_replace, [{}, {}]), - (client.db.test.aggregate, [[{"$limit": 1}]]), - (client.db.test.find, []), + (client.db.coll.find_one, [{"_id": 1}]), + (client.db.coll.delete_one, [{}]), + (client.db.coll.update_one, [{}, {"$set": {"x": 2}}]), + (client.db.coll.bulk_write, [[UpdateOne({}, {"$set": {"x": 2}})]]), + (client.db.coll.find_one_and_delete, [{}]), + (client.db.coll.find_one_and_update, [{}, {"$set": {"x": 1}}]), + (client.db.coll.find_one_and_replace, [{}, {}]), + (client.db.coll.aggregate, [[{"$limit": 1}]]), + (client.db.coll.find, []), (client.server_info, []), (client.db.aggregate, [[{"$listLocalSessions": {}}, {"$limit": 1}]]), (cursor.distinct, ["_id"]), @@ -415,7 +415,7 @@ def test_collection(self): self._test_ops(client, *ops) def test_cursor_clone(self): - coll = self.client.pymongo_test.collection + coll = self.db.collection # Ensure some batches. coll.insert_many({} for _ in range(10)) self.addCleanup(coll.drop) @@ -689,7 +689,7 @@ def test_aggregate_error(self): self.assertIn(lsid, session_ids(client)) def _test_cursor_helper(self, create_cursor, close_cursor): - coll = self.client.pymongo_test.collection + coll = self.db.collection coll.insert_many([{} for _ in range(1000)]) cursor = create_cursor(coll, None) @@ -828,7 +828,7 @@ def _test_unacknowledged_ops(self, client, *ops): def test_unacknowledged_writes(self): # Ensure the collection exists. - self.client.pymongo_test.create_collection("test_unacked_writes") + self.db.create_collection("test_unacked_writes") client = self.rs_or_single_client(w=0, event_listeners=[self.listener]) db = client.pymongo_test coll = db.test_unacked_writes @@ -870,7 +870,7 @@ def test_session_not_copyable(self): self.assertRaises(TypeError, lambda: copy.copy(s)) def test_nested_session_binding(self): - coll = self.client.pymongo_test.test + coll = self.db.coll coll.insert_one({"x": 1}) session1 = self.client.start_session() @@ -921,7 +921,7 @@ def test_nested_session_binding(self): session2.end_session() def test_session_binding_end_session(self): - coll = self.client.pymongo_test.test + coll = self.db.coll coll.insert_one({"x": 1}) with self.client.start_session().bind() as s1: @@ -939,7 +939,7 @@ def test_session_binding_end_session(self): def test_getmore_preserves_lsid_after_session_support_lost(self): listener = OvertCommandListener() client = self.rs_or_single_client(event_listeners=[listener], maxPoolSize=1) - coll = client.pymongo_test.test + coll = client.pymongo_test.coll coll.drop() coll.insert_many([{"x": i} for i in range(10)]) self.addCleanup(coll.drop) @@ -979,8 +979,8 @@ def setUp(self): super().setUp() self.listener = SessionTestListener() self.client = self.rs_or_single_client(event_listeners=[self.listener]) - self.client.pymongo_test.drop_collection("test") - self.client.pymongo_test.create_collection("test") + self.client.pymongo_test.drop_collection("coll") + self.client.pymongo_test.create_collection("coll") @client_context.require_no_standalone def test_core(self): @@ -988,7 +988,7 @@ def test_core(self): self.assertIsNone(sess.cluster_time) self.assertIsNone(sess.operation_time) self.listener.reset() - self.client.pymongo_test.test.find_one(session=sess) + self.client.pymongo_test.coll.find_one(session=sess) started = self.listener.started_events[0] cmd = started.command self.assertIsNone(cmd.get("readConcern")) @@ -999,7 +999,7 @@ def test_core(self): self.assertEqual(op_time, reply.get("operationTime")) # No explicit session - self.client.pymongo_test.test.insert_one({}) + self.client.pymongo_test.coll.insert_one({}) self.assertEqual(sess.operation_time, op_time) self.listener.reset() try: @@ -1031,7 +1031,7 @@ def test_core(self): self.assertEqual(sess.operation_time, sess2.operation_time) def _test_reads(self, op, exception=None): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll with self.client.start_session() as sess: coll.find_one({}, session=sess) operation_time = sess.operation_time @@ -1072,7 +1072,7 @@ def find_raw(coll, session): self._test_reads(lambda coll, session: coll.estimated_document_count(session=session)) def _test_writes(self, op): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll with self.client.start_session() as sess: op(coll, sess) operation_time = sess.operation_time @@ -1123,7 +1123,7 @@ def test_writes(self): self._test_writes(lambda coll, session: coll.drop_indexes(session=session)) def _test_no_read_concern(self, op): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll with self.client.start_session() as sess: coll.find_one({}, session=sess) operation_time = sess.operation_time @@ -1139,7 +1139,7 @@ def test_explain_does_not_include_read_concern(self): @client_context.require_no_standalone def test_get_more_does_not_include_read_concern(self): - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll with self.client.start_session() as sess: coll.find_one({}, session=sess) operation_time = sess.operation_time @@ -1155,9 +1155,9 @@ def test_get_more_does_not_include_read_concern(self): def test_session_not_causal(self): with self.client.start_session(causal_consistency=False) as s: - self.client.pymongo_test.test.insert_one({}, session=s) + self.client.pymongo_test.coll.insert_one({}, session=s) self.listener.reset() - self.client.pymongo_test.test.find_one({}, session=s) + self.client.pymongo_test.coll.find_one({}, session=s) act = ( self.listener.started_events[0] .command.get("readConcern", {}) @@ -1168,9 +1168,9 @@ def test_session_not_causal(self): @client_context.require_standalone def test_server_not_causal(self): with self.client.start_session(causal_consistency=True) as s: - self.client.pymongo_test.test.insert_one({}, session=s) + self.client.pymongo_test.coll.insert_one({}, session=s) self.listener.reset() - self.client.pymongo_test.test.find_one({}, session=s) + self.client.pymongo_test.coll.find_one({}, session=s) act = ( self.listener.started_events[0] .command.get("readConcern", {}) @@ -1181,7 +1181,7 @@ def test_server_not_causal(self): @client_context.require_no_standalone def test_read_concern(self): with self.client.start_session(causal_consistency=True) as s: - coll = self.client.pymongo_test.test + coll = self.client.pymongo_test.coll coll.insert_one({}, session=s) self.listener.reset() coll.find_one({}, session=s) @@ -1201,14 +1201,14 @@ def test_read_concern(self): @client_context.require_no_standalone def test_cluster_time_with_server_support(self): self.listener.reset() - self.client.pymongo_test.test.find_one({}) + self.client.pymongo_test.coll.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime") self.assertIsNotNone(after_cluster_time) @client_context.require_standalone def test_cluster_time_no_server_support(self): self.listener.reset() - self.client.pymongo_test.test.find_one({}) + self.client.pymongo_test.coll.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime") self.assertIsNone(after_cluster_time) @@ -1315,7 +1315,7 @@ def test_cluster_time_not_used_by_sdam(self): self.assertEqual(c1._topology.max_cluster_time(), cluster_time) # Advance the server's $clusterTime by performing an insert via another client. - self.db.test.insert_one({"advance": "$clusterTime"}) + self.db.coll.insert_one({"advance": "$clusterTime"}) # Wait until the client C1 processes the next pair of SDAM heartbeat started + succeeded events. heartbeat_listener.reset() diff --git a/test/test_ssl.py b/test/test_ssl.py index 58e8c7e189..c614f016e7 100644 --- a/test/test_ssl.py +++ b/test/test_ssl.py @@ -815,7 +815,7 @@ def test_mongodb_x509_auth(self): ) with self.assertRaises(OperationFailure): - noauth.pymongo_test.test.find_one() + noauth.pymongo_test.coll.find_one() listener = EventListener() auth = self.simple_client( @@ -828,7 +828,7 @@ def test_mongodb_x509_auth(self): ) # No error - auth.pymongo_test.test.find_one() + auth.pymongo_test.coll.find_one() names = listener.started_command_names() if client_context.version.at_least(4, 4, -1): # Speculative auth skips the authenticate command. @@ -845,14 +845,14 @@ def test_mongodb_x509_auth(self): uri, ssl=True, tlsAllowInvalidCertificates=True, tlsCertificateKeyFile=CLIENT_PEM ) # No error - client.pymongo_test.test.find_one() + client.pymongo_test.coll.find_one() uri = "mongodb://%s:%d/?authMechanism=MONGODB-X509" % (host, port) client = self.simple_client( uri, ssl=True, tlsAllowInvalidCertificates=True, tlsCertificateKeyFile=CLIENT_PEM ) # No error - client.pymongo_test.test.find_one() + client.pymongo_test.coll.find_one() # Auth should fail if username and certificate do not match uri = "mongodb://%s@%s:%d/?authMechanism=MONGODB-X509" % ( quote_plus("not the username"), @@ -865,7 +865,7 @@ def test_mongodb_x509_auth(self): ) with self.assertRaises(OperationFailure): - bad_client.pymongo_test.test.find_one() + bad_client.pymongo_test.coll.find_one() bad_client = self.simple_client( client_context.pair, @@ -877,7 +877,7 @@ def test_mongodb_x509_auth(self): ) with self.assertRaises(OperationFailure): - bad_client.pymongo_test.test.find_one() + bad_client.pymongo_test.coll.find_one() # Invalid certificate (using CA certificate as client certificate) uri = "mongodb://%s@%s:%d/?authMechanism=MONGODB-X509" % ( diff --git a/test/test_transactions.py b/test/test_transactions.py index 5cf9b28a23..3ee76f894d 100644 --- a/test/test_transactions.py +++ b/test/test_transactions.py @@ -105,7 +105,7 @@ def test_transaction_write_concern_override(self): """Test txn overrides Client/Database/Collection write_concern.""" client = self.rs_client(w=0) db = client.test - coll = db.test + coll = db.coll coll.insert_one({}) with client.start_session() as s: with s.start_transaction(write_concern=WriteConcern(w=1)): @@ -150,7 +150,7 @@ def test_unpin_for_next_transaction(self): # to avoid false positives. client = self.rs_client(client_context.mongos_seeds(), localThresholdMS=1000) wait_until(lambda: len(client.nodes) > 1, "discover both mongoses") - coll = client.test.test + coll = client.db.coll # Create the collection. coll.insert_one({}) with client.start_session() as s: @@ -177,7 +177,7 @@ def test_unpin_for_non_transaction_operation(self): # to avoid false positives. client = self.rs_client(client_context.mongos_seeds(), localThresholdMS=1000) wait_until(lambda: len(client.nodes) > 1, "discover both mongoses") - coll = client.test.test + coll = client.db.coll # Create the collection. coll.insert_one({}) with client.start_session() as s: @@ -199,7 +199,7 @@ def test_unpin_for_non_transaction_operation(self): @client_context.require_transactions def test_create_collection(self): client = client_context.client - db = client.pymongo_test + db = self.db coll = db.test_create_collection self.addCleanup(coll.drop) @@ -226,7 +226,7 @@ def create_and_insert(session): @client_context.require_transactions def test_gridfs_does_not_support_transactions(self): client = client_context.client - db = client.pymongo_test + db = self.db gfs = GridFS(db) bucket = GridFSBucket(db) @@ -308,7 +308,7 @@ def test_transaction_starts_with_batched_write(self): # split. listener = OvertCommandListener() client = self.rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll coll.delete_many({}) listener.reset() self.addCleanup(coll.drop) @@ -336,7 +336,7 @@ def test_transaction_starts_with_batched_write(self): @client_context.require_transactions def test_transaction_direct_connection(self): client = self.single_client() - coll = client.pymongo_test.test + coll = client.pymongo_test.coll # Make sure the collection exists. coll.insert_one({}) @@ -440,10 +440,10 @@ def callback(_): with self.client.start_session() as s: self.assertEqual(s.with_transaction(callback), "Foo") - self.db.test.insert_one({}) + self.db.coll.insert_one({}) def callback2(session): - self.db.test.insert_one({}, session=session) + self.db.coll.insert_one({}, session=session) return "Foo" with self.client.start_session() as s: @@ -464,7 +464,7 @@ def callback(_): def test_3_1_callback_not_retried_after_timeout(self): listener = OvertCommandListener() client = self.rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll def callback(session): coll.insert_one({}, session=session) @@ -494,7 +494,7 @@ def callback(session): def test_3_2_callback_not_retried_after_commit_timeout(self): listener = OvertCommandListener() client = self.rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll def callback(session): coll.insert_one({}, session=session) @@ -528,7 +528,7 @@ def callback(session): def test_3_3_commit_not_retried_after_timeout(self): listener = OvertCommandListener() client = self.rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll def callback(session): coll.insert_one({}, session=session) @@ -566,7 +566,7 @@ def callback(session): def test_callback_not_retried_after_csot_timeout(self): listener = OvertCommandListener() client = self.rs_client(event_listeners=[listener]) - coll = client[self.db.name].test + coll = client[self.db.name].coll def callback(session): coll.insert_one({}, session=session) @@ -603,7 +603,7 @@ def callback(session): @client_context.require_transactions def test_in_transaction_property(self): client = client_context.client - coll = client.test.testcollection + coll = client.db.collcollection coll.insert_one({}) self.addCleanup(coll.drop) @@ -640,7 +640,7 @@ def callback(session): @client_context.require_transactions def test_4_retry_backoff_is_enforced(self): client = client_context.client - coll = client[self.db.name].test + coll = client[self.db.name].coll end = start = no_backoff_time = 0 # Make random.random always return 0 (no backoff) @@ -703,7 +703,7 @@ def test_case_1(self): # Write concern not inherited from collection object inside transaction # Create a MongoClient running against a configured sharded/replica set/load balanced cluster. client = client_context.client - coll = client[self.db.name].test + coll = client[self.db.name].coll coll.delete_many({}) # Start a new session on the client. with client.start_session() as s: diff --git a/test/test_typing.py b/test/test_typing.py index c4c80189ae..656da2b1b1 100644 --- a/test/test_typing.py +++ b/test/test_typing.py @@ -114,11 +114,11 @@ class TestPymongo(IntegrationTest): def setUp(self): super().setUp() - self.coll = self.client.test.test + self.coll = self.client.db.coll def test_insert_find(self) -> None: doc = {"my": "doc"} - coll2 = self.client.test.test2 + coll2 = self.client.db.coll2 result = self.coll.insert_one(doc) self.assertEqual(result.inserted_id, doc["_id"]) retrieved = self.coll.find_one({"_id": doc["_id"]}) @@ -215,7 +215,7 @@ def test_list_databases(self) -> None: def test_default_document_type(self) -> None: client = self.rs_or_single_client() self.addCleanup(client.close) - coll = client.test.test + coll = client.db.coll doc = {"my": "doc"} coll.insert_one(doc) retrieved = coll.find_one({"_id": doc["_id"]}) @@ -223,7 +223,7 @@ def test_default_document_type(self) -> None: retrieved["a"] = 1 def test_aggregate_pipeline(self) -> None: - coll3 = self.client.test.test3 + coll3 = self.client.db.coll3 coll3.insert_many( [ {"x": 1, "tags": ["dog", "cat"]}, @@ -402,7 +402,7 @@ class TestDocumentType(PyMongoTestCase): @only_type_check def test_default(self) -> None: client: MongoClient = MongoClient() - coll = client.test.test + coll = client.db.coll retrieved = coll.find_one({"_id": "foo"}) assert retrieved is not None retrieved["a"] = 1 @@ -410,7 +410,7 @@ def test_default(self) -> None: @only_type_check def test_explicit_document_type(self) -> None: client: MongoClient[dict[str, Any]] = MongoClient() - coll = client.test.test + coll = client.db.coll retrieved = coll.find_one({"_id": "foo"}) assert retrieved is not None retrieved["a"] = 1 @@ -418,7 +418,7 @@ def test_explicit_document_type(self) -> None: @only_type_check def test_typeddict_document_type(self) -> None: client: MongoClient[Movie] = MongoClient() - coll = client.test.test + coll = client.db.coll retrieved = coll.find_one({"_id": "foo"}) assert retrieved is not None assert retrieved["year"] == 1 @@ -427,7 +427,7 @@ def test_typeddict_document_type(self) -> None: @only_type_check def test_typeddict_document_type_insertion(self) -> None: client: MongoClient[Movie] = MongoClient() - coll = client.test.test + coll = client.db.coll mov = {"name": "THX-1138", "year": 1971} movie = Movie(name="THX-1138", year=1971) coll.insert_one(mov) # type: ignore[arg-type] @@ -449,7 +449,7 @@ def test_typeddict_document_type_insertion(self) -> None: @only_type_check def test_bulk_write_document_type_insertion(self): client: MongoClient[MovieWithId] = MongoClient() - coll: Collection[MovieWithId] = client.test.test + coll: Collection[MovieWithId] = client.db.coll coll.bulk_write( [InsertOne(Movie({"name": "THX-1138", "year": 1971}))] # type:ignore[arg-type] ) @@ -466,7 +466,7 @@ def test_bulk_write_document_type_insertion(self): @only_type_check def test_bulk_write_document_type_replacement(self): client: MongoClient[MovieWithId] = MongoClient() - coll: Collection[MovieWithId] = client.test.test + coll: Collection[MovieWithId] = client.db.coll coll.bulk_write( [ReplaceOne({}, Movie({"name": "THX-1138", "year": 1971}))] # type:ignore[arg-type] ) @@ -513,7 +513,7 @@ def test_typeddict_find_notrequired(self): if NotRequired is None or ImplicitMovie is None: raise unittest.SkipTest("Python 3.11+ is required to use NotRequired.") client: MongoClient[ImplicitMovie] = self.rs_or_single_client() - coll = client.test.test + coll = client.db.coll coll.insert_one(ImplicitMovie(name="THX-1138", year=1971)) out = coll.find_one({}) assert out is not None @@ -523,7 +523,7 @@ def test_typeddict_find_notrequired(self): @only_type_check def test_raw_bson_document_type(self) -> None: client = MongoClient(document_class=RawBSONDocument) - coll = client.test.test + coll = client.db.coll retrieved = coll.find_one({"_id": "foo"}) assert retrieved is not None assert len(retrieved.raw) > 0 @@ -531,7 +531,7 @@ def test_raw_bson_document_type(self) -> None: @only_type_check def test_son_document_type(self) -> None: client = MongoClient(document_class=SON[str, Any]) - coll = client.test.test + coll = client.db.coll retrieved = coll.find_one({"_id": "foo"}) assert retrieved is not None retrieved["a"] = 1 diff --git a/test/test_versioned_api_integration.py b/test/test_versioned_api_integration.py index e97ed16601..f65c114de4 100644 --- a/test/test_versioned_api_integration.py +++ b/test/test_versioned_api_integration.py @@ -46,7 +46,7 @@ def assertServerApiInAllCommands(self, events): def test_command_options(self): listener = OvertCommandListener() client = self.rs_or_single_client(server_api=ServerApi("1"), event_listeners=[listener]) - coll = client.test.test + coll = client.db.coll coll.insert_many([{} for _ in range(100)]) self.addCleanup(coll.delete_many, {}) coll.find(batch_size=25).to_list() @@ -58,7 +58,7 @@ def test_command_options(self): def test_command_options_txn(self): listener = OvertCommandListener() client = self.rs_or_single_client(server_api=ServerApi("1"), event_listeners=[listener]) - coll = client.test.test + coll = client.db.coll coll.insert_many([{} for _ in range(100)]) self.addCleanup(coll.delete_many, {}) @@ -66,7 +66,7 @@ def test_command_options_txn(self): with client.start_session() as s, s.start_transaction(): coll.insert_many([{} for _ in range(100)], session=s) coll.find(batch_size=25, session=s).to_list() - client.test.command("find", "test", session=s) + client.db.command("find", "coll", session=s) self.assertServerApiInAllCommands(listener.started_events) diff --git a/test/utils_shared.py b/test/utils_shared.py index 65627956c0..11784c63cb 100644 --- a/test/utils_shared.py +++ b/test/utils_shared.py @@ -568,13 +568,13 @@ def lazy_client_trial(reset, target, test, get_client): `test` takes the lazily-connecting collection and asserts a post-condition to prove `target` succeeded. """ - collection = client_context.client.pymongo_test.test + collection = client_context.client.pymongo_test.coll with frequent_thread_switches(): for _i in range(NTRIALS): reset(collection) lazy_client = get_client() - lazy_collection = lazy_client.pymongo_test.test + lazy_collection = lazy_client.pymongo_test.coll run_threads(lazy_collection, target) test(lazy_collection)