diff --git a/elasticsearch/client/__init__.py b/elasticsearch/client/__init__.py index f0930c31..e966d5aa 100644 --- a/elasticsearch/client/__init__.py +++ b/elasticsearch/client/__init__.py @@ -79,6 +79,18 @@ class Elasticsearch(object): self.indices = IndicesClient(weakref.proxy(self)) self.cluster = ClusterClient(weakref.proxy(self)) + def __repr__(self): + try: + # get a lost of all connections + cons = self.transport.hosts + # truncate to 10 if there are too many + if len(cons) > 5: + cons = cons[:5] + ['...'] + return '' % cons + except: + # probably operating on custom transport and connection_pool, ignore + return super(Elasticsearch, self).__repr__() + def _bulk_body(self, body): # if not passed in a string, serialize items and join by newline if not isinstance(body, (type(''), type(u''))): diff --git a/test_elasticsearch/test_cases.py b/test_elasticsearch/test_cases.py index 1baa3db9..43550e5c 100644 --- a/test_elasticsearch/test_cases.py +++ b/test_elasticsearch/test_cases.py @@ -9,6 +9,7 @@ from elasticsearch import Elasticsearch class DummyTransport(object): def __init__(self, hosts, responses=None, **kwargs): + self.hosts = hosts self.responses = responses self.call_count = 0 self.calls = defaultdict(list) diff --git a/test_elasticsearch/test_client/__init__.py b/test_elasticsearch/test_client/__init__.py index 9ffba6a8..f19e6ebe 100644 --- a/test_elasticsearch/test_client/__init__.py +++ b/test_elasticsearch/test_client/__init__.py @@ -1,6 +1,6 @@ from mock import patch -from elasticsearch.client import _normalize_hosts +from elasticsearch.client import _normalize_hosts, Elasticsearch from ..test_cases import TestCase, ElasticsearchTestCase @@ -41,3 +41,19 @@ class TestClient(ElasticsearchTestCase): self.client.search(index='i', doc_type='t', from_=10) calls = self.assert_url_called('GET', '/i/t/_search') self.assertEquals([({'from': '10'}, None)], calls) + + def test_repr_contains_hosts(self): + self.assertEquals('', repr(self.client)) + + def test_repr_contains_hosts_passed_in(self): + self.assertEquals( + '' % {"host": "es.org", "port": 123}, + repr(Elasticsearch(['es.org:123'])) + ) + + def test_repr_truncates_host_to_10(self): + hosts = [{"host": "es" + str(i)} for i in range(20)] + self.assertEquals( + '' % [{'host': 'es0'}, {'host': 'es1'}, {'host': 'es2'}, {'host': 'es3'}, {'host': 'es4'}, '...'], + repr(Elasticsearch(hosts)) + )