File: test_collation.py

package info (click to toggle)
pymongo 4.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 23,676 kB
  • sloc: python: 107,763; ansic: 4,597; javascript: 137; makefile: 38; sh: 18
file content (283 lines) | stat: -rw-r--r-- 10,964 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# Copyright 2016-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Test the collation module."""
from __future__ import annotations

import functools
import warnings
from test import IntegrationTest, client_context, unittest
from test.utils_shared import EventListener, OvertCommandListener
from typing import Any

from pymongo.collation import (
    Collation,
    CollationAlternate,
    CollationCaseFirst,
    CollationMaxVariable,
    CollationStrength,
)
from pymongo.errors import ConfigurationError
from pymongo.operations import (
    DeleteMany,
    DeleteOne,
    IndexModel,
    ReplaceOne,
    UpdateMany,
    UpdateOne,
)
from pymongo.synchronous.helpers import next
from pymongo.write_concern import WriteConcern

_IS_SYNC = True


class TestCollationObject(unittest.TestCase):
    def test_constructor(self):
        self.assertRaises(TypeError, Collation, locale=42)
        # Fill in a locale to test the other options.
        _Collation = functools.partial(Collation, "en_US")
        # No error.
        _Collation(caseFirst=CollationCaseFirst.UPPER)
        self.assertRaises(TypeError, _Collation, caseLevel="true")
        self.assertRaises(ValueError, _Collation, strength="six")
        self.assertRaises(TypeError, _Collation, numericOrdering="true")
        self.assertRaises(TypeError, _Collation, alternate=5)
        self.assertRaises(TypeError, _Collation, maxVariable=2)
        self.assertRaises(TypeError, _Collation, normalization="false")
        self.assertRaises(TypeError, _Collation, backwards="true")

        # No errors.
        Collation("en_US", future_option="bar", another_option=42)
        collation = Collation(
            "en_US",
            caseLevel=True,
            caseFirst=CollationCaseFirst.UPPER,
            strength=CollationStrength.QUATERNARY,
            numericOrdering=True,
            alternate=CollationAlternate.SHIFTED,
            maxVariable=CollationMaxVariable.SPACE,
            normalization=True,
            backwards=True,
        )

        self.assertEqual(
            {
                "locale": "en_US",
                "caseLevel": True,
                "caseFirst": "upper",
                "strength": 4,
                "numericOrdering": True,
                "alternate": "shifted",
                "maxVariable": "space",
                "normalization": True,
                "backwards": True,
            },
            collation.document,
        )

        self.assertEqual(
            {"locale": "en_US", "backwards": True}, Collation("en_US", backwards=True).document
        )


