diff --git a/README.md b/README.md index 983e1eace..348081396 100644 --- a/README.md +++ b/README.md @@ -288,6 +288,51 @@ When targets are discovered automatically (running `pytest` with no `--connection-string`), each test runs against every discovered target it applies to, so no manual selection is needed. +### Reference Version and Spec Versions + +Expected results are pinned to MongoDB 8.2.4, the version CI runs against. +Every test except smoke tests always runs and expects the 8.2.4 answer, +whatever `--spec-version` is set to. + +Only smoke tests (`pytest.mark.smoke`) can select a target minor version, +with `--spec-version` (`8.0`, `8.2` or `8.3`, default `8.2`). A smoke test for +a feature added in a later version declares it with the `requires` marker: + +```python +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.3")] +``` + +`spec_until` works the same way for a feature a later version removed. A smoke +test with no spec gate runs under every spec version. There is no `8.1` spec +version: a feature added in 8.1 uses `spec_since="8.2"`. A spec gate on a test +that is not a smoke test is a collection error. + +Out-of-scope smoke tests are deselected and listed, with the gate that excluded +them, in the report's `.deselected.json` sidecar. The JSON report records the +run's spec version and each target's server version under `run`. + +The gate can be set on a smoke test, a smoke test file (`pytestmark`, as above) +or a folder that holds only smoke tests, from the folder's `conftest.py`: + +```python +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") +``` + +Gates combine with capability gates such as `requires(change_streams=True)`; +on the same key the closest level wins. + +```bash +# Run the smoke tests for spec 8.3 against the 8.3 dev server +docker compose -f dev/compose.yaml --profile mongo-standalone-8.3 up -d --wait +pytest -m smoke --connection-string mongodb://localhost:27019 --engine-name mongodb --spec-version 8.3 + +# Run the smoke tests for spec 8.0 against the 8.0 dev server +docker compose -f dev/compose.yaml --profile mongo-standalone-8.0 up -d --wait +pytest -m smoke --connection-string mongodb://localhost:27020 --engine-name mongodb --spec-version 8.0 +``` + ## Writing Tests ### Basic Test Structure diff --git a/dev/compose.yaml b/dev/compose.yaml index 4ab97e7a1..4014eb5ce 100644 --- a/dev/compose.yaml +++ b/dev/compose.yaml @@ -66,7 +66,7 @@ services: soft: 1048576 hard: 1048576 ports: - - "27017:27017" + - "127.0.0.1:27017:27017" healthcheck: test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ping:1}).ok"] interval: 5s @@ -75,6 +75,46 @@ services: x-test-target: engine: mongodb + # mongo-standalone-8.0: a standalone server on the 8.0 release, for runs + # scoped to the 8.0 spec (smoke tests only, --spec-version 8.0). It has no + # x-test-target, so it is not auto-discovered and not part of the CI + # matrix; point pytest at it explicitly: + # + # docker compose -f dev/compose.yaml --profile mongo-standalone-8.0 up -d --wait + # pytest -m smoke --connection-string mongodb://localhost:27020 --engine-name mongodb \ + # --spec-version 8.0 + mongo-standalone-8.0: + image: mongo:8.0.38 + profiles: ["mongo-standalone-8.0"] + command: ["--wiredTigerCacheSizeGB", "1.5"] + ports: + - "127.0.0.1:27020:27017" + healthcheck: + test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ping:1}).ok"] + interval: 5s + timeout: 5s + retries: 10 + + # mongo-standalone-8.3: a standalone server on the 8.3 release, for runs + # scoped to the 8.3 spec (smoke tests only, --spec-version 8.3). It has no + # x-test-target, so it is not auto-discovered and not part of the CI + # matrix; point pytest at it explicitly: + # + # docker compose -f dev/compose.yaml --profile mongo-standalone-8.3 up -d --wait + # pytest -m smoke --connection-string mongodb://localhost:27019 --engine-name mongodb \ + # --spec-version 8.3 + mongo-standalone-8.3: + image: mongo:8.3.13 + profiles: ["mongo-standalone-8.3"] + command: ["--wiredTigerCacheSizeGB", "1.5"] + ports: + - "127.0.0.1:27019:27017" + healthcheck: + test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ping:1}).ok"] + interval: 5s + timeout: 5s + retries: 10 + # mongo-replset: a single-node replica set. Provides capabilities the # reference server gates behind a replica set (change streams, transactions, # queryable encryption, cluster-wide admin). Connect with directConnection=true. @@ -110,7 +150,7 @@ services: soft: 1048576 hard: 1048576 ports: - - "27018:27017" + - "127.0.0.1:27018:27017" healthcheck: test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ping:1}).ok"] interval: 5s diff --git a/docs/REVIEW.md b/docs/REVIEW.md index b8bfec176..c3d991854 100644 --- a/docs/REVIEW.md +++ b/docs/REVIEW.md @@ -60,6 +60,7 @@ Follow every rule in [`FOLDER_STRUCTURE.md`](testing/FOLDER_STRUCTURE.md). Addit - [ ] Type annotations on helper functions - [ ] Order-independent output uses `ignore_doc_order=True` - [ ] Tests that depend on an environment capability are gated with `@pytest.mark.requires(=)` (e.g. `requires(change_streams=True)`), not a topology marker +- [ ] Expected results match MongoDB 8.2.4 (the CI target). Only smoke tests may carry a spec gate: a smoke test for a feature added after 8.0 uses `requires(spec_since="")` (8.1 features use `"8.2"`; see README "Reference Version and Spec Versions"), not an `engine_xfail` for the reference server. Other tests never get a spec gate - [ ] Tests that cannot run in parallel are tagged `@pytest.mark.no_parallel` - [ ] Tests where MongoDB itself fails are tagged with `engine_xfail` (not skipped) - [ ] Tests with non-deterministic output (e.g. `$rand`, `$sample`, server timestamps) assert structure/bounds, not exact values diff --git a/docs/SMOKE_TEST_NOTE.md b/docs/SMOKE_TEST_NOTE.md index a66784f78..16b7d1598 100644 --- a/docs/SMOKE_TEST_NOTE.md +++ b/docs/SMOKE_TEST_NOTE.md @@ -2,8 +2,8 @@ ## Overview -Smoke test files: 456 -Feature tree entries: 469 +Smoke test files: 487 +Feature tree entries: 499 Missing: 13 ## Missing Features (13) diff --git a/docs/feature-tree.csv b/docs/feature-tree.csv index c6e093511..9a4a353e1 100644 --- a/docs/feature-tree.csv +++ b/docs/feature-tree.csv @@ -133,6 +133,7 @@ core,operator,expressions,conditional,-,ifNull core,operator,expressions,conditional,-,switch core,operator,expressions,custom,-,function core,operator,expressions,custom,-,operator_accumulator +core,operator,expressions,date,-,currentDate core,operator,expressions,date,-,dateAdd core,operator,expressions,date,-,dateDiff core,operator,expressions,date,-,dateFromParts @@ -156,7 +157,10 @@ core,operator,expressions,date,-,week core,operator,expressions,date,-,year core,operator,expressions,misc,-,binarySize core,operator,expressions,misc,-,bsonSize +core,operator,expressions,misc,-,createObjectId core,operator,expressions,misc,-,getField +core,operator,expressions,misc,-,hash +core,operator,expressions,misc,-,hexHash core,operator,expressions,misc,-,rand core,operator,expressions,misc,-,sampleRate core,operator,expressions,misc,-,toHashedIndexKey @@ -208,19 +212,37 @@ core,operator,expressions,trigonometry,-,sinh core,operator,expressions,trigonometry,-,tan core,operator,expressions,trigonometry,-,tanh core,operator,expressions,type,-,convert +core,operator,expressions,type,-,deserializeEJSON core,operator,expressions,type,-,isNumber +core,operator,expressions,type,-,serializeEJSON +core,operator,expressions,type,-,subtype +core,operator,expressions,type,-,toArray core,operator,expressions,type,-,toBool core,operator,expressions,type,-,toDecimal core,operator,expressions,type,-,toDouble core,operator,expressions,type,-,toInt core,operator,expressions,type,-,toLong +core,operator,expressions,type,-,toObject core,operator,expressions,type,-,toObjectId core,operator,expressions,type,-,toUUID core,operator,expressions,type,-,toDate core,operator,expressions,type,-,type core,operator,expressions,variable,-,let +core,operator,expressions,variable,system-variables,cluster_time +core,operator,expressions,variable,system-variables,current +core,operator,expressions,variable,system-variables,descend +core,operator,expressions,variable,system-variables,idx +core,operator,expressions,variable,system-variables,keep +core,operator,expressions,variable,system-variables,now +core,operator,expressions,variable,system-variables,prune +core,operator,expressions,variable,system-variables,remove core,operator,expressions,variable,system-variables,root +core,operator,expressions,variable,system-variables,user_roles +core,operator,expressions,vector-similarity,-,similarityCosine +core,operator,expressions,vector-similarity,-,similarityDotProduct +core,operator,expressions,vector-similarity,-,similarityEuclidean core,operator,projection,-,-,elemMatch +core,operator,projection,-,-,meta core,operator,projection,-,-,positional core,operator,projection,-,-,slice core,operator,query,-,-,text @@ -292,6 +314,8 @@ core,operator,stages,-,-,redact core,operator,stages,-,-,replaceRoot core,operator,stages,-,-,replaceWith core,operator,stages,-,-,sample +core,operator,stages,-,-,score +core,operator,stages,-,-,scoreFusion core,operator,stages,-,-,search core,operator,stages,-,-,searchMeta core,operator,stages,-,-,set @@ -341,14 +365,20 @@ core,operator,window,-,-,derivative core,operator,window,-,-,documentNumber core,operator,window,-,-,expMovingAvg core,operator,window,-,-,first +core,operator,window,-,-,firstN core,operator,window,-,-,integral core,operator,window,-,-,last +core,operator,window,-,-,lastN core,operator,window,-,-,linearFill core,operator,window,-,-,locf core,operator,window,-,-,max core,operator,window,-,-,maxN +core,operator,window,-,-,median +core,operator,window,-,-,mergeObjects core,operator,window,-,-,min +core,operator,window,-,-,minMaxScaler core,operator,window,-,-,minN +core,operator,window,-,-,percentile core,operator,window,-,-,push core,operator,window,-,-,rank core,operator,window,-,-,shift diff --git a/documentdb_tests/compatibility/tests/core/operator/accumulators/concatArrays/test_smoke_accumulator_concatArrays.py b/documentdb_tests/compatibility/tests/core/operator/accumulators/concatArrays/test_smoke_accumulator_concatArrays.py index 8742bf322..203928650 100644 --- a/documentdb_tests/compatibility/tests/core/operator/accumulators/concatArrays/test_smoke_accumulator_concatArrays.py +++ b/documentdb_tests/compatibility/tests/core/operator/accumulators/concatArrays/test_smoke_accumulator_concatArrays.py @@ -9,7 +9,7 @@ from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command -pytestmark = pytest.mark.smoke +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] def test_smoke_accumulator_concatArrays(collection): diff --git a/documentdb_tests/compatibility/tests/core/operator/accumulators/setUnion/test_smoke_accumulator_setUnion.py b/documentdb_tests/compatibility/tests/core/operator/accumulators/setUnion/test_smoke_accumulator_setUnion.py index 25eaa7d05..a5639e07a 100644 --- a/documentdb_tests/compatibility/tests/core/operator/accumulators/setUnion/test_smoke_accumulator_setUnion.py +++ b/documentdb_tests/compatibility/tests/core/operator/accumulators/setUnion/test_smoke_accumulator_setUnion.py @@ -9,7 +9,7 @@ from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command -pytestmark = pytest.mark.smoke +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] def test_smoke_accumulator_setUnion(collection): diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/arithmetic/sigmoid/test_smoke_expression_sigmoid.py b/documentdb_tests/compatibility/tests/core/operator/expressions/arithmetic/sigmoid/test_smoke_expression_sigmoid.py index 6fe68ba49..ee5699d14 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/arithmetic/sigmoid/test_smoke_expression_sigmoid.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/arithmetic/sigmoid/test_smoke_expression_sigmoid.py @@ -9,7 +9,7 @@ from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command -pytestmark = pytest.mark.smoke +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] def test_smoke_expression_sigmoid(collection): diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/test_smoke_currentDate.py b/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/test_smoke_currentDate.py new file mode 100644 index 000000000..5c6edf804 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/date/currentDate/test_smoke_currentDate.py @@ -0,0 +1,24 @@ +"""Smoke test for the $currentDate aggregation expression: the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_currentDate(collection): + """Test the engine accepts $currentDate as an aggregation expression.""" + collection.insert_one({"_id": 1}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": {"$currentDate": {}}}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $currentDate expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/misc/createObjectId/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/createObjectId/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/createObjectId/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/misc/createObjectId/test_smoke_createObjectId.py b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/createObjectId/test_smoke_createObjectId.py new file mode 100644 index 000000000..13989d707 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/createObjectId/test_smoke_createObjectId.py @@ -0,0 +1,24 @@ +"""Smoke test for the $createObjectId expression (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_createObjectId(collection): + """Test the engine accepts the $createObjectId expression.""" + collection.insert_one({"_id": 1}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": {"$createObjectId": {}}}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $createObjectId expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hash/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hash/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hash/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hash/test_smoke_hash.py b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hash/test_smoke_hash.py new file mode 100644 index 000000000..22f0d6514 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hash/test_smoke_hash.py @@ -0,0 +1,31 @@ +"""Smoke test for the $hash expression (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_hash(collection): + """Test the engine accepts the $hash expression.""" + collection.insert_one({"_id": 1, "s": "abc"}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$project": { + "_id": 0, + "result": {"$hash": {"input": "$s", "algorithm": "sha256"}}, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $hash expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hexHash/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hexHash/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hexHash/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hexHash/test_smoke_hexHash.py b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hexHash/test_smoke_hexHash.py new file mode 100644 index 000000000..cbbf281c3 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/misc/hexHash/test_smoke_hexHash.py @@ -0,0 +1,31 @@ +"""Smoke test for the $hexHash expression (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_hexHash(collection): + """Test the engine accepts the $hexHash expression.""" + collection.insert_one({"_id": 1, "s": "abc"}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$project": { + "_id": 0, + "result": {"$hexHash": {"input": "$s", "algorithm": "sha256"}}, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $hexHash expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/test_smoke_deserializeEJSON.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/test_smoke_deserializeEJSON.py new file mode 100644 index 000000000..dc49f0bd5 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/deserializeEJSON/test_smoke_deserializeEJSON.py @@ -0,0 +1,33 @@ +"""Smoke test for the $deserializeEJSON expression (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_deserializeEJSON(collection): + """Test the engine accepts the $deserializeEJSON expression.""" + collection.insert_one({"_id": 1}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$project": { + "_id": 0, + "result": { + "$deserializeEJSON": {"input": {"$literal": {"$numberInt": "1"}}} + }, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $deserializeEJSON expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/test_smoke_serializeEJSON.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/test_smoke_serializeEJSON.py new file mode 100644 index 000000000..e4c4426b5 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/serializeEJSON/test_smoke_serializeEJSON.py @@ -0,0 +1,24 @@ +"""Smoke test for the $serializeEJSON expression (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_serializeEJSON(collection): + """Test the engine accepts the $serializeEJSON expression.""" + collection.insert_one({"_id": 1, "x": 1}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": {"$serializeEJSON": {"input": "$x"}}}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $serializeEJSON expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/test_smoke_subtype.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/test_smoke_subtype.py new file mode 100644 index 000000000..f4676bc68 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/subtype/test_smoke_subtype.py @@ -0,0 +1,25 @@ +"""Smoke test for the $subtype expression (new in 8.3): the engine accepts it.""" + +import pytest +from bson import Binary + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_subtype(collection): + """Test the engine accepts the $subtype expression.""" + collection.insert_one({"_id": 1, "b": Binary(b"\x01\x02", 0)}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": {"$subtype": "$b"}}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $subtype expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/test_smoke_toArray.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/test_smoke_toArray.py new file mode 100644 index 000000000..7a1e23e1a --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toArray/test_smoke_toArray.py @@ -0,0 +1,24 @@ +"""Smoke test for the $toArray expression (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_toArray(collection): + """Test the engine accepts the $toArray expression.""" + collection.insert_one({"_id": 1, "s": "[1, 2]"}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": {"$toArray": "$s"}}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $toArray expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/test_smoke_toObject.py b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/test_smoke_toObject.py new file mode 100644 index 000000000..1f82190b3 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/type/toObject/test_smoke_toObject.py @@ -0,0 +1,24 @@ +"""Smoke test for the $toObject expression (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_toObject(collection): + """Test the engine accepts the $toObject expression.""" + collection.insert_one({"_id": 1, "s": '{"a": 1}'}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": {"$toObject": "$s"}}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $toObject expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/descend/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/descend/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/descend/test_smoke_descend.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/descend/test_smoke_descend.py new file mode 100644 index 000000000..f8f363339 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/descend/test_smoke_descend.py @@ -0,0 +1,20 @@ +"""Smoke test for the $$DESCEND system variable: the engine accepts it in $redact.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_descend(collection): + """Test the engine accepts $$DESCEND as a $redact result.""" + collection.insert_one({"_id": 1, "o": {"a": 1}}) + + result = execute_command( + collection, + {"aggregate": collection.name, "pipeline": [{"$redact": "$$DESCEND"}], "cursor": {}}, + ) + + assertCommandSupported(result, msg="Should support $$DESCEND system variable") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/conftest.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/test_smoke_idx.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/test_smoke_idx.py new file mode 100644 index 000000000..506221b1c --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/idx/test_smoke_idx.py @@ -0,0 +1,26 @@ +"""Smoke test for the $$IDX system variable (new in 8.3): the engine accepts it in $map.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_idx(collection): + """Test the engine accepts $$IDX inside $map.""" + collection.insert_one({"_id": 1, "arr": [10, 20]}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$project": {"_id": 0, "result": {"$map": {"input": "$arr", "in": "$$IDX"}}}} + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $$IDX system variable") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/keep/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/keep/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/keep/test_smoke_keep.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/keep/test_smoke_keep.py new file mode 100644 index 000000000..bc956059b --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/keep/test_smoke_keep.py @@ -0,0 +1,20 @@ +"""Smoke test for the $$KEEP system variable: the engine accepts it in $redact.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_keep(collection): + """Test the engine accepts $$KEEP as a $redact result.""" + collection.insert_one({"_id": 1, "o": {"a": 1}}) + + result = execute_command( + collection, + {"aggregate": collection.name, "pipeline": [{"$redact": "$$KEEP"}], "cursor": {}}, + ) + + assertCommandSupported(result, msg="Should support $$KEEP system variable") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/prune/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/prune/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/prune/test_smoke_prune.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/prune/test_smoke_prune.py new file mode 100644 index 000000000..dc0484484 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/prune/test_smoke_prune.py @@ -0,0 +1,20 @@ +"""Smoke test for the $$PRUNE system variable: the engine accepts it in $redact.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_prune(collection): + """Test the engine accepts $$PRUNE as a $redact result.""" + collection.insert_one({"_id": 1, "o": {"a": 1}}) + + result = execute_command( + collection, + {"aggregate": collection.name, "pipeline": [{"$redact": "$$PRUNE"}], "cursor": {}}, + ) + + assertCommandSupported(result, msg="Should support $$PRUNE system variable") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/user_roles/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/user_roles/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/user_roles/test_smoke_user_roles.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/user_roles/test_smoke_user_roles.py new file mode 100644 index 000000000..7d9c3303d --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/user_roles/test_smoke_user_roles.py @@ -0,0 +1,24 @@ +"""Smoke test for the $$USER_ROLES system variable: the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_user_roles(collection): + """Test the engine accepts $$USER_ROLES in an expression.""" + collection.insert_one({"_id": 1}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": "$$USER_ROLES"}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $$USER_ROLES system variable") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityCosine/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityCosine/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityCosine/test_smoke_similarityCosine.py b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityCosine/test_smoke_similarityCosine.py new file mode 100644 index 000000000..f971f3897 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityCosine/test_smoke_similarityCosine.py @@ -0,0 +1,24 @@ +"""Smoke test for the $similarityCosine expression: the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] + + +def test_smoke_similarityCosine(collection): + """Test the engine accepts the $similarityCosine expression.""" + collection.insert_one({"_id": 1, "a": [1.0, 0.0], "b": [1.0, 1.0]}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$project": {"_id": 0, "result": {"$similarityCosine": ["$a", "$b"]}}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $similarityCosine expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityDotProduct/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityDotProduct/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityDotProduct/test_smoke_similarityDotProduct.py b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityDotProduct/test_smoke_similarityDotProduct.py new file mode 100644 index 000000000..ffbbb9780 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityDotProduct/test_smoke_similarityDotProduct.py @@ -0,0 +1,26 @@ +"""Smoke test for the $similarityDotProduct expression: the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] + + +def test_smoke_similarityDotProduct(collection): + """Test the engine accepts the $similarityDotProduct expression.""" + collection.insert_one({"_id": 1, "a": [1.0, 2.0], "b": [3.0, 4.0]}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$project": {"_id": 0, "result": {"$similarityDotProduct": ["$a", "$b"]}}} + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $similarityDotProduct expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityEuclidean/__init__.py b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityEuclidean/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityEuclidean/test_smoke_similarityEuclidean.py b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityEuclidean/test_smoke_similarityEuclidean.py new file mode 100644 index 000000000..7030c2059 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/vector_similarity/similarityEuclidean/test_smoke_similarityEuclidean.py @@ -0,0 +1,26 @@ +"""Smoke test for the $similarityEuclidean expression: the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] + + +def test_smoke_similarityEuclidean(collection): + """Test the engine accepts the $similarityEuclidean expression.""" + collection.insert_one({"_id": 1, "a": [0.0, 0.0], "b": [3.0, 4.0]}) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$project": {"_id": 0, "result": {"$similarityEuclidean": ["$a", "$b"]}}} + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $similarityEuclidean expression") diff --git a/documentdb_tests/compatibility/tests/core/operator/projection/meta/__init__.py b/documentdb_tests/compatibility/tests/core/operator/projection/meta/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/projection/meta/test_smoke_projection_meta.py b/documentdb_tests/compatibility/tests/core/operator/projection/meta/test_smoke_projection_meta.py new file mode 100644 index 000000000..8bbe10d70 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/projection/meta/test_smoke_projection_meta.py @@ -0,0 +1,25 @@ +"""Smoke test for the $meta projection operator: the engine accepts it in a find projection.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_projection_meta(collection): + """Test the engine accepts {$meta: "textScore"} in a find projection.""" + collection.insert_one({"_id": 1, "t": "hello world"}) + collection.create_index([("t", "text")]) + + result = execute_command( + collection, + { + "find": collection.name, + "filter": {"$text": {"$search": "hello"}}, + "projection": {"score": {"$meta": "textScore"}}, + }, + ) + + assertCommandSupported(result, msg="Should support $meta projection") diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/rankFusion/test_smoke_rankFusion.py b/documentdb_tests/compatibility/tests/core/operator/stages/rankFusion/test_smoke_rankFusion.py index 92fd76c1c..001697d74 100644 --- a/documentdb_tests/compatibility/tests/core/operator/stages/rankFusion/test_smoke_rankFusion.py +++ b/documentdb_tests/compatibility/tests/core/operator/stages/rankFusion/test_smoke_rankFusion.py @@ -9,7 +9,7 @@ from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command -pytestmark = pytest.mark.smoke +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] def test_smoke_rankFusion(collection): diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/score/__init__.py b/documentdb_tests/compatibility/tests/core/operator/stages/score/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/score/test_smoke_score.py b/documentdb_tests/compatibility/tests/core/operator/stages/score/test_smoke_score.py new file mode 100644 index 000000000..9cabbf938 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/stages/score/test_smoke_score.py @@ -0,0 +1,24 @@ +"""Smoke test for the $score stage (new in 8.2): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] + + +def test_smoke_score(collection): + """Test the engine accepts the $score stage.""" + collection.insert_many([{"_id": 1, "x": 1}, {"_id": 2, "x": 3}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [{"$score": {"score": "$x"}}], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $score stage") diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/scoreFusion/__init__.py b/documentdb_tests/compatibility/tests/core/operator/stages/scoreFusion/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/scoreFusion/test_smoke_scoreFusion.py b/documentdb_tests/compatibility/tests/core/operator/stages/scoreFusion/test_smoke_scoreFusion.py new file mode 100644 index 000000000..c7dfcf764 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/stages/scoreFusion/test_smoke_scoreFusion.py @@ -0,0 +1,33 @@ +"""Smoke test for the $scoreFusion stage (GA in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] + + +def test_smoke_scoreFusion(collection): + """Test the engine accepts the $scoreFusion stage.""" + collection.insert_many([{"_id": 1, "x": 1}, {"_id": 2, "x": 3}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$scoreFusion": { + "input": { + "pipelines": {"p1": [{"$score": {"score": "$x"}}]}, + "normalization": "none", + } + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $scoreFusion stage") diff --git a/documentdb_tests/compatibility/tests/core/operator/window/firstN/test_smoke_window_firstN.py b/documentdb_tests/compatibility/tests/core/operator/window/firstN/test_smoke_window_firstN.py new file mode 100644 index 000000000..45d864336 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/window/firstN/test_smoke_window_firstN.py @@ -0,0 +1,36 @@ +"""Smoke test for the $firstN window operator: the engine accepts it in $setWindowFields.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_window_firstN(collection): + """Test the engine accepts $firstN as a window operator.""" + collection.insert_many([{"_id": 1, "x": 1}, {"_id": 2, "x": 3}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$setWindowFields": { + "sortBy": {"_id": 1}, + "output": { + "result": { + "$firstN": {"input": "$x", "n": 2}, + "window": {"documents": ["unbounded", "current"]}, + } + }, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $firstN window operator") diff --git a/documentdb_tests/compatibility/tests/core/operator/window/lastN/test_smoke_window_lastN.py b/documentdb_tests/compatibility/tests/core/operator/window/lastN/test_smoke_window_lastN.py new file mode 100644 index 000000000..3a34291dd --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/window/lastN/test_smoke_window_lastN.py @@ -0,0 +1,36 @@ +"""Smoke test for the $lastN window operator: the engine accepts it in $setWindowFields.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_window_lastN(collection): + """Test the engine accepts $lastN as a window operator.""" + collection.insert_many([{"_id": 1, "x": 1}, {"_id": 2, "x": 3}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$setWindowFields": { + "sortBy": {"_id": 1}, + "output": { + "result": { + "$lastN": {"input": "$x", "n": 2}, + "window": {"documents": ["unbounded", "current"]}, + } + }, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $lastN window operator") diff --git a/documentdb_tests/compatibility/tests/core/operator/window/median/test_smoke_window_median.py b/documentdb_tests/compatibility/tests/core/operator/window/median/test_smoke_window_median.py new file mode 100644 index 000000000..efd18e77f --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/window/median/test_smoke_window_median.py @@ -0,0 +1,36 @@ +"""Smoke test for the $median window operator: the engine accepts it in $setWindowFields.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_window_median(collection): + """Test the engine accepts $median as a window operator.""" + collection.insert_many([{"_id": 1, "x": 1}, {"_id": 2, "x": 3}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$setWindowFields": { + "sortBy": {"_id": 1}, + "output": { + "result": { + "$median": {"input": "$x", "method": "approximate"}, + "window": {"documents": ["unbounded", "current"]}, + } + }, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $median window operator") diff --git a/documentdb_tests/compatibility/tests/core/operator/window/mergeObjects/conftest.py b/documentdb_tests/compatibility/tests/core/operator/window/mergeObjects/conftest.py new file mode 100644 index 000000000..76c9a7858 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/window/mergeObjects/conftest.py @@ -0,0 +1,5 @@ +"""Every test in this folder covers behavior added in spec 8.3.""" + +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") diff --git a/documentdb_tests/compatibility/tests/core/operator/window/mergeObjects/test_smoke_window_mergeObjects.py b/documentdb_tests/compatibility/tests/core/operator/window/mergeObjects/test_smoke_window_mergeObjects.py new file mode 100644 index 000000000..c5f7786a8 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/window/mergeObjects/test_smoke_window_mergeObjects.py @@ -0,0 +1,36 @@ +"""Smoke test for $mergeObjects as a window operator (new in 8.3): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_window_mergeObjects(collection): + """Test the engine accepts $mergeObjects as a window operator.""" + collection.insert_many([{"_id": 1, "o": {"a": 1}}, {"_id": 2, "o": {"b": 2}}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$setWindowFields": { + "sortBy": {"_id": 1}, + "output": { + "result": { + "$mergeObjects": "$o", + "window": {"documents": ["unbounded", "current"]}, + } + }, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $mergeObjects window operator") diff --git a/documentdb_tests/compatibility/tests/core/operator/window/minMaxScaler/test_smoke_window_minMaxScaler.py b/documentdb_tests/compatibility/tests/core/operator/window/minMaxScaler/test_smoke_window_minMaxScaler.py new file mode 100644 index 000000000..dbcb5d8c3 --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/window/minMaxScaler/test_smoke_window_minMaxScaler.py @@ -0,0 +1,31 @@ +"""Smoke test for the $minMaxScaler window operator (new in 8.2): the engine accepts it.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] + + +def test_smoke_window_minMaxScaler(collection): + """Test the engine accepts $minMaxScaler as a window operator.""" + collection.insert_many([{"_id": 1, "x": 1}, {"_id": 2, "x": 3}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$setWindowFields": { + "sortBy": {"_id": 1}, + "output": {"result": {"$minMaxScaler": {"input": "$x"}}}, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $minMaxScaler window operator") diff --git a/documentdb_tests/compatibility/tests/core/operator/window/percentile/test_smoke_window_percentile.py b/documentdb_tests/compatibility/tests/core/operator/window/percentile/test_smoke_window_percentile.py new file mode 100644 index 000000000..14871e97c --- /dev/null +++ b/documentdb_tests/compatibility/tests/core/operator/window/percentile/test_smoke_window_percentile.py @@ -0,0 +1,40 @@ +"""Smoke test for the $percentile window operator: the engine accepts it in $setWindowFields.""" + +import pytest + +from documentdb_tests.framework.assertions import assertCommandSupported +from documentdb_tests.framework.executor import execute_command + +pytestmark = pytest.mark.smoke + + +def test_smoke_window_percentile(collection): + """Test the engine accepts $percentile as a window operator.""" + collection.insert_many([{"_id": 1, "x": 1}, {"_id": 2, "x": 3}]) + + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + { + "$setWindowFields": { + "sortBy": {"_id": 1}, + "output": { + "result": { + "$percentile": { + "input": "$x", + "p": [0.5], + "method": "approximate", + }, + "window": {"documents": ["unbounded", "current"]}, + } + }, + } + } + ], + "cursor": {}, + }, + ) + + assertCommandSupported(result, msg="Should support $percentile window operator") diff --git a/documentdb_tests/compatibility/tests/system/administration/commands/setFeatureCompatibilityVersion/test_smoke_setFeatureCompatibilityVersion.py b/documentdb_tests/compatibility/tests/system/administration/commands/setFeatureCompatibilityVersion/test_smoke_setFeatureCompatibilityVersion.py index 0c381df45..6613bd2f7 100644 --- a/documentdb_tests/compatibility/tests/system/administration/commands/setFeatureCompatibilityVersion/test_smoke_setFeatureCompatibilityVersion.py +++ b/documentdb_tests/compatibility/tests/system/administration/commands/setFeatureCompatibilityVersion/test_smoke_setFeatureCompatibilityVersion.py @@ -9,23 +9,21 @@ from documentdb_tests.framework.assertions import assertSuccessPartial from documentdb_tests.framework.executor import execute_admin_command -from .utils.setFeatureCompatibilityVersion_common import get_fcv - pytestmark = [pytest.mark.smoke, pytest.mark.no_parallel] def test_smoke_setFeatureCompatibilityVersion(collection): - """Test basic setFeatureCompatibilityVersion behavior.""" - original_fcv = get_fcv(collection) - new_fcv = "8.0" if original_fcv != "8.0" else "8.2" + """Test the engine accepts setFeatureCompatibilityVersion set to its own current version.""" result = execute_admin_command( - collection, {"setFeatureCompatibilityVersion": new_fcv, "confirm": True} + collection, {"getParameter": 1, "featureCompatibilityVersion": 1} ) + if not isinstance(result, Exception): + current_fcv = result["featureCompatibilityVersion"]["version"] + result = execute_admin_command( + collection, {"setFeatureCompatibilityVersion": current_fcv, "confirm": True} + ) assertSuccessPartial( result, {"ok": 1.0}, - msg="setFeatureCompatibilityVersion should succeed with a valid version change", - ) - execute_admin_command( - collection, {"setFeatureCompatibilityVersion": original_fcv, "confirm": True} + msg="setFeatureCompatibilityVersion should accept the server's current version", ) diff --git a/documentdb_tests/conftest.py b/documentdb_tests/conftest.py index 93efd0f0f..9ecd2cc6d 100644 --- a/documentdb_tests/conftest.py +++ b/documentdb_tests/conftest.py @@ -34,11 +34,16 @@ validate_marker_reasons, ) from documentdb_tests.framework.preconditions import ( # noqa: E402 + DEFAULT_SPEC_VERSION, REQUIRES_MARKER, + SPEC_VERSIONS, + check_spec_gates_on_smoke_only, detect_capabilities, known_engines, marker_spec, + merged_requirements, unmet_requirements, + unmet_spec, ) from documentdb_tests.framework.test_format_validator import validate_test_format # noqa: E402 from documentdb_tests.framework.test_structure_validator import ( # noqa: E402 @@ -69,6 +74,15 @@ def pytest_addoption(parser): "are skipped by default because they kill the server; enable this only " "in an isolated job that can tolerate (and expects) a server crash.", ) + parser.addoption( + "--spec-version", + action="store", + default=DEFAULT_SPEC_VERSION, + choices=SPEC_VERSIONS, + help="Reference spec version that decides which smoke tests are in " + "scope. Other tests always run and expect the pinned reference " + f"version's answer. Default: {DEFAULT_SPEC_VERSION}.", + ) def pytest_configure(config): @@ -125,6 +139,11 @@ def pytest_configure(config): # not be duplicated in the pytest configuration file. config.addinivalue_line("markers", marker_spec()) + # Only the process that writes the JSON report (not an xdist worker) needs + # the run header. + if not hasattr(config, "workerinput"): + config.pluginmanager.register(_RunHeaderPlugin(config), "run-header") + def pytest_generate_tests(metafunc): """Parametrize tests over the resolved test targets. @@ -209,6 +228,58 @@ def pytest_json_runtest_metadata(item, call): return {"xfail_reason": reason} if reason else {} +def _server_version(connection_string: str) -> str | None: + """Return a target's buildInfo version, or None when it cannot be read.""" + from pymongo import MongoClient + + try: + client: MongoClient = MongoClient(connection_string, serverSelectionTimeoutMS=5000) + except Exception: + return None + try: + return client.admin.command("buildInfo").get("version") + except Exception: + return None + finally: + client.close() + + +def _run_header(config) -> dict: + """Describe what a run measured: the spec version and each target's version. + + Target versions are not probed when only collecting, which must work + without a live server. + """ + collect_only = config.option.collectonly + return { + "spec_version": config.getoption("--spec-version"), + "targets": [ + { + "name": target.name, + "engine": target.engine, + "version": None if collect_only else _server_version(target.connection_string), + } + for target in getattr(config, "test_targets", []) + ], + } + + +class _RunHeaderPlugin: + """Record the run's spec version and target versions in the JSON report. + + A run is scoped by ``--spec-version`` rather than by the target, so the + report states both to make a result readable on its own. Registered as a + plugin because the report hook is not given the config. + """ + + def __init__(self, config): + self._config = config + + @pytest.hookimpl(optionalhook=True) + def pytest_json_modifyreport(self, json_report): + json_report["run"] = _run_header(self._config) + + @pytest.fixture(scope="session") def engine_client(request): """ @@ -435,22 +506,32 @@ def pytest_collection_modifyitems(session, config, items): capabilities do not match what the test requires, so they do not run against a target they do not apply to (rather than appearing as skips). A target's capabilities are determined by its engine, topology, and connection source, - resolved per target at runtime (see ``framework.preconditions``). + resolved per target at runtime (see ``framework.preconditions``). Smoke + tests whose spec gate excludes the run's ``--spec-version`` are deselected + the same way; a spec gate on any other test is a usage error. """ - # Deselect a capability-gated test when its target's capabilities do not - # match its requires(...) marker. Each item is parametrized over a target; - # probe each distinct target once. + # Deselect a gated test when the run's spec version is out of its scope, or + # when its target's capabilities do not match its requires(...) markers. + # Markers from the folder, module, class and test all apply. Each item is + # parametrized over a target; probe each distinct target once. + spec_version = config.getoption("--spec-version") + check_spec_gates_on_smoke_only(items) capabilities_by_target: dict[str, frozenset[str]] = {} kept: list = [] requires_deselected: list = [] - # nodeid -> the requirements the target did not meet, for the report sidecar. + # nodeid -> the requirements the run did not meet, for the report sidecar. deselected_reasons: dict[str, dict] = {} for item in items: - marker = item.get_closest_marker(REQUIRES_MARKER) - if marker is None or not marker.kwargs: + required = merged_requirements(item.iter_markers(REQUIRES_MARKER)) + if not required: kept.append(item) continue + out_of_spec = unmet_spec(required, spec_version) + if out_of_spec: + requires_deselected.append(item) + deselected_reasons[item.nodeid] = out_of_spec + continue target = _item_target(item) if target is None: kept.append(item) @@ -459,9 +540,10 @@ def pytest_collection_modifyitems(session, config, items): if capabilities is None: capabilities = detect_capabilities(target.engine, target.connection_string) capabilities_by_target[target.connection_string] = capabilities - if unmet_requirements(marker.kwargs, capabilities): + unmet = unmet_requirements(required, capabilities) + if unmet: requires_deselected.append(item) - deselected_reasons[item.nodeid] = unmet_requirements(marker.kwargs, capabilities) + deselected_reasons[item.nodeid] = unmet else: kept.append(item) if requires_deselected: @@ -555,7 +637,8 @@ def pytest_collection_modifyitems(session, config, items): "\nMarkers that skip or reclassify a test (skip/skipif/xfail/" "engine_xfail/engine_xcrash) must carry a reason=, and runtime " "pytest.skip()/fail()/xfail() calls must pass a message, so the " - "outcome is never unexplained. See docs/testing/TEST_FORMAT.md " + "outcome is never unexplained. A requires(spec_since=/spec_until=) " + "gate must name a known spec version. See docs/testing/TEST_FORMAT.md " "for rules.\n", file=sys.stderr, ) @@ -667,6 +750,7 @@ def pytest_sessionfinish(session, exitstatus): if override_conn: cmd.extend(["--connection-string", override_conn]) cmd.extend(["--engine-name", config.getoption("--engine-name")]) + cmd.extend(["--spec-version", config.getoption("--spec-version")]) # Detect Phase 1 report paths and set up Phase 2 temp report files phase1_json = getattr(config.option, "json_report_file", None) diff --git a/documentdb_tests/framework/engine_registry.py b/documentdb_tests/framework/engine_registry.py index 1e2bf1664..1c00baee3 100644 --- a/documentdb_tests/framework/engine_registry.py +++ b/documentdb_tests/framework/engine_registry.py @@ -51,8 +51,9 @@ def _host_port(service: dict) -> str | None: ports = service.get("ports") or [] if not ports: return None - # Entries look like "27017:27017"; the host port is the left side. - return str(ports[0]).split(":")[0] + # Entries look like "127.0.0.1:27017:27017" or "27017:27017"; the host port + # is the second-to-last field. + return str(ports[0]).split(":")[-2] def load_targets(compose_path: Path = COMPOSE_PATH) -> list[Target]: diff --git a/documentdb_tests/framework/marker_reason_validator.py b/documentdb_tests/framework/marker_reason_validator.py index 7f86233c8..0e3e10c33 100644 --- a/documentdb_tests/framework/marker_reason_validator.py +++ b/documentdb_tests/framework/marker_reason_validator.py @@ -11,12 +11,18 @@ ``engine_xfail`` / ``engine_xcrash`` variants, via their ``reason=``. - **Runtime calls** — ``pytest.skip(...)`` / ``fail(...)`` / ``xfail(...)``, via their positional message or ``reason=`` / ``msg=``. + +It also checks that a ``requires(spec_since=...)`` / ``requires(spec_until=...)`` +spec gate names a known spec version, since a bad version would scope the test +out of every run. """ from __future__ import annotations import ast +from documentdb_tests.framework.preconditions import REQUIRES_MARKER, SPEC_KEYS, SPEC_VERSIONS + # Markers that must justify why they suppress or reclassify an outcome. MARKERS_REQUIRING_REASON = frozenset({"skip", "skipif", "xfail", "engine_xfail", "engine_xcrash"}) @@ -92,6 +98,21 @@ def _runtime_call_has_message(call: ast.Call) -> bool: return False +def _spec_gate_errors(call: ast.Call) -> list[str]: + """A ``requires`` spec gate must name a known spec version as a literal.""" + errors = [] + for keyword in call.keywords: + if keyword.arg not in SPEC_KEYS: + continue + value = keyword.value + if not (isinstance(value, ast.Constant) and value.value in SPEC_VERSIONS): + errors.append( + f" Line {call.lineno}: requires({keyword.arg}=...) must be one of " + f"{', '.join(repr(v) for v in SPEC_VERSIONS)}." + ) + return errors + + def validate_marker_reasons(file_path: str) -> list[str]: """ Validate that outcome-suppressing markers carry a reason. @@ -125,6 +146,9 @@ def validate_marker_reasons(file_path: str) -> list[str]: f" Line {node.lineno}: pytest.{runtime_name}() must be called with " f"a non-empty message explaining why." ) + # Spec gates: requires(spec_since=...) / requires(spec_until=...). + if name == REQUIRES_MARKER: + errors.extend(_spec_gate_errors(node)) # Bare decorator form: @pytest.mark.skip / @pytest.mark.xfail (no reason at all). for node in ast.walk(tree): diff --git a/documentdb_tests/framework/preconditions.py b/documentdb_tests/framework/preconditions.py index 4462b3c89..c6afc3032 100644 --- a/documentdb_tests/framework/preconditions.py +++ b/documentdb_tests/framework/preconditions.py @@ -26,10 +26,28 @@ defining its own). Adding an engine or a new topology (e.g. a search-backed deployment) is a new row in ``_CAPABILITIES_BY_PROFILE`` plus teaching ``_detect_topology`` to recognize it. + +Expected results are pinned to one reference version (MongoDB 8.2.4, the CI +target). The same marker also scopes a smoke test to versions of the +reference spec. A run picks one spec version (``--spec-version``), which +decides which smoke tests are in scope; it is independent of the target:: + + @pytest.mark.requires(spec_since="8.3") # feature added in spec 8.3 + @pytest.mark.requires(spec_until="8.2") # feature a later spec removed + +Only smoke tests (``pytest.mark.smoke``) may carry a spec gate; a gate on any +other test is a collection error (``check_spec_gates_on_smoke_only``), and +every other test runs under every spec version. A smoke test with no spec gate +belongs to the oldest spec and runs under every spec version. A folder of +smoke tests is gated from its ``conftest.py`` with ``spec_gate_folder``. """ from __future__ import annotations +from pathlib import Path +from typing import Any, Callable, Iterable + +import pytest from pymongo import MongoClient # The capabilities the harness knows about, each mapped to a human-readable @@ -140,6 +158,18 @@ # Every known capability name, for validation of requires(...) kwargs. CAPABILITIES = frozenset(_CAPABILITY_DESCRIPTIONS) +# The reference spec versions a run can be scoped to, oldest first. A test with +# no spec gate belongs to the oldest one. 8.1 is not a spec version (it was a +# rapid release with no published server image), so behavior added in 8.1 is +# gated with spec_since="8.2". +SPEC_VERSIONS: tuple[str, ...] = ("8.0", "8.2", "8.3") +DEFAULT_SPEC_VERSION = "8.2" + +# requires(...) keys that gate on the run's spec version rather than on a +# target capability. spec_since: in scope from this version on. spec_until: in +# scope up to and including this version. +SPEC_KEYS = frozenset({"spec_since", "spec_until"}) + def _check_consistency() -> None: """Fail at import if the descriptions and the profile table diverge. @@ -205,7 +235,8 @@ def marker_spec() -> str: """Return the pytest marker definition line for the ``requires`` marker.""" return ( "requires(**capabilities): gate a test on capabilities the target must have " - "(name=True) or lack (name=False); known names: " + ", ".join(sorted(CAPABILITIES)) + "(name=True) or lack (name=False), or on the run's spec version " + "(spec_since=/spec_until=); known names: " + ", ".join(sorted(CAPABILITIES)) ) @@ -253,10 +284,114 @@ def unmet_requirements(required: dict[str, bool], capabilities: frozenset[str]) (True) or absent (False). A requirement is unmet when the capability's presence does not match. Unknown capability names raise, so a typo in a ``requires(...)`` marker fails loudly rather than silently never gating. + Spec-version keys are not capabilities and are ignored here (see + ``unmet_spec``). """ - unknown = set(required) - CAPABILITIES + unknown = set(required) - CAPABILITIES - SPEC_KEYS if unknown: raise RuntimeError(f"requires(...) names unknown capabilities: {sorted(unknown)}") return { - name: expected for name, expected in required.items() if (name in capabilities) != expected + name: expected + for name, expected in required.items() + if name not in SPEC_KEYS and (name in capabilities) != expected } + + +def _check_spec_gate(gate: dict[str, Any]) -> None: + """Raise if a spec gate names an unknown key or version.""" + unknown = set(gate) - SPEC_KEYS + if unknown: + raise RuntimeError(f"unknown spec gate keys: {sorted(unknown)}") + for key, version in gate.items(): + if version not in SPEC_VERSIONS: + raise RuntimeError( + f"requires({key}={version!r}) names an unknown spec version; " + f"known versions: {', '.join(SPEC_VERSIONS)}" + ) + + +def unmet_spec(required: dict[str, Any], spec_version: str) -> dict[str, str]: + """Return the spec gates in ``required`` that put a test out of scope. + + A test is out of scope when the run's spec version is older than its + ``spec_since`` or newer than its ``spec_until``. An unknown version raises, + so a typo fails loudly rather than silently never running the test. + """ + gate = {key: value for key, value in required.items() if key in SPEC_KEYS} + _check_spec_gate(gate) + run = SPEC_VERSIONS.index(spec_version) + unmet = {} + since = gate.get("spec_since") + if since is not None and run < SPEC_VERSIONS.index(since): + unmet["spec_since"] = since + until = gate.get("spec_until") + if until is not None and run > SPEC_VERSIONS.index(until): + unmet["spec_until"] = until + return unmet + + +SMOKE_MARKER = "smoke" + + +def check_spec_gates_on_smoke_only(items: Iterable[Any]) -> None: + """Raise a usage error if a test that is not a smoke test has a spec gate. + + Only smoke tests are scoped by ``--spec-version``. Every other test always + runs and expects the pinned reference version's answer. + """ + bad = [ + item.nodeid + for item in items + if not item.get_closest_marker(SMOKE_MARKER) + and SPEC_KEYS & set(merged_requirements(item.iter_markers(REQUIRES_MARKER))) + ] + if bad: + shown = "\n ".join(bad[:20]) + ("\n ..." if len(bad) > 20 else "") + raise pytest.UsageError( + f"{len(bad)} test(s) have a spec_since/spec_until gate but are not smoke " + "tests. Only smoke tests (pytest.mark.smoke) can be scoped by " + f"--spec-version:\n {shown}" + ) + + +def merged_requirements(markers: Iterable[Any]) -> dict[str, Any]: + """Combine every ``requires`` marker on a test into one mapping. + + Markers are given closest first (as ``item.iter_markers`` yields them), so + a folder or module gate and a test's own capability gate both apply, and on + a key set at two levels the closest one wins. + """ + merged: dict[str, Any] = {} + for marker in markers: + for key, value in marker.kwargs.items(): + merged.setdefault(key, value) + return merged + + +def spec_gate_folder(conftest_file: str, **gate: str) -> Callable[..., None]: + """Return a collection hook that spec-gates every test under a folder. + + Use it from the folder's ``conftest.py``:: + + pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") + + The gate is added to each test module under the folder, after the module's + own marks, so a file or test gate still wins on the same key and capability + gates combine with it. + """ + _check_spec_gate(gate) + folder = Path(conftest_file).resolve().parent + mark = getattr(pytest.mark, REQUIRES_MARKER)(**gate) + + @pytest.hookimpl(tryfirst=True) + def pytest_collection_modifyitems(items: list) -> None: + checked: set[int] = set() + for item in items: + module = item.getparent(pytest.Module) + if module is None or id(module) in checked: + continue + checked.add(id(module)) + if folder in Path(module.path).resolve().parents: + module.add_marker(mark) + + return pytest_collection_modifyitems diff --git a/documentdb_tests/framework/test_engine_registry.py b/documentdb_tests/framework/test_engine_registry.py new file mode 100644 index 000000000..74c3a9561 --- /dev/null +++ b/documentdb_tests/framework/test_engine_registry.py @@ -0,0 +1,24 @@ +"""Unit tests for reading test targets from the compose file (no database needed).""" + +import pytest + +from documentdb_tests.framework.engine_registry import _host_port, load_targets + + +@pytest.mark.unit +class TestHostPort: + def test_loopback_mapping(self): + assert _host_port({"ports": ["127.0.0.1:27017:27017"]}) == "27017" + + def test_bare_mapping(self): + assert _host_port({"ports": ["27018:27017"]}) == "27018" + + def test_no_ports(self): + assert _host_port({}) is None + + +@pytest.mark.unit +def test_compose_targets_connect_to_their_host_ports(): + by_name = {t.name: t.connection_string for t in load_targets()} + assert by_name["mongo-standalone"] == "mongodb://localhost:27017" + assert by_name["mongo-replset"] == "mongodb://localhost:27018/?directConnection=true" diff --git a/documentdb_tests/framework/test_marker_reason_validator.py b/documentdb_tests/framework/test_marker_reason_validator.py index 6daff4f60..65c69a90b 100644 --- a/documentdb_tests/framework/test_marker_reason_validator.py +++ b/documentdb_tests/framework/test_marker_reason_validator.py @@ -109,3 +109,23 @@ def test_unrelated_fail_method_is_not_flagged(self, tmp_path): def test_unparseable_file_is_skipped(self, tmp_path): assert validate_marker_reasons(_write(tmp_path, "def (:\n")) == [] + + +@pytest.mark.unit +class TestSpecGateValidation: + def test_known_spec_version_is_clean(self, tmp_path): + src = 'pytestmark = pytest.mark.requires(spec_since="8.3")\n' + assert validate_marker_reasons(_write(tmp_path, src)) == [] + + def test_unknown_spec_version_is_flagged(self, tmp_path): + src = '@pytest.mark.requires(spec_until="8.1")\ndef test_a():\n pass\n' + errors = validate_marker_reasons(_write(tmp_path, src)) + assert len(errors) == 1 and "spec_until" in errors[0] + + def test_non_literal_spec_version_is_flagged(self, tmp_path): + src = "pytestmark = pytest.mark.requires(spec_since=VERSION)\n" + assert len(validate_marker_reasons(_write(tmp_path, src))) == 1 + + def test_capability_gate_is_not_checked_as_a_version(self, tmp_path): + src = "pytestmark = pytest.mark.requires(change_streams=True)\n" + assert validate_marker_reasons(_write(tmp_path, src)) == [] diff --git a/documentdb_tests/framework/test_spec_version.py b/documentdb_tests/framework/test_spec_version.py new file mode 100644 index 000000000..c4554ec06 --- /dev/null +++ b/documentdb_tests/framework/test_spec_version.py @@ -0,0 +1,255 @@ +"""Unit tests for spec-version gating with the requires marker (no database needed).""" + +import json +import textwrap +from pathlib import Path + +import pytest + +from documentdb_tests.framework.preconditions import ( + merged_requirements, + spec_gate_folder, + unmet_requirements, + unmet_spec, +) + +pytest_plugins = ["pytester"] + + +@pytest.mark.unit +class TestUnmetSpec: + def test_ungated_test_is_in_every_spec(self): + assert unmet_spec({}, "8.0") == {} + assert unmet_spec({}, "8.2") == {} + assert unmet_spec({}, "8.3") == {} + + def test_spec_since_is_out_of_an_older_spec(self): + assert unmet_spec({"spec_since": "8.3"}, "8.2") == {"spec_since": "8.3"} + + def test_spec_since_is_in_its_own_spec(self): + assert unmet_spec({"spec_since": "8.3"}, "8.3") == {} + + def test_spec_until_is_out_of_a_newer_spec(self): + assert unmet_spec({"spec_until": "8.2"}, "8.3") == {"spec_until": "8.2"} + + def test_spec_until_is_in_its_own_spec(self): + assert unmet_spec({"spec_until": "8.2"}, "8.2") == {} + + def test_8_0_gates_skip_the_missing_8_1(self): + assert unmet_spec({"spec_since": "8.2"}, "8.0") == {"spec_since": "8.2"} + assert unmet_spec({"spec_until": "8.0"}, "8.2") == {"spec_until": "8.0"} + + def test_8_1_is_not_a_spec_version(self): + with pytest.raises(RuntimeError, match="unknown spec version"): + unmet_spec({"spec_since": "8.1"}, "8.2") + + def test_capability_keys_are_ignored(self): + assert unmet_spec({"change_streams": True}, "8.2") == {} + + def test_unknown_version_raises(self): + with pytest.raises(RuntimeError, match="unknown spec version"): + unmet_spec({"spec_since": "8.4"}, "8.3") + + +@pytest.mark.unit +class TestUnmetRequirementsIgnoresSpecKeys: + def test_spec_keys_are_not_unknown_capabilities(self): + required = {"spec_since": "8.3", "change_streams": True} + assert unmet_requirements(required, frozenset()) == {"change_streams": True} + + +class _Marker: + def __init__(self, **kwargs): + self.kwargs = kwargs + + +@pytest.mark.unit +class TestMergedRequirements: + def test_levels_combine(self): + merged = merged_requirements([_Marker(change_streams=True), _Marker(spec_since="8.3")]) + assert merged == {"change_streams": True, "spec_since": "8.3"} + + def test_closest_wins_on_the_same_key(self): + merged = merged_requirements([_Marker(spec_since="8.3"), _Marker(spec_since="8.2")]) + assert merged == {"spec_since": "8.3"} + + +@pytest.mark.unit +class TestSpecGateFolder: + def test_unknown_version_raises_at_import(self): + with pytest.raises(RuntimeError, match="unknown spec version"): + spec_gate_folder(__file__, spec_since="9.0") + + def test_unknown_key_raises_at_import(self): + with pytest.raises(RuntimeError, match="unknown spec gate keys"): + spec_gate_folder(__file__, since="8.3") + + +# A test tree run in a child pytest session, wired to the real collection hooks. +# Capability detection is stubbed so no server is needed: the target has no +# capabilities. +_ROOT_CONFTEST = """ +import documentdb_tests.conftest as root + +root.detect_capabilities = lambda engine, connection_string: frozenset() + +pytest_addoption = root.pytest_addoption +pytest_configure = root.pytest_configure +pytest_generate_tests = root.pytest_generate_tests +pytest_collection_modifyitems = root.pytest_collection_modifyitems +""" + +_FOLDER_CONFTEST = """ +from documentdb_tests.framework.preconditions import spec_gate_folder + +pytest_collection_modifyitems = spec_gate_folder(__file__, spec_since="8.3") +""" + +_FILES = { + "conftest.py": _ROOT_CONFTEST, + "test_ungated.py": """ + def test_ungated(engine_client): + pass + """, + "test_smoke_ungated.py": """ + import pytest + + pytestmark = pytest.mark.smoke + + def test_smoke_ungated(engine_client): + pass + """, + "test_file_gated.py": """ + import pytest + + pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.3")] + + def test_file_gated(engine_client): + pass + """, + "test_until.py": """ + import pytest + + @pytest.mark.smoke + @pytest.mark.requires(spec_until="8.2") + def test_until(engine_client): + pass + """, + "test_smoke_new_in_8_2.py": """ + import pytest + + pytestmark = [pytest.mark.smoke, pytest.mark.requires(spec_since="8.2")] + + def test_new_in_8_2(engine_client): + pass + """, + "new_op/conftest.py": _FOLDER_CONFTEST, + "new_op/test_folder_gated.py": """ + import pytest + + pytestmark = pytest.mark.smoke + + def test_folder_gated(engine_client): + pass + """, + "new_op/test_folder_and_capability.py": """ + import pytest + + @pytest.mark.smoke + @pytest.mark.requires(change_streams=True) + def test_folder_and_capability(engine_client): + pass + """, +} + + +@pytest.fixture +def run_tree(pytester, monkeypatch): + """Write the test tree and return a runner for one spec version.""" + monkeypatch.setenv("PYTHONPATH", str(Path(__file__).resolve().parents[2])) + for name, source in _FILES.items(): + path = pytester.path / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(source)) + pytester.makeini("[pytest]\nmarkers =\n smoke: smoke\n") + + def _run(*spec_args): + report = pytester.path / "report.json" + result = pytester.runpytest_subprocess( + "--collect-only", + "-q", + "--connection-string=mongodb://127.0.0.1:1", + "--engine-name=mongodb", + "--json-report", + f"--json-report-file={report}", + *spec_args, + ) + sidecar = json.loads((pytester.path / "report.json.deselected.json").read_text()) + header = json.loads(report.read_text())["run"] + collected = {line.split("::")[1].split("[")[0] for line in result.outlines if "::" in line} + reasons = {nodeid.split("::")[1].split("[")[0]: why for nodeid, why in sidecar.items()} + return collected, reasons, header + + return _run + + +@pytest.mark.unit +class TestSpecGatingInASession: + def test_default_spec_is_8_2(self, run_tree): + collected, reasons, header = run_tree() + assert header["spec_version"] == "8.2" + assert collected == {"test_ungated", "test_smoke_ungated", "test_until", "test_new_in_8_2"} + assert reasons == { + "test_file_gated": {"spec_since": "8.3"}, + "test_folder_gated": {"spec_since": "8.3"}, + "test_folder_and_capability": {"spec_since": "8.3"}, + } + + def test_spec_8_3_runs_newer_tests_and_ungated_ones(self, run_tree): + collected, reasons, header = run_tree("--spec-version=8.3") + assert header["spec_version"] == "8.3" + assert header["targets"] == [{"name": "mongodb", "engine": "mongodb", "version": None}] + assert collected == { + "test_ungated", + "test_smoke_ungated", + "test_new_in_8_2", + "test_file_gated", + "test_folder_gated", + } + assert reasons == { + "test_until": {"spec_until": "8.2"}, + "test_folder_and_capability": {"change_streams": True}, + } + + def test_spec_8_0_drops_newer_smoke_tests_only(self, run_tree): + collected, reasons, header = run_tree("--spec-version=8.0") + assert header["spec_version"] == "8.0" + assert collected == {"test_ungated", "test_smoke_ungated", "test_until"} + assert reasons == { + "test_new_in_8_2": {"spec_since": "8.2"}, + "test_file_gated": {"spec_since": "8.3"}, + "test_folder_gated": {"spec_since": "8.3"}, + "test_folder_and_capability": {"spec_since": "8.3"}, + } + + def test_spec_gate_on_a_non_smoke_test_is_a_usage_error(self, pytester, run_tree): + pytester.makepyfile( + test_not_smoke=( + "import pytest\n\n" + '@pytest.mark.requires(spec_since="8.2")\n' + "def test_not_smoke(engine_client):\n" + " pass\n" + ) + ) + result = pytester.runpytest_subprocess( + "--collect-only", + "--connection-string=mongodb://127.0.0.1:1", + "--engine-name=mongodb", + ) + assert result.ret == pytest.ExitCode.USAGE_ERROR + result.stderr.fnmatch_lines(["*not smoke tests*", "*test_not_smoke*"]) + + def test_unknown_spec_version_is_a_usage_error(self, pytester, run_tree): + result = pytester.runpytest_subprocess("--collect-only", "--spec-version=9.9") + assert result.ret == pytest.ExitCode.USAGE_ERROR + result.stderr.fnmatch_lines(["*--spec-version*invalid choice*"])