Skip to content

Commit e821b27

Browse files
authored
Merge branch 'master' into dependabot/pip/pyright-1.1.384
2 parents d77606f + 463518b commit e821b27

26 files changed

+1235
-1090
lines changed

.evergreen/config.yml

Lines changed: 616 additions & 106 deletions
Large diffs are not rendered by default.

.evergreen/hatch.sh

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,25 @@ if [ -n "$SKIP_HATCH" ]; then
1818
run_hatch() {
1919
bash ./.evergreen/run-tests.sh
2020
}
21-
elif $PYTHON_BINARY -m hatch --version; then
22-
run_hatch() {
23-
$PYTHON_BINARY -m hatch run "$@"
24-
}
25-
else # No toolchain hatch present, set up virtualenv before installing hatch
21+
else # Set up virtualenv before installing hatch
2622
# Use a random venv name because the encryption tasks run this script multiple times in the same run.
2723
ENV_NAME=hatchenv-$RANDOM
2824
createvirtualenv "$PYTHON_BINARY" $ENV_NAME
2925
# shellcheck disable=SC2064
3026
trap "deactivate; rm -rf $ENV_NAME" EXIT HUP
3127
python -m pip install -q hatch
28+
29+
# Ensure hatch does not write to user or global locations.
30+
touch hatch_config.toml
31+
HATCH_CONFIG=$(pwd)/hatch_config.toml
32+
if [ "Windows_NT" = "$OS" ]; then # Magic variable in cygwin
33+
HATCH_CONFIG=$(cygpath -m "$HATCH_CONFIG")
34+
fi
35+
export HATCH_CONFIG
36+
hatch config restore
37+
hatch config set dirs.data "$(pwd)/.hatch/data"
38+
hatch config set dirs.cache "$(pwd)/.hatch/cache"
39+
3240
run_hatch() {
3341
python -m hatch run "$@"
3442
}

.evergreen/run-tests.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ set -o xtrace
3030

3131
AUTH=${AUTH:-noauth}
3232
SSL=${SSL:-nossl}
33-
TEST_SUITES=""
33+
TEST_SUITES=${TEST_SUITES:-}
3434
TEST_ARGS="${*:1}"
3535

3636
export PIP_QUIET=1 # Quiet by default

