diff --git a/pymongo/mongo_client.py b/pymongo/mongo_client.py index 759ee7f0c..2c7f49c63 100644 --- a/pymongo/mongo_client.py +++ b/pymongo/mongo_client.py @@ -1346,10 +1346,11 @@ class MongoClient(common.BaseObject): member = self.__member - # We're disconnected, but can't risk taking the lock to reconnect - # if we're being called from Cursor.__del__, see PYTHON-799. + # We can't risk taking the lock to reconnect if we're being called + # from Cursor.__del__, see PYTHON-799. if not member: - raise AutoReconnect() + warnings.warn("not connected, couldn't close cursor") + return _, kill_cursors_msg = message.kill_cursors(cursor_ids) sock_info = self.__socket(member) diff --git a/test/test_client.py b/test/test_client.py index 1baf592b1..f370be28c 100644 --- a/test/test_client.py +++ b/test/test_client.py @@ -937,6 +937,28 @@ with client.start_request() as request: client = get_client(_connect=False) client.pymongo_test.test.remove(w=0) + def test_kill_cursors_warning(self): + # If kill_cursors is called while the client is disconnected, it + # can't risk taking the lock to reconnect, in case it's being called + # from Cursor.__del__, see PYTHON-799. Test that it shows a warning + # in this case. + client = MongoClient(host, port) + collection = client.pymongo_test.test + collection.insert({} for _ in range(4)) + cursor = collection.find().batch_size(1) + next(cursor) + client.disconnect() + ctx = catch_warnings() + try: + warnings.simplefilter("error", UserWarning) + self.assertRaises(UserWarning, cursor.close) + finally: + ctx.exit() + + # Reconnect. + collection.find_one() + cursor.close() + class TestClientLazyConnect(unittest.TestCase, _TestLazyConnectMixin): def _get_client(self, **kwargs):