Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock elastic search python?

I need to mock elasticsearch calls, but I am not sure how to mock them in my python unit tests. I saw this framework called ElasticMock. I tried using it the way indicated in the documentation and it gave me plenty of errors. It is here : https://github.com/vrcmarcos/elasticmock

My question is, is there any other way to mock elastic search calls?

This doesn't seem to have an answer either: Mock elastic search data. And this just indicates to actually do integration tests rather than unit tests, which is not what I want: Unit testing elastic search inside Django app.

Can anyone point me in the right direction? I have never mocked things with ElasticSearch.

like image 750
LoveMeow Avatar asked Feb 14 '18 13:02

LoveMeow


People also ask

How do you mock in Elasticsearch?

The best way to mock Elasticsearch with the official clients is to replace the Connection component since it has very few responsibilities and it does not interact with other internal components other than getting requests and returning responses.

What is elastic search in Python?

What is ElasticSearch? ElasticSearch (ES) is a distributed and highly available open-source search engine that is built on top of Apache Lucene. It's an open-source which is built in Java thus available for many platforms. You store unstructured data in JSON format which also makes it a NoSQL database.

What is elastic search in testing?

Elasticsearch provides a jar file, which can be added to any java IDE and can be used to test the code which is related to Elasticsearch. A range of tests can be performed by using the framework provided by Elasticsearch. In this chapter, we will discuss these tests in detail − Unit testing. Integration testing.


2 Answers

After looking at the decorator source code, the trick for me was to reference Elasticsearch with the module:

import elasticsearch
...
elasticsearch.Elasticsearch(...

instead of

from elasticsearch import Elasticsearch
...
Elasticsearch(...
like image 171
Javi Carnero Avatar answered Oct 14 '22 10:10

Javi Carnero


You have to mock the attr or method you need, for example:

import mock

with mock.patch("elasticsearch.Elasticsearch.search") as mocked_search, \
                mock.patch("elasticsearch.client.IndicesClient.create") as mocked_index_create:

            mocked_search.return_value = "pipopapu"
            mocked_index_create.return_value = {"acknowledged": True}

In order to know the path you need to mock, just explore the lib with your IDE. When you already know one you can easily find the others.

like image 23
xpeiro Avatar answered Oct 14 '22 09:10

xpeiro