Skip to content

Commit 21d3f58

Browse files
authored
Merge branch 'master' into PYTHON-3636
2 parents 99a5c8a + 894d5e1 commit 21d3f58

31 files changed

+1643
-734
lines changed

.evergreen/run-tests.sh

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,6 @@ else
2424
exit 1
2525
fi
2626

27-
# Source the local secrets export file if available.
28-
if [ -f "./secrets-export.sh" ]; then
29-
echo "Sourcing local secrets file"
30-
. "./secrets-export.sh"
31-
fi
32-
3327
# List the packages.
3428
uv sync ${UV_ARGS} --reinstall
3529
uv pip list

.evergreen/scripts/run_server.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,6 @@ def start_server():
2828
elif test_name == "load_balancer":
2929
set_env("LOAD_BALANCER")
3030

31-
elif test_name == "auth_oidc":
32-
raise ValueError(
33-
"OIDC auth does not use run-orchestration directly, do not use run-server!"
34-
)
35-
3631
elif test_name == "ocsp":
3732
opts.ssl = True
3833
if "ORCHESTRATION_FILE" not in os.environ:

.evergreen/scripts/setup_tests.py

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,17 @@ def setup_libmongocrypt():
115115
run_command("chmod +x libmongocrypt/nocrypto/bin/mongocrypt.dll")
116116

117117

118-
def get_secrets(name: str) -> None:
119-
run_command(f"bash {DRIVERS_TOOLS}/.evergreen/secrets_handling/setup-secrets.sh {name}")
118+
def load_config_from_file(path: str | Path) -> dict[str, str]:
119+
config = read_env(path)
120+
for key, value in config.items():
121+
write_env(key, value)
122+
return config
123+
124+
125+
def get_secrets(name: str) -> dict[str, str]:
126+
secrets_dir = Path(f"{DRIVERS_TOOLS}/.evergreen/secrets_handling")
127+
run_command(f"bash {secrets_dir}/setup-secrets.sh {name}", cwd=secrets_dir)
128+
return load_config_from_file(secrets_dir / "secrets-export.sh")
120129

121130

122131
def handle_test_env() -> None:
@@ -158,7 +167,7 @@ def handle_test_env() -> None:
158167

159168
# Handle pass through env vars.
160169
for var in PASS_THROUGH_ENV:
161-
if is_set(var):
170+
if is_set(var) or getattr(opts, var.lower()):
162171
write_env(var, os.environ[var])
163172

164173
if extra := EXTRAS_MAP.get(test_name, ""):
@@ -233,12 +242,11 @@ def handle_test_env() -> None:
233242
if is_set("MONGODB_URI"):
234243
write_env("PYMONGO_MUST_CONNECT", "true")
235244

236-
if is_set("DISABLE_TEST_COMMANDS"):
245+
if is_set("DISABLE_TEST_COMMANDS") or opts.disable_test_commands:
237246
write_env("PYMONGO_DISABLE_TEST_COMMANDS", "1")
238247

239248
if test_name == "enterprise_auth":
240-
get_secrets("drivers/enterprise_auth")
241-
config = read_env(f"{ROOT}/secrets-export.sh")
249+
config = get_secrets("drivers/enterprise_auth")
242250
if PLATFORM == "windows":
243251
LOGGER.info("Setting GSSAPI_PASS")
244252
write_env("GSSAPI_PASS", config["SASL_PASS"])
@@ -316,7 +324,7 @@ def handle_test_env() -> None:
316324
write_env("CLIENT_PEM", f"{DRIVERS_TOOLS}/.evergreen/x509gen/client.pem")
317325
write_env("CA_PEM", f"{DRIVERS_TOOLS}/.evergreen/x509gen/ca.pem")
318326

319-
compressors = os.environ.get("COMPRESSORS")
327+
compressors = os.environ.get("COMPRESSORS") or opts.compressor
320328
if compressors == "snappy":
321329
UV_ARGS.append("--extra snappy")
322330
elif compressors == "zstd":
@@ -349,13 +357,15 @@ def handle_test_env() -> None:
349357
if test_name == "encryption":
350358
if not DRIVERS_TOOLS:
351359
raise RuntimeError("Missing DRIVERS_TOOLS")
352-
run_command(f"bash {DRIVERS_TOOLS}/.evergreen/csfle/setup-secrets.sh")
353-
run_command(f"bash {DRIVERS_TOOLS}/.evergreen/csfle/start-servers.sh")
360+
csfle_dir = Path(f"{DRIVERS_TOOLS}/.evergreen/csfle")
361+
run_command(f"bash {csfle_dir}/setup-secrets.sh", cwd=csfle_dir)
362+
load_config_from_file(csfle_dir / "secrets-export.sh")
363+
run_command(f"bash {csfle_dir}/start-servers.sh")
354364

