Skip to content

Commit 3e783f5

Browse files
authored
PYTHON-5088 Convert test.test_max_staleness to async (#2105)
1 parent 44d1d40 commit 3e783f5

File tree

3 files changed

+159
-2
lines changed

3 files changed

+159
-2
lines changed
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# Copyright 2016 MongoDB, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Test maxStalenessSeconds support."""
16+
from __future__ import annotations
17+
18+
import asyncio
19+
import os
20+
import sys
21+
import time
22+
import warnings
23+
from pathlib import Path
24+
25+
from pymongo import AsyncMongoClient
26+
from pymongo.operations import _Op
27+
28+
sys.path[0:0] = [""]
29+
30+
from test.asynchronous import AsyncPyMongoTestCase, async_client_context, unittest
31+
from test.utils_selection_tests import create_selection_tests
32+
33+
from pymongo.errors import ConfigurationError
34+
from pymongo.server_selectors import writable_server_selector
35+
36+
_IS_SYNC = False
37+
38+
# Location of JSON test specifications.
39+
if _IS_SYNC:
40+
TEST_PATH = os.path.join(Path(__file__).resolve().parent, "max_staleness")
41+
else:
42+
TEST_PATH = os.path.join(Path(__file__).resolve().parent.parent, "max_staleness")
43+
44+
45+
class TestAllScenarios(create_selection_tests(TEST_PATH)): # type: ignore
46+
pass
47+
48+
49+
class TestMaxStaleness(AsyncPyMongoTestCase):
50+
async def test_max_staleness(self):
51+
client = self.simple_client()
52+
self.assertEqual(-1, client.read_preference.max_staleness)
53+
54+
client = self.simple_client("mongodb://a/?readPreference=secondary")
55+
self.assertEqual(-1, client.read_preference.max_staleness)
56+
57+
# These tests are specified in max-staleness-tests.rst.
58+
with self.assertRaises(ConfigurationError):
59+
# Default read pref "primary" can't be used with max staleness.
60+
self.simple_client("mongodb://a/?maxStalenessSeconds=120")
61+
62+
with self.assertRaises(ConfigurationError):
63+
# Read pref "primary" can't be used with max staleness.
64+
self.simple_client("mongodb://a/?readPreference=primary&maxStalenessSeconds=120")
65+
66+
client = self.simple_client("mongodb://host/?maxStalenessSeconds=-1")
67+
self.assertEqual(-1, client.read_preference.max_staleness)
68+
69+
client = self.simple_client("mongodb://host/?readPreference=primary&maxStalenessSeconds=-1")
70+
self.assertEqual(-1, client.read_preference.max_staleness)
71+
72+
client = self.simple_client(
73+
"mongodb://host/?readPreference=secondary&maxStalenessSeconds=120"
74+
)
75+
self.assertEqual(120, client.read_preference.max_staleness)
76+
77+
client = self.simple_client("mongodb://a/?readPreference=secondary&maxStalenessSeconds=1")
78+
self.assertEqual(1, client.read_preference.max_staleness)
79+
80+
client = self.simple_client("mongodb://a/?readPreference=secondary&maxStalenessSeconds=-1")
81+
self.assertEqual(-1, client.read_preference.max_staleness)
82+
83+
client = self.simple_client(maxStalenessSeconds=-1, readPreference="nearest")
84+
self.assertEqual(-1, client.read_preference.max_staleness)
85+
86+
with self.assertRaises(TypeError):
87+
# Prohibit None.
88+
self.simple_client(maxStalenessSeconds=None, readPreference="nearest")
89+
90+
async def test_max_staleness_float(self):
91+
with self.assertRaises(TypeError) as ctx:
92+
await self.async_rs_or_single_client(maxStalenessSeconds=1.5, readPreference="nearest")
93+
94+
self.assertIn("must be an integer", str(ctx.exception))
95+
96+
with warnings.catch_warnings(record=True) as ctx:
97+
warnings.simplefilter("always")
98+
client = self.simple_client(
99+
"mongodb://host/?maxStalenessSeconds=1.5&readPreference=nearest"
100+
)
101+
102+
# Option was ignored.
103+
self.assertEqual(-1, client.read_preference.max_staleness)
104+
self.assertIn("must be an integer", str(ctx[0]))
105+
106+
async def test_max_staleness_zero(self):
107+
# Zero is too small.
108+
with self.assertRaises(ValueError) as ctx:
109+
await self.async_rs_or_single_client(maxStalenessSeconds=0, readPreference="nearest")
110+
111+
self.assertIn("must be a positive integer", str(ctx.exception))
112+
113+
with warnings.catch_warnings(record=True) as ctx:
114+
warnings.simplefilter("always")
115+
client = self.simple_client(
116+
"mongodb://host/?maxStalenessSeconds=0&readPreference=nearest"
117+
)
118+
119+
# Option was ignored.
120+
self.assertEqual(-1, client.read_preference.max_staleness)
121+
self.assertIn("must be a positive integer", str(ctx[0]))
122+
123+
@async_client_context.require_replica_set
124+
async def test_last_write_date(self):
125+
# From max-staleness-tests.rst, "Parse lastWriteDate".
126+
client = await self.async_rs_or_single_client(heartbeatFrequencyMS=500)
127+
await client.pymongo_test.test.insert_one({})
128+
# Wait for the server description to be updated.
129+
await asyncio.sleep(1)
130+
server = await client._topology.select_server(writable_server_selector, _Op.TEST)
131+
first = server.description.last_write_date
132+
self.assertTrue(first)
133+
# The first last_write_date may correspond to a internal server write,
134+
# sleep so that the next write does not occur within the same second.
135+
await asyncio.sleep(1)
136+
await client.pymongo_test.test.insert_one({})
137+
# Wait for the server description to be updated.
138+
await asyncio.sleep(1)
139+
server = await client._topology.select_server(writable_server_selector, _Op.TEST)
140+
second = server.description.last_write_date
141+
assert first is not None
142+
143+
assert second is not None
144+
self.assertGreater(second, first)
145+
self.assertLess(second, first + 10)
146+
147+
148+
if __name__ == "__main__":
149+
unittest.main()

test/test_max_staleness.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@
1515
"""Test maxStalenessSeconds support."""
1616
from __future__ import annotations
1717

18+
import asyncio
1819
import os
1920
import sys
2021
import time
2122
import warnings
23+
from pathlib import Path
2224

2325
from pymongo import MongoClient
2426
from pymongo.operations import _Op
@@ -31,11 +33,16 @@
3133
from pymongo.errors import ConfigurationError
3234
from pymongo.server_selectors import writable_server_selector
3335

36+
_IS_SYNC = True
37+
3438
# Location of JSON test specifications.
35-
_TEST_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "max_staleness")
39+
if _IS_SYNC:
40+
TEST_PATH = os.path.join(Path(__file__).resolve().parent, "max_staleness")
41+
else:
42+
TEST_PATH = os.path.join(Path(__file__).resolve().parent.parent, "max_staleness")
3643

3744

38-
class TestAllScenarios(create_selection_tests(_TEST_PATH)): # type: ignore
45+
class TestAllScenarios(create_selection_tests(TEST_PATH)): # type: ignore
3946
pass
4047

4148

tools/synchro.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ def async_only_test(f: str) -> bool:
215215
"test_json_util_integration.py",
216216
"test_gridfs_spec.py",
217217
"test_logger.py",
218+
"test_max_staleness.py",
218219
"test_monitoring.py",
219220
"test_on_demand_csfle.py",
220221
"test_raw_bson.py",

0 commit comments

Comments
 (0)