Unit testing elastic search inside a Django application

I have a django application that uses search in search mode. I want to have 100% code testing coverage, so I need to test the API calls for elasticsearch (which is "installed" locally).

So my question is: is it better to make fun of the entire elastics search or should I run elasticserver and check the results?

IMO It's best to mock elasticsearch and just check the python code (check if everything was called with the correct parameters).

+8
python django unit-testing elasticsearch
source share
1 answer

You can write some basic integration tests, which are actually called elasticsearch, and then cover the remaining related methods inside views, models, etc. with unit tests. This way you can test everything without having to mock elasticsearch and detect possible errors / behavior that you would not want.

We use django haystack ( https://github.com/django-haystack/django-haystack ), which provides a unified search api, including elasticsearch, as well as the following control commands:

  • build_solr_schema
  • clear_index
  • haystack_info
  • rebuild_index
  • update_index

You can wrap this in your base integration test class for managing search indexes. For example:.

from django.core.management import call_command from django.test import TestCase from model_mommy import mommy class IntegrationTestCase(TestCase): def rebuild_index(self): call_command('rebuild_index', verbosity=0, interactive=False) class IntegrationTestUsers(IntegrationTestCase): def test_search_users_in_elasticsearch(self): user = mommy.make(User, first_name='John', last_name='Smith') user = mommy.make(User, first_name='Andy', last_name='Smith') user = mommy.make(User, first_name='Jane', last_name='Smith') self.rebuild_index() # Search api and verify results eg /api/users/?last_name=smith 
+1
source share

All Articles