diff --git a/test/asynchronous/test_change_stream.py b/test/asynchronous/test_change_stream.py index 2e1f83884b..e4128b2499 100644 --- a/test/asynchronous/test_change_stream.py +++ b/test/asynchronous/test_change_stream.py @@ -926,7 +926,7 @@ async def asyncSetUp(self): await super().asyncSetUp() # Use a new collection for each test. await self.watched_collection().drop() - await self.watched_collection().insert_one({}) + await self.db.create_collection(self.watched_collection().name) async def change_stream_with_client(self, client, *args, **kwargs): return ( diff --git a/test/asynchronous/test_collection.py b/test/asynchronous/test_collection.py index 3232650487..704d407491 100644 --- a/test/asynchronous/test_collection.py +++ b/test/asynchronous/test_collection.py @@ -229,7 +229,7 @@ async def test_create_indexes(self): self.assertRaises(ValueError, IndexModel, []) await db.test.drop_indexes() - await db.test.insert_one({}) + await db.create_collection("test") self.assertEqual(len(await db.test.index_information()), 1) await db.test.create_indexes([IndexModel("hello")]) @@ -292,7 +292,7 @@ async def test_create_index(self): await db.test.create_index([]) await db.test.drop_indexes() - await db.test.insert_one({}) + await db.create_collection("test") self.assertEqual(len(await db.test.index_information()), 1) await db.test.create_index("hello") @@ -392,7 +392,7 @@ async def test_index_management_max_time_ms(self): async def test_list_indexes(self): db = self.db await db.test.drop() - await db.test.insert_one({}) # create collection + await db.create_collection("test") def map_indexes(indexes): return {index["name"]: index for index in indexes} @@ -426,7 +426,7 @@ def map_indexes(indexes): async def test_index_info(self): db = self.db await db.test.drop() - await db.test.insert_one({}) # create collection + await db.create_collection("test") self.assertEqual(len(await db.test.index_information()), 1) self.assertIn("_id_", await db.test.index_information()) diff --git a/test/asynchronous/test_cursor.py b/test/asynchronous/test_cursor.py index 95604f65df..8b6d888f33 100644 --- a/test/asynchronous/test_cursor.py +++ b/test/asynchronous/test_cursor.py @@ -1513,9 +1513,12 @@ 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() + async def test_find_raw(self): c = self.db.test - await c.drop() 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() @@ -1525,7 +1528,6 @@ async def test_find_raw(self): @async_client_context.require_transactions async def test_find_raw_transaction(self): c = self.db.test - await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1555,7 +1557,6 @@ async def test_find_raw_transaction(self): @async_client_context.require_failCommand_fail_point async def test_find_raw_retryable_reads(self): c = self.db.test - await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1576,7 +1577,6 @@ async def test_find_raw_retryable_reads(self): @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")) - await c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] await c.insert_many(docs) @@ -1595,12 +1595,10 @@ async def test_find_raw_snapshot_reads(self): async def test_explain(self): c = self.db.test - await c.insert_one({}) explanation = await c.find_raw_batches().explain() self.assertIsInstance(explanation, dict) async def test_empty(self): - await self.db.test.drop() cursor = self.db.test.find_raw_batches() with self.assertRaises(StopAsyncIteration): await anext(cursor) @@ -1615,7 +1613,6 @@ async def test_clone(self): @async_client_context.require_no_mongos async def test_exhaust(self): c = self.db.test - await c.drop() 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)) @@ -1632,6 +1629,7 @@ async def test_get_item(self): self.db.test.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"))) async def test_read_concern(self): @@ -1645,7 +1643,6 @@ async def test_monitoring(self): listener = OvertCommandListener() client = await self.async_rs_or_single_client(event_listeners=[listener]) c = client.pymongo_test.test - await c.drop() await c.insert_many([{"_id": i} for i in range(10)]) listener.reset() diff --git a/test/asynchronous/test_index_management.py b/test/asynchronous/test_index_management.py index 591278414a..cd20b27986 100644 --- a/test/asynchronous/test_index_management.py +++ b/test/asynchronous/test_index_management.py @@ -96,9 +96,7 @@ async def asyncSetUp(self) -> None: ) await self.client.drop_database(_NAME) self.db = self.client[self.db_name] - - async def asyncTearDown(self): - await self.client.drop_database(_NAME) + self.coll0 = await self.db.create_collection(f"col{uuid.uuid4()}") async def wait_for_ready(self, coll, name=_NAME, predicate=None): """Wait for a search index to be ready.""" @@ -117,14 +115,10 @@ class TestSearchIndexIntegration(SearchIndexIntegrationBase): db_name = "test_search_index" async def test_comment_field(self): - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - await coll0.insert_one({}) - - # Create a new search index on ``coll0`` that implicitly passes its type. + # Create a new search index on ``self.coll0`` that implicitly passes its type. search_definition = {"mappings": {"dynamic": False}} self.listener.reset() - implicit_search_resp = await coll0.create_search_index( + implicit_search_resp = await self.coll0.create_search_index( model={"name": _NAME + "-implicit", "definition": search_definition}, comment="foo" ) event = self.listener.events[0] @@ -132,7 +126,9 @@ async def test_comment_field(self): # Get the index definition. self.listener.reset() - await (await coll0.list_search_indexes(name=implicit_search_resp, comment="foo")).next() + await ( + await self.coll0.list_search_indexes(name=implicit_search_resp, comment="foo") + ).next() event = self.listener.events[0] self.assertEqual(event.command["comment"], "foo") @@ -143,20 +139,16 @@ class TestSearchIndexProse(SearchIndexIntegrationBase): async def test_case_1(self): """Driver can successfully create and list search indexes.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - - # Create a new search index on ``coll0`` with the ``createSearchIndex`` helper. Use the following definition: + # Create a new search index on ``self.coll0`` with the ``createSearchIndex`` helper. Use the following definition: model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} - await coll0.insert_one({}) - resp = await coll0.create_search_index(model) + resp = await self.coll0.create_search_index(model) # Assert that the command returns the name of the index: ``"test-search-index"``. self.assertEqual(resp, _NAME) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied and store the value in a variable ``index``: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied and store the value in a variable ``index``: # An index with the ``name`` of ``test-search-index`` is present and the index has a field ``queryable`` with a value of ``true``. - index = await self.wait_for_ready(coll0) + index = await self.wait_for_ready(self.coll0) # . Assert that ``index`` has a property ``latestDefinition`` whose value is ``{ 'mappings': { 'dynamic': false } }`` self.assertIn("latestDefinition", index) @@ -165,11 +157,7 @@ async def test_case_1(self): async def test_case_2(self): """Driver can successfully create multiple indexes in batch.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - await coll0.insert_one({}) - - # Create two new search indexes on ``coll0`` with the ``createSearchIndexes`` helper. + # Create two new search indexes on ``self.coll0`` with the ``createSearchIndexes`` helper. name1 = "test-search-index-1" name2 = "test-search-index-2" definition = {"mappings": {"dynamic": False}} @@ -177,21 +165,21 @@ async def test_case_2(self): {"name": name1, "definition": definition}, {"name": name2, "definition": definition}, ] - await coll0.create_search_indexes( + await self.coll0.create_search_indexes( [SearchIndexModel(i["definition"], i["name"]) for i in index_definitions] ) # .Assert that the command returns an array containing the new indexes' names: ``["test-search-index-1", "test-search-index-2"]``. - indices = await (await coll0.list_search_indexes()).to_list() + indices = await (await self.coll0.list_search_indexes()).to_list() names = [i["name"] for i in indices] self.assertIn(name1, names) self.assertIn(name2, names) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied. + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied. # An index with the ``name`` of ``test-search-index-1`` is present and index has a field ``queryable`` with the value of ``true``. Store result in ``index1``. # An index with the ``name`` of ``test-search-index-2`` is present and index has a field ``queryable`` with the value of ``true``. Store result in ``index2``. - index1 = await self.wait_for_ready(coll0, name1) - index2 = await self.wait_for_ready(coll0, name2) + index1 = await self.wait_for_ready(self.coll0, name1) + index2 = await self.wait_for_ready(self.coll0, name2) # Assert that ``index1`` and ``index2`` have the property ``latestDefinition`` whose value is ``{ "mappings" : { "dynamic" : false } }`` for index in [index1, index2]: @@ -201,28 +189,24 @@ async def test_case_2(self): async def test_case_3(self): """Driver can successfully drop search indexes.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - await coll0.insert_one({}) - - # Create a new search index on ``coll0``. + # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} - resp = await coll0.create_search_index(model) + resp = await self.coll0.create_search_index(model) # Assert that the command returns the name of the index: ``"test-search-index"``. self.assertEqual(resp, "test-search-index") - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: # An index with the ``name`` of ``test-search-index`` is present and index has a field ``queryable`` with the value of ``true``. - await self.wait_for_ready(coll0) + await self.wait_for_ready(self.coll0) - # Run a ``dropSearchIndex`` on ``coll0``, using ``test-search-index`` for the name. - await coll0.drop_search_index(_NAME) + # Run a ``dropSearchIndex`` on ``self.coll0``, using ``test-search-index`` for the name. + await self.coll0.drop_search_index(_NAME) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until ``listSearchIndexes`` returns an empty array. + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until ``listSearchIndexes`` returns an empty array. t0 = time.time() while True: - indices = await (await coll0.list_search_indexes()).to_list() + indices = await (await self.coll0.list_search_indexes()).to_list() if not indices: break if (time.time() - t0) / 60 > 5: @@ -231,34 +215,31 @@ async def test_case_3(self): async def test_case_4(self): """Driver can update a search index.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - await coll0.insert_one({}) - # Create a new search index on ``coll0``. + # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} - resp = await coll0.create_search_index(model) + resp = await self.coll0.create_search_index(model) # Assert that the command returns the name of the index: ``"test-search-index"``. self.assertEqual(resp, _NAME) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: # An index with the ``name`` of ``test-search-index`` is present and index has a field ``queryable`` with the value of ``true``. - await self.wait_for_ready(coll0) + await self.wait_for_ready(self.coll0) - # Run a ``updateSearchIndex`` on ``coll0``. + # Run a ``updateSearchIndex`` on ``self.coll0``. # Assert that the command does not error and the server responds with a success. model2: dict[str, Any] = {"name": _NAME, "definition": {"mappings": {"dynamic": True}}} - await coll0.update_search_index(_NAME, model2["definition"]) + await self.coll0.update_search_index(_NAME, model2["definition"]) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: # An index with the ``name`` of ``test-search-index`` is present. This index is referred to as ``index``. # The index has a field ``queryable`` with a value of ``true`` and has a field ``status`` with the value of ``READY``. predicate = lambda index: index.get("queryable") is True and index.get("status") == "READY" - await self.wait_for_ready(coll0, predicate=predicate) + await self.wait_for_ready(self.coll0, predicate=predicate) # Assert that an index is present with the name ``test-search-index`` and the definition has a property ``latestDefinition`` whose value is ``{ 'mappings': { 'dynamic': true } }``. - index = (await (await coll0.list_search_indexes(_NAME)).to_list())[0] + index = (await (await self.coll0.list_search_indexes(_NAME)).to_list())[0] self.assertIn("latestDefinition", index) self.assertEqual(index["latestDefinition"], model2["definition"]) @@ -272,12 +253,9 @@ async def test_case_5(self): async def test_case_6(self): """Driver can successfully create and list search indexes with non-default readConcern and writeConcern.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - await coll0.insert_one({}) - # Apply a write concern ``WriteConcern(w=1)`` and a read concern with ``ReadConcern(level="majority")`` to ``coll0``. - coll0 = coll0.with_options( + # Apply a write concern ``WriteConcern(w=1)`` and a read concern with ``ReadConcern(level="majority")`` to ``self.coll0``. + coll0 = self.coll0.with_options( write_concern=WriteConcern(w="1"), read_concern=ReadConcern(level="majority") ) @@ -300,10 +278,6 @@ async def test_case_6(self): async def test_case_7(self): """Driver handles index types.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - await coll0.insert_one({}) - # Use these search and vector search definitions for indexes. search_definition = {"mappings": {"dynamic": False}} vector_search_definition = { @@ -317,30 +291,30 @@ async def test_case_7(self): ] } - # Create a new search index on ``coll0`` that implicitly passes its type. - implicit_search_resp = await coll0.create_search_index( + # Create a new search index on ``self.coll0`` that implicitly passes its type. + implicit_search_resp = await self.coll0.create_search_index( model={"name": _NAME + "-implicit", "definition": search_definition} ) # Get the index definition. - resp = await (await coll0.list_search_indexes(name=implicit_search_resp)).next() + resp = await (await self.coll0.list_search_indexes(name=implicit_search_resp)).next() # Assert that the index model contains the correct index type: ``"search"``. self.assertEqual(resp["type"], "search") - # Create a new search index on ``coll0`` that explicitly passes its type. - explicit_search_resp = await coll0.create_search_index( + # Create a new search index on ``self.coll0`` that explicitly passes its type. + explicit_search_resp = await self.coll0.create_search_index( model={"name": _NAME + "-explicit", "type": "search", "definition": search_definition} ) # Get the index definition. - resp = await (await coll0.list_search_indexes(name=explicit_search_resp)).next() + resp = await (await self.coll0.list_search_indexes(name=explicit_search_resp)).next() # Assert that the index model contains the correct index type: ``"search"``. self.assertEqual(resp["type"], "search") - # Create a new vector search index on ``coll0`` that explicitly passes its type. - explicit_vector_resp = await coll0.create_search_index( + # Create a new vector search index on ``self.coll0`` that explicitly passes its type. + explicit_vector_resp = await self.coll0.create_search_index( model={ "name": _NAME + "-vector", "type": "vectorSearch", @@ -349,14 +323,14 @@ async def test_case_7(self): ) # Get the index definition. - resp = await (await coll0.list_search_indexes(name=explicit_vector_resp)).next() + resp = await (await self.coll0.list_search_indexes(name=explicit_vector_resp)).next() # Assert that the index model contains the correct index type: ``"vectorSearch"``. self.assertEqual(resp["type"], "vectorSearch") # Catch the error raised when trying to create a vector search index without specifying the type with self.assertRaises(OperationFailure) as e: - await coll0.create_search_index( + await self.coll0.create_search_index( model={"name": _NAME + "-error", "definition": vector_search_definition} ) self.assertIn("Attribute mappings missing.", e.exception.details["errmsg"]) diff --git a/test/asynchronous/test_sdam_monitoring_spec.py b/test/asynchronous/test_sdam_monitoring_spec.py index 71ec6c6b46..2fe560ab48 100644 --- a/test/asynchronous/test_sdam_monitoring_spec.py +++ b/test/asynchronous/test_sdam_monitoring_spec.py @@ -296,10 +296,12 @@ async def asyncSetUp(self): event_listeners=[self.listener], retryWrites=retry_writes ) self.coll = self.test_client[self.client.db.name].test - await self.coll.insert_one({}) + await self.coll.drop() # necessary for first test run + await self.coll.database.create_collection(self.coll.name) self.listener.reset() async def asyncTearDown(self): + await self.coll.drop() await super().asyncTearDown() async def _test_app_error(self, fail_command_opts, expected_error): diff --git a/test/asynchronous/test_session.py b/test/asynchronous/test_session.py index c5e51fa2f2..65476c8687 100644 --- a/test/asynchronous/test_session.py +++ b/test/asynchronous/test_session.py @@ -675,7 +675,7 @@ async def test_aggregate_error(self): coll = client.pymongo_test.collection # 3.6.0 mongos only validates the aggregate pipeline when the # database exists. - await coll.insert_one({}) + await coll.database.create_collection(coll.name) listener.reset() with self.assertRaises(OperationFailure): @@ -827,7 +827,7 @@ async def _test_unacknowledged_ops(self, client, *ops): async def test_unacknowledged_writes(self): # Ensure the collection exists. - await self.client.pymongo_test.test_unacked_writes.insert_one({}) + await self.client.pymongo_test.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 @@ -978,6 +978,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") @async_client_context.require_no_standalone async def test_core(self): @@ -1048,9 +1050,6 @@ async def _test_reads(self, op, exception=None): @async_client_context.require_no_standalone async def test_reads(self): - # Make sure the collection exists. - await self.client.pymongo_test.test.insert_one({}) - async def aggregate(coll, session): return await (await coll.aggregate([], session=session)).to_list() @@ -1206,7 +1205,6 @@ async def test_read_concern(self): @async_client_context.require_no_standalone async def test_cluster_time_with_server_support(self): - await self.client.pymongo_test.test.insert_one({}) self.listener.reset() await self.client.pymongo_test.test.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime") @@ -1214,7 +1212,6 @@ async def test_cluster_time_with_server_support(self): @async_client_context.require_standalone async def test_cluster_time_no_server_support(self): - await self.client.pymongo_test.test.insert_one({}) self.listener.reset() await self.client.pymongo_test.test.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime") diff --git a/test/test_change_stream.py b/test/test_change_stream.py index 792b39cc29..717d7d3bd7 100644 --- a/test/test_change_stream.py +++ b/test/test_change_stream.py @@ -908,7 +908,7 @@ def setUp(self): super().setUp() # Use a new collection for each test. self.watched_collection().drop() - self.watched_collection().insert_one({}) + self.db.create_collection(self.watched_collection().name) def change_stream_with_client(self, client, *args, **kwargs): return ( diff --git a/test/test_collection.py b/test/test_collection.py index ac469782e9..a7912100b0 100644 --- a/test/test_collection.py +++ b/test/test_collection.py @@ -229,7 +229,7 @@ def test_create_indexes(self): self.assertRaises(ValueError, IndexModel, []) db.test.drop_indexes() - db.test.insert_one({}) + db.create_collection("test") self.assertEqual(len(db.test.index_information()), 1) db.test.create_indexes([IndexModel("hello")]) @@ -292,7 +292,7 @@ def test_create_index(self): db.test.create_index([]) db.test.drop_indexes() - db.test.insert_one({}) + db.create_collection("test") self.assertEqual(len(db.test.index_information()), 1) db.test.create_index("hello") @@ -386,7 +386,7 @@ def test_index_management_max_time_ms(self): def test_list_indexes(self): db = self.db db.test.drop() - db.test.insert_one({}) # create collection + db.create_collection("test") def map_indexes(indexes): return {index["name"]: index for index in indexes} @@ -420,7 +420,7 @@ def map_indexes(indexes): def test_index_info(self): db = self.db db.test.drop() - db.test.insert_one({}) # create collection + db.create_collection("test") self.assertEqual(len(db.test.index_information()), 1) self.assertIn("_id_", db.test.index_information()) diff --git a/test/test_cursor.py b/test/test_cursor.py index cd13e9bfff..b6f9c4d508 100644 --- a/test/test_cursor.py +++ b/test/test_cursor.py @@ -1504,9 +1504,12 @@ def test_command_cursor_to_list_csot_applied(self): class TestRawBatchCursor(IntegrationTest): + def setUp(self): + super().setUp() + self.db.test.drop() + def test_find_raw(self): c = self.db.test - c.drop() 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() @@ -1516,7 +1519,6 @@ def test_find_raw(self): @client_context.require_transactions def test_find_raw_transaction(self): c = self.db.test - c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1546,7 +1548,6 @@ def test_find_raw_transaction(self): @client_context.require_failCommand_fail_point def test_find_raw_retryable_reads(self): c = self.db.test - c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1567,7 +1568,6 @@ def test_find_raw_retryable_reads(self): @client_context.require_no_standalone def test_find_raw_snapshot_reads(self): c = self.db.get_collection("test", write_concern=WriteConcern(w="majority")) - c.drop() docs = [{"_id": i, "x": 3.0 * i} for i in range(10)] c.insert_many(docs) @@ -1586,12 +1586,10 @@ def test_find_raw_snapshot_reads(self): def test_explain(self): c = self.db.test - c.insert_one({}) explanation = c.find_raw_batches().explain() self.assertIsInstance(explanation, dict) def test_empty(self): - self.db.test.drop() cursor = self.db.test.find_raw_batches() with self.assertRaises(StopIteration): next(cursor) @@ -1606,7 +1604,6 @@ def test_clone(self): @client_context.require_no_mongos def test_exhaust(self): c = self.db.test - c.drop() 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)) @@ -1623,6 +1620,7 @@ def test_get_item(self): self.db.test.find_raw_batches()[0] def test_collation(self): + self.db.test.insert_one({}) next(self.db.test.find_raw_batches(collation=Collation("en_US"))) def test_read_concern(self): @@ -1634,7 +1632,6 @@ def test_monitoring(self): listener = OvertCommandListener() client = self.rs_or_single_client(event_listeners=[listener]) c = client.pymongo_test.test - c.drop() c.insert_many([{"_id": i} for i in range(10)]) listener.reset() diff --git a/test/test_index_management.py b/test/test_index_management.py index 18552d0640..425e6e47c7 100644 --- a/test/test_index_management.py +++ b/test/test_index_management.py @@ -96,9 +96,7 @@ def setUp(self) -> None: ) self.client.drop_database(_NAME) self.db = self.client[self.db_name] - - def tearDown(self): - self.client.drop_database(_NAME) + self.coll0 = self.db.create_collection(f"col{uuid.uuid4()}") def wait_for_ready(self, coll, name=_NAME, predicate=None): """Wait for a search index to be ready.""" @@ -117,14 +115,10 @@ class TestSearchIndexIntegration(SearchIndexIntegrationBase): db_name = "test_search_index" def test_comment_field(self): - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - coll0.insert_one({}) - - # Create a new search index on ``coll0`` that implicitly passes its type. + # Create a new search index on ``self.coll0`` that implicitly passes its type. search_definition = {"mappings": {"dynamic": False}} self.listener.reset() - implicit_search_resp = coll0.create_search_index( + implicit_search_resp = self.coll0.create_search_index( model={"name": _NAME + "-implicit", "definition": search_definition}, comment="foo" ) event = self.listener.events[0] @@ -132,7 +126,7 @@ def test_comment_field(self): # Get the index definition. self.listener.reset() - (coll0.list_search_indexes(name=implicit_search_resp, comment="foo")).next() + (self.coll0.list_search_indexes(name=implicit_search_resp, comment="foo")).next() event = self.listener.events[0] self.assertEqual(event.command["comment"], "foo") @@ -143,20 +137,16 @@ class TestSearchIndexProse(SearchIndexIntegrationBase): def test_case_1(self): """Driver can successfully create and list search indexes.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - - # Create a new search index on ``coll0`` with the ``createSearchIndex`` helper. Use the following definition: + # Create a new search index on ``self.coll0`` with the ``createSearchIndex`` helper. Use the following definition: model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} - coll0.insert_one({}) - resp = coll0.create_search_index(model) + resp = self.coll0.create_search_index(model) # Assert that the command returns the name of the index: ``"test-search-index"``. self.assertEqual(resp, _NAME) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied and store the value in a variable ``index``: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied and store the value in a variable ``index``: # An index with the ``name`` of ``test-search-index`` is present and the index has a field ``queryable`` with a value of ``true``. - index = self.wait_for_ready(coll0) + index = self.wait_for_ready(self.coll0) # . Assert that ``index`` has a property ``latestDefinition`` whose value is ``{ 'mappings': { 'dynamic': false } }`` self.assertIn("latestDefinition", index) @@ -165,11 +155,7 @@ def test_case_1(self): def test_case_2(self): """Driver can successfully create multiple indexes in batch.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - coll0.insert_one({}) - - # Create two new search indexes on ``coll0`` with the ``createSearchIndexes`` helper. + # Create two new search indexes on ``self.coll0`` with the ``createSearchIndexes`` helper. name1 = "test-search-index-1" name2 = "test-search-index-2" definition = {"mappings": {"dynamic": False}} @@ -177,21 +163,21 @@ def test_case_2(self): {"name": name1, "definition": definition}, {"name": name2, "definition": definition}, ] - coll0.create_search_indexes( + self.coll0.create_search_indexes( [SearchIndexModel(i["definition"], i["name"]) for i in index_definitions] ) # .Assert that the command returns an array containing the new indexes' names: ``["test-search-index-1", "test-search-index-2"]``. - indices = (coll0.list_search_indexes()).to_list() + indices = (self.coll0.list_search_indexes()).to_list() names = [i["name"] for i in indices] self.assertIn(name1, names) self.assertIn(name2, names) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied. + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied. # An index with the ``name`` of ``test-search-index-1`` is present and index has a field ``queryable`` with the value of ``true``. Store result in ``index1``. # An index with the ``name`` of ``test-search-index-2`` is present and index has a field ``queryable`` with the value of ``true``. Store result in ``index2``. - index1 = self.wait_for_ready(coll0, name1) - index2 = self.wait_for_ready(coll0, name2) + index1 = self.wait_for_ready(self.coll0, name1) + index2 = self.wait_for_ready(self.coll0, name2) # Assert that ``index1`` and ``index2`` have the property ``latestDefinition`` whose value is ``{ "mappings" : { "dynamic" : false } }`` for index in [index1, index2]: @@ -201,28 +187,24 @@ def test_case_2(self): def test_case_3(self): """Driver can successfully drop search indexes.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - coll0.insert_one({}) - - # Create a new search index on ``coll0``. + # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} - resp = coll0.create_search_index(model) + resp = self.coll0.create_search_index(model) # Assert that the command returns the name of the index: ``"test-search-index"``. self.assertEqual(resp, "test-search-index") - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: # An index with the ``name`` of ``test-search-index`` is present and index has a field ``queryable`` with the value of ``true``. - self.wait_for_ready(coll0) + self.wait_for_ready(self.coll0) - # Run a ``dropSearchIndex`` on ``coll0``, using ``test-search-index`` for the name. - coll0.drop_search_index(_NAME) + # Run a ``dropSearchIndex`` on ``self.coll0``, using ``test-search-index`` for the name. + self.coll0.drop_search_index(_NAME) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until ``listSearchIndexes`` returns an empty array. + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until ``listSearchIndexes`` returns an empty array. t0 = time.time() while True: - indices = (coll0.list_search_indexes()).to_list() + indices = (self.coll0.list_search_indexes()).to_list() if not indices: break if (time.time() - t0) / 60 > 5: @@ -231,34 +213,31 @@ def test_case_3(self): def test_case_4(self): """Driver can update a search index.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - coll0.insert_one({}) - # Create a new search index on ``coll0``. + # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} - resp = coll0.create_search_index(model) + resp = self.coll0.create_search_index(model) # Assert that the command returns the name of the index: ``"test-search-index"``. self.assertEqual(resp, _NAME) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: # An index with the ``name`` of ``test-search-index`` is present and index has a field ``queryable`` with the value of ``true``. - self.wait_for_ready(coll0) + self.wait_for_ready(self.coll0) - # Run a ``updateSearchIndex`` on ``coll0``. + # Run a ``updateSearchIndex`` on ``self.coll0``. # Assert that the command does not error and the server responds with a success. model2: dict[str, Any] = {"name": _NAME, "definition": {"mappings": {"dynamic": True}}} - coll0.update_search_index(_NAME, model2["definition"]) + self.coll0.update_search_index(_NAME, model2["definition"]) - # Run ``coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: + # Run ``self.coll0.listSearchIndexes()`` repeatedly every 5 seconds until the following condition is satisfied: # An index with the ``name`` of ``test-search-index`` is present. This index is referred to as ``index``. # The index has a field ``queryable`` with a value of ``true`` and has a field ``status`` with the value of ``READY``. predicate = lambda index: index.get("queryable") is True and index.get("status") == "READY" - self.wait_for_ready(coll0, predicate=predicate) + self.wait_for_ready(self.coll0, predicate=predicate) # Assert that an index is present with the name ``test-search-index`` and the definition has a property ``latestDefinition`` whose value is ``{ 'mappings': { 'dynamic': true } }``. - index = ((coll0.list_search_indexes(_NAME)).to_list())[0] + index = ((self.coll0.list_search_indexes(_NAME)).to_list())[0] self.assertIn("latestDefinition", index) self.assertEqual(index["latestDefinition"], model2["definition"]) @@ -272,12 +251,9 @@ def test_case_5(self): def test_case_6(self): """Driver can successfully create and list search indexes with non-default readConcern and writeConcern.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - coll0.insert_one({}) - # Apply a write concern ``WriteConcern(w=1)`` and a read concern with ``ReadConcern(level="majority")`` to ``coll0``. - coll0 = coll0.with_options( + # Apply a write concern ``WriteConcern(w=1)`` and a read concern with ``ReadConcern(level="majority")`` to ``self.coll0``. + coll0 = self.coll0.with_options( write_concern=WriteConcern(w="1"), read_concern=ReadConcern(level="majority") ) @@ -300,10 +276,6 @@ def test_case_6(self): def test_case_7(self): """Driver handles index types.""" - # Create a collection with the "create" command using a randomly generated name (referred to as ``coll0``). - coll0 = self.db[f"col{uuid.uuid4()}"] - coll0.insert_one({}) - # Use these search and vector search definitions for indexes. search_definition = {"mappings": {"dynamic": False}} vector_search_definition = { @@ -317,30 +289,30 @@ def test_case_7(self): ] } - # Create a new search index on ``coll0`` that implicitly passes its type. - implicit_search_resp = coll0.create_search_index( + # Create a new search index on ``self.coll0`` that implicitly passes its type. + implicit_search_resp = self.coll0.create_search_index( model={"name": _NAME + "-implicit", "definition": search_definition} ) # Get the index definition. - resp = (coll0.list_search_indexes(name=implicit_search_resp)).next() + resp = (self.coll0.list_search_indexes(name=implicit_search_resp)).next() # Assert that the index model contains the correct index type: ``"search"``. self.assertEqual(resp["type"], "search") - # Create a new search index on ``coll0`` that explicitly passes its type. - explicit_search_resp = coll0.create_search_index( + # Create a new search index on ``self.coll0`` that explicitly passes its type. + explicit_search_resp = self.coll0.create_search_index( model={"name": _NAME + "-explicit", "type": "search", "definition": search_definition} ) # Get the index definition. - resp = (coll0.list_search_indexes(name=explicit_search_resp)).next() + resp = (self.coll0.list_search_indexes(name=explicit_search_resp)).next() # Assert that the index model contains the correct index type: ``"search"``. self.assertEqual(resp["type"], "search") - # Create a new vector search index on ``coll0`` that explicitly passes its type. - explicit_vector_resp = coll0.create_search_index( + # Create a new vector search index on ``self.coll0`` that explicitly passes its type. + explicit_vector_resp = self.coll0.create_search_index( model={ "name": _NAME + "-vector", "type": "vectorSearch", @@ -349,14 +321,14 @@ def test_case_7(self): ) # Get the index definition. - resp = (coll0.list_search_indexes(name=explicit_vector_resp)).next() + resp = (self.coll0.list_search_indexes(name=explicit_vector_resp)).next() # Assert that the index model contains the correct index type: ``"vectorSearch"``. self.assertEqual(resp["type"], "vectorSearch") # Catch the error raised when trying to create a vector search index without specifying the type with self.assertRaises(OperationFailure) as e: - coll0.create_search_index( + self.coll0.create_search_index( model={"name": _NAME + "-error", "definition": vector_search_definition} ) self.assertIn("Attribute mappings missing.", e.exception.details["errmsg"]) diff --git a/test/test_sdam_monitoring_spec.py b/test/test_sdam_monitoring_spec.py index 2167e561cf..9b09c59f83 100644 --- a/test/test_sdam_monitoring_spec.py +++ b/test/test_sdam_monitoring_spec.py @@ -296,10 +296,12 @@ def setUp(self): event_listeners=[self.listener], retryWrites=retry_writes ) self.coll = self.test_client[self.client.db.name].test - self.coll.insert_one({}) + self.coll.drop() # necessary for first test run + self.coll.database.create_collection(self.coll.name) self.listener.reset() def tearDown(self): + self.coll.drop() super().tearDown() def _test_app_error(self, fail_command_opts, expected_error): diff --git a/test/test_session.py b/test/test_session.py index 684c21260d..0ed27fa95f 100644 --- a/test/test_session.py +++ b/test/test_session.py @@ -675,7 +675,7 @@ def test_aggregate_error(self): coll = client.pymongo_test.collection # 3.6.0 mongos only validates the aggregate pipeline when the # database exists. - coll.insert_one({}) + coll.database.create_collection(coll.name) listener.reset() with self.assertRaises(OperationFailure): @@ -827,7 +827,7 @@ def _test_unacknowledged_ops(self, client, *ops): def test_unacknowledged_writes(self): # Ensure the collection exists. - self.client.pymongo_test.test_unacked_writes.insert_one({}) + self.client.pymongo_test.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 @@ -978,6 +978,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") @client_context.require_no_standalone def test_core(self): @@ -1048,9 +1050,6 @@ def _test_reads(self, op, exception=None): @client_context.require_no_standalone def test_reads(self): - # Make sure the collection exists. - self.client.pymongo_test.test.insert_one({}) - def aggregate(coll, session): return (coll.aggregate([], session=session)).to_list() @@ -1200,7 +1199,6 @@ def test_read_concern(self): @client_context.require_no_standalone def test_cluster_time_with_server_support(self): - self.client.pymongo_test.test.insert_one({}) self.listener.reset() self.client.pymongo_test.test.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime") @@ -1208,7 +1206,6 @@ def test_cluster_time_with_server_support(self): @client_context.require_standalone def test_cluster_time_no_server_support(self): - self.client.pymongo_test.test.insert_one({}) self.listener.reset() self.client.pymongo_test.test.find_one({}) after_cluster_time = self.listener.started_events[0].command.get("$clusterTime")