355365
if sub_test_name == "pyopenssl":
356366
UV_ARGS.append("--extra ocsp")
357367

358-
if is_set("TEST_CRYPT_SHARED"):
368+
if is_set("TEST_CRYPT_SHARED") or opts.crypt_shared:
359369
config = read_env(f"{DRIVERS_TOOLS}/mo-expansion.sh")
360370
CRYPT_SHARED_DIR = Path(config["CRYPT_SHARED_LIB_PATH"]).parent.as_posix()
361371
LOGGER.info("Using crypt_shared_dir %s", CRYPT_SHARED_DIR)
@@ -414,15 +424,15 @@ def handle_test_env() -> None:
414424

415425
# Add coverage if requested.
416426
# Only cover CPython. PyPy reports suspiciously low coverage.
417-
if is_set("COVERAGE") and platform.python_implementation() == "CPython":
427+
if (is_set("COVERAGE") or opts.cov) and platform.python_implementation() == "CPython":
418428
# Keep in sync with combine-coverage.sh.
419429
# coverage >=5 is needed for relative_files=true.
420430
UV_ARGS.append("--group coverage")
421431
TEST_ARGS = f"{TEST_ARGS} --cov"
422432
write_env("COVERAGE")
423433

424-
if is_set("GREEN_FRAMEWORK"):
425-
framework = os.environ["GREEN_FRAMEWORK"]
434+
if is_set("GREEN_FRAMEWORK") or opts.green_framework:
435+
framework = opts.green_framework or os.environ["GREEN_FRAMEWORK"]
426436
UV_ARGS.append(f"--group {framework}")
427437

428438
else:

.evergreen/scripts/utils.py

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,10 @@ class Distro:
5252
# Tests that require a sub test suite.
5353
SUB_TEST_REQUIRED = ["auth_aws", "auth_oidc", "kms", "mod_wsgi", "perf"]
5454

55-
EXTRA_TESTS = ["mod_wsgi", "aws_lambda", "search_index"]
55+
EXTRA_TESTS = ["mod_wsgi", "aws_lambda"]
56+
57+
# Tests that do not use run-orchestration.
58+
NO_RUN_ORCHESTRATION = ["auth_oidc", "atlas_connect", "data_lake", "mockupdb", "serverless"]
5659

5760

