Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a minimum working example #35

Closed
jeromepin opened this issue Feb 19, 2020 · 3 comments
Closed

Provide a minimum working example #35

jeromepin opened this issue Feb 19, 2020 · 3 comments

Comments

@jeromepin
Copy link

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 !

@vrcmarcos
Copy link
Owner

First of all, you need to have a non-test code snippet that actually calls ES. Do you have it?

@vrcmarcos
Copy link
Owner

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!

@vrcmarcos
Copy link
Owner

@jeromepin just added this example on README. TY for your suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants