diff --git a/eventtracking/backends/mongodb.py b/eventtracking/backends/mongodb.py index 59d871e..1561feb 100644 --- a/eventtracking/backends/mongodb.py +++ b/eventtracking/backends/mongodb.py @@ -80,13 +80,20 @@ def _create_indexes(self): # TODO: The creation of indexes can be moved to a Django # management command or equivalent. There is also an option to # run the indexing on the background, without locking. - self.collection.create_index([('time', pymongo.DESCENDING)]) - self.collection.create_index('name') + if pymongo.version_tuple[0] == 3: + self.collection.ensure_index([('time', pymongo.DESCENDING)]) + self.collection.ensure_index('name') + else: + self.collection.create_index([('time', pymongo.DESCENDING)]) + self.collection.create_index('name') def send(self, event): """Insert the event in to the Mongo collection""" try: - self.collection.insert_one(event) + if pymongo.version_tuple[0] == 3: + self.collection.insert(event, manipulate=False) + else: + self.collection.insert_one(event) except (PyMongoError, BSONError): # The event will be lost in case of a connection error or any error # that occurs when trying to insert the event into Mongo. diff --git a/eventtracking/backends/tests/test_mongodb.py b/eventtracking/backends/tests/test_mongodb.py index f5602b6..d9e6ea7 100644 --- a/eventtracking/backends/tests/test_mongodb.py +++ b/eventtracking/backends/tests/test_mongodb.py @@ -4,6 +4,7 @@ from unittest.mock import patch from unittest.mock import sentinel +import pymongo from pymongo.errors import PyMongoError from bson.errors import BSONError @@ -28,8 +29,10 @@ def test_mongo_backend(self): self.backend.send(events[1]) # Check if we inserted events into the database - - calls = self.backend.collection.insert_one.mock_calls + if pymongo.version_tuple[0] == 3: + calls = self.backend.collection.insert.mock_calls + else: + calls = self.backend.collection.insert_one.mock_calls self.assertEqual(len(calls), 2) diff --git a/eventtracking/backends/tests/test_mongodb_integration.py b/eventtracking/backends/tests/test_mongodb_integration.py index e0f60ea..4cf80aa 100644 --- a/eventtracking/backends/tests/test_mongodb_integration.py +++ b/eventtracking/backends/tests/test_mongodb_integration.py @@ -7,6 +7,7 @@ from datetime import datetime from uuid import uuid4 +import pymongo from pytz import UTC from eventtracking.backends.mongodb import MongoBackend @@ -55,8 +56,13 @@ def test_sequential_events(self): mem_events[event['data']['sequence']] = event self.assertEqual(len(mem_events), 10) - cursor = self.mongo_backend.collection.find() - self.assertEqual(cursor.count_documents({}), 10) + if pymongo.version_tuple[0] == 3: + cursor = self.mongo_backend.collection.find() + self.assertEqual(cursor.count(), 10) + else: + collection = self.mongo_backend.collection + cursor = collection.find() + self.assertEqual(collection.count_documents({}), 10) for event in cursor: mem_event = mem_events[event['data']['sequence']]