我有一个使用 Elasticsearch 的 Django 应用程序。我想要 100% 的代码测试覆盖率,所以我需要测试对 elasticsearch(在本地“安装”)的 API 调用。
所以我的问题是:模拟整个 elasticsearch 更好还是我应该运行 elasticserver 并检查结果?
IMO 最好模拟 elasticsearch 并只检查 python 代码(测试是否使用正确的参数调用了所有内容)。
最佳答案
您可以编写一些实际调用 elasticsearch 的基本集成测试,然后用单元测试覆盖 View 、模型等内部剩余的相关方法。通过这种方式,您无需模拟 elasticsearch 即可测试所有内容,并发现您不会以其他方式发现的可能错误/行为。
我们正在使用 django haystack ( https://github.com/django-haystack/django-haystack ),它为包括 elasticsearch 在内的搜索后端提供了一个统一的 API 以及以下管理命令:
- build_solr_schema
- clear_index
- 干草堆信息
- 重建索引
- 更新索引
您可以将以上内容包装在您的基础集成测试类中以管理搜索索引。例如:
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
关于python - Django 应用程序中的单元测试 Elasticsearch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36128632/