Mocking elasticsearch-py calls Mocking elasticsearch-py calls elasticsearch elasticsearch

Mocking elasticsearch-py calls


You should be mocking with respect to where you are testing. Based on the example provided, this means that the Escli class you are using in the settings.py module needs to be mocked with respect to settings.py. So, more practically, your patch call would look like this inside setUp instead:

self.patcher = patch('escli.settings.Escli')

With this, you are now mocking what you want in the right place based on how your tests are running.

Furthermore, to add more robustness to your testing, you might want to consider speccing for the Elasticsearch instance you are creating in order to validate that you are in fact calling valid methods that correlate to Elasticsearch. With that in mind, you can do something like this, instead:

self.patcher = patch('escli.settings.Escli', Mock(Elasticsearch))

To read a bit more about what exactly is meant by spec, check the patch section in the documentation.

As a final note, if you are interested in exploring the great world of pytest, there is a pytest-elasticsearch plugin created to assist with this.