diff --git a/tests/resources/test_snippets.py b/tests/resources/test_snippets.py index ab1eca0..4d6cd17 100644 --- a/tests/resources/test_snippets.py +++ b/tests/resources/test_snippets.py @@ -46,7 +46,7 @@ class TestSnippets(metaclass=AIOTestMeta): async def test_get_no_snippets(self): app = create_app(self.conf) - await app['db'].snippets.drop() + await app['db'].snippets.remove() async with AIOTestApp(app) as testapp: resp = await testapp.get('/snippets') @@ -57,7 +57,7 @@ async def test_get_no_snippets(self): async def test_get_snippets(self): app = create_app(self.conf) - await app['db'].snippets.drop() + await app['db'].snippets.remove() await app['db'].snippets.insert(self.snippets) async with AIOTestApp(app) as testapp: @@ -69,7 +69,7 @@ async def test_get_snippets(self): async def test_post_snippet(self): app = create_app(self.conf) - await app['db'].snippets.drop() + await app['db'].snippets.remove() async with AIOTestApp(app) as testapp: snippet = copy.deepcopy(self.snippets[0]) @@ -91,3 +91,13 @@ async def test_post_snippet(self): ) assert snippet_resp == snippet_db + + async def test_data_model_indexes_exist(self): + app = create_app(self.conf) + + res = await app['db'].snippets.index_information() + + assert res['author_idx']['key'] == [('author_id', 1)] + assert res['tags_idx']['key'] == [('tags', 1)] + assert res['updated_idx']['key'] == [('updated_at', -1)] + assert res['created_idx']['key'] == [('created_at', -1)] diff --git a/xsnippet_api/database.py b/xsnippet_api/database.py index 1ab759d..fc7507a 100644 --- a/xsnippet_api/database.py +++ b/xsnippet_api/database.py @@ -13,6 +13,7 @@ from motor.motor_asyncio import AsyncIOMotorClient from pymongo.son_manipulator import SONManipulator +import pymongo def create_connection(conf, loop=None): @@ -44,6 +45,21 @@ def create_connection(conf, loop=None): # is doing this implicitly for us on application level. db.add_son_manipulator(_AutoincrementId()) + # ensure necessary indexes exist. background=True allows operations + # read/write operations on collections while indexes are being built + db.snippets.create_index('author_id', + name='author_idx', + background=True) + db.snippets.create_index('tags', + name='tags_idx', + background=True), + db.snippets.create_index([('created_at', pymongo.DESCENDING)], + name='created_idx', + background=True) + db.snippets.create_index([('updated_at', pymongo.DESCENDING)], + name='updated_idx', + background=True) + return db