Every API test follows: Setup → Execute → Assert.
from documentdb_tests.framework.assertions import assertSuccess
from documentdb_tests.framework.executor import execute_command
def test_descriptive_name(collection):
"""Clear description of what this test validates."""
# Setup (insert documents if needed)
collection.insert_many([{"_id": 0, "a": 1}, {"_id": 1, "a": 2}])
# Execute — always use runCommand format
result = execute_command(collection, {
"find": collection.name,
"filter": {"a": 1}
})
# Assert — use framework assertion helpers
assertSuccess(result, [{"_id": 0, "a": 1}])Files: test_<feature_area>.py — files in feature subfolders must include the feature name.
✅ /tests/aggregate/unwind/test_unwind_path.py
❌ /tests/aggregate/unwind/test_path.py
Functions: test_<what_is_being_tested> — descriptive, self-documenting.
✅ test_find_with_gt_operator, test_unwind_preserves_null_arrays
❌ test_1, test_query, test_edge_case
Use helpers from framework.assertions, not plain assert:
# assertResult — parametrized tests mixing success and error cases
assertResult(result, expected=5) # checks cursor.firstBatch == [{"result": 5}]
assertResult(result, error_code=16555) # checks error code only
# assertSuccess — raw command output
assertSuccess(result, [{"_id": 0, "a": 1}])
assertSuccess(result, expected, ignore_doc_order=True)
# assertFailureCode — error cases (only check code, not message)
assertFailureCode(result, 14)assertResult is the single entry point the other helpers wrap. Give it
exactly one expectation per call — passing more than one raises
TestSetupError rather than silently honoring one by precedence:
| Expectation | Meaning |
|---|---|
expected=<value> |
success; compare the result (or cursor.firstBatch) to the value |
expected=<checks> / properties=True |
success; apply property_checks by dotted path |
error={"code": c, "msg": m} |
failure; exact code and message |
error_code=<int> |
failure; check the code only |
exception_type=<cls> |
client-side exception of that type (e.g. InvalidBSON) |
not_error=True |
only assert the result is not an error |
The remaining keywords shape how the chosen expectation is compared; they are not expectation selectors and may be combined with one:
| Modifier | Effect |
|---|---|
raw_res=True |
compare the raw command result instead of cursor.firstBatch |
partial=True |
compare only the fields present in expected (implies raw_res) |
nan=True |
treat NaN == NaN as equal |
transform=<fn> |
transform the actual value before comparison |
ignore_order_in=[...] |
sort the named fields' list values before comparing |
ignore_doc_order=True |
compare top-level lists ignoring order |
msg=<str> |
prefix for the failure message |
partial cannot be combined with nan or transform, and nan cannot be
combined with transform; those also raise TestSetupError.
One assertion per test function. Split multiple assertions into separate tests.
collection— most common. Auto cleanup after test. Insert documents in test body.database_client— when you need multiple collections or database-level ops. Auto dropped after test.engine_client— raw client access.
Always use execute_command() with runCommand format to get test result, not driver methods. Setups can use methods.
# ✅ runCommand format
result = execute_command(collection, {"find": collection.name, "filter": {"a": 1}})
# ❌ Driver methods
result = collection.find({"a": 1})Avoid deep helper function chains. One layer of abstraction on top of execute_command() is acceptable, don't add more abstraction layers unless justified.
# ✅ Good: execute_expression wraps execute_command with aggregate pipeline boilerplate
result = execute_expression(collection, {"$add": [1, 2]})
# ❌ Bad: trivial wrappers that just save a few characters add indirection for no clarity gain
# result = execute_operator(collection, "$add", [1, 2])Keep helpers in utils/ at each test level. Helpers should reduce meaningful boilerplate (e.g., building an aggregate pipeline), not just shorten a single line.
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.
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 (20 seconds by default), the last result is returned so the assertion reports it.
# ✅ 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)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:
@dataclass(frozen=True)
class DivideTest(BaseTestCase):
dividend: Any = None
divisor: Any = None
DIVIDE_TESTS: list[DivideTest] = [
DivideTest("int32", dividend=10, divisor=2, expected=5.0, msg="Should divide int32 values"),
DivideTest("null_divisor", dividend=10, divisor=None, expected=None, msg="Should return null when divisor is null"),
DivideTest("string_err", dividend=10, divisor="string", error_code=TYPE_MISMATCH_ERROR, msg="Should reject string"),
]
@pytest.mark.parametrize("test", DIVIDE_TESTS, ids=lambda t: t.id)
def test_divide(collection, test):
"""Test $divide operator."""
result = execute_expression(collection, {"$divide": [test.dividend, test.divisor]})
assertResult(result, expected=test.expected, error_code=test.error_code, msg=test.msg)BaseTestCase(fromframework.test_case) providesid,expected,error_code,msg— extend it per operator- Shared helpers/dataclasses live in
utils/at each level msgis required — describes expected behavior, not input- Use constants from
framework.test_constants(INT32_MAX,FLOAT_NAN, etc.) andframework.error_codes(TYPE_MISMATCH_ERROR, etc.)
Markers that suppress or reclassify a test's outcome must always explain why, so a run never has an unexplained skipped/xfailed test. This is checked statically at collection time.
# ✅ Good
@pytest.mark.skip(reason="Requires Atlas Search configuration")
@pytest.mark.engine_xfail(engine="mongodb", reason="MongoDB misparses multi-digit years")
# ❌ Bad — no reason
@pytest.mark.skip
@pytest.mark.engine_xfail(engine="mongodb")Applies to skip, skipif, xfail, engine_xfail, and engine_xcrash. The
same rule covers runtime pytest.skip() / fail() / xfail() calls, via their
message argument:
# ✅ Good
pytest.skip("Engine supports this; skipping not-supported test")
pytest.skip(f"Unrecognized os.type {os_type!r}; skipping platform-specific check")
# ❌ Bad — no message
pytest.skip()The explanation must be present, and if written as a string literal it must be non-empty. A non-literal explanation (a shared constant or an f-string) is accepted — a static check can't resolve its value — so a reason constant reused across cases and a runtime message embedding dynamic context are both fine.
engine_xfail is strict: the marked test is expected to fail on that engine,
and if it passes the run fails with an [XPASS(strict)] error rather than
silently tolerating the unexpected pass. This is deliberate — a documented gap
that the server has since fixed should surface loudly so the stale marker is
removed and the test resumes guarding real behavior. If a test starts failing
with [XPASS(strict)], delete its engine_xfail marker.
A pytest hook auto-validates during collection:
- Files must match
test_*.py(except__init__.py) - Test functions must have docstrings
- Must use assertion helpers, not plain
assert - One assertion per test function
- Must use
execute_command()or helpers from utils - Outcome-suppressing markers must carry a
reason=, and runtimepytest.skip()/fail()/xfail()calls must pass a message (see Marker Reasons)
Some tests are only meaningful when the client is connecting to a remote server — for example, commands whose behavior differs depending on whether the connection is local. Gate these with the requires marker and the remote_target capability:
@pytest.mark.requires(remote_target=True)
def test_shutdown_remote_only(collection):
...The harness detects the connection source from the server-side whatsmyuri command. If the server reports a localhost address (localhost, 127.0.0.1, ::1, 0.0.0.0) or the target cannot be reached, the test is deselected rather than run.