How to mock elastic search python?
I'm going to give a very abstract answer because this applies to more than ES.
class ProductionCodeIWantToTest: def __init__(self): pass def do_something(data): es = ES() #or some database or whatever es.post(data) #or the right syntax
Now I can't test this.With one small change, injecting a dependency:
class ProductionCodeIWantToTest: def __init__(self, database): self.database = database def do_something(data): database.save(data) #or the right syntax
Now you can use the real db:
es = ES() #or some database or whateverthing = ProductionCodeIWantToTest(es)
or test it
mock = #... up to you - just needs a save method so farthing = ProductionCodeIWantToTest(mock)
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(...
You have to mock the attr or method you need, for example:
import mockwith 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.