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
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 All @@ -33,10 +33,22 @@ def test_smoke_changeStream_modify(collection):
# cleanly instead of a TypeError from subscripting an exception object.
cursor_id = result.get("cursor", {}).get("id", 0) if isinstance(result, dict) else 0

execute_command(collection, {"collMod": collection.name, "validator": {"x": {"$type": "int"}}})
# A $jsonSchema validator is the most widely supported validator form, so the
# probe tests the modify event rather than which query operators a validator
# may use.
execute_command(
collection,
{"collMod": collection.name, "validator": {"$jsonSchema": {"required": ["x"]}}},
)

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 modify event was not emitted; fail with a
# clear message instead of an IndexError when indexing nextBatch[0].
# An empty batch means the modify event was not emitted; fail with a clear
# message instead of an IndexError when indexing nextBatch[0].
assertChangeStreamEvent(result, msg="Should support modify change stream event")
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
"""Tests for $sample stage statistical properties.

These tests verify statistical properties (randomness, distribution) of
$sample, which require repeated execution and custom assertions rather
than the deterministic StageTestCase/assertResult pattern.
$sample, which require repeated execution rather than the single-command
StageTestCase pattern. Each test computes its statistic over the repeated
runs and checks it with assertSuccess.
"""

from __future__ import annotations

import pytest

from documentdb_tests.framework.assertions import assertSuccess
from documentdb_tests.framework.executor import execute_command


Expand All @@ -29,6 +31,7 @@ def test_sample_statistical_randomness(collection):
all_ids = set(range(n_docs))
collection.insert_many([{"_id": i} for i in all_ids])
seen: set[int] = set()
result = None
for _ in range(max_iterations):
result = execute_command(
collection,
Expand All @@ -39,14 +42,19 @@ def test_sample_statistical_randomness(collection):
},
)
if isinstance(result, Exception):
raise AssertionError(f"$sample should succeed but got error: {result}")
docs = result["cursor"]["firstBatch"]
seen.add(docs[0]["_id"])
break
seen.add(result["cursor"]["firstBatch"][0]["_id"])
if seen == all_ids:
return
raise AssertionError(
f"$sample failed to reach all documents after {max_iterations} iterations: "
f"missing {all_ids - seen}"
break

# An error from any run is reported as is; otherwise check which documents
# were never returned.
summary = result if isinstance(result, Exception) else {"unreached": sorted(all_ids - seen)}
assertSuccess(
summary,
{"unreached": []},
raw_res=True,
msg=f"$sample should reach every document within {max_iterations} iterations",
)


Expand All @@ -67,6 +75,7 @@ def test_sample_statistical_uniformity(collection):

collection.insert_many([{"_id": i} for i in range(n_docs)])
counts: dict[int, int] = dict.fromkeys(range(n_docs), 0)
result = None
for _ in range(n_samples):
result = execute_command(
collection,
Expand All @@ -77,12 +86,21 @@ def test_sample_statistical_uniformity(collection):
},
)
if isinstance(result, Exception):
raise AssertionError(f"$sample should succeed but got error: {result}")
docs = result["cursor"]["firstBatch"]
counts[docs[0]["_id"]] += 1
underfilled = {k: v for k, v in counts.items() if v < min_count}
if underfilled:
raise AssertionError(
f"$sample appears biased: documents {underfilled} were selected fewer "
f"than {min_count} times out of {n_samples} (expected ~{n_samples // n_docs})"
)
break
counts[result["cursor"]["firstBatch"][0]["_id"]] += 1

# An error from any run is reported as is; otherwise check which documents
# were selected fewer than min_count times.
if isinstance(result, Exception):
summary = result
else:
summary = {"underfilled": sorted(k for k, v in counts.items() if v < min_count)}
assertSuccess(
summary,
{"underfilled": []},
raw_res=True,
msg=(
f"$sample should select every document at least {min_count} times out of "
f"{n_samples} (expected ~{n_samples // n_docs})"
),
)
Loading