.evergreen/scripts/generate_config.py

Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
# /// script
2+
# requires-python = ">=3.9"
3+
# dependencies = [
4+
# "shrub.py>=3.2.0",
5+
# "pyyaml>=6.0.2"
6+
# ]
7+
# ///
8+
9+
# Note: Run this file with `hatch run`, `pipx run`, or `uv run`.
10+
from __future__ import annotations
11+
12+
from dataclasses import dataclass
13+
from itertools import cycle, product, zip_longest
14+
from typing import Any
15+
16+
from shrub.v3.evg_build_variant import BuildVariant
17+
from shrub.v3.evg_project import EvgProject
18+
from shrub.v3.evg_task import EvgTaskRef
19+
from shrub.v3.shrub_service import ShrubService
20+
21+
##############
22+
# Globals
23+
##############
24+
25+
ALL_VERSIONS = ["4.0", "4.4", "5.0", "6.0", "7.0", "8.0", "rapid", "latest"]
26+
CPYTHONS = ["3.9", "3.10", "3.11", "3.12", "3.13"]
27+
PYPYS = ["pypy3.9", "pypy3.10"]
28+
ALL_PYTHONS = CPYTHONS + PYPYS
29+
MIN_MAX_PYTHON = [CPYTHONS[0], CPYTHONS[-1]]
30+
BATCHTIME_WEEK = 10080
31+
AUTH_SSLS = [("auth", "ssl"), ("noauth", "ssl"), ("noauth", "nossl")]
32+
TOPOLOGIES = ["standalone", "replica_set", "sharded_cluster"]
33+
SYNCS = ["sync", "async"]
34+
DISPLAY_LOOKUP = dict(
35+
ssl=dict(ssl="SSL", nossl="NoSSL"),
36+
auth=dict(auth="Auth", noauth="NoAuth"),
37+
test_suites=dict(default="Sync", default_async="Async"),
38+
coverage=dict(coverage="cov"),
39+
)
40+
HOSTS = dict()
41+
42+
43+
@dataclass
44+
class Host:
45+
name: str
46+
run_on: str
47+
display_name: str
48+
expansions: dict[str, str]
49+
50+
51+
_macos_expansions = dict( # CSOT tests are unreliable on slow hosts.
52+
SKIP_CSOT_TESTS="true"
53+
)
54+
55+
HOSTS["rhel8"] = Host("rhel8", "rhel87-small", "RHEL8", dict())
56+
HOSTS["win64"] = Host("win64", "windows-64-vsMulti-small", "Win64", _macos_expansions)
57+
HOSTS["win32"] = Host("win32", "windows-64-vsMulti-small", "Win32", _macos_expansions)
58+
HOSTS["macos"] = Host("macos", "macos-14", "macOS", _macos_expansions)
59+
HOSTS["macos-arm64"] = Host("macos-arm64", "macos-14-arm64", "macOS Arm64", _macos_expansions)
60+
61+
62+
##############
63+
# Helpers
64+
##############
65+
66+
67+
def create_variant(
68+
task_names: list[str],
69+
display_name: str,
70+
*,
71+
python: str | None = None,
72+
version: str | None = None,
73+
host: str | None = None,
74+
**kwargs: Any,
75+
) -> BuildVariant:
76+
"""Create a build variant for the given inputs."""
77+
task_refs = [EvgTaskRef(name=n) for n in task_names]
78+
kwargs.setdefault("expansions", dict())
79+
expansions = kwargs.pop("expansions", dict()).copy()
80+
host = host or "rhel8"
81+
run_on = [HOSTS[host].run_on]
82+
name = display_name.replace(" ", "-").lower()
83+
if python:
84+
expansions["PYTHON_BINARY"] = get_python_binary(python, host)
85+
if version:
86+
expansions["VERSION"] = version
87+
expansions.update(HOSTS[host].expansions)
88+
expansions = expansions or None
89+
return BuildVariant(
90+
name=name,
91+
display_name=display_name,
92+
tasks=task_refs,
93+
expansions=expansions,
94+
run_on=run_on,
95+
**kwargs,
96+
)
97+
98+
99+
def get_python_binary(python: str, host: str) -> str:
100+
"""Get the appropriate python binary given a python version and host."""
101+
if host in ["win64", "win32"]:
102+
if host == "win32":
103+
base = "C:/python/32"
104+
else:
105+
base = "C:/python"
106+
python = python.replace(".", "")
107+
return f"{base}/Python{python}/python.exe"
108+
109+
if host == "rhel8":
110+
return f"/opt/python/{python}/bin/python3"
111+
112+
if host in ["macos", "macos-arm64"]:
113+
return f"/Library/Frameworks/Python.Framework/Versions/{python}/bin/python3"
114+
115+
raise ValueError(f"no match found for python {python} on {host}")
116+
117+
118+
def get_display_name(base: str, host: str, **kwargs) -> str:
119+
"""Get the display name of a variant."""
120+
display_name = f"{base} {HOSTS[host].display_name}"
121+
for key, value in kwargs.items():
122+
name = value
123+
if key == "version":
124+
if value not in ["rapid", "latest"]:
125+
name = f"v{value}"
126+
elif key == "python":
127+
if not value.startswith("pypy"):
128+
name = f"py{value}"
129+
elif key.lower() in DISPLAY_LOOKUP:
130+
name = DISPLAY_LOOKUP[key.lower()][value]
131+
else:
132+
raise ValueError(f"Missing display handling for {key}")
133+
display_name = f"{display_name} {name}"
134+
return display_name
135+
136+
137+
def zip_cycle(*iterables, empty_default=None):
138+
"""Get all combinations of the inputs, cycling over the shorter list(s)."""
139+
cycles = [cycle(i) for i in iterables]
140+
for _ in zip_longest(*iterables):
141+
yield tuple(next(i, empty_default) for i in cycles)
142+
143+
144+
def generate_yaml(tasks=None, variants=None):
145+
"""Generate the yaml for a given set of tasks and variants."""
146+
project = EvgProject(tasks=tasks, buildvariants=variants)
147+
out = ShrubService.generate_yaml(project)
148+
# Dedent by two spaces to match what we use in config.yml
149+
lines = [line[2:] for line in out.splitlines()]
150+
print("\n".join(lines)) # noqa: T201
151+
152+
153+
##############
154+
# Variants
155+
##############
156+
157+
158+
def create_ocsp_variants() -> list[BuildVariant]:
159+
variants = []
160+
batchtime = BATCHTIME_WEEK * 2
161+
expansions = dict(AUTH="noauth", SSL="ssl", TOPOLOGY="server")
162+
base_display = "OCSP test"
163+
164+
# OCSP tests on rhel8 with all servers v4.4+ and all python versions.
165+
versions = [v for v in ALL_VERSIONS if v != "4.0"]
166+
for version, python in zip_cycle(versions, ALL_PYTHONS):
167+
host = "rhel8"
168+
variant = create_variant(
169+
[".ocsp"],
170+
get_display_name(base_display, host, version, python),
171+
python=python,
172+
version=version,
173+
host=host,
174+
expansions=expansions,
175+
batchtime=batchtime,
176+
)
177+
variants.append(variant)
178+
179+
# OCSP tests on Windows and MacOS.
180+
# MongoDB servers on these hosts do not staple OCSP responses and only support RSA.
181+
for host, version in product(["win64", "macos"], ["4.4", "8.0"]):
182+
python = CPYTHONS[0] if version == "4.4" else CPYTHONS[-1]
183+
variant = create_variant(
184+
[".ocsp-rsa !.ocsp-staple"],
185+
get_display_name(base_display, host, version, python),
186+
python=python,
187+
version=version,
188+
host=host,
189+
expansions=expansions,
190+
batchtime=batchtime,
191+
)
192+
variants.append(variant)
193+
194+
return variants
195+
196+
197+
def create_server_variants() -> list[BuildVariant]:
198+
variants = []
199+
200+
# Run the full matrix on linux with min and max CPython, and latest pypy.
201+
host = "rhel8"
202+
for python, (auth, ssl) in product([*MIN_MAX_PYTHON, PYPYS[-1]], AUTH_SSLS):
203+
display_name = f"Test {host}"
204+
expansions = dict(AUTH=auth, SSL=ssl, COVERAGE="coverage")
205+
display_name = get_display_name("Test", host, python=python, **expansions)
206+
variant = create_variant(
207+
[f".{t}" for t in TOPOLOGIES],
208+
display_name,
209+
python=python,
210+
host=host,
211+
tags=["coverage_tag"],
212+
expansions=expansions,
213+
)
214+
variants.append(variant)
215+
216+
# Test the rest of the pythons on linux.
217+
for python, (auth, ssl), topology in zip_cycle(
218+
CPYTHONS[1:-1] + PYPYS[:-1], AUTH_SSLS, TOPOLOGIES
219+
):
220+
display_name = f"Test {host}"
221+
expansions = dict(AUTH=auth, SSL=ssl)
222+
display_name = get_display_name("Test", host, python=python, **expansions)
223+
variant = create_variant(
224+
[f".{topology}"],
225+
display_name,
226+
python=python,
227+
host=host,
228+
expansions=expansions,
229+
)
230+
variants.append(variant)
231+
232+
# Test a subset on each of the other platforms.
233+
for host in ("macos", "macos-arm64", "win64", "win32"):
234+
for (python, (auth, ssl), topology), sync in product(
235+
zip_cycle(MIN_MAX_PYTHON, AUTH_SSLS, TOPOLOGIES), SYNCS
236+
):
237+
test_suite = "default" if sync == "sync" else "default_async"
238+
expansions = dict(AUTH=auth, SSL=ssl, TEST_SUITES=test_suite)
239+
display_name = get_display_name("Test", host, python=python, **expansions)
240+
variant = create_variant(
241+
[f".{topology}"],
242+
display_name,
243+
python=python,
244+
host=host,
245+
expansions=expansions,
246+
)
247+
variants.append(variant)
248+
249+
return variants
250+
251+
252+
##################
253+
# Generate Config
254+
##################
255+
256+
generate_yaml(variants=create_server_variants())

