Skip to content

Commit 33163ec

Browse files
authored
PYTHON-4804 Migrate test_comment.py to async (mongodb#1887)
1 parent 4eeaa4b commit 33163ec

File tree

3 files changed

+179
-42
lines changed

3 files changed

+179
-42
lines changed

test/asynchronous/test_comment.py

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
# Copyright 2022-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 keyword argument 'comment' in various helpers."""
16+
17+
from __future__ import annotations
18+
19+
import inspect
20+
import sys
21+
22+
sys.path[0:0] = [""]
23+
from asyncio import iscoroutinefunction
24+
from test.asynchronous import AsyncIntegrationTest, async_client_context, unittest
25+
from test.utils import OvertCommandListener
26+
27+
from bson.dbref import DBRef
28+
from pymongo.asynchronous.command_cursor import AsyncCommandCursor
29+
from pymongo.operations import IndexModel
30+
31+
_IS_SYNC = False
32+
33+
34+
class AsyncTestComment(AsyncIntegrationTest):
35+
async def _test_ops(
36+
self,
37+
helpers,
38+
already_supported,
39+
listener,
40+
):
41+
for h, args in helpers:
42+
c = "testing comment with " + h.__name__
43+
with self.subTest("collection-" + h.__name__ + "-comment"):
44+
for cc in [c, {"key": c}, ["any", 1]]:
45+
listener.reset()
46+
kwargs = {"comment": cc}
47+
try:
48+
maybe_cursor = await h(*args, **kwargs)
49+
except Exception:
50+
maybe_cursor = None
51+
self.assertIn(
52+
"comment",
53+
inspect.signature(h).parameters,
54+
msg="Could not find 'comment' in the "
55+
"signature of function %s" % (h.__name__),
56+
)
57+
self.assertEqual(
58+
inspect.signature(h).parameters["comment"].annotation, "Optional[Any]"
59+
)
60+
if isinstance(maybe_cursor, AsyncCommandCursor):
61+
await maybe_cursor.close()
62+
63+
cmd = listener.started_events[0]
64+
self.assertEqual(cc, cmd.command.get("comment"), msg=cmd)
65+
66+
if h.__name__ != "aggregate_raw_batches":
67+
self.assertIn(
68+
":param comment:",
69+
h.__doc__,
70+
)
71+
if h not in already_supported:
72+
self.assertIn(
73+
"Added ``comment`` parameter",
74+
h.__doc__,
75+
)
76+
else:
77+
self.assertNotIn(
78+
"Added ``comment`` parameter",
79+
h.__doc__,
80+
)
81+
82+
listener.reset()
83+
84+
@async_client_context.require_version_min(4, 7, -1)
85+
@async_client_context.require_replica_set
86+
async def test_database_helpers(self):
87+
listener = OvertCommandListener()
88+
db = (await self.async_rs_or_single_client(event_listeners=[listener])).db
89+
helpers = [
90+
(db.watch, []),
91+
(db.command, ["hello"]),
92+
(db.list_collections, []),
93+
(db.list_collection_names, []),
94+
(db.drop_collection, ["hello"]),
95+
(db.validate_collection, ["test"]),
96+
(db.dereference, [DBRef("collection", 1)]),
97+
]
98+
already_supported = [db.command, db.list_collections, db.list_collection_names]
99+
await self._test_ops(helpers, already_supported, listener)
100+
101+
@async_client_context.require_version_min(4, 7, -1)
102+
@async_client_context.require_replica_set
103+
async def test_client_helpers(self):
104+
listener = OvertCommandListener()
105+
cli = await self.async_rs_or_single_client(event_listeners=[listener])
106+
helpers = [
107+
(cli.watch, []),
108+
(cli.list_databases, []),
109+
(cli.list_database_names, []),
110+
(cli.drop_database, ["test"]),
111+
]
112+
already_supported = [
113+
cli.list_databases,
114+
]
115+
await self._test_ops(helpers, already_supported, listener)
116+
117+
@async_client_context.require_version_min(4, 7, -1)
118+
async def test_collection_helpers(self):
119+
listener = OvertCommandListener()
120+
db = (await self.async_rs_or_single_client(event_listeners=[listener]))[self.db.name]
121+
coll = db.get_collection("test")
122+
123+
helpers = [
124+
(coll.list_indexes, []),
125+
(coll.drop, []),
126+
(coll.index_information, []),
127+
(coll.options, []),
128+
(coll.aggregate, [[{"$set": {"x": 1}}]]),
129+
(coll.aggregate_raw_batches, [[{"$set": {"x": 1}}]]),
130+
(coll.rename, ["temp_temp_temp"]),
131+
(coll.distinct, ["_id"]),
132+
(coll.find_one_and_delete, [{}]),
133+
(coll.find_one_and_replace, [{}, {}]),
134+
(coll.find_one_and_update, [{}, {"$set": {"a": 1}}]),
135+
(coll.estimated_document_count, []),
136+
(coll.count_documents, [{}]),
137+
(coll.create_indexes, [[IndexModel("a")]]),
138+
(coll.create_index, ["a"]),
139+
(coll.drop_index, [[("a", 1)]]),
140+
(coll.drop_indexes, []),
141+
]
142+
already_supported = [
143+
coll.estimated_document_count,
144+
coll.count_documents,
145+
coll.create_indexes,
146+
coll.drop_indexes,
147+
coll.options,
148+
coll.find_one_and_replace,
149+
coll.drop_index,
150+
coll.rename,
151+
coll.distinct,
152+
coll.find_one_and_delete,
153+
coll.find_one_and_update,
154+
]
155+
await self._test_ops(helpers, already_supported, listener)
156+
157+
158+
if __name__ == "__main__":
159+
unittest.main()

test/test_comment.py

Lines changed: 18 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,15 @@
2020
import sys
2121

2222
sys.path[0:0] = [""]
23-
23+
from asyncio import iscoroutinefunction
2424
from test import IntegrationTest, client_context, unittest
25-
from test.utils import EventListener
25+
from test.utils import OvertCommandListener
2626

2727
from bson.dbref import DBRef
2828
from pymongo.operations import IndexModel
2929
from pymongo.synchronous.command_cursor import CommandCursor
3030

31-
32-
class Empty:
33-
def __getattr__(self, item):
34-
try:
35-
self.__dict__[item]
36-
except KeyError:
37-
return self.empty
38-
39-
def empty(self, *args, **kwargs):
40-
return Empty()
31+
_IS_SYNC = True
4132

4233

4334
class TestComment(IntegrationTest):
@@ -46,28 +37,17 @@ def _test_ops(
4637
helpers,
4738
already_supported,
4839
listener,
49-
db=Empty(), # noqa: B008
50-
coll=Empty(), # noqa: B008
5140
):
5241
for h, args in helpers:
5342
c = "testing comment with " + h.__name__
5443
with self.subTest("collection-" + h.__name__ + "-comment"):
5544
for cc in [c, {"key": c}, ["any", 1]]:
5645
listener.reset()
5746
kwargs = {"comment": cc}
58-
if h == coll.rename:
59-
_ = db.get_collection("temp_temp_temp").drop()
60-
destruct_coll = db.get_collection("test_temp")
61-
destruct_coll.insert_one({})
62-
maybe_cursor = destruct_coll.rename(*args, **kwargs)
63-
destruct_coll.drop()
64-
elif h == db.validate_collection:
65-
coll = db.get_collection("test")
66-
coll.insert_one({})
67-
maybe_cursor = db.validate_collection(*args, **kwargs)
68-
else:
69-
coll.create_index("a")
47+
try:
7048
maybe_cursor = h(*args, **kwargs)
49+
except Exception:
50+
maybe_cursor = None
7151
self.assertIn(
7252
"comment",
7353
inspect.signature(h).parameters,
@@ -79,15 +59,11 @@ def _test_ops(
7959
)
8060
if isinstance(maybe_cursor, CommandCursor):
8161
maybe_cursor.close()
82-
tested = False
83-
# For some reason collection.list_indexes creates two commands and the first
84-
# one doesn't contain 'comment'.
85-
for i in listener.started_events:
86-
if cc == i.command.get("comment", ""):
87-
self.assertEqual(cc, i.command["comment"])
88-
tested = True
89-
self.assertTrue(tested)
90-
if h not in [coll.aggregate_raw_batches]:
62+
63+
cmd = listener.started_events[0]
64+
self.assertEqual(cc, cmd.command.get("comment"), msg=cmd)
65+
66+
if h.__name__ != "aggregate_raw_batches":
9167
self.assertIn(
9268
":param comment:",
9369
h.__doc__,
@@ -108,8 +84,8 @@ def _test_ops(
10884
@client_context.require_version_min(4, 7, -1)
10985
@client_context.require_replica_set
11086
def test_database_helpers(self):
111-
listener = EventListener()
112-
db = self.rs_or_single_client(event_listeners=[listener]).db
87+
listener = OvertCommandListener()
88+
db = (self.rs_or_single_client(event_listeners=[listener])).db
11389
helpers = [
11490
(db.watch, []),
11591
(db.command, ["hello"]),
@@ -120,12 +96,12 @@ def test_database_helpers(self):
12096
(db.dereference, [DBRef("collection", 1)]),
12197
]
12298
already_supported = [db.command, db.list_collections, db.list_collection_names]
123-
self._test_ops(helpers, already_supported, listener, db=db, coll=db.get_collection("test"))
99+
self._test_ops(helpers, already_supported, listener)
124100

125101
@client_context.require_version_min(4, 7, -1)
126102
@client_context.require_replica_set
127103
def test_client_helpers(self):
128-
listener = EventListener()
104+
listener = OvertCommandListener()
129105
cli = self.rs_or_single_client(event_listeners=[listener])
130106
helpers = [
131107
(cli.watch, []),
@@ -140,8 +116,8 @@ def test_client_helpers(self):
140116

141117
@client_context.require_version_min(4, 7, -1)
142118
def test_collection_helpers(self):
143-
listener = EventListener()
144-
db = self.rs_or_single_client(event_listeners=[listener])[self.db.name]
119+
listener = OvertCommandListener()
120+
db = (self.rs_or_single_client(event_listeners=[listener]))[self.db.name]
145121
coll = db.get_collection("test")
146122

147123
helpers = [
@@ -176,7 +152,7 @@ def test_collection_helpers(self):
176152
coll.find_one_and_delete,
177153
coll.find_one_and_update,
178154
]
179-
self._test_ops(helpers, already_supported, listener, coll=coll, db=db)
155+
self._test_ops(helpers, already_supported, listener)
180156

181157

182158
if __name__ == "__main__":

tools/synchro.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,9 @@ def async_only_test(f: str) -> bool:
193193
"test_collation.py",
194194
"test_collection.py",
195195
"test_command_logging.py",
196+
"test_command_logging.py",
196197
"test_command_monitoring.py",
198+
"test_comment.py",
197199
"test_common.py",
198200
"test_connection_logging.py",
199201
"test_connections_survive_primary_stepdown_spec.py",

0 commit comments

Comments
 (0)