单元测试Django app内的弹性搜索

kar*_*tan 10 python django unit-testing elasticsearch

我有一个使用弹性搜索的django应用程序.我想要100%的代码测试覆盖率,所以我需要测试对elasticsearch的API调用(在本地"安装").

所以我的问题是:模拟整个elasticsearch是否更好,还是应该运行elasticserver并检查结果?

IMO最好模拟elasticsearch并检查python代码(测试是否所有内容都使用正确的params调用).

fip*_*ips 3

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

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

  • 构建_solr_模式
  • 清除索引
  • 干草堆信息
  • 重建索引
  • 更新索引

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

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
Run Code Online (Sandbox Code Playgroud)