From abb74afe47a2f441da7a0c60b8071d744acd467a Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Mon, 26 Oct 2026 19:41:49 +0000 Subject: [PATCH 1/8] test: route cursor open/getMore failures through the assertion helper killCursors/getMore tests opened a cursor with a raw command and indexed res["cursor"]["id"] directly. When the engine rejects the open the result is an exception, so the index raised a bare TypeError outside the assertion helper and the test could not take an override. Add open_find_cursors_or_error and forward a captured open failure into each test's single assertion so it fails through the helper with the engine's real result. MongoDB behavior and test intent unchanged. Signed-off-by: Samar Farooqi --- .../getMore/test_getMore_lifecycle.py | 19 +- .../commands/getMore/test_getMore_term.py | 11 +- .../killCursors/test_killCursors_lifecycle.py | 269 +++++++++++------- .../killCursors/test_killCursors_response.py | 14 +- .../commands/utils/cursor_test_case.py | 19 ++ 5 files changed, 208 insertions(+), 124 deletions(-) diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py index 9bb31edbb..ef13fc653 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py @@ -5,6 +5,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( open_cursor, open_find_cursors, + open_find_cursors_or_error, ) from documentdb_tests.framework.assertions import assertResult from documentdb_tests.framework.error_codes import ( @@ -221,13 +222,17 @@ def test_getMore_new_inserts_visible(collection): def test_getMore_updated_docs_show_new_value(collection): """Test getMore returns the new value of a document updated before it is reached.""" collection.insert_many([{"_id": i, "v": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - # firstBatch returned _id 0,1; cursor is positioned at _id 2. - collection.update_one({"_id": 4}, {"$set": {"v": 999}}) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, - ) + cursors = open_find_cursors_or_error(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + # firstBatch returned _id 0,1; cursor is positioned at _id 2. + collection.update_one({"_id": 4}, {"$set": {"v": 999}}) + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, + ) assertResult( result, expected={ diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py index 0035c9135..bb81a079c 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py @@ -10,7 +10,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, - open_find_cursors, + open_find_cursors_or_error, ) from documentdb_tests.framework.assertions import assertResult from documentdb_tests.framework.error_codes import TYPE_MISMATCH_ERROR @@ -88,11 +88,14 @@ def test_getMore_term(collection, test_case: CursorCommandTestCase): """Test getMore term field acceptance and type rejection.""" collection.insert_many([{"_id": i, "v": i} for i in range(5)]) - cursors = open_find_cursors( + cursors = open_find_cursors_or_error( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test_case.build_command(ctx)) + if isinstance(cursors, Exception): + result = cursors + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py index 9932ec6f4..1b6817a13 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py @@ -11,6 +11,7 @@ CursorCommandContext, CursorCommandTestCase, open_find_cursors, + open_find_cursors_or_error, ) from documentdb_tests.framework import fixtures from documentdb_tests.framework.assertions import ( @@ -66,12 +67,16 @@ def test_killCursors_lifecycle(database_client, collection, test): """Test killCursors cursor lifecycle.""" collection = test.prepare(database_client, collection) - cursors = open_find_cursors(collection, test.cursor_count) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test.build_command(ctx)) + cursors = open_find_cursors_or_error(collection, test.cursor_count) + if isinstance(cursors, Exception): + result, expected = cursors, None + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test.build_command(ctx)) + expected = test.build_expected(ctx) assertResult( result, - expected=test.build_expected(ctx), + expected=expected, error_code=test.error_code, msg=test.msg, raw_res=True, @@ -85,10 +90,14 @@ def test_killCursors_aggregate_cursor(collection): collection, {"aggregate": collection.name, "pipeline": [], "cursor": {"batchSize": 1}}, ) - cursor_id = res["cursor"]["id"] - result = execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, + cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] + result = ( + res + if isinstance(res, Exception) + else execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) ) assertResult( result, @@ -113,10 +122,14 @@ def test_killCursors_list_collections_cursor(database_client, collection): collection, {"listCollections": 1, "cursor": {"batchSize": 1}}, ) - cursor_id = res["cursor"]["id"] - result = execute_command( - collection, - {"killCursors": "$cmd.listCollections", "cursors": [cursor_id]}, + cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] + result = ( + res + if isinstance(res, Exception) + else execute_command( + collection, + {"killCursors": "$cmd.listCollections", "cursors": [cursor_id]}, + ) ) assertResult( result, @@ -141,10 +154,14 @@ def test_killCursors_list_indexes_cursor(collection): collection, {"listIndexes": collection.name, "cursor": {"batchSize": 1}}, ) - cursor_id = res["cursor"]["id"] - result = execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, + cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] + result = ( + res + if isinstance(res, Exception) + else execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) ) assertResult( result, @@ -201,10 +218,14 @@ def test_killCursors_timeseries_cursor(database_client, collection): [{"ts": datetime.datetime(2024, 1, 1) + datetime.timedelta(minutes=i)} for i in range(20)] ) res = execute_command(ts, {"find": ts_name, "batchSize": 1}) - cursor_id = res["cursor"]["id"] - result = execute_command( - ts, - {"killCursors": ts_name, "cursors": [cursor_id]}, + cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] + result = ( + res + if isinstance(res, Exception) + else execute_command( + ts, + {"killCursors": ts_name, "cursors": [cursor_id]}, + ) ) assertResult( result, @@ -275,15 +296,19 @@ def test_killCursors_getmore_after_kill(collection): def test_killCursors_sibling_unaffected(collection): """Test killing one cursor does not affect siblings.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursor_a, cursor_b = open_find_cursors(collection, 2) - execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_a]}, - ) - getmore = execute_command( - collection, - {"getMore": cursor_b, "collection": collection.name}, - ) + cursors = open_find_cursors_or_error(collection, 2) + if isinstance(cursors, Exception): + getmore = cursors + else: + cursor_a, cursor_b = cursors + execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_a]}, + ) + getmore = execute_command( + collection, + {"getMore": cursor_b, "collection": collection.name}, + ) assertSuccessPartial(getmore, {"ok": 1.0}, msg="killCursors should not affect sibling cursors") @@ -293,15 +318,19 @@ def test_killCursors_sibling_unaffected(collection): def test_killCursors_atomic_precheck_cursor_survives(collection): """Test valid cursors survive when type validation fails.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) - execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id, "bad"]}, - ) - getmore = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors_or_error(collection, 1) + if isinstance(cursors, Exception): + getmore = cursors + else: + (cursor_id,) = cursors + execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id, "bad"]}, + ) + getmore = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertSuccessPartial( getmore, {"ok": 1.0}, @@ -314,26 +343,31 @@ def test_killCursors_atomic_precheck_cursor_survives(collection): def test_killCursors_idempotency(collection): """Test killing the same cursor twice.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) - - execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) + cursors = open_find_cursors_or_error(collection, 1) + if isinstance(cursors, Exception): + result, expected = cursors, None + else: + (cursor_id,) = cursors + + execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) - result = execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) - assertResult( - result, - expected={ + result = execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) + expected = { "cursorsKilled": [], "cursorsNotFound": [cursor_id], "cursorsAlive": [], "cursorsUnknown": [], "ok": 1.0, - }, + } + assertResult( + result, + expected=expected, msg="killCursors should report cursor in cursorsNotFound on second kill", raw_res=True, ) @@ -346,31 +380,36 @@ def test_killCursors_mixed_states(collection): """Test mixed active, killed, and non-existent cursor IDs.""" collection.insert_many([{"_id": i} for i in range(10)]) - active_cursor, pre_killed_cursor = open_find_cursors(collection, 2) + cursors = open_find_cursors_or_error(collection, 2) + if isinstance(cursors, Exception): + result, expected = cursors, None + else: + active_cursor, pre_killed_cursor = cursors - execute_command( - collection, - {"killCursors": collection.name, "cursors": [pre_killed_cursor]}, - ) + execute_command( + collection, + {"killCursors": collection.name, "cursors": [pre_killed_cursor]}, + ) - nonexistent_cursor = Int64(999_999_999) + nonexistent_cursor = Int64(999_999_999) - result = execute_command( - collection, - { - "killCursors": collection.name, - "cursors": [active_cursor, pre_killed_cursor, nonexistent_cursor], - }, - ) - assertResult( - result, - expected={ + result = execute_command( + collection, + { + "killCursors": collection.name, + "cursors": [active_cursor, pre_killed_cursor, nonexistent_cursor], + }, + ) + expected = { "cursorsKilled": [active_cursor], "cursorsNotFound": [pre_killed_cursor, nonexistent_cursor], "cursorsAlive": [], "cursorsUnknown": [], "ok": 1.0, - }, + } + assertResult( + result, + expected=expected, msg="killCursors should categorize active, killed, and non-existent IDs correctly", raw_res=True, ) @@ -382,23 +421,28 @@ def test_killCursors_mixed_states(collection): def test_killCursors_after_drop_collection(database_client, collection): """Test cursor remains killable after source collection is dropped.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) + cursors = open_find_cursors_or_error(collection, 1) + if isinstance(cursors, Exception): + result, expected = cursors, None + else: + (cursor_id,) = cursors - database_client.drop_collection(collection.name) + database_client.drop_collection(collection.name) - result = execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) - assertResult( - result, - expected={ + result = execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) + expected = { "cursorsKilled": [cursor_id], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], "ok": 1.0, - }, + } + assertResult( + result, + expected=expected, msg="killCursors should kill cursor after collection is dropped", raw_res=True, ) @@ -441,24 +485,29 @@ def test_killCursors_after_rename_collection( def test_killCursors_after_recreate_collection(database_client, collection): """Test cursor remains killable after source collection is recreated.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) + cursors = open_find_cursors_or_error(collection, 1) + if isinstance(cursors, Exception): + result, expected = cursors, None + else: + (cursor_id,) = cursors - database_client.drop_collection(collection.name) - database_client[collection.name].insert_one({"_id": 1, "new": True}) + database_client.drop_collection(collection.name) + database_client[collection.name].insert_one({"_id": 1, "new": True}) - result = execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) - assertResult( - result, - expected={ + result = execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) + expected = { "cursorsKilled": [cursor_id], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], "ok": 1.0, - }, + } + assertResult( + result, + expected=expected, msg="killCursors should kill cursor after collection is recreated", raw_res=True, ) @@ -494,26 +543,30 @@ def test_killCursors_after_drop_database(engine_client, database_client, collect def test_killCursors_cross_connection(connection_string, database_client, collection): """Test killing a cursor from a different connection.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) - - second_client = fixtures.create_engine_client(connection_string, "second") - try: - second_coll = second_client[database_client.name][collection.name] - result = execute_command( - second_coll, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) - assertResult( - result, - expected={ + cursors = open_find_cursors_or_error(collection, 1) + if isinstance(cursors, Exception): + result, expected = cursors, None + else: + (cursor_id,) = cursors + second_client = fixtures.create_engine_client(connection_string, "second") + try: + second_coll = second_client[database_client.name][collection.name] + result = execute_command( + second_coll, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) + expected = { "cursorsKilled": [cursor_id], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], "ok": 1.0, - }, - msg="killCursors should kill cursor from a different connection", - raw_res=True, - ) - finally: - second_client.close() + } + finally: + second_client.close() + assertResult( + result, + expected=expected, + msg="killCursors should kill cursor from a different connection", + raw_res=True, + ) diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py index 712b3280c..a9c2c7890 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py @@ -8,7 +8,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, - open_find_cursors, + open_find_cursors_or_error, ) from documentdb_tests.compatibility.tests.core.utils.command_test_case import ( CommandContext, @@ -174,12 +174,16 @@ def test_killCursors_response_cmd(collection, test): def test_killCursors_response_cursor(database_client, collection, test): """Test killCursors response structure with active cursors.""" collection = test.prepare(database_client, collection) - cursors = open_find_cursors(collection, test.cursor_count) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test.build_command(ctx)) + cursors = open_find_cursors_or_error(collection, test.cursor_count) + if isinstance(cursors, Exception): + result, expected = cursors, None + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test.build_command(ctx)) + expected = test.build_expected(ctx) assertResult( result, - expected=test.build_expected(ctx), + expected=expected, error_code=test.error_code, msg=test.msg, raw_res=True, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py b/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py index 110f8e8d5..c2cfbc4ff 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py @@ -46,6 +46,25 @@ def open_find_cursors( return tuple(ids) +def open_find_cursors_or_error( + collection: Collection, count: int, *, batch_size: int = 1 +) -> tuple[Any, ...] | Exception: + """Like ``open_find_cursors`` but return the engine error instead of crashing. + + When opening any of the find cursors fails, the exception is returned so the + caller can forward it to the test's single assertion rather than indexing + into the exception (which would raise a bare ``TypeError`` outside the + assertion helper). + """ + ids = [] + for _ in range(count): + res = execute_command(collection, {"find": collection.name, "batchSize": batch_size}) + if isinstance(res, Exception): + return res + ids.append(res["cursor"]["id"]) + return tuple(ids) + + def open_cursor(collection: Collection, find_options: dict[str, Any]) -> Any: """Open a cursor on ``collection`` with the given find options and return its ID. From 467104b7c3ba40890f9c00b6a6926bb9dd0ee0fa Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Mon, 26 Oct 2026 19:41:49 +0000 Subject: [PATCH 2/8] test: route change-stream open failures through the assertion helper These tests opened a base $changeStream and read opened["cursor"]["postBatchResumeToken"] directly; when the open is rejected the result is an exception and the index raised a bare TypeError outside the helper. Forward a captured open failure into the single assertResult. MongoDB behavior and test intent unchanged. Signed-off-by: Samar Farooqi --- ..._changeStream_resume_mutual_exclusivity.py | 23 +++++++++++-------- .../test_changeStream_spec_acceptance.py | 13 +++++++---- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume_mutual_exclusivity.py b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume_mutual_exclusivity.py index 52528e793..f5ef55ab2 100644 --- a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume_mutual_exclusivity.py +++ b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume_mutual_exclusivity.py @@ -53,14 +53,17 @@ def test_changeStream_resume_option_mutual_exclusivity(collection, test_case): opened = execute_command( collection, change_stream_command(collection, pipeline=[{"$changeStream": {}}]) ) - token = opened["cursor"]["postBatchResumeToken"] - operation_time = opened["operationTime"] - substitutions = {id(RESUME_TOKEN): token, id(OPERATION_TIME): operation_time} - spec = { - key: substitutions.get(id(value), value) - for key, value in test_case.pipeline[0]["$changeStream"].items() - } - result = execute_command( - collection, change_stream_command(collection, pipeline=[{"$changeStream": spec}]) - ) + if isinstance(opened, Exception): + result = opened + else: + token = opened["cursor"]["postBatchResumeToken"] + operation_time = opened["operationTime"] + substitutions = {id(RESUME_TOKEN): token, id(OPERATION_TIME): operation_time} + spec = { + key: substitutions.get(id(value), value) + for key, value in test_case.pipeline[0]["$changeStream"].items() + } + result = execute_command( + collection, change_stream_command(collection, pipeline=[{"$changeStream": spec}]) + ) assertResult(result, error_code=test_case.error_code, msg=test_case.msg) diff --git a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_spec_acceptance.py b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_spec_acceptance.py index d30312287..b3fdbe451 100644 --- a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_spec_acceptance.py +++ b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_spec_acceptance.py @@ -213,12 +213,15 @@ def test_changeStream_null_resume_option_non_conflict(collection, present_field, opened = execute_command( collection, change_stream_command(collection, pipeline=[{"$changeStream": {}}]) ) - token = opened["cursor"]["postBatchResumeToken"] + if isinstance(opened, Exception): + result = opened + else: + token = opened["cursor"]["postBatchResumeToken"] - spec = {present_field: token, null_field: None} - result = execute_command( - collection, change_stream_command(collection, pipeline=[{"$changeStream": spec}]) - ) + spec = {present_field: token, null_field: None} + result = execute_command( + collection, change_stream_command(collection, pipeline=[{"$changeStream": spec}]) + ) assertResult( result, expected={"ok": Eq(1.0)}, From 60b2a5c49d672dbac7b30aaf02840c2e237c5da1 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Mon, 26 Oct 2026 19:41:49 +0000 Subject: [PATCH 3/8] test: route projection/collStats command failures through the assertion helper test_rand_in_object_expression indexed result["cursor"]["firstBatch"] on a raw result, and the collStats histogram test raised a bare AssertionError on an engine error. Route both through the assertion helper (guarded index / assertResult not_error) so they fail overridably with the real result. MongoDB behavior unchanged. Signed-off-by: Samar Farooqi --- .../expressions/test_expressions_combination_rand.py | 2 +- .../operator/stages/collStats/test_collStats_output.py | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_rand.py b/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_rand.py index 2c81fa1af..77eb29022 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_rand.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_rand.py @@ -28,7 +28,7 @@ def test_rand_nested_in_multiply(collection): def test_rand_in_object_expression(collection): """Test rand in object expression context.""" result = execute_project(collection, {"result": {"a": {"$rand": {}}}}) - batch = result["cursor"]["firstBatch"] + batch = result["cursor"]["firstBatch"] if isinstance(result, dict) else None assertSuccess(result, batch, msg="Should produce object with rand field") diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py b/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py index f46ef86d9..1c13a385e 100644 --- a/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py +++ b/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py @@ -8,7 +8,7 @@ from documentdb_tests.compatibility.tests.core.operator.stages.collStats.utils.collStats_helpers import ( # noqa: E501 CollStatsTestCase, ) -from documentdb_tests.framework.assertions import assertProperties +from documentdb_tests.framework.assertions import assertProperties, assertResult from documentdb_tests.framework.executor import execute_command from documentdb_tests.framework.parametrize import pytest_params from documentdb_tests.framework.property_checks import Eq, Exists, IsType, NotExists @@ -238,7 +238,13 @@ def test_collStats_output_histogram_structure(collection): ) if isinstance(result, Exception): - raise AssertionError(f"unexpected error: {result}") + # Route the engine error through the assertion helper so it fails + # overridably with the real result instead of raising outside it. + assertResult( + result, + not_error=True, + msg="$collStats latencyStats histograms should succeed", + ) doc = result["cursor"]["firstBatch"][0] errors: list[str] = [] for name in ["reads", "writes", "commands", "transactions"]: From b5818cccb60aef1bae8dc9ea078f3ec62529bb1c Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Mon, 26 Oct 2026 19:41:49 +0000 Subject: [PATCH 4/8] test: route data-load/setup/commit failures through the assertion helper geospatial and wildcard valid-data tests loaded docs with collection.insert_many (raises BulkWriteError); dbStats re-raised a setup failure; listIndexes enabled the profiler with a raw db.command; commitTransaction called session.commit_transaction after an op the engine rejects in a txn. Each raised outside the assertion helper. Load via execute_command / forward the captured setup/commit failure into the single assertion so each fails overridably with the engine's real result. MongoDB unchanged. Signed-off-by: Samar Farooqi --- .../test_listIndexes_collection_variants.py | 62 ++++++++++--------- .../geospatial/test_geospatial_creation.py | 6 +- .../wildcard/test_wildcard_data_types.py | 6 +- ..._commitTransaction_supported_operations.py | 24 ++++++- .../test_dbStats_collection_scenarios.py | 11 +++- 5 files changed, 73 insertions(+), 36 deletions(-) diff --git a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py index 5a3b36b86..c4d4fb02a 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py +++ b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py @@ -256,36 +256,40 @@ def test_listIndexes_comment_inherited_by_getMore(collection): }, ) - db.command({"profile": 2}) - - try: - result = execute_command( - collection, - { - "listIndexes": collection.name, - "cursor": {"batchSize": 1}, - "comment": "getmore_inherit_test", - }, - ) - cursor_id = result["cursor"]["id"] - execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) - - result = execute_command( - db["system.profile"], - { - "count": "system.profile", - "query": { - "command.getMore": {"$exists": True}, - "command.comment": "getmore_inherit_test", + # Enabling the profiler can be rejected by the engine (profiling is not a + # supported feature on every target). Route that through the single + # assertion so it fails overridably with the real error instead of raising + # outside the helper. No cleanup is needed when it was never enabled. + profile_on = execute_command(collection, {"profile": 2}) + if isinstance(profile_on, Exception): + result = profile_on + else: + try: + listed = execute_command( + collection, + { + "listIndexes": collection.name, + "cursor": {"batchSize": 1}, + "comment": "getmore_inherit_test", }, - }, - ) - assertSuccessPartial( - result, {"n": 1}, msg="Comment should be inherited by getMore in profiler" - ) - finally: - db.command({"profile": 0}) - db.system.profile.drop() + ) + cursor_id = listed["cursor"]["id"] + execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) + + result = execute_command( + db["system.profile"], + { + "count": "system.profile", + "query": { + "command.getMore": {"$exists": True}, + "command.comment": "getmore_inherit_test", + }, + }, + ) + finally: + db.command({"profile": 0}) + db.system.profile.drop() + assertSuccessPartial(result, {"n": 1}, msg="Comment should be inherited by getMore in profiler") def test_listIndexes_system_buckets_collection(database_client): diff --git a/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py b/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py index d59839b0d..d4d729033 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py +++ b/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py @@ -272,7 +272,11 @@ def test_geospatial_2dsphere_valid_data(collection, test): collection, {"createIndexes": collection.name, "indexes": list(test.indexes)}, ) - collection.insert_many(list(test.doc)) + # Load the documents through execute_command (not collection.insert_many) so a + # rejection by the engine is captured rather than raising BulkWriteError + # outside the assertion helper; a rejected insert then surfaces as the find + # result diverging from the expected documents in the single assertion below. + execute_command(collection, {"insert": collection.name, "documents": list(test.doc)}) result = execute_command( collection, {"find": collection.name, "hint": test.indexes[0]["name"], "sort": {"_id": 1}} ) diff --git a/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py b/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py index 18afa27da..9ec391a31 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py +++ b/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py @@ -524,7 +524,11 @@ def test_wildcard_special_types(collection, test): collection, {"createIndexes": collection.name, "indexes": list(test.indexes)}, ) - collection.insert_many(list(test.doc)) + # Load through execute_command (not collection.insert_many) so a value the + # engine rejects (e.g. a JavaScript-code BSON value) is captured instead of + # raising outside the assertion helper; a rejected insert then surfaces as + # the find result diverging from the expected document below. + execute_command(collection, {"insert": collection.name, "documents": list(test.doc)}) result = execute_command( collection, {"find": collection.name, "filter": test.filter, "hint": test.hint} ) diff --git a/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py b/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py index 9cc3b8dc2..754b41cde 100644 --- a/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py +++ b/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py @@ -18,6 +18,24 @@ pytestmark = [pytest.mark.admin, pytest.mark.requires(transactions=True)] +def _commit_or_error(session, result): + """Commit the transaction, returning the engine error instead of raising. + + When the operation under test already failed (``result`` is an exception), + the transaction cannot commit, so its failure is returned unchanged. When + the operation succeeded, a commit failure is captured and returned so the + single assertion surfaces the engine's real error instead of raising a bare + exception outside the assertion helper. + """ + if isinstance(result, Exception): + return result + try: + session.commit_transaction() + except Exception as error: # noqa: BLE001 - forwarded to the assertion helper + return error + return result + + def test_find_runs_in_transaction(collection): """A find issued inside a transaction returns the collection's documents.""" collection.insert_one({"_id": 1}) @@ -117,7 +135,7 @@ def test_bulkWrite_runs_in_transaction(collection): }, session=session, ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) @@ -127,7 +145,7 @@ def test_create_collection_runs_in_transaction(collection): with client.start_session() as session: session.start_transaction() result = execute_command(collection, {"create": f"{collection.name}_new"}, session=session) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) @@ -174,7 +192,7 @@ def test_createIndexes_on_new_collection_runs_in_transaction(collection): {"createIndexes": new_collection, "indexes": [{"key": {"x": 1}, "name": "x_1"}]}, session=session, ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/commands/dbStats/test_dbStats_collection_scenarios.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/dbStats/test_dbStats_collection_scenarios.py index e631c837e..e20c90a87 100644 --- a/documentdb_tests/compatibility/tests/system/diagnostic/commands/dbStats/test_dbStats_collection_scenarios.py +++ b/documentdb_tests/compatibility/tests/system/diagnostic/commands/dbStats/test_dbStats_collection_scenarios.py @@ -61,9 +61,16 @@ @pytest.mark.parametrize("test", pytest_params(COLLECTION_SCENARIO_TESTS)) def test_dbStats_collection_scenarios(collection, test): """Test dbStats database-level counts and sizes across collection variants and data shapes.""" + # Forward a setup failure (e.g. an unsupported capped collection) to the + # single assertion so it fails through the helper with the engine's real + # error instead of raising outside it. + setup_failure = None for setup_command in test.setup: setup_result = execute_command(collection, setup_command) if isinstance(setup_result, Exception): - raise setup_result - result = execute_command(collection, test.command) + setup_failure = setup_result + break + result = ( + setup_failure if setup_failure is not None else execute_command(collection, test.command) + ) assertProperties(result, test.checks, msg=test.msg, raw_res=True) From 7834bf4fc059910862cfa93b0f1aafaf26019c5f Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Mon, 26 Oct 2026 19:27:49 +0000 Subject: [PATCH 5/8] fix(smoke): Isolate auth smoke tests and tolerate unsupported setup commands Four section-4 "smoke tests no run can judge" issues not covered by #731: - logout: run on a dedicated client. logout de-authenticates the connection it runs on; on the shared pooled session connection it logs out every later test on the same xdist worker (authorization failure). - rolesInfo / usersInfo: query only the role/user the test creates, not the whole database. `{"rolesInfo": 1}` / `{"usersInfo": 1}` list every object, including ones parallel tests create and drop, so the result is non-deterministic. - fsync/autoCompact setup helpers (drain_fsync_lock, ensure_autocompact_idle): return instead of raising when the command is unsupported (COMMAND_NOT_FOUND 59 / FEATURE_NOT_SUPPORTED 303), so the test under test runs and judges the command instead of failing in setup. Each probe keeps the same assertion and is unchanged on an engine that supports the command. Verified on MongoDB 8.2.4. Signed-off-by: Samar Farooqi --- .../autoCompact/utils/autoCompact_common.py | 17 ++++++++++++++++- .../system/administration/utils/fsync_lock.py | 18 +++++++++++++++--- .../commands/logout/test_smoke_logout.py | 18 +++++++++++++++--- .../commands/rolesInfo/test_smoke_rolesInfo.py | 17 +++++++++++++++-- .../commands/usersInfo/test_smoke_usersInfo.py | 17 +++++++++++++++-- 5 files changed, 76 insertions(+), 11 deletions(-) diff --git a/documentdb_tests/compatibility/tests/system/administration/commands/autoCompact/utils/autoCompact_common.py b/documentdb_tests/compatibility/tests/system/administration/commands/autoCompact/utils/autoCompact_common.py index ee9b6a833..6803d2a3c 100644 --- a/documentdb_tests/compatibility/tests/system/administration/commands/autoCompact/utils/autoCompact_common.py +++ b/documentdb_tests/compatibility/tests/system/administration/commands/autoCompact/utils/autoCompact_common.py @@ -2,9 +2,18 @@ from __future__ import annotations -from documentdb_tests.framework.error_codes import OBJECT_IS_BUSY_ERROR +from documentdb_tests.framework.error_codes import ( + COMMAND_NOT_FOUND_ERROR, + FEATURE_NOT_SUPPORTED_ERROR, + OBJECT_IS_BUSY_ERROR, +) from documentdb_tests.framework.executor import execute_admin_with_retry_command +# Codes a server returns when autoCompact is not available at all (command +# unknown, or the feature unsupported). On such an engine there is no +# server-wide compaction state to reset, so the idle baseline is already met. +_UNSUPPORTED_CODES = frozenset({COMMAND_NOT_FOUND_ERROR, FEATURE_NOT_SUPPORTED_ERROR}) + def ensure_autocompact_idle(collection): """Reset autoCompact to a disabled baseline before a test runs. @@ -16,9 +25,15 @@ def ensure_autocompact_idle(collection): Callers must be marked no_parallel: this only resets state left by a prior test, not a concurrent worker mutating the shared setting between the reset and the command under test. + + If autoCompact is unsupported, there is no compaction state to reset, so + return instead of raising and let the test under test run and judge the + command. """ result = execute_admin_with_retry_command( collection, {"autoCompact": False}, retry_code=OBJECT_IS_BUSY_ERROR ) + if isinstance(result, Exception) and getattr(result, "code", None) in _UNSUPPORTED_CODES: + return if not (isinstance(result, dict) and result.get("ok") == 1.0): raise RuntimeError(f"autoCompact did not reach an idle state: {result!r}") diff --git a/documentdb_tests/compatibility/tests/system/administration/utils/fsync_lock.py b/documentdb_tests/compatibility/tests/system/administration/utils/fsync_lock.py index 219c3ed22..d0c27f814 100644 --- a/documentdb_tests/compatibility/tests/system/administration/utils/fsync_lock.py +++ b/documentdb_tests/compatibility/tests/system/administration/utils/fsync_lock.py @@ -11,21 +11,33 @@ import pytest -from documentdb_tests.framework.error_codes import ILLEGAL_OPERATION_ERROR +from documentdb_tests.framework.error_codes import ( + COMMAND_NOT_FOUND_ERROR, + FEATURE_NOT_SUPPORTED_ERROR, + ILLEGAL_OPERATION_ERROR, +) from documentdb_tests.framework.executor import execute_admin_command +# Codes a server returns when fsyncUnlock is not available at all (command +# unknown, or the feature unsupported). On such an engine there is no +# server-global fsync lock to manage, so the unlocked baseline is already met. +_UNSUPPORTED_CODES = frozenset({COMMAND_NOT_FOUND_ERROR, FEATURE_NOT_SUPPORTED_ERROR}) + def drain_fsync_lock(collection) -> None: """Release outstanding fsync locks until the server-global count reaches 0. Loops fsyncUnlock until the reported count is 0, treating the not-locked error as "already 0" and re-raising any other error so an unexpected failure - cannot silently leave the server locked. + cannot silently leave the server locked. If fsyncUnlock itself is + unsupported, there is no lock state to drain, so return instead of failing + every fsync/fsyncUnlock test's setup. """ while True: result = execute_admin_command(collection, {"fsyncUnlock": 1}) if isinstance(result, Exception): - if getattr(result, "code", None) == ILLEGAL_OPERATION_ERROR: + code = getattr(result, "code", None) + if code == ILLEGAL_OPERATION_ERROR or code in _UNSUPPORTED_CODES: return raise result if result.get("lockCount", 0) == 0: diff --git a/documentdb_tests/compatibility/tests/system/security/authentication/commands/logout/test_smoke_logout.py b/documentdb_tests/compatibility/tests/system/security/authentication/commands/logout/test_smoke_logout.py index 254384a45..5aec8d165 100644 --- a/documentdb_tests/compatibility/tests/system/security/authentication/commands/logout/test_smoke_logout.py +++ b/documentdb_tests/compatibility/tests/system/security/authentication/commands/logout/test_smoke_logout.py @@ -5,6 +5,7 @@ """ import pytest +from pymongo import MongoClient from documentdb_tests.framework.assertions import assertCommandSupported from documentdb_tests.framework.executor import execute_command @@ -12,8 +13,19 @@ pytestmark = pytest.mark.smoke -def test_smoke_logout(collection): - """Test basic logout behavior.""" - result = execute_command(collection, {"logout": 1}) +def test_smoke_logout(collection, connection_string): + """Test basic logout behavior. + + logout de-authenticates the connection it runs on, so it must run on a + dedicated client. Running it on the shared, pooled session connection would + log that connection out and make every later test on the same worker fail + with an authorization error. + """ + dedicated_client: MongoClient = MongoClient(connection_string) + try: + isolated_collection = dedicated_client[collection.database.name][collection.name] + result = execute_command(isolated_collection, {"logout": 1}) + finally: + dedicated_client.close() assertCommandSupported(result, msg="Should support logout command") diff --git a/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py b/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py index 35fc4b782..186ffae80 100644 --- a/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py +++ b/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py @@ -13,8 +13,21 @@ def test_smoke_rolesInfo(collection): - """Test basic rolesInfo behavior.""" - result = execute_admin_command(collection, {"rolesInfo": 1}) + """Test basic rolesInfo behavior. + + Queries rolesInfo for only the role this test creates, not the whole + server. ``{"rolesInfo": 1}`` lists every role in the database, including + roles that parallel tests create and drop, which makes the result + non-deterministic. Scoping to the test's own role keeps the capability + probe deterministic under parallel execution. + """ + role_name = f"{collection.name}_test_role" + + execute_admin_command(collection, {"createRole": role_name, "privileges": [], "roles": []}) + try: + result = execute_admin_command(collection, {"rolesInfo": role_name}) + finally: + execute_admin_command(collection, {"dropRole": role_name}) expected = {"ok": 1.0} assertSuccessPartial(result, expected, msg="Should support rolesInfo command") diff --git a/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py b/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py index 048f3b983..2a5e5074b 100644 --- a/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py +++ b/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py @@ -13,8 +13,21 @@ def test_smoke_usersInfo(collection): - """Test basic usersInfo behavior.""" - result = execute_admin_command(collection, {"usersInfo": 1}) + """Test basic usersInfo behavior. + + Queries usersInfo for only the user this test creates, not the whole + server. ``{"usersInfo": 1}`` lists every user in the database, including + users that parallel tests create and drop, which makes the result + non-deterministic. Scoping to the test's own user keeps the capability + probe deterministic under parallel execution. + """ + user_name = f"{collection.name}_test_user" + + execute_admin_command(collection, {"createUser": user_name, "pwd": "testPassword", "roles": []}) + try: + result = execute_admin_command(collection, {"usersInfo": user_name}) + finally: + execute_admin_command(collection, {"dropUser": user_name}) expected = {"ok": 1.0} assertSuccessPartial(result, expected, msg="Should support usersInfo command") From b38cf102b318679ce0f3ba88f2d3cd8aba7fd0a8 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Wed, 28 Oct 2026 21:41:39 +0000 Subject: [PATCH 6/8] fix(smoke): Use assertCommandSupported for rolesInfo/usersInfo probes Match the capability-probe pattern from #731 so these smoke tests stop failing on the cosmetic ok int32 vs double difference. Signed-off-by: Samar Farooqi --- .../role/commands/rolesInfo/test_smoke_rolesInfo.py | 5 ++--- .../user/commands/usersInfo/test_smoke_usersInfo.py | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py b/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py index 186ffae80..c21210da5 100644 --- a/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py +++ b/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py @@ -6,7 +6,7 @@ import pytest -from documentdb_tests.framework.assertions import assertSuccessPartial +from documentdb_tests.framework.assertions import assertCommandSupported from documentdb_tests.framework.executor import execute_admin_command pytestmark = pytest.mark.smoke @@ -29,5 +29,4 @@ def test_smoke_rolesInfo(collection): finally: execute_admin_command(collection, {"dropRole": role_name}) - expected = {"ok": 1.0} - assertSuccessPartial(result, expected, msg="Should support rolesInfo command") + assertCommandSupported(result, msg="Should support rolesInfo command") diff --git a/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py b/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py index 2a5e5074b..c8833f63b 100644 --- a/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py +++ b/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py @@ -6,7 +6,7 @@ import pytest -from documentdb_tests.framework.assertions import assertSuccessPartial +from documentdb_tests.framework.assertions import assertCommandSupported from documentdb_tests.framework.executor import execute_admin_command pytestmark = pytest.mark.smoke @@ -29,5 +29,4 @@ def test_smoke_usersInfo(collection): finally: execute_admin_command(collection, {"dropUser": user_name}) - expected = {"ok": 1.0} - assertSuccessPartial(result, expected, msg="Should support usersInfo command") + assertCommandSupported(result, msg="Should support usersInfo command") From 203e2e2455e71dd7df698a23af588d3448d15e00 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Wed, 21 Oct 2026 00:14:40 +0000 Subject: [PATCH 7/8] Close server cursors that tests open with raw commands execute_command and execute_admin_command return the raw command result, so a find with a small batchSize or an aggregate with $changeStream leaves a server cursor that no driver object owns. Nothing closes it when the test ends, and dropping the test database does not close it on every engine. The cursor stays open until the server's idle timeout. On an engine that caps open cursors per instance, those leftovers add up until a later test's find or aggregate is rejected with "Cannot open a new cursor since too many cursors are already opened". Which test hits the cap depends on timing and test order, so the failures look flaky and land on tests that did nothing wrong. Track the cursor id and namespace of every command result that returns an open cursor, and kill them with killCursors at teardown: in the collection and database_client fixtures before the drop, and in a new autouse fixture for tests that use neither. Cleanup is best effort and never changes a test's outcome. Signed-off-by: Samar Farooqi --- documentdb_tests/conftest.py | 21 ++- documentdb_tests/framework/executor.py | 47 +++++- .../test_executor_cursor_tracking.py | 137 ++++++++++++++++++ 3 files changed, 201 insertions(+), 4 deletions(-) create mode 100644 documentdb_tests/framework/test_executor_cursor_tracking.py diff --git a/documentdb_tests/conftest.py b/documentdb_tests/conftest.py index 59153419c..93efd0f0f 100644 --- a/documentdb_tests/conftest.py +++ b/documentdb_tests/conftest.py @@ -17,7 +17,7 @@ import warnings # noqa: E402 from pathlib import Path # noqa: E402 -from documentdb_tests.framework import fixtures # noqa: E402 +from documentdb_tests.framework import executor, fixtures # noqa: E402 from documentdb_tests.framework.engine_registry import ( # noqa: E402 Target, ensure_initiated, @@ -305,7 +305,9 @@ def database_client(engine_client, request, worker_id): yield db - # Cleanup: drop test database + # Cleanup: close the server cursors the test left open, then drop the + # test database. Dropping does not close cursors on every engine. + executor.close_tracked_cursors() fixtures.cleanup_database(engine_client, db_name) @@ -333,10 +335,23 @@ def collection(database_client, request, worker_id): yield coll - # Cleanup: drop collection + # Cleanup: close the server cursors the test left open, then drop the + # collection. Dropping does not close cursors on every engine. + executor.close_tracked_cursors() fixtures.cleanup_collection(database_client, collection_name) +@pytest.fixture(autouse=True) +def close_leaked_cursors(): + """Close server cursors left open by tests that use neither fixture above. + + Runs after every test. Tests that use ``collection`` or ``database_client`` + have their cursors closed before the drop; this catches the rest. + """ + yield + executor.close_tracked_cursors() + + @pytest.fixture(scope="function") def register_db_cleanup(engine_client): """Provide a callback to register extra databases or namespaces for post-test cleanup. diff --git a/documentdb_tests/framework/executor.py b/documentdb_tests/framework/executor.py index e028b4a11..812aa70aa 100644 --- a/documentdb_tests/framework/executor.py +++ b/documentdb_tests/framework/executor.py @@ -4,7 +4,7 @@ import time from datetime import timezone -from typing import Any, Dict +from typing import Any, Dict, List, Tuple from bson.codec_options import CodecOptions @@ -12,6 +12,49 @@ TZ_AWARE_CODEC: CodecOptions = CodecOptions(tz_aware=True, tzinfo=timezone.utc) +# Server cursors opened through execute_command/execute_admin_command. +# +# A raw command such as {"find": ..., "batchSize": 2} or an aggregate with +# $changeStream returns a cursor id that no driver object owns, so nothing +# closes it when the test ends. The server keeps it until its idle timeout, +# and engines that cap open cursors per instance then reject the next test's +# find/aggregate with "too many cursors". Each entry is (client, namespace, +# cursor id); close_tracked_cursors() kills them at test teardown. +_tracked_cursors: List[Tuple[Any, str, int]] = [] + + +def _track_cursor(client, result: Any) -> None: + """Remember the server cursor a command result left open, if any.""" + if not isinstance(result, dict): + return + cursor = result.get("cursor") + if not isinstance(cursor, dict): + return + cursor_id = cursor.get("id") + ns = cursor.get("ns") + if cursor_id and isinstance(ns, str) and "." in ns: + _tracked_cursors.append((client, ns, cursor_id)) + + +def close_tracked_cursors() -> None: + """Kill every server cursor tracked since the last call, best effort. + + Cursors that are already exhausted or killed are reported by the server + in cursorsNotFound, which is not an error. Any failure is ignored: this is + cleanup, and it must never change a test's outcome. + """ + by_namespace: Dict[Tuple[int, str], Tuple[Any, List[int]]] = {} + for client, ns, cursor_id in _tracked_cursors: + _, ids = by_namespace.setdefault((id(client), ns), (client, [])) + ids.append(cursor_id) + _tracked_cursors.clear() + for (_, ns), (client, ids) in by_namespace.items(): + db_name, coll_name = ns.split(".", 1) + try: + client[db_name].command({"killCursors": coll_name, "cursors": ids}) + except Exception: + pass + def execute_command(collection, command: Dict, codec_options=TZ_AWARE_CODEC, session=None) -> Any: """ @@ -30,6 +73,7 @@ def execute_command(collection, command: Dict, codec_options=TZ_AWARE_CODEC, ses try: db = collection.database result = db.command(materialize(command), codec_options=codec_options, session=session) + _track_cursor(db.client, result) return result except Exception as e: return e @@ -50,6 +94,7 @@ def execute_admin_command(collection, command: Dict, session=None) -> Any: try: db = collection.database.client.admin result = db.command(materialize(command), session=session) + _track_cursor(db.client, result) return result except Exception as e: return e diff --git a/documentdb_tests/framework/test_executor_cursor_tracking.py b/documentdb_tests/framework/test_executor_cursor_tracking.py new file mode 100644 index 000000000..a2d9d2760 --- /dev/null +++ b/documentdb_tests/framework/test_executor_cursor_tracking.py @@ -0,0 +1,137 @@ +"""Unit tests for server cursor tracking in the executor (no database needed).""" + +import pytest +from bson import Int64 + +from documentdb_tests.framework import executor + + +class _FakeDatabase: + def __init__(self, client, name): + self.client = client + self.name = name + + def command(self, command, **kwargs): + self.client.commands.append((self.name, command)) + if self.client.fail_with is not None: + raise self.client.fail_with + return self.client.results.pop(0) if self.client.results else {"ok": 1.0} + + +class _FakeClient: + """Client whose databases record every command and return queued results.""" + + def __init__(self, results=None, fail_with=None): + self.results = list(results or []) + self.fail_with = fail_with + self.commands = [] + self.admin = _FakeDatabase(self, "admin") + + def __getitem__(self, name): + return _FakeDatabase(self, name) + + +class _FakeCollection: + def __init__(self, client, db_name="db", name="coll"): + self.database = _FakeDatabase(client, db_name) + self.name = name + + +@pytest.fixture(autouse=True) +def empty_registry(): + executor._tracked_cursors.clear() + yield + executor._tracked_cursors.clear() + + +def _cursor_result(cursor_id, ns="db.coll"): + return {"cursor": {"id": Int64(cursor_id), "ns": ns, "firstBatch": []}, "ok": 1.0} + + +def _kills(client): + return [(db, cmd) for db, cmd in client.commands if "killCursors" in cmd] + + +@pytest.mark.unit +def test_open_cursor_is_killed_on_close(): + client = _FakeClient(results=[_cursor_result(42)]) + result = executor.execute_command(_FakeCollection(client), {"find": "coll", "batchSize": 1}) + assert result["cursor"]["id"] == 42 + + executor.close_tracked_cursors() + + assert _kills(client) == [("db", {"killCursors": "coll", "cursors": [Int64(42)]})] + + +@pytest.mark.unit +def test_exhausted_cursor_is_not_tracked(): + client = _FakeClient(results=[_cursor_result(0)]) + executor.execute_command(_FakeCollection(client), {"find": "coll"}) + + executor.close_tracked_cursors() + + assert _kills(client) == [] + + +@pytest.mark.unit +def test_failed_command_is_not_tracked(): + client = _FakeClient(fail_with=RuntimeError("boom")) + result = executor.execute_command(_FakeCollection(client), {"find": "coll"}) + assert isinstance(result, RuntimeError) + + assert executor._tracked_cursors == [] + + +@pytest.mark.unit +def test_cursors_are_grouped_by_namespace(): + client = _FakeClient( + results=[ + _cursor_result(1), + _cursor_result(2), + _cursor_result(3, ns="db.$cmd.aggregate"), + ] + ) + coll = _FakeCollection(client) + for _ in range(3): + executor.execute_command(coll, {"aggregate": "coll", "pipeline": [], "cursor": {}}) + + executor.close_tracked_cursors() + + assert sorted(_kills(client), key=lambda k: k[1]["killCursors"]) == [ + ("db", {"killCursors": "$cmd.aggregate", "cursors": [Int64(3)]}), + ("db", {"killCursors": "coll", "cursors": [Int64(1), Int64(2)]}), + ] + + +@pytest.mark.unit +def test_admin_command_cursor_is_killed_on_its_namespace(): + client = _FakeClient(results=[_cursor_result(7, ns="admin.$cmd.aggregate")]) + executor.execute_admin_command( + _FakeCollection(client), {"aggregate": 1, "pipeline": [], "cursor": {}} + ) + + executor.close_tracked_cursors() + + assert _kills(client) == [("admin", {"killCursors": "$cmd.aggregate", "cursors": [Int64(7)]})] + + +@pytest.mark.unit +def test_close_clears_registry_and_is_idempotent(): + client = _FakeClient(results=[_cursor_result(5)]) + executor.execute_command(_FakeCollection(client), {"find": "coll", "batchSize": 1}) + + executor.close_tracked_cursors() + executor.close_tracked_cursors() + + assert len(_kills(client)) == 1 + + +@pytest.mark.unit +def test_kill_failure_is_ignored(): + client = _FakeClient(results=[_cursor_result(9)]) + executor.execute_command(_FakeCollection(client), {"find": "coll", "batchSize": 1}) + client.fail_with = RuntimeError("namespace dropped") + + executor.close_tracked_cursors() + + assert executor._tracked_cursors == [] From 12742c6af2d02406c6c226680c0e3e18e3f915a5 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Wed, 4 Nov 2026 00:16:01 +0000 Subject: [PATCH 8/8] test: address review on the helper-routing, smoke and cursor fixes - collStats histogram: return after the error assertion, so an override that handles the error doesn't fall through into the histogram checks. - open_find_cursors and open_cursor return the open error instead of indexing into it; open_find_cursors_or_error is folded into open_find_cursors. Every caller in getMore/ and killCursors/ (and the direct find/aggregate/listIndexes opens and intermediate getMore replies in those files) passes a failed reply to the test's assertion. - commitTransaction supported operations: every commit goes through _commit_or_error, and the three driver writes through _apply_and_commit. - rolesInfo/usersInfo smoke: back to {"rolesInfo": 1} / {"usersInfo": 1}; assertCommandSupported alone fixes the int32 ok case. - geospatial/wildcard data load: a writeErrors entry in an ok: 1 insert reply is forwarded as the WriteError the driver would raise for it. - listIndexes comment-inherited-by-getMore: a failed listIndexes is forwarded instead of indexed. Signed-off-by: Samar Farooqi --- .../getMore/test_getMore_batch_retrieval.py | 112 ++++++++----- .../getMore/test_getMore_batch_size.py | 35 ++-- .../commands/getMore/test_getMore_comment.py | 7 +- .../getMore/test_getMore_cursor_sources.py | 65 +++++--- .../getMore/test_getMore_field_type_errors.py | 7 +- .../test_getMore_field_value_errors.py | 7 +- .../getMore/test_getMore_lifecycle.py | 155 +++++++++++------- .../getMore/test_getMore_max_time_ms.py | 139 ++++++++++------ .../getMore/test_getMore_namespace.py | 41 +++-- .../getMore/test_getMore_null_fields.py | 7 +- .../commands/getMore/test_getMore_response.py | 40 +++-- .../commands/getMore/test_getMore_session.py | 74 +++++---- .../commands/getMore/test_getMore_term.py | 4 +- .../killCursors/test_killCursors_lifecycle.py | 117 +++++++------ .../killCursors/test_killCursors_response.py | 4 +- .../commands/utils/cursor_test_case.py | 25 +-- .../test_listIndexes_collection_variants.py | 28 ++-- .../geospatial/test_geospatial_creation.py | 25 ++- .../wildcard/test_wildcard_data_types.py | 24 ++- .../stages/collStats/test_collStats_output.py | 4 +- ..._commitTransaction_supported_operations.py | 62 +++++-- .../rolesInfo/test_smoke_rolesInfo.py | 17 +- .../usersInfo/test_smoke_usersInfo.py | 17 +- 23 files changed, 620 insertions(+), 396 deletions(-) diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_retrieval.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_retrieval.py index bf72b5646..2d0d705a5 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_retrieval.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_retrieval.py @@ -2,6 +2,8 @@ from __future__ import annotations +from typing import Any + from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( open_cursor, open_find_cursors, @@ -17,11 +19,15 @@ def test_getMore_batch_from_find(collection): """Test getMore returns subsequent batches from a find cursor.""" collection.insert_many([{"_id": i, "v": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=3) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 4}, - ) + cursors = open_find_cursors(collection, 1, batch_size=3) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 4}, + ) assertResult( result, expected={ @@ -39,11 +45,15 @@ def test_getMore_batch_size_zero_tailable_keeps_open(collection): """Test getMore with batchSize=0 on tailable cursor keeps it open.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "batchSize": 2}) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "batchSize": 0}, - ) + opened = open_cursor(capped, {"tailable": True, "batchSize": 2}) + if isinstance(opened, Exception): + result = opened + else: + cursor_id = opened + result = execute_command( + collection, + {"getMore": cursor_id, "collection": capped.name, "batchSize": 0}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3), "id": Gte(1)}}, @@ -58,16 +68,22 @@ def test_getMore_batch_size_independent(collection): """Test each getMore call sets its own batchSize independently.""" docs = [{"_id": i, "v": i} for i in range(10)] collection.insert_many(docs) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - result1 = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, - ) - cursor_id = result1["cursor"]["id"] - result2 = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 5}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result2 = cursors + else: + (cursor_id,) = cursors + result1 = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, + ) + if isinstance(result1, Exception): + result2 = result1 + else: + result2 = execute_command( + collection, + {"getMore": result1["cursor"]["id"], "collection": collection.name, "batchSize": 5}, + ) assertResult( result2, expected={ @@ -86,11 +102,14 @@ def test_getMore_find_limit_caps_total(collection): docs = [{"_id": i, "v": i} for i in range(10)] collection.insert_many(docs) find_result = execute_command(collection, {"find": collection.name, "batchSize": 2, "limit": 5}) - cursor_id = find_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3), "id": Eq(INT64_ZERO)}}, @@ -105,21 +124,34 @@ def test_getMore_independent_cursors(collection): """Test two cursors on the same collection maintain independent positions.""" docs = [{"_id": i, "v": i} for i in range(10)] collection.insert_many(docs) - (cursor_a,) = open_find_cursors(collection, 1, batch_size=3) - (cursor_b,) = open_find_cursors(collection, 1, batch_size=5) - result_a = execute_command( - collection, - {"getMore": cursor_a, "collection": collection.name, "batchSize": 2}, - ) - result_b = execute_command( - collection, - {"getMore": cursor_b, "collection": collection.name, "batchSize": 2}, - ) - # Cursor A started at position 3, cursor B started at position 5. - combined = { - "a": result_a["cursor"]["nextBatch"], - "b": result_b["cursor"]["nextBatch"], - } + cursors_a = open_find_cursors(collection, 1, batch_size=3) + cursors_b = open_find_cursors(collection, 1, batch_size=5) + combined: Any + if isinstance(cursors_a, Exception): + combined = cursors_a + elif isinstance(cursors_b, Exception): + combined = cursors_b + else: + (cursor_a,) = cursors_a + (cursor_b,) = cursors_b + result_a = execute_command( + collection, + {"getMore": cursor_a, "collection": collection.name, "batchSize": 2}, + ) + result_b = execute_command( + collection, + {"getMore": cursor_b, "collection": collection.name, "batchSize": 2}, + ) + if isinstance(result_a, Exception): + combined = result_a + elif isinstance(result_b, Exception): + combined = result_b + else: + # Cursor A started at position 3, cursor B started at position 5. + combined = { + "a": result_a["cursor"]["nextBatch"], + "b": result_b["cursor"]["nextBatch"], + } assertResult( combined, expected={ diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_size.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_size.py index 04febefeb..aba9678b7 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_size.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_batch_size.py @@ -454,8 +454,11 @@ def test_getMore_batch_size_coercion(collection, test_case: CursorCommandTestCas cursors = open_find_cursors( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test_case.build_command(ctx)) + if isinstance(cursors, Exception): + result = cursors + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, @@ -473,11 +476,15 @@ def test_getMore_16mib_batch_limit(collection): big_val = "x" * 1_100_000 docs = [{"_id": i, "data": big_val} for i in range(20)] collection.insert_many(docs) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(15)}}, @@ -493,11 +500,15 @@ def test_getMore_16mib_batch_size_wins(collection): big_val = "x" * 1_100_000 docs = [{"_id": i, "data": big_val} for i in range(20)] collection.insert_many(docs) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3)}}, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_comment.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_comment.py index d6c7b9726..b03a25533 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_comment.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_comment.py @@ -100,8 +100,11 @@ def test_getMore_comment(collection, test_case: CursorCommandTestCase): cursors = open_find_cursors( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test_case.build_command(ctx)) + if isinstance(cursors, Exception): + result = cursors + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_cursor_sources.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_cursor_sources.py index 84d8e2ace..8227e0ec1 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_cursor_sources.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_cursor_sources.py @@ -24,11 +24,14 @@ def test_getMore_aggregate_cursor(collection): collection, {"aggregate": collection.name, "pipeline": [], "cursor": {"batchSize": 2}}, ) - cursor_id = agg_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, - ) + if isinstance(agg_result, Exception): + result = agg_result + else: + cursor_id = agg_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3)}}, @@ -45,11 +48,14 @@ def test_getMore_view_cursor(collection): view_name = f"{collection.name}_view" execute_command(collection, {"create": view_name, "viewOn": collection.name, "pipeline": []}) find_result = execute_command(collection, {"find": view_name, "batchSize": 2}) - cursor_id = find_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": view_name}, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": view_name}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3)}}, @@ -75,11 +81,14 @@ def test_getMore_timeseries_cursor(collection): }, ) find_result = execute_command(collection, {"find": ts_name, "batchSize": 2}) - cursor_id = find_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": ts_name, "batchSize": 3}, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": ts_name, "batchSize": 3}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3)}}, @@ -98,11 +107,14 @@ def test_getMore_list_collections_cursor(collection): collection, {"listCollections": 1, "cursor": {"batchSize": 1}}, ) - cursor_id = list_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": "$cmd.listCollections"}, - ) + if isinstance(list_result, Exception): + result = list_result + else: + cursor_id = list_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": "$cmd.listCollections"}, + ) assertResult( result, expected={"ok": Eq(1.0)}, @@ -128,11 +140,14 @@ def test_getMore_list_indexes_cursor(collection): collection, {"listIndexes": collection.name, "cursor": {"batchSize": 1}}, ) - cursor_id = list_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + if isinstance(list_result, Exception): + result = list_result + else: + cursor_id = list_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, expected={"ok": Eq(1.0)}, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_type_errors.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_type_errors.py index 82273c976..7d4f3c302 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_type_errors.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_type_errors.py @@ -153,8 +153,11 @@ def test_getMore_field_type_errors(collection, test_case: CursorCommandTestCase) cursors = open_find_cursors( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test_case.build_command(ctx)) + if isinstance(cursors, Exception): + result = cursors + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_value_errors.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_value_errors.py index 82452a763..736615b99 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_value_errors.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_field_value_errors.py @@ -393,8 +393,11 @@ def test_getMore_field_value_errors(collection, test_case: CursorCommandTestCase cursors = open_find_cursors( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test_case.build_command(ctx)) + if isinstance(cursors, Exception): + result = cursors + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py index ef13fc653..4a0492b6e 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_lifecycle.py @@ -5,7 +5,6 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( open_cursor, open_find_cursors, - open_find_cursors_or_error, ) from documentdb_tests.framework.assertions import assertResult from documentdb_tests.framework.error_codes import ( @@ -23,15 +22,19 @@ def test_getMore_exhausted_cursor_error(collection): """Test getMore on an exhausted cursor produces CursorNotFound.""" collection.insert_many([{"_id": i} for i in range(4)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, - ) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, + ) + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, error_code=CURSOR_NOT_FOUND_ERROR, @@ -45,12 +48,16 @@ def test_getMore_exhausted_cursor_error(collection): def test_getMore_killed_cursor_error(collection): """Test getMore on a killed cursor produces CursorNotFound.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - execute_command(collection, {"killCursors": collection.name, "cursors": [cursor_id]}) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + execute_command(collection, {"killCursors": collection.name, "cursors": [cursor_id]}) + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, error_code=CURSOR_NOT_FOUND_ERROR, @@ -64,12 +71,16 @@ def test_getMore_killed_cursor_error(collection): def test_getMore_after_collection_drop(collection): """Test getMore after collection drop produces QueryPlanKilled.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - collection.drop() - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + collection.drop() + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, error_code=QUERY_PLAN_KILLED_ERROR, @@ -83,13 +94,17 @@ def test_getMore_after_collection_drop(collection): def test_getMore_after_drop_and_recreate(collection): """Test getMore after drop and recreate still produces QueryPlanKilled.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - collection.drop() - collection.insert_many([{"_id": i, "new": True} for i in range(5)]) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + collection.drop() + collection.insert_many([{"_id": i, "new": True} for i in range(5)]) + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, error_code=QUERY_PLAN_KILLED_ERROR, @@ -104,11 +119,15 @@ def test_getMore_after_drop_and_recreate(collection): def test_getMore_find_batch_size_zero(collection): """Test getMore returns documents after find with batchSize=0.""" collection.insert_many([{"_id": i} for i in range(5)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=0) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, - ) + cursors = open_find_cursors(collection, 1, batch_size=0) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 3}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Eq([{"_id": 0}, {"_id": 1}, {"_id": 2}])}}, @@ -123,11 +142,15 @@ def test_getMore_tailable_stays_open_at_end(collection): """Test tailable cursor stays open at end of data.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) - gm = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0}, - ) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) + if isinstance(opened, Exception): + gm = opened + else: + cursor_id = opened + gm = execute_command( + collection, + {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0}, + ) assertResult( gm, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Eq([]), "id": Gte(1)}}, @@ -142,13 +165,17 @@ def test_getMore_tailable_sees_new_inserts(collection): """Test tailable cursor sees new inserts on subsequent getMore.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) - # Insert new data after find consumed all existing docs in firstBatch. - capped.insert_one({"_id": 99, "new": True}) - gm = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 100}, - ) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) + if isinstance(opened, Exception): + gm = opened + else: + cursor_id = opened + # Insert new data after find consumed all existing docs in firstBatch. + capped.insert_one({"_id": 99, "new": True}) + gm = execute_command( + collection, + {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 100}, + ) assertResult( gm, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Eq([{"_id": 99, "new": True}])}}, @@ -163,13 +190,17 @@ def test_getMore_tailable_sees_new_inserts(collection): def test_getMore_deleted_docs_still_visible(collection): """Test getMore skips documents deleted before the cursor reaches them.""" collection.insert_many([{"_id": i, "v": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - # firstBatch returned _id 0,1; cursor is positioned at _id 2. - collection.delete_many({"_id": {"$gte": 5}}) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + # firstBatch returned _id 0,1; cursor is positioned at _id 2. + collection.delete_many({"_id": {"$gte": 5}}) + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 10}, + ) assertResult( result, expected={ @@ -189,12 +220,16 @@ def test_getMore_deleted_docs_still_visible(collection): def test_getMore_new_inserts_visible(collection): """Test new documents inserted during iteration are visible in getMore.""" collection.insert_many([{"_id": i} for i in range(5)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - collection.insert_many([{"_id": 100 + i, "new": True} for i in range(3)]) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 100}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + collection.insert_many([{"_id": 100 + i, "new": True} for i in range(3)]) + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 100}, + ) assertResult( result, expected={ @@ -222,7 +257,7 @@ def test_getMore_new_inserts_visible(collection): def test_getMore_updated_docs_show_new_value(collection): """Test getMore returns the new value of a document updated before it is reached.""" collection.insert_many([{"_id": i, "v": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 1, batch_size=2) + cursors = open_find_cursors(collection, 1, batch_size=2) if isinstance(cursors, Exception): result = cursors else: diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_max_time_ms.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_max_time_ms.py index 702a998e5..3074622f6 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_max_time_ms.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_max_time_ms.py @@ -172,9 +172,13 @@ def test_getMore_max_time_ms_accepted(collection, test_case: CursorCommandTestCa """Test getMore maxTimeMS accepted values on awaitData tailable cursor.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) - ctx = CursorCommandContext.from_collection(capped, cursors=(cursor_id,)) - result = execute_command(collection, test_case.build_command(ctx)) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) + if isinstance(opened, Exception): + result = opened + else: + cursor_id = opened + ctx = CursorCommandContext.from_collection(capped, cursors=(cursor_id,)) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, @@ -222,8 +226,11 @@ def test_getMore_max_time_ms_semantic_non_tailable(collection, test_case: Cursor cursors = open_find_cursors( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test_case.build_command(ctx)) + if isinstance(cursors, Exception): + result = cursors + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, @@ -254,9 +261,13 @@ def test_getMore_max_time_ms_semantic_tailable(collection, test_case: CursorComm """Test getMore rejects maxTimeMS on tailable cursors without awaitData.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "batchSize": 2}) - ctx = CursorCommandContext.from_collection(capped, cursors=(cursor_id,)) - result = execute_command(collection, test_case.build_command(ctx)) + opened = open_cursor(capped, {"tailable": True, "batchSize": 2}) + if isinstance(opened, Exception): + result = opened + else: + cursor_id = opened + ctx = CursorCommandContext.from_collection(capped, cursors=(cursor_id,)) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, @@ -271,11 +282,15 @@ def test_getMore_max_time_ms_semantic_tailable(collection, test_case: CursorComm def test_getMore_max_time_ms_null_bypasses_semantic_check(collection): """Test getMore maxTimeMS=null bypasses the non-awaitData semantic check.""" collection.insert_many([{"_id": i} for i in range(5)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "maxTimeMS": None}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "maxTimeMS": None}, + ) assertResult( result, expected={"ok": Eq(1.0)}, @@ -290,16 +305,22 @@ def test_getMore_max_time_ms_varies_between_calls(collection): """Test getMore accepts a different maxTimeMS on each successive call on the same cursor.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) - r1 = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 50}, - ) - cursor_id2 = r1["cursor"]["id"] - r2 = execute_command( - collection, - {"getMore": cursor_id2, "collection": capped.name, "maxTimeMS": 200}, - ) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) + if isinstance(opened, Exception): + r2 = opened + else: + cursor_id = opened + r1 = execute_command( + collection, + {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 50}, + ) + if isinstance(r1, Exception): + r2 = r1 + else: + r2 = execute_command( + collection, + {"getMore": r1["cursor"]["id"], "collection": capped.name, "maxTimeMS": 200}, + ) assertResult( r2, expected={"ok": Eq(1.0)}, @@ -314,11 +335,15 @@ def test_getMore_max_time_ms_returns_immediately_with_data(collection): """Test getMore accepts maxTimeMS and returns available data.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 5_000}, - ) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) + if isinstance(opened, Exception): + result = opened + else: + cursor_id = opened + result = execute_command( + collection, + {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 5_000}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3)}}, @@ -333,12 +358,18 @@ def test_getMore_max_time_ms_no_data_empty_batch(collection): """Test getMore with maxTimeMS returns empty batch and keeps cursor open when no data.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) - execute_command(collection, {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0}) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0}, - ) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) + if isinstance(opened, Exception): + result = opened + else: + cursor_id = opened + execute_command( + collection, {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0} + ) + result = execute_command( + collection, + {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Eq([]), "id": Gte(1)}}, @@ -354,19 +385,25 @@ def test_getMore_max_time_ms_wait_elapsed_retains_cursor(collection): """Test a getMore whose awaitData wait elapses keeps the cursor open for later calls.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) - # maxTimeMS=0 returns immediately (no wait), positioning the cursor at the tail. - result = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0}, - ) - cursor_id = result["cursor"]["id"] - # maxTimeMS=100 lets the awaitData wait window elapse with no new data; the - # cursor must remain open afterward. - result2 = execute_command( - collection, - {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 100}, - ) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 10}) + if isinstance(opened, Exception): + result2 = opened + else: + cursor_id = opened + # maxTimeMS=0 returns immediately (no wait), positioning the cursor at the tail. + result = execute_command( + collection, + {"getMore": cursor_id, "collection": capped.name, "maxTimeMS": 0}, + ) + if isinstance(result, Exception): + result2 = result + else: + # maxTimeMS=100 lets the awaitData wait window elapse with no new data; + # the cursor must remain open afterward. + result2 = execute_command( + collection, + {"getMore": result["cursor"]["id"], "collection": capped.name, "maxTimeMS": 100}, + ) assertResult( result2, expected={"ok": Eq(1.0), "cursor": {"id": Gte(1)}}, @@ -381,8 +418,12 @@ def test_getMore_missing_max_time_ms_await_data(collection): """Test getMore succeeds with maxTimeMS omitted on awaitData tailable cursor.""" capped = CappedCollection().resolve(collection.database, collection) capped.insert_many([{"_id": i} for i in range(5)]) - cursor_id = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) - result = execute_command(collection, {"getMore": cursor_id, "collection": capped.name}) + opened = open_cursor(capped, {"tailable": True, "awaitData": True, "batchSize": 2}) + if isinstance(opened, Exception): + result = opened + else: + cursor_id = opened + result = execute_command(collection, {"getMore": cursor_id, "collection": capped.name}) assertResult( result, expected={"ok": Eq(1.0)}, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_namespace.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_namespace.py index fb3ab1e4c..f778481d3 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_namespace.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_namespace.py @@ -16,11 +16,15 @@ def test_getMore_namespace_match_find(collection): """Test getMore succeeds with exact collection name match for find cursor.""" collection.insert_many([{"_id": i} for i in range(5)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, expected={"ok": Eq(1.0), "cursor": {"nextBatch": Len(3)}}, @@ -34,11 +38,15 @@ def test_getMore_namespace_match_find(collection): def test_getMore_namespace_case_sensitive(collection): """Test getMore requires exact case-sensitive match for collection name.""" collection.insert_many([{"_id": i} for i in range(5)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name.upper()}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name.upper()}, + ) assertResult( result, error_code=UNAUTHORIZED_ERROR, @@ -55,11 +63,14 @@ def test_getMore_namespace_view_bound_to_view_name(collection): view_name = f"{collection.name}_view" execute_command(collection, {"create": view_name, "viewOn": collection.name, "pipeline": []}) find_result = execute_command(collection, {"find": view_name, "batchSize": 2}) - cursor_id = find_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, error_code=UNAUTHORIZED_ERROR, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_null_fields.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_null_fields.py index 80b8f2a4c..1d4b4ab6d 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_null_fields.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_null_fields.py @@ -86,8 +86,11 @@ def test_getMore_field_presence(collection, test_case: CursorCommandTestCase): cursors = open_find_cursors( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) - ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test_case.build_command(ctx)) + if isinstance(cursors, Exception): + result = cursors + else: + ctx = CursorCommandContext.from_collection(collection, cursors=cursors) + result = execute_command(collection, test_case.build_command(ctx)) assertResult( result, expected=test_case.expected, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_response.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_response.py index 9d0441441..33e8ef061 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_response.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_response.py @@ -16,11 +16,15 @@ def test_getMore_response_structure(collection): """Test getMore response structure and field types.""" collection.insert_many([{"_id": i} for i in range(5)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 2}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 2}, + ) assertResult( result, expected={ @@ -44,16 +48,22 @@ def test_getMore_response_structure(collection): def test_getMore_exhausted_cursor_response(collection): """Test getMore response when cursor is exhausted.""" collection.insert_many([{"_id": i} for i in range(4)]) - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) - gm1 = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name, "batchSize": 2}, - ) - cursor_id2 = gm1["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id2, "collection": collection.name, "batchSize": 2}, - ) + cursors = open_find_cursors(collection, 1, batch_size=2) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + gm1 = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name, "batchSize": 2}, + ) + if isinstance(gm1, Exception): + result = gm1 + else: + result = execute_command( + collection, + {"getMore": gm1["cursor"]["id"], "collection": collection.name, "batchSize": 2}, + ) assertResult( result, expected={ diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_session.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_session.py index 950fdb647..00fb62c97 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_session.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_session.py @@ -24,12 +24,15 @@ def test_getMore_session_mismatch_different_session(collection): find_result = execute_command( collection, {"find": collection.name, "batchSize": 2}, session=session_a ) - cursor_id = find_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - session=session_b, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + session=session_b, + ) assertResult( result, error_code=CURSOR_SESSION_MISMATCH_ERROR, @@ -52,12 +55,15 @@ def test_getMore_session_same_session_succeeds(collection): find_result = execute_command( collection, {"find": collection.name, "batchSize": 2}, session=session_a ) - cursor_id = find_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - session=session_a, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + session=session_a, + ) assertResult( result, expected={"ok": Eq(1.0)}, @@ -74,14 +80,18 @@ def test_getMore_session_implicit_cursor_explicit_getmore(collection): """Test getMore with explicit session on implicit session cursor succeeds.""" collection.insert_many([{"_id": i} for i in range(10)]) client = collection.database.client - (cursor_id,) = open_find_cursors(collection, 1, batch_size=2) + cursors = open_find_cursors(collection, 1, batch_size=2) session_b = client.start_session() try: - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - session=session_b, - ) + if isinstance(cursors, Exception): + result = cursors + else: + (cursor_id,) = cursors + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + session=session_b, + ) assertResult( result, expected={"ok": Eq(1.0)}, @@ -104,11 +114,14 @@ def test_getMore_session_explicit_cursor_implicit_getmore(collection): find_result = execute_command( collection, {"find": collection.name, "batchSize": 2}, session=session_a ) - cursor_id = find_result["cursor"]["id"] - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, error_code=CURSOR_SESSION_MISMATCH_ERROR, @@ -132,12 +145,15 @@ def test_getMore_session_survives_session_end(collection): find_result = execute_command( collection, {"find": collection.name, "batchSize": 2}, session=session_a ) - cursor_id = find_result["cursor"]["id"] - session_a.end_session() - result = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + if isinstance(find_result, Exception): + result = find_result + else: + cursor_id = find_result["cursor"]["id"] + session_a.end_session() + result = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertResult( result, expected={"ok": Eq(1.0)}, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py index bb81a079c..79b60612d 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/getMore/test_getMore_term.py @@ -10,7 +10,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, - open_find_cursors_or_error, + open_find_cursors, ) from documentdb_tests.framework.assertions import assertResult from documentdb_tests.framework.error_codes import TYPE_MISMATCH_ERROR @@ -88,7 +88,7 @@ def test_getMore_term(collection, test_case: CursorCommandTestCase): """Test getMore term field acceptance and type rejection.""" collection.insert_many([{"_id": i, "v": i} for i in range(5)]) - cursors = open_find_cursors_or_error( + cursors = open_find_cursors( collection, test_case.cursor_count, batch_size=test_case.find_batch_size ) if isinstance(cursors, Exception): diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py index 1b6817a13..e60c6113f 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py @@ -11,7 +11,6 @@ CursorCommandContext, CursorCommandTestCase, open_find_cursors, - open_find_cursors_or_error, ) from documentdb_tests.framework import fixtures from documentdb_tests.framework.assertions import ( @@ -67,7 +66,7 @@ def test_killCursors_lifecycle(database_client, collection, test): """Test killCursors cursor lifecycle.""" collection = test.prepare(database_client, collection) - cursors = open_find_cursors_or_error(collection, test.cursor_count) + cursors = open_find_cursors(collection, test.cursor_count) if isinstance(cursors, Exception): result, expected = cursors, None else: @@ -187,11 +186,15 @@ def test_killCursors_view_cursor(database_client, collection): ) view = database_client[view_name] res = execute_command(view, {"find": view_name, "batchSize": 1}) - cursor_id = res["cursor"]["id"] - result = execute_command( - view, - {"killCursors": view_name, "cursors": [cursor_id]}, - ) + if isinstance(res, Exception): + result = res + cursor_id = None + else: + cursor_id = res["cursor"]["id"] + result = execute_command( + view, + {"killCursors": view_name, "cursors": [cursor_id]}, + ) assertResult( result, expected={ @@ -251,11 +254,15 @@ def test_killCursors_tailable_cursor(database_client): capped, {"find": "capped_for_kill", "batchSize": 1, "tailable": True}, ) - cursor_id = res["cursor"]["id"] - result = execute_command( - capped, - {"killCursors": "capped_for_kill", "cursors": [cursor_id]}, - ) + if isinstance(res, Exception): + result = res + cursor_id = None + else: + cursor_id = res["cursor"]["id"] + result = execute_command( + capped, + {"killCursors": "capped_for_kill", "cursors": [cursor_id]}, + ) assertResult( result, expected={ @@ -275,15 +282,19 @@ def test_killCursors_tailable_cursor(database_client): def test_killCursors_getmore_after_kill(collection): """Test getMore fails after cursor is killed.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) - execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) - getmore = execute_command( - collection, - {"getMore": cursor_id, "collection": collection.name}, - ) + cursors = open_find_cursors(collection, 1) + if isinstance(cursors, Exception): + getmore = cursors + else: + (cursor_id,) = cursors + execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) + getmore = execute_command( + collection, + {"getMore": cursor_id, "collection": collection.name}, + ) assertFailureCode( getmore, CURSOR_NOT_FOUND_ERROR, @@ -296,7 +307,7 @@ def test_killCursors_getmore_after_kill(collection): def test_killCursors_sibling_unaffected(collection): """Test killing one cursor does not affect siblings.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 2) + cursors = open_find_cursors(collection, 2) if isinstance(cursors, Exception): getmore = cursors else: @@ -318,7 +329,7 @@ def test_killCursors_sibling_unaffected(collection): def test_killCursors_atomic_precheck_cursor_survives(collection): """Test valid cursors survive when type validation fails.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 1) + cursors = open_find_cursors(collection, 1) if isinstance(cursors, Exception): getmore = cursors else: @@ -343,7 +354,7 @@ def test_killCursors_atomic_precheck_cursor_survives(collection): def test_killCursors_idempotency(collection): """Test killing the same cursor twice.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 1) + cursors = open_find_cursors(collection, 1) if isinstance(cursors, Exception): result, expected = cursors, None else: @@ -380,7 +391,7 @@ def test_killCursors_mixed_states(collection): """Test mixed active, killed, and non-existent cursor IDs.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 2) + cursors = open_find_cursors(collection, 2) if isinstance(cursors, Exception): result, expected = cursors, None else: @@ -421,7 +432,7 @@ def test_killCursors_mixed_states(collection): def test_killCursors_after_drop_collection(database_client, collection): """Test cursor remains killable after source collection is dropped.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 1) + cursors = open_find_cursors(collection, 1) if isinstance(cursors, Exception): result, expected = cursors, None else: @@ -453,21 +464,26 @@ def test_killCursors_after_rename_collection( ): """Test cursor remains killable after source collection is renamed.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) - - renamed = collection.name + "_renamed" - register_db_cleanup(f"{database_client.name}.{renamed}") - engine_client.admin.command( - { - "renameCollection": f"{database_client.name}.{collection.name}", - "to": f"{database_client.name}.{renamed}", - } - ) + cursors = open_find_cursors(collection, 1) + if isinstance(cursors, Exception): + result = cursors + cursor_id = None + else: + (cursor_id,) = cursors - result = execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) + renamed = collection.name + "_renamed" + register_db_cleanup(f"{database_client.name}.{renamed}") + engine_client.admin.command( + { + "renameCollection": f"{database_client.name}.{collection.name}", + "to": f"{database_client.name}.{renamed}", + } + ) + + result = execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) assertResult( result, expected={ @@ -485,7 +501,7 @@ def test_killCursors_after_rename_collection( def test_killCursors_after_recreate_collection(database_client, collection): """Test cursor remains killable after source collection is recreated.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 1) + cursors = open_find_cursors(collection, 1) if isinstance(cursors, Exception): result, expected = cursors, None else: @@ -516,14 +532,19 @@ def test_killCursors_after_recreate_collection(database_client, collection): def test_killCursors_after_drop_database(engine_client, database_client, collection): """Test cursor remains killable after source database is dropped.""" collection.insert_many([{"_id": i} for i in range(10)]) - (cursor_id,) = open_find_cursors(collection, 1) + cursors = open_find_cursors(collection, 1) + if isinstance(cursors, Exception): + result = cursors + cursor_id = None + else: + (cursor_id,) = cursors - engine_client.drop_database(database_client.name) + engine_client.drop_database(database_client.name) - result = execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, - ) + result = execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ) assertResult( result, expected={ @@ -543,7 +564,7 @@ def test_killCursors_after_drop_database(engine_client, database_client, collect def test_killCursors_cross_connection(connection_string, database_client, collection): """Test killing a cursor from a different connection.""" collection.insert_many([{"_id": i} for i in range(10)]) - cursors = open_find_cursors_or_error(collection, 1) + cursors = open_find_cursors(collection, 1) if isinstance(cursors, Exception): result, expected = cursors, None else: diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py index a9c2c7890..64090f510 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py @@ -8,7 +8,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, - open_find_cursors_or_error, + open_find_cursors, ) from documentdb_tests.compatibility.tests.core.utils.command_test_case import ( CommandContext, @@ -174,7 +174,7 @@ def test_killCursors_response_cmd(collection, test): def test_killCursors_response_cursor(database_client, collection, test): """Test killCursors response structure with active cursors.""" collection = test.prepare(database_client, collection) - cursors = open_find_cursors_or_error(collection, test.cursor_count) + cursors = open_find_cursors(collection, test.cursor_count) if isinstance(cursors, Exception): result, expected = cursors, None else: diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py b/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py index c2cfbc4ff..124394b81 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py @@ -37,23 +37,12 @@ def from_collection( def open_find_cursors( collection: Collection, count: int, *, batch_size: int = 1 -) -> tuple[Any, ...]: - """Open count find cursors with the given batchSize and return their IDs.""" - ids = [] - for _ in range(count): - res = execute_command(collection, {"find": collection.name, "batchSize": batch_size}) - ids.append(res["cursor"]["id"]) - return tuple(ids) - - -def open_find_cursors_or_error( - collection: Collection, count: int, *, batch_size: int = 1 ) -> tuple[Any, ...] | Exception: - """Like ``open_find_cursors`` but return the engine error instead of crashing. + """Open count find cursors with the given batchSize and return their IDs. - When opening any of the find cursors fails, the exception is returned so the - caller can forward it to the test's single assertion rather than indexing - into the exception (which would raise a bare ``TypeError`` outside the + When opening any of the find cursors fails, the engine error is returned + instead, so the caller can forward it to the test's single assertion rather + than indexing into it (which would raise a bare ``TypeError`` outside the assertion helper). """ ids = [] @@ -69,9 +58,13 @@ def open_cursor(collection: Collection, find_options: dict[str, Any]) -> Any: """Open a cursor on ``collection`` with the given find options and return its ID. ``find_options`` is merged into the find command (e.g. - ``{"tailable": True, "awaitData": True, "batchSize": 10}``). + ``{"tailable": True, "awaitData": True, "batchSize": 10}``). When the find + fails, the engine error is returned instead, so the caller can forward it + to the test's single assertion. """ res = execute_command(collection, {"find": collection.name, **find_options}) + if isinstance(res, Exception): + return res return res["cursor"]["id"] diff --git a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py index c4d4fb02a..a5f069f84 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py +++ b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_collection_variants.py @@ -273,19 +273,23 @@ def test_listIndexes_comment_inherited_by_getMore(collection): "comment": "getmore_inherit_test", }, ) - cursor_id = listed["cursor"]["id"] - execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) - - result = execute_command( - db["system.profile"], - { - "count": "system.profile", - "query": { - "command.getMore": {"$exists": True}, - "command.comment": "getmore_inherit_test", + if isinstance(listed, Exception): + result = listed + else: + execute_command( + collection, + {"getMore": listed["cursor"]["id"], "collection": collection.name}, + ) + result = execute_command( + db["system.profile"], + { + "count": "system.profile", + "query": { + "command.getMore": {"$exists": True}, + "command.comment": "getmore_inherit_test", + }, }, - }, - ) + ) finally: db.command({"profile": 0}) db.system.profile.drop() diff --git a/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py b/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py index d4d729033..b03fcbbe8 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py +++ b/documentdb_tests/compatibility/tests/core/indexes/types/geospatial/test_geospatial_creation.py @@ -7,6 +7,7 @@ """ import pytest +from pymongo.errors import WriteError from documentdb_tests.compatibility.tests.core.indexes.commands.utils.index_test_case import ( IndexTestCase, @@ -272,14 +273,22 @@ def test_geospatial_2dsphere_valid_data(collection, test): collection, {"createIndexes": collection.name, "indexes": list(test.indexes)}, ) - # Load the documents through execute_command (not collection.insert_many) so a - # rejection by the engine is captured rather than raising BulkWriteError - # outside the assertion helper; a rejected insert then surfaces as the find - # result diverging from the expected documents in the single assertion below. - execute_command(collection, {"insert": collection.name, "documents": list(test.doc)}) - result = execute_command( - collection, {"find": collection.name, "hint": test.indexes[0]["name"], "sort": {"_id": 1}} - ) + # Load through execute_command (not collection.insert_many) so a document + # the engine rejects is captured instead of raising BulkWriteError outside + # the assertion helper. A rejected insert is forwarded to the assertion in + # place of the find result: a command error as is, and the first writeErrors + # entry of an ok: 1 reply as the WriteError the driver would raise for it. + inserted = execute_command(collection, {"insert": collection.name, "documents": list(test.doc)}) + if isinstance(inserted, Exception): + result = inserted + elif inserted.get("writeErrors"): + first = inserted["writeErrors"][0] + result = WriteError(first["errmsg"], code=first["code"], details=first) + else: + result = execute_command( + collection, + {"find": collection.name, "hint": test.indexes[0]["name"], "sort": {"_id": 1}}, + ) assertSuccess(result, test.expected, msg=test.msg) diff --git a/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py b/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py index 9ec391a31..96c467a0d 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py +++ b/documentdb_tests/compatibility/tests/core/indexes/types/wildcard/test_wildcard_data_types.py @@ -5,6 +5,7 @@ import pytest from bson import Binary, Code, Decimal128, Int64, MaxKey, MinKey, ObjectId, Timestamp +from pymongo.errors import WriteError from documentdb_tests.compatibility.tests.core.indexes.commands.utils.index_test_case import ( IndexQueryTestCase, @@ -524,14 +525,21 @@ def test_wildcard_special_types(collection, test): collection, {"createIndexes": collection.name, "indexes": list(test.indexes)}, ) - # Load through execute_command (not collection.insert_many) so a value the - # engine rejects (e.g. a JavaScript-code BSON value) is captured instead of - # raising outside the assertion helper; a rejected insert then surfaces as - # the find result diverging from the expected document below. - execute_command(collection, {"insert": collection.name, "documents": list(test.doc)}) - result = execute_command( - collection, {"find": collection.name, "filter": test.filter, "hint": test.hint} - ) + # Load through execute_command (not collection.insert_many) so a document + # the engine rejects is captured instead of raising BulkWriteError outside + # the assertion helper. A rejected insert is forwarded to the assertion in + # place of the find result: a command error as is, and the first writeErrors + # entry of an ok: 1 reply as the WriteError the driver would raise for it. + inserted = execute_command(collection, {"insert": collection.name, "documents": list(test.doc)}) + if isinstance(inserted, Exception): + result = inserted + elif inserted.get("writeErrors"): + first = inserted["writeErrors"][0] + result = WriteError(first["errmsg"], code=first["code"], details=first) + else: + result = execute_command( + collection, {"find": collection.name, "filter": test.filter, "hint": test.hint} + ) assertSuccess(result, test.expected, msg=test.msg) diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py b/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py index 1c13a385e..d9440fc23 100644 --- a/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py +++ b/documentdb_tests/compatibility/tests/core/operator/stages/collStats/test_collStats_output.py @@ -239,12 +239,14 @@ def test_collStats_output_histogram_structure(collection): if isinstance(result, Exception): # Route the engine error through the assertion helper so it fails - # overridably with the real result instead of raising outside it. + # overridably with the real result instead of raising outside it. An + # override provider may handle the call and return, so stop here. assertResult( result, not_error=True, msg="$collStats latencyStats histograms should succeed", ) + return doc = result["cursor"]["firstBatch"][0] errors: list[str] = [] for name in ["reads", "writes", "commands", "transactions"]: diff --git a/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py b/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py index 754b41cde..f6f429c08 100644 --- a/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py +++ b/documentdb_tests/compatibility/tests/core/sessions/commands/commitTransaction/test_commitTransaction_supported_operations.py @@ -36,6 +36,20 @@ def _commit_or_error(session, result): return result +def _apply_and_commit(session, operation): + """Run a driver write in the transaction and commit it. + + Returns the engine error instead of raising, from either the write or the + commit, so the test's single assertion surfaces it. Returns None when both + succeed. + """ + try: + operation() + except Exception as error: # noqa: BLE001 - forwarded to the assertion helper + return error + return _commit_or_error(session, None) + + def test_find_runs_in_transaction(collection): """A find issued inside a transaction returns the collection's documents.""" collection.insert_one({"_id": 1}) @@ -45,7 +59,7 @@ def test_find_runs_in_transaction(collection): result = execute_command( collection, {"find": collection.name, "filter": {}}, session=session ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccess(result, [{"_id": 1}]) @@ -60,7 +74,7 @@ def test_aggregate_count_runs_in_transaction(collection): {"aggregate": collection.name, "pipeline": [{"$count": "n"}], "cursor": {}}, session=session, ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccess(result, [{"n": 2}]) @@ -70,9 +84,15 @@ def test_update_runs_in_transaction(collection): client = collection.database.client with client.start_session() as session: session.start_transaction() - collection.update_one({"_id": 1}, {"$set": {"x": "after"}}, session=session) - session.commit_transaction() - readback = execute_command(collection, {"find": collection.name, "filter": {}}) + failed = _apply_and_commit( + session, + lambda: collection.update_one({"_id": 1}, {"$set": {"x": "after"}}, session=session), + ) + readback = ( + failed + if failed is not None + else execute_command(collection, {"find": collection.name, "filter": {}}) + ) assertSuccess(readback, [{"_id": 1, "x": "after"}]) @@ -82,9 +102,14 @@ def test_delete_runs_in_transaction(collection): client = collection.database.client with client.start_session() as session: session.start_transaction() - collection.delete_one({"_id": 1}, session=session) - session.commit_transaction() - readback = execute_command(collection, {"find": collection.name, "filter": {}}) + failed = _apply_and_commit( + session, lambda: collection.delete_one({"_id": 1}, session=session) + ) + readback = ( + failed + if failed is not None + else execute_command(collection, {"find": collection.name, "filter": {}}) + ) assertSuccess(readback, []) @@ -97,7 +122,7 @@ def test_distinct_runs_in_transaction(collection): result = execute_command( collection, {"distinct": collection.name, "key": "x"}, session=session ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) @@ -116,7 +141,7 @@ def test_findAndModify_runs_in_transaction(collection): }, session=session, ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) @@ -174,9 +199,14 @@ def test_implicitly_created_collection_persists_after_commit(collection): client = collection.database.client with client.start_session() as session: session.start_transaction() - new_collection.insert_one({"_id": 1}, session=session) - session.commit_transaction() - result = execute_command(collection, {"find": new_collection.name, "filter": {}}) + failed = _apply_and_commit( + session, lambda: new_collection.insert_one({"_id": 1}, session=session) + ) + result = ( + failed + if failed is not None + else execute_command(collection, {"find": new_collection.name, "filter": {}}) + ) assertSuccess(result, [{"_id": 1}]) @@ -213,7 +243,7 @@ def test_near_query_runs_in_transaction(collection): }, session=session, ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) @@ -234,7 +264,7 @@ def test_nearSphere_query_runs_in_transaction(collection): }, session=session, ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) @@ -262,5 +292,5 @@ def test_geoNear_stage_runs_in_transaction(collection): }, session=session, ) - session.commit_transaction() + result = _commit_or_error(session, result) assertSuccessPartial(result, {"ok": 1.0}) diff --git a/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py b/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py index c21210da5..22ea5d92b 100644 --- a/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py +++ b/documentdb_tests/compatibility/tests/system/security/authorization/role/commands/rolesInfo/test_smoke_rolesInfo.py @@ -13,20 +13,7 @@ def test_smoke_rolesInfo(collection): - """Test basic rolesInfo behavior. - - Queries rolesInfo for only the role this test creates, not the whole - server. ``{"rolesInfo": 1}`` lists every role in the database, including - roles that parallel tests create and drop, which makes the result - non-deterministic. Scoping to the test's own role keeps the capability - probe deterministic under parallel execution. - """ - role_name = f"{collection.name}_test_role" - - execute_admin_command(collection, {"createRole": role_name, "privileges": [], "roles": []}) - try: - result = execute_admin_command(collection, {"rolesInfo": role_name}) - finally: - execute_admin_command(collection, {"dropRole": role_name}) + """Test basic rolesInfo behavior.""" + result = execute_admin_command(collection, {"rolesInfo": 1}) assertCommandSupported(result, msg="Should support rolesInfo command") diff --git a/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py b/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py index c8833f63b..12a97619c 100644 --- a/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py +++ b/documentdb_tests/compatibility/tests/system/security/authorization/user/commands/usersInfo/test_smoke_usersInfo.py @@ -13,20 +13,7 @@ def test_smoke_usersInfo(collection): - """Test basic usersInfo behavior. - - Queries usersInfo for only the user this test creates, not the whole - server. ``{"usersInfo": 1}`` lists every user in the database, including - users that parallel tests create and drop, which makes the result - non-deterministic. Scoping to the test's own user keeps the capability - probe deterministic under parallel execution. - """ - user_name = f"{collection.name}_test_user" - - execute_admin_command(collection, {"createUser": user_name, "pwd": "testPassword", "roles": []}) - try: - result = execute_admin_command(collection, {"usersInfo": user_name}) - finally: - execute_admin_command(collection, {"dropUser": user_name}) + """Test basic usersInfo behavior.""" + result = execute_admin_command(collection, {"usersInfo": 1}) assertCommandSupported(result, msg="Should support usersInfo command")