Skip to content

Commit

Permalink
Add code example on README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
vrcmarcos committed Feb 19, 2020
1 parent 3bf2013 commit e14d124
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,58 @@ You can also disable all behaviours by calling `behaviour.disable_all()` (Consid
}
```

## Code example

Let's say you have a prod code snippet like this one:

```python
import elasticsearch

class FooService:

def __init__(self):
self.es = elasticsearch.Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}])

def create(self, index, body):
es_object = self.es.index(index, body)
return es_object.get('_id')

def read(self, index, id):
es_object = self.es.get(index, id)
return es_object.get('_source')

```

Than you should be able to test this class by mocking ElasticSearch using the following test class:

```python
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'
expected_document = {
'foo': 'bar'
}

# Instantiate service
service = FooService()

# Index document on ElasticSearch
id = service.create(index, expected_document)
self.assertIsNotNone(id)

# Retrive dpcument from ElasticSearch
document = service.read(index, id)
self.assertEquals(expected_document, document)

```

## Notes:

- The mocked **search** method returns **all available documents** indexed on the index with the requested document type.
Expand Down

0 comments on commit e14d124

Please sign in to comment.