在Django应用中进行单元测试弹性搜索 [英] Unit testing elastic search inside Django app

查看:79
本文介绍了在Django应用中进行单元测试弹性搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用弹性搜索的Django应用。我想拥有100%的代码测试覆盖率,因此我需要测试对Elasticsearch(在本地安装)的API调用。

I have a django app that uses elastic search. I want to have 100% code test coverage so I need to test API calls to elasticsearch (which is "installed" locally).

所以我的问题是这样吗?更好地模拟整个elasticsearch还是应该运行elasticserver并检查结果?

So my question is this: is it better to mock whole elasticsearch or should I run elasticserver and check the results?

IMO IMO更好地模拟elasticsearch并仅检查python代码(测试是否使用正确的参数。)

IMO It is better to mock elasticsearch and just check the python code (test if everything was called with the correct params).

推荐答案

您可以编写一些基本的集成测试,这些测试实际上是在调用Elasticsearch,然后覆盖视图中其余的相关方法,模型等以及单元测试。这样一来,您就可以测试所有内容,而无需模拟elasticsearch,并发现您可能不会遇到的可能的错误/行为。

You can write some basic integration tests that are actually calling elasticsearch and then cover remaining related methods inside views, models etc. with unit tests. This way you can test everything without having to mock elasticsearch, and discover possible errors/behavior that you wouldn't otherwise.

我们正在使用django haystack( https://github.com/django-haystack/django-haystack ),它提供了用于搜索的统一api后端,包括elasticsearch以及以下管理命令:

We are using django haystack (https://github.com/django-haystack/django-haystack) which provides a unified api for search backends including elasticsearch and also the following management commands:


  • build_solr_schema

  • clear_index

  • haystack_info

  • rebuild_index

  • update_index

  • build_solr_schema
  • clear_index
  • haystack_info
  • rebuild_index
  • update_index

您可以将以上内容包装在基本集成测试类中,以管理搜索索引。例如:

You can wrap the above inside your base integration test class to manage search indexes. E.g.:

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 e.g. /api/users/?last_name=smith

这篇关于在Django应用中进行单元测试弹性搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