Provide a minimum working example
jeromepin opened this issue · 3 comments
I'm very new to testing and I'm very quite a hard time getting started with elasticmock. Could you provide (either here or in the README) a small (but real) example how to use it ?
For now, I try to make it work with the following piece of code :
from unittest import TestCase
from elasticmock import elasticmock
from elasticmock import FakeElasticsearch
class TestClass(TestCase):
@elasticmock
def test_should_return_something_from_elasticsearch(self):
es = FakeElasticsearch()
self.assertTrue(es.indices.get(index="_all"))
(I'm aware indices.get
won't return a boolean, but that's not the point here)
Thank you very much anyway ! It looks like a wonderful lib !
First of all, you need to have a non-test code snippet that actually calls ES. Do you have it?
For example, if you have a prod code snippet like this one:
import elasticsearch
class FooService:
def __init__(self):
self.es = elasticsearch.Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}])
def create(self, index, body):
object = self.es.index(index, body)
return object.get('_id')
def read(self, index, id):
return self.es.get(index, id)
Than you should be able to test this class by mocking ES using the following test class:
from unittest import TestCase
from elasticmock import elasticmock
from foo.bar import FooService
class FooServiceTest(TestCase):
@elasticmock
def should_create_and_read_object(self):
# Variables used to test
index = 'test-index'
document = {
'foo': 'bar'
}
# Instantiate service
service = FooService()
# Index document on ElasticSearch
id = service.create(index, document)
self.assertIsNotNone(id)
# Retrive dpcument from ElasticSearch
object = service.read(index, id)
self.assertEquals(document, object.get('_source'))
If this example is not sufficient, please reopen this issue :)
I will add it to README as you suggested! Ty!
@jeromepin just added this example on README. TY for your suggestion!