Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/testing/TEST_FORMAT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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].
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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].
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(){}")),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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": [],
Expand Down Expand Up @@ -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": [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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_<i>"`` 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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": [],
Expand Down
Loading
Loading