doc/changelog.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ PyMongo 4.11 brings a number of changes including:
1414
- Dropped support for MongoDB 3.6.
1515
- Added support for free-threaded Python with the GIL disabled. For more information see:
1616
`Free-threaded CPython <https://docs.python.org/3.13/whatsnew/3.13.html#whatsnew313-free-threaded-cpython>`_.
17+
- :attr:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.address` and
18+
:attr:`~pymongo.mongo_client.MongoClient.address` now correctly block when called on unconnected clients
19+
until either connection succeeds or a server selection timeout error is raised.
20+
- Added :func:`repr` support to :class:`pymongo.operations.IndexModel`.
21+
- Added :func:`repr` support to :class:`pymongo.operations.SearchIndexModel`.
1722

1823
Issues Resolved
1924
...............

pymongo/asynchronous/mongo_client.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1453,13 +1453,6 @@ async def address(self) -> Optional[tuple[str, int]]:
14531453
'Cannot use "address" property when load balancing among'
14541454
' mongoses, use "nodes" instead.'
14551455
)
1456-
if topology_type not in (
1457-
TOPOLOGY_TYPE.ReplicaSetWithPrimary,
1458-
TOPOLOGY_TYPE.Single,
1459-
TOPOLOGY_TYPE.LoadBalanced,
1460-
TOPOLOGY_TYPE.Sharded,
1461-
):
1462-
return None
14631456
return await self._server_property("address")
14641457

14651458
@property

pymongo/operations.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -773,6 +773,13 @@ def document(self) -> dict[str, Any]:
773773
"""
774774
return self.__document
775775

776+
def __repr__(self) -> str:
777+
return "{}({}{})".format(
778+
self.__class__.__name__,
779+
self.document["key"],
780+
"".join([f", {key}={value!r}" for key, value in self.document.items() if key != "key"]),
781+
)
782+
776783

777784
class SearchIndexModel:
778785
"""Represents a search index to create."""
@@ -812,3 +819,9 @@ def __init__(
812819
def document(self) -> Mapping[str, Any]:
813820
"""The document for this index."""
814821
return self.__document
822+
823+
def __repr__(self) -> str:
824+
return "{}({})".format(
825+
self.__class__.__name__,
826+
", ".join([f"{key}={value!r}" for key, value in self.document.items()]),
827+
)

pymongo/synchronous/mongo_client.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1447,13 +1447,6 @@ def address(self) -> Optional[tuple[str, int]]:
14471447
'Cannot use "address" property when load balancing among'
14481448
' mongoses, use "nodes" instead.'
14491449
)
1450-
if topology_type not in (
1451-
TOPOLOGY_TYPE.ReplicaSetWithPrimary,
1452-
TOPOLOGY_TYPE.Single,
1453-
TOPOLOGY_TYPE.LoadBalanced,
1454-
TOPOLOGY_TYPE.Sharded,
1455-
):
1456-
return None
14571450
return self._server_property("address")
14581451

14591452
@property

test/asynchronous/test_client.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -838,8 +838,6 @@ async def test_init_disconnected(self):
838838
c = await self.async_rs_or_single_client(connect=False)
839839
self.assertIsInstance(c.topology_description, TopologyDescription)
840840
self.assertEqual(c.topology_description, c._topology._description)
841-
self.assertIsNone(await c.address) # PYTHON-2981
842-
await c.admin.command("ping") # connect
843841
if async_client_context.is_rs:
844842
# The primary's host and port are from the replica set config.
845843
self.assertIsNotNone(await c.address)
@@ -2019,6 +2017,22 @@ async def test_handshake_08_invalid_aws_ec2(self):
20192017
None,
20202018
)
20212019

2020+
async def test_handshake_09_container_with_provider(self):
2021+
await self._test_handshake(
2022+
{
2023+
ENV_VAR_K8S: "1",
2024+
"AWS_LAMBDA_RUNTIME_API": "1",
2025+
"AWS_REGION": "us-east-1",
2026+
"AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "256",
2027+
},
2028+
{
2029+
"container": {"orchestrator": "kubernetes"},
2030+
"name": "aws.lambda",
2031+
"region": "us-east-1",
2032+
"memory_mb": 256,
2033+
},
2034+
)
2035+
20222036
def test_dict_hints(self):
20232037
self.db.t.find(hint={"x": 1})
20242038

0 commit comments

Comments
 (0)