class TestCollation(IntegrationTest):
    listener: EventListener
    warn_context: Any
    collation: Collation

    @client_context.require_connection
    def setUp(self) -> None:
        super().setUp()
        self.listener = OvertCommandListener()
        self.client = self.rs_or_single_client(event_listeners=[self.listener])
        self.db = self.client.pymongo_test
        self.collation = Collation("en_US")
        self.warn_context = warnings.catch_warnings()
        self.warn_context.__enter__()

    def tearDown(self) -> None:
        self.warn_context.__exit__()
        self.warn_context = None
        self.listener.reset()
        super().tearDown()

    def last_command_started(self):
        return self.listener.started_events[-1].command

    def assertCollationInLastCommand(self):
        self.assertEqual(self.collation.document, self.last_command_started()["collation"])

    def test_create_collection(self):
        self.db.test.drop()
        self.db.create_collection("test", collation=self.collation)
        self.assertCollationInLastCommand()

        # Test passing collation as a dict as well.
        self.db.test.drop()
        self.listener.reset()
        self.db.create_collection("test", collation=self.collation.document)
        self.assertCollationInLastCommand()

    def test_index_model(self):
        model = IndexModel([("a", 1), ("b", -1)], collation=self.collation)
        self.assertEqual(self.collation.document, model.document["collation"])

    def test_create_index(self):
        self.db.test.create_index("foo", collation=self.collation)
        ci_cmd = self.listener.started_events[0].command
        self.assertEqual(self.collation.document, ci_cmd["indexes"][0]["collation"])

    def test_aggregate(self):
        self.db.test.aggregate([{"$group": {"_id": 42}}], collation=self.collation)
        self.assertCollationInLastCommand()

    def test_count_documents(self):
        self.db.test.count_documents({}, collation=self.collation)
        self.assertCollationInLastCommand()

    def test_distinct(self):
        self.db.test.distinct("foo", collation=self.collation)
        self.assertCollationInLastCommand()

        self.listener.reset()
        self.db.test.find(collation=self.collation).distinct("foo")
        self.assertCollationInLastCommand()

    def test_find_command(self):
        self.db.test.insert_one({"is this thing on?": True})
        self.listener.reset()
        next(self.db.test.find(collation=self.collation))
        self.assertCollationInLastCommand()

    def test_explain_command(self):
        self.listener.reset()
        self.db.test.find(collation=self.collation).explain()
        # The collation should be part of the explained command.
        self.assertEqual(
            self.collation.document, self.last_command_started()["explain"]["collation"]
        )

    def test_delete(self):
        self.db.test.delete_one({"foo": 42}, collation=self.collation)
        command = self.listener.started_events[0].command
        self.assertEqual(self.collation.document, command["deletes"][0]["collation"])

        self.listener.reset()
        self.db.test.delete_many({"foo": 42}, collation=self.collation)
        command = self.listener.started_events[0].command
        self.assertEqual(self.collation.document, command["deletes"][0]["collation"])

    def test_update(self):
        self.db.test.replace_one({"foo": 42}, {"foo": 43}, collation=self.collation)
        command = self.listener.started_events[0].command
        self.assertEqual(self.collation.document, command["updates"][0]["collation"])

        self.listener.reset()
        self.db.test.update_one({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation)
        command = self.listener.started_events[0].command
        self.assertEqual(self.collation.document, command["updates"][0]["collation"])

        self.listener.reset()
        self.db.test.update_many({"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation)
        command = self.listener.started_events[0].command
        self.assertEqual(self.collation.document, command["updates"][0]["collation"])

    def test_find_and(self):
        self.db.test.find_one_and_delete({"foo": 42}, collation=self.collation)
        self.assertCollationInLastCommand()

        self.listener.reset()
        self.db.test.find_one_and_update(
            {"foo": 42}, {"$set": {"foo": 43}}, collation=self.collation
        )
        self.assertCollationInLastCommand()

        self.listener.reset()
        self.db.test.find_one_and_replace({"foo": 42}, {"foo": 43}, collation=self.collation)
        self.assertCollationInLastCommand()

    def test_bulk_write(self):
        self.db.test.collection.bulk_write(
            [
                DeleteOne({"noCollation": 42}),
                DeleteMany({"noCollation": 42}),
                DeleteOne({"foo": 42}, collation=self.collation),
                DeleteMany({"foo": 42}, collation=self.collation),
                ReplaceOne({"noCollation": 24}, {"bar": 42}),
                UpdateOne({"noCollation": 84}, {"$set": {"bar": 10}}, upsert=True),
                UpdateMany({"noCollation": 45}, {"$set": {"bar": 42}}),
                ReplaceOne({"foo": 24}, {"foo": 42}, collation=self.collation),
                UpdateOne(
                    {"foo": 84}, {"$set": {"foo": 10}}, upsert=True, collation=self.collation
                ),
                UpdateMany({"foo": 45}, {"$set": {"foo": 42}}, collation=self.collation),
            ]
        )

        delete_cmd = self.listener.started_events[0].command
        update_cmd = self.listener.started_events[1].command

        def check_ops(ops):
            for op in ops:
                if "noCollation" in op["q"]:
                    self.assertNotIn("collation", op)
                else:
                    self.assertEqual(self.collation.document, op["collation"])

        check_ops(delete_cmd["deletes"])
        check_ops(update_cmd["updates"])

    def test_indexes_same_keys_different_collations(self):
        self.db.test.drop()
        usa_collation = Collation("en_US")
        ja_collation = Collation("ja")
        self.db.test.create_indexes(
            [
                IndexModel("fieldname", collation=usa_collation),
                IndexModel("fieldname", name="japanese_version", collation=ja_collation),
                IndexModel("fieldname", name="simple"),
            ]
        )
        indexes = self.db.test.index_information()
        self.assertEqual(
            usa_collation.document["locale"], indexes["fieldname_1"]["collation"]["locale"]
        )
        self.assertEqual(
            ja_collation.document["locale"], indexes["japanese_version"]["collation"]["locale"]
        )
        self.assertNotIn("collation", indexes["simple"])
        self.db.test.drop_index("fieldname_1")
        indexes = self.db.test.index_information()
        self.assertIn("japanese_version", indexes)
        self.assertIn("simple", indexes)
        self.assertNotIn("fieldname", indexes)

    def test_unacknowledged_write(self):
        unacknowledged = WriteConcern(w=0)
        collection = self.db.get_collection("test", write_concern=unacknowledged)
        with self.assertRaises(ConfigurationError):
            collection.update_one(
                {"hello": "world"}, {"$set": {"hello": "moon"}}, collation=self.collation
            )
        update_one = UpdateOne(
            {"hello": "world"}, {"$set": {"hello": "moon"}}, collation=self.collation
        )
        with self.assertRaises(ConfigurationError):
            collection.bulk_write([update_one])

    def test_cursor_collation(self):
        self.db.test.insert_one({"hello": "world"})
        next(self.db.test.find().collation(self.collation))
        self.assertCollationInLastCommand()