Skip to content

Commit c2338d8

Browse files
authored
PYTHON-4839 - Convert test.test_collation to async (mongodb#1911)
1 parent d1e4167 commit c2338d8

File tree

3 files changed

+298
-4
lines changed

3 files changed

+298
-4
lines changed

test/asynchronous/test_collation.py

Lines changed: 290 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
# Copyright 2016-present 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 the collation module."""
16+
from __future__ import annotations
17+
18+
import functools
19+
import warnings
20+
from test.asynchronous import AsyncIntegrationTest, async_client_context, unittest
21+
from test.utils import EventListener
22+
from typing import Any
23+
24+
from pymongo.asynchronous.helpers import anext
25+
from pymongo.collation import (
26+
Collation,
27+
CollationAlternate,
28+
CollationCaseFirst,
29+
CollationMaxVariable,
30+
CollationStrength,
31+
)
32+
from pymongo.errors import ConfigurationError
33+
from pymongo.operations import (
34+
DeleteMany,
35+
DeleteOne,
36+
IndexModel,
37+
ReplaceOne,
38+
UpdateMany,
39+
UpdateOne,
40+
)
41+
from pymongo.write_concern import WriteConcern
42+
43+
_IS_SYNC = False
44+
45+
46+
class TestCollationObject(unittest.TestCase):
47+
def test_constructor(self):
48+
self.assertRaises(TypeError, Collation, locale=42)
49+
# Fill in a locale to test the other options.
50+
_Collation = functools.partial(Collation, "en_US")
51+
# No error.
52+
_Collation(caseFirst=CollationCaseFirst.UPPER)
53+
self.assertRaises(TypeError, _Collation, caseLevel="true")
54+
self.assertRaises(ValueError, _Collation, strength="six")
55+
self.assertRaises(TypeError, _Collation, numericOrdering="true")
56+
self.assertRaises(TypeError, _Collation, alternate=5)
57+
self.assertRaises(TypeError, _Collation, maxVariable=2)
58+
self.assertRaises(TypeError, _Collation, normalization="false")
59+
self.assertRaises(TypeError, _Collation, backwards="true")
60+
61+
# No errors.
62+
Collation("en_US", future_option="bar", another_option=42)
63+
collation = Collation(
64+
"en_US",
65+
caseLevel=True,
66+
caseFirst=CollationCaseFirst.UPPER,
67+
strength=CollationStrength.QUATERNARY,
68+
numericOrdering=True,
69+
alternate=CollationAlternate.SHIFTED,
70+
maxVariable=CollationMaxVariable.SPACE,
71+
normalization=True,
72+
backwards=True,
73+
)
74+
75+
self.assertEqual(
76+
{
77+
"locale": "en_US",
78+
"caseLevel": True,
79+
"caseFirst": "upper",
80+
"strength": 4,
81+
"numericOrdering": True,
82+
"alternate": "shifted",
83+
"maxVariable": "space",
84+
"normalization": True,
85+
"backwards": True,
86+
},
87+
collation.document,
88+
)
89+
90+
self.assertEqual(
91+
{"locale": "en_US", "backwards": True}, Collation("en_US", backwards=True).document
92+
)
93+
94+
95+
class TestCollation(AsyncIntegrationTest):
96+
listener: EventListener
97+
warn_context: Any
98+
collation: Collation
99+
100+
@classmethod
101+
@async_client_context.require_connection
102+
async def _setup_class(cls):
103+
await super()._setup_class()
104+
cls.listener = EventListener()
105+
cls.client = await cls.unmanaged_async_rs_or_single_client(event_listeners=[cls.listener])
106+
cls.db = cls.client.pymongo_test
107+
cls.collation = Collation("en_US")
108+
cls.warn_context = warnings.catch_warnings()
109+
cls.warn_context.__enter__()
110+
warnings.simplefilter("ignore", DeprecationWarning)
111+
112+
@classmethod
113+
async def _tearDown_class(cls):
114+
cls.warn_context.__exit__()
115+
cls.warn_context = None
116+
await cls.client.close()
117+
await super()._tearDown_class()
118+
119+
def tearDown(self):
120+
self.listener.reset()
121+
super().tearDown()
122+
123+
def last_command_started(self):
124+
return self.listener.started_events[-1].command
125+
126+
def assertCollationInLastCommand(self):
127+
self.assertEqual(self.collation.document, self.last_command_started()["collation"])
128+
129+
async def test_create_collection(self):
130+
await self.db.test.drop()
131+
await self.db.create_collection("test", collation=self.collation)
132+
self.assertCollationInLastCommand()
133+
134+
# Test passing collation as a dict as well.
135+
await self.db.test.drop()
136+
self.listener.reset()
137+
await self.db.create_collection("test", collation=self.collation.document)
138+
self.assertCollationInLastCommand()
139+
140+
def test_index_model(self):
141+
model = IndexModel([("a", 1), ("b", -1)], collation=self.collation)
142+
self.assertEqual(self.collation.document, model.document["collation"])
143+
144+
async def test_create_index(self):
145+
await self.db.test.create_index("foo", collation=self.collation)
146+
ci_cmd = self.listener.started_events[0].command
147+
self.assertEqual(self.collation.document, ci_cmd["indexes"][0]["collation"])
148+
149+
async def test_aggregate(self):
150+
await self.db.test.aggregate([{"$group": {"_id": 42}}], collation=self.collation)
151+
self.assertCollationInLastCommand()
152+
153+
async def test_count_documents(self):
154+
await self.db.test.count_documents({}, collation=self.collation)
155+
self.assertCollationInLastCommand()
156+
157+
async def test_distinct(self):
158+
await self.db.test.distinct("foo", collation=self.collation)
159+
self.assertCollationInLastCommand()
160+
161+
self.listener.reset()
162+
await self.db.test.find(collation=self.collation).distinct("foo")
163+
self.assertCollationInLastCommand()
164+
165+
async def test_find_command(self):
166+
await self.db.test.insert_one({"is this thing on?": True})
167+
self.listener.reset()
168+
await anext(self.db.test.find(collation=self.collation))
169+
self.assertCollationInLastCommand()
170+
171+
async def test_explain_command(self):
172+
self.listener.reset()
173+
await self.db.test.find(collation=self.collation).explain()
174+
# The collation should be part of the explained command.
175+
self.assertEqual(
176+
self.collation.document, self.last_command_started()["explain"]["collation"]
177+
)
178+
179+
async def test_delete(self):
180+
await self.db.test.delete_one({"foo": 42}, collation=self.collation)
181+
command = self.listener.started_events[0].command
182+
self.assertEqual(self.collation.document, command["deletes"][0]["collation"])
183+
184+
self.listener.reset()
185+
await self.db.test.delete_many({"foo": 42}, collation=self.collation)
186+
command = self.listener.started_events[0].command
187+
self.assertEqual(self.collation.document, command["deletes"][0]["collation"])
188+
189+
async def test_update(self):
190+
await self.db.test.replace_one({"foo": 42}, {"foo": 43}, collation=self.collation)
191+
command = self.listener.started_events[0].command
192+
self.assertEqual(self.collation.document, command["updates"][0]["collation"])
193+
194+
self.listener.reset()
195+
await self.db.test.update_one({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation)
196+
command = self.listener.started_events[0].command
197+
self.assertEqual(self.collation.document, command["updates"][0]["collation"])
198+
199+
self.listener.reset()
200+
await self.db.test.update_many({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation)
201+
command = self.listener.started_events[0].command
202+
self.assertEqual(self.collation.document, command["updates"][0]["collation"])
203+
204+
async def test_find_and(self):
205+
await self.db.test.find_one_and_delete({"foo": 42}, collation=self.collation)
206+
self.assertCollationInLastCommand()
207+
208+
self.listener.reset()
209+
await self.db.test.find_one_and_update(
210+
{"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation
211+
)
212+
self.assertCollationInLastCommand()
213+
214+
self.listener.reset()
215+
await self.db.test.find_one_and_replace({"foo": 42}, {"foo": 43}, collation=self.collation)
216+
self.assertCollationInLastCommand()
217+
218+
async def test_bulk_write(self):
219+
await self.db.test.collection.bulk_write(
220+
[
221+
DeleteOne({"noCollation": 42}),
222+
DeleteMany({"noCollation": 42}),
223+
DeleteOne({"foo": 42}, collation=self.collation),
224+
DeleteMany({"foo": 42}, collation=self.collation),
225+
ReplaceOne({"noCollation": 24}, {"bar": 42}),
226+
UpdateOne({"noCollation": 84}, {"$set": {"bar": 10}}, upsert=True),
227+
UpdateMany({"noCollation": 45}, {"$set": {"bar": 42}}),
228+
ReplaceOne({"foo": 24}, {"foo": 42}, collation=self.collation),
229+
UpdateOne(
230+
{"foo": 84}, {"$set": {"foo": 10}}, upsert=True, collation=self.collation
231+
),
232+
UpdateMany({"foo": 45}, {"$set": {"foo": 42}}, collation=self.collation),
233+
]
234+
)
235+
236+
delete_cmd = self.listener.started_events[0].command
237+
update_cmd = self.listener.started_events[1].command
238+
239+
def check_ops(ops):
240+
for op in ops:
241+
if "noCollation" in op["q"]:
242+
self.assertNotIn("collation", op)
243+
else:
244+
self.assertEqual(self.collation.document, op["collation"])
245+
246+
check_ops(delete_cmd["deletes"])
247+
check_ops(update_cmd["updates"])
248+
249+
async def test_indexes_same_keys_different_collations(self):
250+
await self.db.test.drop()
251+
usa_collation = Collation("en_US")
252+
ja_collation = Collation("ja")
253+
await self.db.test.create_indexes(
254+
[
255+
IndexModel("fieldname", collation=usa_collation),
256+
IndexModel("fieldname", name="japanese_version", collation=ja_collation),
257+
IndexModel("fieldname", name="simple"),
258+
]
259+
)
260+
indexes = await self.db.test.index_information()
261+
self.assertEqual(
262+
usa_collation.document["locale"], indexes["fieldname_1"]["collation"]["locale"]
263+
)
264+
self.assertEqual(
265+
ja_collation.document["locale"], indexes["japanese_version"]["collation"]["locale"]
266+
)
267+
self.assertNotIn("collation", indexes["simple"])
268+
await self.db.test.drop_index("fieldname_1")
269+
indexes = await self.db.test.index_information()
270+
self.assertIn("japanese_version", indexes)
271+
self.assertIn("simple", indexes)
272+
self.assertNotIn("fieldname", indexes)
273+
274+
async def test_unacknowledged_write(self):
275+
unacknowledged = WriteConcern(w=0)
276+
collection = self.db.get_collection("test", write_concern=unacknowledged)
277+
with self.assertRaises(ConfigurationError):
278+
await collection.update_one(
279+
{"hello": "world"}, {"$set": {"hello": "moon"}}, collation=self.collation
280+
)
281+
update_one = UpdateOne(
282+
{"hello": "world"}, {"$set": {"hello": "moon"}}, collation=self.collation
283+
)
284+
with self.assertRaises(ConfigurationError):
285+
await collection.bulk_write([update_one])
286+
287+
async def test_cursor_collation(self):
288+
await self.db.test.insert_one({"hello": "world"})
289+
await anext(self.db.test.find().collation(self.collation))
290+
self.assertCollationInLastCommand()

test/test_collation.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,11 @@
3737
UpdateMany,
3838
UpdateOne,
3939
)
40+
from pymongo.synchronous.helpers import next
4041
from pymongo.write_concern import WriteConcern
4142

43+
_IS_SYNC = True
44+
4245

4346
class TestCollationObject(unittest.TestCase):
4447
def test_constructor(self):
@@ -96,8 +99,8 @@ class TestCollation(IntegrationTest):
9699

97100
@classmethod
98101
@client_context.require_connection
99-
def setUpClass(cls):
100-
super().setUpClass()
102+
def _setup_class(cls):
103+
super()._setup_class()
101104
cls.listener = EventListener()
102105
cls.client = cls.unmanaged_rs_or_single_client(event_listeners=[cls.listener])
103106
cls.db = cls.client.pymongo_test
@@ -107,11 +110,11 @@ def setUpClass(cls):
107110
warnings.simplefilter("ignore", DeprecationWarning)
108111

109112
@classmethod
110-
def tearDownClass(cls):
113+
def _tearDown_class(cls):
111114
cls.warn_context.__exit__()
112115
cls.warn_context = None
113116
cls.client.close()
114-
super().tearDownClass()
117+
super()._tearDown_class()
115118

116119
def tearDown(self):
117120
self.listener.reset()

tools/synchro.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ def async_only_test(f: str) -> bool:
188188
"test_client.py",
189189
"test_client_bulk_write.py",
190190
"test_client_context.py",
191+
"test_collation.py",
191192
"test_collection.py",
192193
"test_common.py",
193194
"test_connections_survive_primary_stepdown_spec.py",

0 commit comments

Comments
 (0)