5861
def get_test_options(
@@ -75,19 +78,47 @@ def get_test_options(
7578
else:
7679
parser.add_argument(
7780
"test_name",
78-
choices=sorted(TEST_SUITE_MAP),
81+
choices=set(TEST_SUITE_MAP) - set(NO_RUN_ORCHESTRATION),
7982
nargs="?",
8083
default="default",
8184
help="The optional name of the test suite to be run, which informs the server configuration.",
8285
)
8386
parser.add_argument(
84-
"--verbose", "-v", action="store_true", help="Whether to log at the DEBUG level"
87+
"--verbose", "-v", action="store_true", help="Whether to log at the DEBUG level."
8588
)
8689
parser.add_argument(
87-
"--quiet", "-q", action="store_true", help="Whether to log at the WARNING level"
90+
"--quiet", "-q", action="store_true", help="Whether to log at the WARNING level."
8891
)
89-
parser.add_argument("--auth", action="store_true", help="Whether to add authentication")
90-
parser.add_argument("--ssl", action="store_true", help="Whether to add TLS configuration")
92+
parser.add_argument("--auth", action="store_true", help="Whether to add authentication.")
93+
parser.add_argument("--ssl", action="store_true", help="Whether to add TLS configuration.")
94+
95+
# Add the test modifiers.
96+
if require_sub_test_name:
97+
parser.add_argument(
98+
"--debug-log", action="store_true", help="Enable pymongo standard logging."
99+
)
100+
parser.add_argument("--cov", action="store_true", help="Add test coverage.")
101+
parser.add_argument(
102+
"--green-framework",
103+
nargs=1,
104+
choices=["eventlet", "gevent"],
105+
help="Optional green framework to test against.",
106+
)
107+
parser.add_argument(
108+
"--compressor",
109+
nargs=1,
110+
choices=["zlib", "zstd", "snappy"],
111+
help="Optional compression algorithm.",
112+
)
113+
parser.add_argument("--crypt-shared", action="store_true", help="Test with crypt_shared.")
114+
parser.add_argument("--no-ext", action="store_true", help="Run without c extensions.")
115+
parser.add_argument(
116+
"--mongodb-api-version", choices=["1"], help="MongoDB stable API version to use."
117+
)
118+
parser.add_argument(
119+
"--disable-test-commands", action="store_true", help="Disable test commands."
120+
)
121+
91122
# Get the options.
92123
if not allow_extra_opts:
93124
opts, extra_opts = parser.parse_args(), []
@@ -113,7 +144,7 @@ def get_test_options(
113144
return opts, extra_opts
114145

115146

116-
def read_env(path: Path | str) -> dict[str, Any]:
147+
def read_env(path: Path | str) -> dict[str, str]:
117148
config = dict()
118149
with Path(path).open() as fid:
119150
for line in fid.readlines():

CONTRIBUTING.md

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,11 @@ the pages will re-render and the browser will automatically refresh.
217217

218218
### Usage
219219

220-
- Run `just run-server` with optional args to set up the server.
221-
All given flags will be passed to `run-orchestration.sh` in `$DRIVERS_TOOLS`.
220+
- Run `just run-server` with optional args to set up the server. All given options will be passed to
221+
`run-orchestration.sh` in `$DRIVERS_TOOLS`. See `$DRIVERS_TOOLS/evergreen/run-orchestration.sh -h`
222+
for a full list of options.
222223
- Run `just setup-tests` with optional args to set up the test environment, secrets, etc.
224+
See `just setup-tests -h` for a full list of available options.
223225
- Run `just run-tests` to run the tests in an appropriate Python environment.
224226
- When done, run `just teardown-tests` to clean up and `just stop-server` to stop the server.
225227

@@ -346,11 +348,28 @@ If you are running one of the `no-responder` tests, omit the `run-server` step.
346348
- Run the tests: `just run-tests`.
347349

348350
## Enable Debug Logs
351+
349352
- Use `-o log_cli_level="DEBUG" -o log_cli=1` with `just test` or `pytest`.
350353
- Add `log_cli_level = "DEBUG` and `log_cli = 1` to the `tool.pytest.ini_options` section in `pyproject.toml` for Evergreen patches or to enable debug logs by default on your machine.
351354
- You can also set `DEBUG_LOG=1` and run either `just setup-tests` or `just-test`.
355+
- Finally, you can use `just setup-tests --debug-log`.
352356
- For evergreen patch builds, you can use `evergreen patch --param DEBUG_LOG=1` to enable debug logs for the patch.
353357

358+
## Adding a new test suite
359+
360+
- If adding new tests files that should only be run for that test suite, add a pytest marker to the file and add
361+
to the list of pytest markers in `pyproject.toml`. Then add the test suite to the `TEST_SUITE_MAP` in `.evergreen/scripts/utils.py`. If for some reason it is not a pytest-runnable test, add it to the list of `EXTRA_TESTS` instead.
362+
- If the test uses Atlas or otherwise doesn't use `run-orchestration.sh`, add it to the `NO_RUN_ORCHESTRATION` list in
363+
`.evergreen/scripts/utils.py`.
364+
- If there is something special required to run the local server or there is an extra flag that should always be set
365+
like `AUTH`, add that logic to `.evergreen/scripts/run_server.py`.
366+
- The bulk of the logic will typically be in `.evergreen/scripts/setup_tests.py`. This is where you should fetch secrets and make them available using `write_env`, start services, and write other env vars needed using `write_env`.
367+
- If there are any special test considerations, including not running `pytest` at all, handle it in `.evergreen/scripts/run_tests.py`.
368+
- If there are any services or atlas clusters to teardown, handle them in `.evergreen/scripts/teardown_tests.py`.
369+
- Add functions to generate the test variant(s) and task(s) to the `.evergreen/scripts/generate_config.py`.
370+
- Regenerate the test variants and tasks using the instructions in `.evergreen/scripts/generate_config.py`.
371+
- Make sure to add instructions for running the test suite to `CONTRIBUTING.md`.
372+
354373
## Re-sync Spec Tests
355374

356375
If you would like to re-sync the copy of the specification tests in the

doc/changelog.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ PyMongo 4.12 brings a number of changes including:
1111
- Support for $lookup in CSFLE and QE supported on MongoDB 8.1+.
1212
- AsyncMongoClient no longer performs DNS resolution for "mongodb+srv://" connection strings on creation.
1313
To avoid blocking the asyncio loop, the resolution is now deferred until the client is first connected.
14+
- Added index hinting support to the
15+
:meth:`~pymongo.asynchronous.collection.AsyncCollection.distinct` and
16+
:meth:`~pymongo.collection.Collection.distinct` commands.
1417

1518
Issues Resolved
1619
...............

pymongo/asynchronous/client_session.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -458,10 +458,10 @@ def _max_time_expired_error(exc: PyMongoError) -> bool:
458458

459459

460460
# From the transactions spec, all the retryable writes errors plus
461-
# WriteConcernFailed.
461+
# WriteConcernTimeout.
462462
_UNKNOWN_COMMIT_ERROR_CODES: frozenset = _RETRYABLE_ERROR_CODES | frozenset(
463463
[
464-
64, # WriteConcernFailed
464+
64, # WriteConcernTimeout
465465
50, # MaxTimeMSExpired
466466
]
467467
)

pymongo/asynchronous/collection.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3111,6 +3111,7 @@ async def distinct(
31113111
filter: Optional[Mapping[str, Any]] = None,
31123112
session: Optional[AsyncClientSession] = None,
31133113
comment: Optional[Any] = None,
3114+
hint: Optional[_IndexKeyHint] = None,
31143115
**kwargs: Any,
31153116
) -> list:
31163117
"""Get a list of distinct values for `key` among all documents
@@ -3138,8 +3139,15 @@ async def distinct(
31383139
:class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
31393140
:param comment: A user-provided comment to attach to this
31403141
command.
3142+
:param hint: An index to use to support the query
3143+
predicate specified either by its string name, or in the same
3144+
format as passed to :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index`
3145+
(e.g. ``[('field', ASCENDING)]``).
31413146
:param kwargs: See list of options above.
31423147
3148+
.. versionchanged:: 4.12
3149+
Added ``hint`` parameter.
3150+
31433151
.. versionchanged:: 3.6
31443152
Added ``session`` parameter.
31453153
@@ -3158,6 +3166,10 @@ async def distinct(
31583166
cmd.update(kwargs)
31593167
if comment is not None:
31603168
cmd["comment"] = comment
3169+
if hint is not None:
3170+
if not isinstance(hint, str):
3171+
hint = helpers_shared._index_document(hint)
3172+
cmd["hint"] = hint # type: ignore[assignment]
31613173

31623174
async def _cmd(
31633175
session: Optional[AsyncClientSession],

pymongo/synchronous/client_session.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -457,10 +457,10 @@ def _max_time_expired_error(exc: PyMongoError) -> bool:
457457

458458

459459
# From the transactions spec, all the retryable writes errors plus
460-
# WriteConcernFailed.
460+
# WriteConcernTimeout.
461461
_UNKNOWN_COMMIT_ERROR_CODES: frozenset = _RETRYABLE_ERROR_CODES | frozenset(
462462
[
463-
64, # WriteConcernFailed
463+
64, # WriteConcernTimeout
464464
50, # MaxTimeMSExpired
465465
]
466466
)

pymongo/synchronous/collection.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3104,6 +3104,7 @@ def distinct(
31043104
filter: Optional[Mapping[str, Any]] = None,
31053105
session: Optional[ClientSession] = None,
31063106
comment: Optional[Any] = None,
3107+
hint: Optional[_IndexKeyHint] = None,
31073108
**kwargs: Any,
31083109
) -> list:
31093110
"""Get a list of distinct values for `key` among all documents
@@ -3131,8 +3132,15 @@ def distinct(
31313132
:class:`~pymongo.client_session.ClientSession`.
31323133
:param comment: A user-provided comment to attach to this
31333134
command.
3135+
:param hint: An index to use to support the query
3136+
predicate specified either by its string name, or in the same
3137+
format as passed to :meth:`~pymongo.collection.Collection.create_index`
3138+
(e.g. ``[('field', ASCENDING)]``).
31343139
:param kwargs: See list of options above.
31353140
3141+
.. versionchanged:: 4.12
3142+
Added ``hint`` parameter.
3143+
31363144
.. versionchanged:: 3.6
31373145
Added ``session`` parameter.
31383146
@@ -3151,6 +3159,10 @@ def distinct(
31513159
cmd.update(kwargs)
31523160
if comment is not None:
31533161
cmd["comment"] = comment
3162+
if hint is not None:
3163+
if not isinstance(hint, str):
3164+
hint = helpers_shared._index_document(hint)
3165+
cmd["hint"] = hint # type: ignore[assignment]
31543166

31553167
def _cmd(
31563168
session: Optional[ClientSession],

test/asynchronous/unified_format.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,11 @@ def maybe_skip_test(self, spec):
568568
self.skipTest("CSOT not implemented for watch()")
569569
if "cursors" in class_name:
570570
self.skipTest("CSOT not implemented for cursors")
571-
if "tailable" in class_name:
571+
if (
572+
"tailable" in class_name
573+
or "tailable" in description
574+
and "non-tailable" not in description
575+
):
572576
self.skipTest("CSOT not implemented for tailable cursors")
573577
if "sessions" in class_name:
574578
self.skipTest("CSOT not implemented for sessions")

test/bson_binary_vector/float32.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
{
3333
"description": "Infinity Vector FLOAT32",
3434
"valid": true,
35-
"vector": ["-inf", 0.0, "inf"],
35+
"vector": [{"$numberDouble": "-Infinity"}, 0.0, {"$numberDouble": "Infinity"} ],
3636
"dtype_hex": "0x27",
3737
"dtype_alias": "FLOAT32",
3838
"padding": 0,

0 commit comments

Comments
 (0)