diff --git a/docs/testing/TEST_FORMAT.md b/docs/testing/TEST_FORMAT.md index 9050b16a0..328532138 100644 --- a/docs/testing/TEST_FORMAT.md +++ b/docs/testing/TEST_FORMAT.md @@ -121,6 +121,23 @@ Keep helpers in `utils/` at each test level. Helpers should reduce meaningful bo Minimize helper scope — one helper should do one thing. If a helper has many if/else branches handling different cases, split it into separate helpers at a lower folder level. +### Polling for Asynchronously Published State + +Use `execute_command_until()` only for state the server may publish asynchronously, such as `$indexStats` counters or a change-stream event that lands after the first `getMore`. It is not a generic retry: + +- The predicate checks that the state is present (for example, the counter is non-zero), not the value the test asserts. The assertion still judges the result. +- Errors are never retried. An error result is returned at once. +- On timeout, the last result is returned so the assertion reports it. + +```python +# ✅ Good: wait until the counter is published, then assert on it +result = execute_command_until(collection, index_stats_cmd, done=index_used("a_1")) +assertResult(result, expected={"accesses.ops": Gte(1)}) + +# ❌ Bad: the predicate repeats the assertion, so a wrong value is polled for the full timeout +# result = execute_command_until(collection, cmd, done=lambda r: r == expected) +``` + ## Parametrized Tests Use `@pytest.mark.parametrize` with dataclasses for operators with many test cases. Dataclasses give named fields instead of anonymous tuples, so `test.dividend` is readable where `test[0]` is not. They also provide automatic `__repr__` for clear test IDs in output, and `frozen=True` prevents accidental mutation between test runs: diff --git a/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py b/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py index 4e1f5cccc..037d3a338 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py +++ b/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py @@ -7,7 +7,7 @@ import pytest from documentdb_tests.framework.assertions import assertChangeStreamEvent -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command, execute_command_until pytestmark = pytest.mark.smoke @@ -38,7 +38,13 @@ def test_smoke_changeStream_createIndexes(collection): {"createIndexes": collection.name, "indexes": [{"key": {"x": 1}, "name": "x_1"}]}, ) - result = execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) + # Some engines publish the DDL event after the first getMore returns, so + # read until a batch is non-empty or the timeout passes. + result = execute_command_until( + collection, + {"getMore": cursor_id, "collection": collection.name}, + lambda r: bool(r.get("cursor", {}).get("nextBatch")), + ) # An empty batch means the expanded createIndexes event was not emitted; fail # with a clear message instead of an IndexError when indexing nextBatch[0]. diff --git a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py index 05f3bde36..a1f00f103 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py +++ b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py @@ -2,7 +2,10 @@ from __future__ import annotations +from typing import Any + import pytest +from pymongo.errors import PyMongoError from documentdb_tests.compatibility.tests.changeStreams.dropIndexes.utils.drop_indexes import ( drop_index_events, @@ -131,25 +134,36 @@ def test_dropIndexes_start_after_star_returns_remaining_events(collection): collection.database.name, collection.name, ) - second_token = drops[1]["_id"] expected_remaining = sorted( event["operationDescription"]["indexes"][0]["name"] for event in drops[2:] ) - with open_change_stream( - collection, - scope="database", - start_after=second_token, - ) as resumed: - replayed_events = collect_until_marker(resumed, collection) - - summary = { - "drop_ok": drop_result.get("ok") if isinstance(drop_result, dict) else None, - "initial_count": len(drops), - "replayed_names": sorted(_event_names(replayed_events, collection)), - } + # With fewer than two drop events there is no token to start after; the + # initial_count check below reports the short event list instead of an + # IndexError here. A failed startAfter open or getMore is passed to the + # assertion as the result. + observed: Any = None + replayed_names = None + if len(drops) >= 2: + try: + with open_change_stream( + collection, + scope="database", + start_after=drops[1]["_id"], + ) as resumed: + replayed_events = collect_until_marker(resumed, collection) + replayed_names = sorted(_event_names(replayed_events, collection)) + except PyMongoError as error: + observed = error + + if observed is None: + observed = { + "drop_ok": drop_result.get("ok") if isinstance(drop_result, dict) else None, + "initial_count": len(drops), + "replayed_names": replayed_names, + } assertProperties( - summary, + observed, { "drop_ok": Eq(1.0), "initial_count": Eq(5), diff --git a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py index 9276a2665..5cea6cb01 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py +++ b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py @@ -170,7 +170,7 @@ class DropIndexSpecificationTestCase(BaseTestCase): def test_dropIndexes_event_preserves_specification(collection, test): """Compare the dropped index definition with listIndexes before deletion.""" collection.insert_one(test.document) - execute_command( + create_result = execute_command( collection, { "createIndexes": collection.name, @@ -183,27 +183,38 @@ def test_dropIndexes_event_preserves_specification(collection, test): ], }, ) - expected_specification = index_specification(collection, test.index_name) + observed: Any + try: + expected_specification = index_specification(collection, test.index_name) + except LookupError as missing: + # listIndexes did not return the index, so there is no specification + # to compare against. Pass the createIndexes error, or the missing + # index if createIndexes reported success, to the assertion below. + observed = create_result if isinstance(create_result, Exception) else missing + expected_specification = None - with open_change_stream(collection, scope="database") as stream: - drop_result = execute_command( - collection, - { - "dropIndexes": collection.name, - "index": test.index_name, - }, - ) - events = collect_until_marker(stream, collection) + if expected_specification is not None: + with open_change_stream(collection, scope="database") as stream: + drop_result = execute_command( + collection, + { + "dropIndexes": collection.name, + "index": test.index_name, + }, + ) + events = collect_until_marker(stream, collection) - matching_events = drop_index_events( - events, - collection.database.name, - collection.name, - ) - observed = { - "dropSucceeded": (not isinstance(drop_result, Exception) and drop_result.get("ok") == 1), - "dropEvents": matching_events, - } + matching_events = drop_index_events( + events, + collection.database.name, + collection.name, + ) + observed = { + "dropSucceeded": ( + not isinstance(drop_result, Exception) and drop_result.get("ok") == 1 + ), + "dropEvents": matching_events, + } expected = { "dropSucceeded": Eq(True), "dropEvents": Len(1), diff --git a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py index 635ba9a4e..c381fda5e 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py +++ b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py @@ -7,7 +7,7 @@ import pytest from documentdb_tests.framework.assertions import assertChangeStreamEvent -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command, execute_command_until pytestmark = pytest.mark.smoke @@ -36,7 +36,13 @@ def test_smoke_changeStream_dropIndexes(collection): execute_command(collection, {"dropIndexes": collection.name, "index": "x_1"}) - result = execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) + # Some engines publish the DDL event after the first getMore returns, so + # read until a batch is non-empty or the timeout passes. + result = execute_command_until( + collection, + {"getMore": cursor_id, "collection": collection.name}, + lambda r: bool(r.get("cursor", {}).get("nextBatch")), + ) # An empty batch means the expanded dropIndexes event was not emitted; fail # with a clear message instead of an IndexError when indexing nextBatch[0]. diff --git a/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py b/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py index 62a5f65f9..305f32553 100644 --- a/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py +++ b/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py @@ -72,7 +72,8 @@ ("int64", Int64(42)), ("decimal128", Decimal128("1")), ("binary", Binary(b"hello")), - ("objectid", ObjectId()), + # A fixed value keeps the command identical on every run. + ("objectid", ObjectId("507f1f77bcf86cd799439011")), ("datetime", datetime(2024, 1, 1, tzinfo=timezone.utc)), ("regex", Regex("test")), ("code", Code("function(){}")), 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 e60c6113f..2bb2c890a 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 @@ -10,6 +10,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, + label_cursor_ids, open_find_cursors, ) from documentdb_tests.framework import fixtures @@ -154,18 +155,23 @@ def test_killCursors_list_indexes_cursor(collection): {"listIndexes": collection.name, "cursor": {"batchSize": 1}}, ) cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] + # The reply is compared with the opened cursor ID replaced by "cursor_0", + # so the compared value does not embed this run's server-assigned ID. result = ( res if isinstance(res, Exception) - else execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, + else label_cursor_ids( + execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ), + [cursor_id], ) ) assertResult( result, expected={ - "cursorsKilled": [cursor_id], + "cursorsKilled": ["cursor_0"], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], @@ -212,28 +218,41 @@ def test_killCursors_view_cursor(database_client, collection): def test_killCursors_timeseries_cursor(database_client, collection): """Test killCursors kills a cursor opened against a time-series collection.""" ts_name = collection.name + "_ts" - execute_command( + created = execute_command( collection, {"create": ts_name, "timeseries": {"timeField": "ts"}}, ) - ts = database_client[ts_name] - ts.insert_many( - [{"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 = 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]}, + # A rejected time-series create is the result: inserting anyway would + # create a regular collection and test a non-time-series cursor instead. + if isinstance(created, Exception): + result = created + else: + ts = database_client[ts_name] + ts.insert_many( + [ + {"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 = None if isinstance(res, Exception) else res["cursor"]["id"] + # The reply is compared with the opened cursor ID replaced by "cursor_0", + # so the compared value does not embed this run's server-assigned ID. + result = ( + res + if isinstance(res, Exception) + else label_cursor_ids( + execute_command( + ts, + {"killCursors": ts_name, "cursors": [cursor_id]}, + ), + [cursor_id], + ) ) - ) assertResult( result, expected={ - "cursorsKilled": [cursor_id], + "cursorsKilled": ["cursor_0"], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], 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 64090f510..38185f194 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,6 +8,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, + label_cursor_ids, open_find_cursors, ) from documentdb_tests.compatibility.tests.core.utils.command_test_case import ( @@ -179,8 +180,10 @@ def test_killCursors_response_cursor(database_client, collection, test): 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) + # Compare with each opened cursor ID replaced by its position label, so + # the compared value does not embed this run's server-assigned IDs. + result = label_cursor_ids(execute_command(collection, test.build_command(ctx)), cursors) + expected = label_cursor_ids(test.build_expected(ctx), cursors) assertResult( result, expected=expected, 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 124394b81..1450a6d0e 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 @@ -68,6 +68,30 @@ def open_cursor(collection: Collection, find_options: dict[str, Any]) -> Any: return res["cursor"]["id"] +KILL_CURSORS_ID_FIELDS = ("cursorsKilled", "cursorsNotFound", "cursorsAlive", "cursorsUnknown") + + +def label_cursor_ids(reply: Any, cursor_ids: tuple[Any, ...] | list[Any]) -> Any: + """Replace each opened cursor ID in a killCursors reply with a stable label. + + Cursor IDs are assigned by the server and differ on every run, so a reply + that embeds them cannot be compared against a recorded result. The ID at + position ``i`` of ``cursor_ids`` becomes ``"cursor_"`` wherever it + appears in the four killCursors ID lists; any other ID is kept as-is. + Field names, list lengths, order and every other field are unchanged, so + the comparison still proves which opened cursor landed in which list. + A non-dict reply (an engine error) is returned unchanged. + """ + if not isinstance(reply, dict): + return reply + labels = {cursor_id: f"cursor_{i}" for i, cursor_id in enumerate(cursor_ids)} + labelled = dict(reply) + for field in KILL_CURSORS_ID_FIELDS: + if isinstance(reply.get(field), list): + labelled[field] = [labels.get(cursor_id, cursor_id) for cursor_id in reply[field]] + return labelled + + @dataclass(frozen=True) class CursorCommandTestCase(CommandTestCase): """CommandTestCase that opens N find cursors before executing. diff --git a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py index e5909708e..4196b9e93 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py +++ b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py @@ -6,6 +6,9 @@ import pytest +from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( + label_cursor_ids, +) from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command @@ -121,17 +124,24 @@ def test_listIndexes_killCursors_succeeds(collection_with_3_indexes): collection_with_3_indexes, {"listIndexes": collection_with_3_indexes.name, "cursor": {"batchSize": 1}}, ) - cursor_id = result["cursor"]["id"] - - kill_result = execute_command( - collection_with_3_indexes, - {"killCursors": collection_with_3_indexes.name, "cursors": [cursor_id]}, - ) + if isinstance(result, Exception): + kill_result = result + else: + cursor_id = result.get("cursor", {}).get("id") + # The reply is compared with the opened cursor ID replaced by "cursor_0", + # so the compared value does not embed this run's server-assigned ID. + kill_result = label_cursor_ids( + execute_command( + collection_with_3_indexes, + {"killCursors": collection_with_3_indexes.name, "cursors": [cursor_id]}, + ), + [cursor_id], + ) assertSuccess( kill_result, { - "cursorsKilled": [cursor_id], + "cursorsKilled": ["cursor_0"], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], diff --git a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py index 8a66bfd75..80ba45a00 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py +++ b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py @@ -10,10 +10,14 @@ IndexTestCase, ) from documentdb_tests.framework.assertions import assertSuccess -from documentdb_tests.framework.executor import execute_admin_command, execute_command +from documentdb_tests.framework.executor import ( + execute_admin_command, + execute_command, + execute_command_until, +) from documentdb_tests.framework.parametrize import pytest_params -from .utils.helpers import get_index_doc, get_index_ops +from .utils.helpers import get_index_doc, get_index_ops, index_stats_command, index_used pytestmark = pytest.mark.index @@ -91,6 +95,9 @@ def test_indexstats_counter(collection, test): execute_command( collection, {"find": collection.name, "filter": {"a": {"$gte": 0}}, "hint": "a_1"} ) + # Wait until the pre-use access is counted, so the toggles below act + # on a non-zero counter even where accesses.ops is updated lazily. + execute_command_until(collection, index_stats_command(collection), index_used("a_1")) for hidden_value in test.input["toggle_sequence"]: execute_command( collection, @@ -100,8 +107,12 @@ def test_indexstats_counter(collection, test): execute_command( collection, {"find": collection.name, "filter": {"a": {"$gte": 0}}, "hint": "a_1"} ) - result = execute_command( - collection, {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} + # A case that expects a non-zero counter reads until the use is counted; + # a case that expects zero reads once, as before. + result = execute_command_until( + collection, + index_stats_command(collection), + index_used("a_1") if test.expected else lambda r: True, ) assertSuccess( result, @@ -349,9 +360,7 @@ def test_indexstats_nonhidden_accesses_increment_nonzero(collection): execute_command( collection, {"find": collection.name, "filter": {"a": {"$gte": 0}}, "hint": "a_1"} ) - result = execute_command( - collection, {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} - ) + result = execute_command_until(collection, index_stats_command(collection), index_used("a_1")) ops = get_index_ops(result, "a_1") assertSuccess( ops >= 1, @@ -380,9 +389,7 @@ def test_indexstats_reset_only_affects_toggled_index_b_unchanged(collection): execute_command( collection, {"collMod": collection.name, "index": {"name": "a_1", "hidden": True}} ) - result = execute_command( - collection, {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} - ) + result = execute_command_until(collection, index_stats_command(collection), index_used("b_1")) b_ops = get_index_ops(result, "b_1") assertSuccess( b_ops >= 1, diff --git a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py index 8e315fb4b..f32b3711f 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py +++ b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py @@ -1,6 +1,6 @@ """Helpers for hidden index property tests.""" -from typing import Any, Iterator, List, Optional +from typing import Any, Callable, Iterator, List, Optional def _walk(node: Any) -> Iterator[dict]: @@ -106,3 +106,17 @@ def get_index_ops(result, index_name): if doc is None: return None return doc["accesses"]["ops"] + + +def index_stats_command(collection) -> dict: + """Return the $indexStats aggregate command for a collection.""" + return {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} + + +def index_used(index_name: str) -> Callable[[dict], bool]: + """Return a predicate that is True once $indexStats reports a use of the index. + + Used with execute_command_until: some engines update accesses.ops + asynchronously, so a single read right after a query can still show 0. + """ + return lambda result: (get_index_ops(result, index_name) or 0) > 0 diff --git a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py index 33cf66668..5be6ea941 100644 --- a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py +++ b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py @@ -243,6 +243,11 @@ def test_accumulator_mergeObjects_input_forms(collection, test_case: Accumulator {"aggregate": collection.name, "pipeline": test_case.pipeline, "cursor": {}}, ) assertSuccess(result, test_case.expected, msg=test_case.msg) + # An error reply fails in assertSuccess, unless an override provider + # handled the call and it returned. Stop then, so the key-order check + # below only reads firstBatch from a successful result. + if isinstance(result, Exception): + return actual_docs = result["cursor"]["firstBatch"] for actual, exp in zip(actual_docs, test_case.expected): if "result" in exp and isinstance(exp["result"], dict): diff --git a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py index ca5fb0cd8..590c9ff1c 100644 --- a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py +++ b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py @@ -278,6 +278,11 @@ def test_accumulator_mergeObjects_null_missing(collection, test_case: Accumulato {"aggregate": collection.name, "pipeline": test_case.pipeline, "cursor": {}}, ) assertSuccess(result, test_case.expected, msg=test_case.msg) + # An error reply fails in assertSuccess, unless an override provider + # handled the call and it returned. Stop then, so the key-order check + # below only reads firstBatch from a successful result. + if isinstance(result, Exception): + return actual_docs = result["cursor"]["firstBatch"] for actual, exp in zip(actual_docs, test_case.expected): if "result" in exp and isinstance(exp["result"], dict): diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py b/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py index f90bf06ab..8eb13dfca 100644 --- a/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py +++ b/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py @@ -11,10 +11,19 @@ populate_collection, ) from documentdb_tests.framework.assertions import assertResult -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command_until from documentdb_tests.framework.parametrize import pytest_params from documentdb_tests.framework.property_checks import Gte + +def _index_used(result: dict) -> bool: + """Return True once any returned $indexStats document has accesses.ops >= 1.""" + return any( + doc.get("accesses", {}).get("ops", 0) >= 1 + for doc in result.get("cursor", {}).get("firstBatch", []) + ) + + # Property [Ops Increment]: accesses.ops increments after index usage. OPS_INCREMENT_TESTS: list[StageTestCase] = [ StageTestCase( @@ -36,13 +45,16 @@ def test_indexStats_ops_counter(collection: Collection, test_case: StageTestCase coll = populate_collection(collection, test_case) if test_case.setup: test_case.setup(coll) - result = execute_command( + # Some engines update accesses.ops asynchronously after the query, so + # read until a matching index reports a use or the timeout passes. + result = execute_command_until( coll, { "aggregate": coll.name, "pipeline": test_case.pipeline, "cursor": {}, }, + _index_used, ) assertResult( result, diff --git a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py index 4e07f5aa4..9d3601a4d 100644 --- a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py +++ b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py @@ -9,6 +9,7 @@ import pytest from bson import Binary, Code, DBRef, Int64, MaxKey, MinKey, ObjectId, Timestamp +from pymongo.errors import PyMongoError from utils.changeStream_common import change_stream_command, get_more_command from documentdb_tests.framework.assertions import assertProperties @@ -429,15 +430,19 @@ def _emit_event(collection, test_case: ChangeStreamEventTestCase) -> dict[str, A """Open a stream, perform the test case mutation, and return the matching event. The mutation happens after the stream is open, so its event is delivered by - the first getMore. If opening the stream or reading the batch fails, the - engine's exception is returned so the test's single assertion surfaces it. - If the batch has no event of the expected type, the getMore reply is - returned instead, so the assertion reports what the stream delivered. + the first getMore. If seeding, opening the stream, performing the mutation + or reading the batch fails, the engine's exception is returned so the + test's single assertion surfaces it. If the batch has no event of the + expected type, the getMore reply is returned instead, so the assertion + reports what the stream delivered. """ mutation = test_case.mutation assert mutation is not None # guaranteed by __post_init__ if mutation.seed is not None: - collection.insert_one(dict(mutation.seed)) + try: + collection.insert_one(dict(mutation.seed)) + except PyMongoError as error: + return error if test_case.pre_and_post_images: execute_command( collection, @@ -448,9 +453,14 @@ def _emit_event(collection, test_case: ChangeStreamEventTestCase) -> dict[str, A ) if isinstance(opened, Exception): return opened - mutation.apply(collection) - if test_case.post_mutation is not None: - test_case.post_mutation(collection) + # The mutation's own write can be rejected (for example an _id type an + # engine does not accept); that error is the result, not a crash. + try: + mutation.apply(collection) + if test_case.post_mutation is not None: + test_case.post_mutation(collection) + except PyMongoError as error: + return error batch_result = execute_command(collection, get_more_command(collection, opened["cursor"]["id"])) if isinstance(batch_result, Exception): return batch_result diff --git a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py index 2fef043c8..3e320bde2 100644 --- a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py +++ b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py @@ -18,7 +18,7 @@ INVALID_RESUME_TOKEN_ERROR, OVERFLOW_ERROR, ) -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command, execute_command_until from documentdb_tests.framework.property_checks import Eq, Len pytestmark = [pytest.mark.requires(change_streams=True), pytest.mark.aggregate] @@ -62,15 +62,29 @@ def _first_event_token(collection, seed, spec=None): def _event_token_of_type(collection, operation_type, seed, spec=None): - """Open a stream, seed events, and return the token of the first matching event.""" + """Open a stream, seed events, and return the token of the first matching event. + + Some engines publish an event (for example a DDL event) after the first + getMore returns, so the stream is read until a batch holds an event of + ``operation_type`` or the timeout passes. On an engine that delivers the + event in the first batch, getMore runs exactly once. + """ opened = _open_stream(collection, spec) if isinstance(opened, Exception): return opened seed(collection) - batch = _drain(collection, opened) - if isinstance(batch, Exception): - return batch - token = next((e["_id"] for e in batch if e["operationType"] == operation_type), None) + result = execute_command_until( + collection, + get_more_command(collection, opened["cursor"]["id"]), + lambda r: any( + e.get("operationType") == operation_type + for e in r.get("cursor", {}).get("nextBatch", []) + ), + ) + if isinstance(result, Exception): + return result + batch = result.get("cursor", {}).get("nextBatch", []) + token = next((e["_id"] for e in batch if e.get("operationType") == operation_type), None) if token is None: return LookupError(f"token-capture stream returned no {operation_type} event: {batch!r}") return token diff --git a/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py b/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py index 3138249d5..9ed261de9 100644 --- a/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py +++ b/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py @@ -7,57 +7,58 @@ from __future__ import annotations +from typing import Any + from pymongo.collection import Collection -from documentdb_tests.framework.assertions import assertNotError, assertSuccess +from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command -def _set_filters(collection: Collection) -> None: +def _set_filters(collection: Collection) -> Any: """Set two distinct index filters on the collection. - Raises AssertionError if the filters are not visible via - planCacheListFilters after being set. + Returns the engine error if a setup command fails, so the caller can + forward it to the test's single assertion, or None on success. Raises + AssertionError if the commands succeed but the filters are not visible + via planCacheListFilters, since the test would then prove nothing. """ collection.insert_many([{"_id": i, "a": i, "b": i % 5} for i in range(10)]) collection.create_index("a") collection.create_index("b") - db = collection.database - db.command( - { - "planCacheSetFilter": collection.name, - "query": {"a": 1}, - "indexes": [{"a": 1}], - } - ) - db.command( - { - "planCacheSetFilter": collection.name, - "query": {"b": 1}, - "indexes": [{"b": 1}], - } - ) + for field in ("a", "b"): + set_result = execute_command( + collection, + { + "planCacheSetFilter": collection.name, + "query": {field: 1}, + "indexes": [{field: 1}], + }, + ) + if isinstance(set_result, Exception): + return set_result list_result = execute_command(collection, {"planCacheListFilters": collection.name}) - assertNotError(list_result, msg="planCacheListFilters precondition check") + if isinstance(list_result, Exception): + return list_result filters = list_result.get("filters", []) if len(filters) < 2: raise AssertionError( f"Precondition failed: expected at least 2 index filters " f"after setup, got {len(filters)}" ) + return None # Property [Clear All Filters]: planCacheClearFilters without query shape # parameters removes all index filters for the collection. def test_planCacheClearFilters_clears_all_filters(collection: Collection): """Test planCacheClearFilters removes all index filters.""" - _set_filters(collection) - - execute_command(collection, {"planCacheClearFilters": collection.name}) - - result = execute_command(collection, {"planCacheListFilters": collection.name}) + result = _set_filters(collection) + if result is None: + execute_command(collection, {"planCacheClearFilters": collection.name}) + result = execute_command(collection, {"planCacheListFilters": collection.name}) assertSuccess( result, {"filters": [], "ok": 1.0}, @@ -70,14 +71,13 @@ def test_planCacheClearFilters_clears_all_filters(collection: Collection): # only the matching filter and leaves other filters intact. def test_planCacheClearFilters_targeted_preserves_other_filters(collection: Collection): """Test planCacheClearFilters with query shape leaves non-targeted filters.""" - _set_filters(collection) - - execute_command( - collection, - {"planCacheClearFilters": collection.name, "query": {"a": 1}}, - ) - - result = execute_command(collection, {"planCacheListFilters": collection.name}) + result = _set_filters(collection) + if result is None: + execute_command( + collection, + {"planCacheClearFilters": collection.name, "query": {"a": 1}}, + ) + result = execute_command(collection, {"planCacheListFilters": collection.name}) assertSuccess( result, { diff --git a/documentdb_tests/framework/executor.py b/documentdb_tests/framework/executor.py index 812aa70aa..7936c0f70 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, List, Tuple +from typing import Any, Callable, Dict, List, Tuple from bson.codec_options import CodecOptions @@ -126,3 +126,41 @@ def execute_admin_with_retry_command( if not should_retry or time.monotonic() >= deadline: return result time.sleep(interval) + + +def execute_command_until( + collection, + command: Dict, + done: Callable[[Dict], bool], + *, + timeout: float = 10.0, + interval: float = 0.1, +) -> Any: + """ + Run a command until ``done`` accepts its result, then return that result. + + For state that some engines publish asynchronously, such as $indexStats + counters or a change-stream event that lands after the first getMore. On + an engine that reports the state at once, the first result is returned + and the command runs exactly once. + + An error result is returned immediately without calling ``done``. On + timeout, the last result is returned as-is so the caller's assertion + reports it. + + Args: + collection: DocumentDB collection + command: Command to execute via runCommand + done: Predicate on a successful result; True stops polling + timeout: Maximum seconds to keep polling + interval: Seconds to wait between attempts + + Returns: + Result if successful, Exception if failed + """ + deadline = time.monotonic() + timeout + while True: + result = execute_command(collection, command) + if isinstance(result, Exception) or done(result) or time.monotonic() >= deadline: + return result + time.sleep(interval) diff --git a/documentdb_tests/framework/test_executor_polling.py b/documentdb_tests/framework/test_executor_polling.py new file mode 100644 index 000000000..828e086af --- /dev/null +++ b/documentdb_tests/framework/test_executor_polling.py @@ -0,0 +1,69 @@ +"""Unit tests for execute_command_until in the executor (no database needed).""" + +import pytest +from pymongo.errors import OperationFailure + +from documentdb_tests.framework import executor + + +class _FakeDatabase: + def __init__(self, results): + self.results = list(results) + self.calls = 0 + self.client = None + + def command(self, command, **kwargs): + self.calls += 1 + result = self.results.pop(0) if len(self.results) > 1 else self.results[0] + if isinstance(result, Exception): + raise result + return result + + +class _FakeCollection: + def __init__(self, results): + self.database = _FakeDatabase(results) + self.name = "coll" + + +def _ready(result): + return result.get("ready") is True + + +@pytest.mark.unit +def test_first_accepted_result_runs_command_once(): + collection = _FakeCollection([{"ready": True, "ok": 1.0}]) + result = executor.execute_command_until(collection, {"ping": 1}, _ready, interval=0) + assert result == {"ready": True, "ok": 1.0} + assert collection.database.calls == 1 + + +@pytest.mark.unit +def test_polls_until_result_is_accepted(): + collection = _FakeCollection([{"ready": False}, {"ready": False}, {"ready": True}]) + result = executor.execute_command_until(collection, {"ping": 1}, _ready, interval=0) + assert result == {"ready": True} + assert collection.database.calls == 3 + + +@pytest.mark.unit +def test_error_is_returned_without_polling(): + error = OperationFailure("boom", code=2) + collection = _FakeCollection([error]) + calls = [] + result = executor.execute_command_until( + collection, {"ping": 1}, lambda r: calls.append(r) or False, interval=0 + ) + assert result is error + assert collection.database.calls == 1 + assert calls == [] + + +@pytest.mark.unit +def test_timeout_returns_last_result(): + collection = _FakeCollection([{"ready": False}]) + result = executor.execute_command_until( + collection, {"ping": 1}, _ready, timeout=0.05, interval=0.01 + ) + assert result == {"ready": False} + assert collection.database.calls >= 2 diff --git a/documentdb_tests/framework/test_format_validator.py b/documentdb_tests/framework/test_format_validator.py index 2c3394942..d7aa5dc88 100644 --- a/documentdb_tests/framework/test_format_validator.py +++ b/documentdb_tests/framework/test_format_validator.py @@ -34,6 +34,7 @@ def validate_test_format(file_path: str) -> list[str]: "execute_expression_single_row", "execute_expression_with_insert", "execute_admin_with_retry_command", + "execute_command_until", "run_window_operator", ] )