Skip to content

Commit

Permalink
added(index): implements exists method
Browse files Browse the repository at this point in the history
Added a method to check if index exists
  • Loading branch information
chloelbn committed Aug 6, 2019
1 parent 97a6f15 commit 21a2601
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
11 changes: 10 additions & 1 deletion algoliasearch/search_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import Optional, List, Union, Iterator

from algoliasearch.configs import SearchConfig
from algoliasearch.exceptions import MissingObjectIdException
from algoliasearch.exceptions import RequestException, MissingObjectIdException
from algoliasearch.helpers import (
assert_object_id,
build_raw_response_batch,
Expand Down Expand Up @@ -45,6 +45,15 @@ def __init__(self, transporter, config, name):
self._config = config
self._name = name

def exists(self):
try:
self.get_settings()
except RequestException as e:
if (e.status_code == 404):
return False
raise e
return True

def save_object(self, obj, request_options=None):
# type: (dict, Optional[Union[dict, RequestOptions]]) -> IndexingResponse # noqa: E501

Expand Down
20 changes: 19 additions & 1 deletion tests/unit/test_search_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import mock

from algoliasearch.exceptions import MissingObjectIdException
from algoliasearch.exceptions import RequestException, MissingObjectIdException
from algoliasearch.http.request_options import RequestOptions
from algoliasearch.responses import Response
from algoliasearch.search_index import SearchIndex
Expand All @@ -29,6 +29,24 @@ def test_app_id_getter(self):
def test_name_getter(self):
self.assertEqual(self.index.name, 'index-name')

def test_index_does_not_exist(self):
with mock.patch.object(self.index, 'get_settings') as submethod_mock:
submethod_mock.side_effect = RequestException("Index does not exist", 404)

indexExists = self.index.exists()

self.index.get_settings.assert_called_once()
self.assertEqual(indexExists, False);

def test_index_exists(self):
with mock.patch.object(self.index, 'get_settings') as submethod_mock:
submethod_mock.return_value = {'hitsPerPage': 20, 'maxValuesPerFacet': 100}

indexExists = self.index.exists()

self.index.get_settings.assert_called_once()
self.assertEqual(indexExists, True);

def test_save_objects(self):
# Saving an object without object id
with self.assertRaises(MissingObjectIdException) as _:
Expand Down

0 comments on commit 21a2601

Please sign in to comment.