Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Switch to all the shorter nose assert helpers and the nose collector.

We'll be able to support non-class-based tests now.
  • Loading branch information...
commit 64813160a84d5501e471559ddf95bd85d8385a90 1 parent 04cabbe
@erikrose erikrose authored
Showing with 68 additions and 67 deletions.
  1. +67 −66 pyelasticsearch/tests.py
  2. +1 −1  setup.py
View
133 pyelasticsearch/tests.py
@@ -9,6 +9,7 @@
from mock import patch
from nose import SkipTest
+from nose.tools import eq_, ok_, assert_raises, assert_not_equal
import requests
import six
@@ -36,7 +37,7 @@ def tearDown(self):
def assert_result_contains(self, result, expected):
for (key, value) in expected.items():
- self.assertEquals(value, result[key])
+ eq_(value, result[key])
class IndexingTestCase(ElasticSearchTestCase):
@@ -56,7 +57,7 @@ def test_indexing_without_id(self):
result = self.conn.index('test-index', 'test-type', {'name': 'Joe Tester'})
self.assert_result_contains(result, {'_type': 'test-type', 'ok': True, '_index': 'test-index'})
# should have an id of some value assigned.
- self.assertTrue('_id' in result and result['_id'])
+ ok_('_id' in result and result['_id'])
def test_explicit_index_create(self):
result = self.conn.create_index('test-index')
@@ -78,8 +79,8 @@ def test_open_index(self):
def test_get_settings(self):
self.conn.create_index('test-index')
result = self.conn.get_settings('test-index')
- self.assertTrue('test-index'in result)
- self.assertTrue('settings' in result['test-index'])
+ ok_('test-index' in result)
+ ok_('settings' in result['test-index'])
def test_update_settings(self):
"""Make sure ``update_settings()`` sends the expected request."""
@@ -110,7 +111,7 @@ def test_health(self):
def test_cluster_state(self):
result = self.conn.cluster_state(filter_routing_table=True)
- self.assertTrue('nodes' in result)
+ ok_('nodes' in result)
self.assertFalse('routing_table' in result)
def test_delete_by_id(self):
@@ -128,9 +129,9 @@ def test_delete_by_0_id(self):
def test_delete_by_id_without_id(self):
self.conn.index('test-index', 'test-type', {'name': 'Joe Tester'}, id=1)
self.conn.refresh(['test-index'])
- self.assertRaises(
+ assert_raises(
ValueError, self.conn.delete, 'test-index', 'test-type', '')
- self.assertRaises(
+ assert_raises(
ValueError, self.conn.delete, 'test-index', 'test-type', None)
def test_delete_by_doc_type(self):
@@ -165,16 +166,16 @@ def test_delete_nonexistent_index(self):
"""
Deleting a nonexistent index should raise ElasticHttpNotFoundError.
"""
- self.assertRaises(ElasticHttpNotFoundError,
+ assert_raises(ElasticHttpNotFoundError,
self.conn.delete_index,
'nonexistent-index')
def test_cannot_create_existing_index(self):
self.conn.create_index('another-index')
- self.assertRaises(
+ assert_raises(
IndexAlreadyExistsError, self.conn.create_index, 'another-index')
self.conn.delete_index('another-index')
- self.assertRaises(ElasticHttpError, self.conn.delete_index, 'another-index')
+ assert_raises(ElasticHttpError, self.conn.delete_index, 'another-index')
def test_put_mapping(self):
result = self.conn.create_index('test-index')
@@ -187,13 +188,13 @@ def test_get_mapping(self):
self.conn.put_mapping('test-index', 'test-type', mapping)
result = self.conn.get_mapping(index=['test-index'], doc_type=['test-type'])
- self.assertEqual(result, mapping)
+ eq_(result, mapping)
def test_index_status(self):
self.conn.create_index('another-index')
result = self.conn.status('another-index')
self.conn.delete_index('another-index')
- self.assertTrue('indices' in result)
+ ok_('indices' in result)
self.assert_result_contains(result, {'ok': True})
def test_index_flush(self):
@@ -216,30 +217,30 @@ def test_index_optimize(self):
def test_bulk_index(self):
# Try counting the docs in a nonexistent index:
- self.assertRaises(ElasticHttpError, self.conn.count, '*:*', index=['test-index'])
+ assert_raises(ElasticHttpError, self.conn.count, '*:*', index=['test-index'])
docs = [
{'name': 'Joe Tester'},
{'name': 'Bill Baloney', 'id': 303},
]
result = self.conn.bulk_index('test-index', 'test-type', docs)
- self.assertEqual(len(result['items']), 2)
- self.assertEqual(result['items'][0]['create']['ok'], True)
- self.assertEqual(result['items'][1]['index']['ok'], True)
- self.assertEqual(result['items'][1]['index']['_id'], '303')
+ eq_(len(result['items']), 2)
+ eq_(result['items'][0]['create']['ok'], True)
+ eq_(result['items'][1]['index']['ok'], True)
+ eq_(result['items'][1]['index']['_id'], '303')
self.conn.refresh()
- self.assertEqual(self.conn.count('*:*',
+ eq_(self.conn.count('*:*',
index=['test-index'])['count'], 2)
def test_error_handling(self):
# Wrong port.
conn = ElasticSearch('http://localhost:1009200/')
- self.assertRaises(ConnectionError, conn.count, '*:*')
+ assert_raises(ConnectionError, conn.count, '*:*')
# Test invalid JSON.
resp = requests.Response()
resp._content = six.b('{"busted" "json" "that": ["is] " wrong')
- self.assertRaises(InvalidJsonResponseError, conn._decode_response, resp)
+ assert_raises(InvalidJsonResponseError, conn._decode_response, resp)
def test_update(self):
"""Smoke-test the ``update()`` API."""
@@ -274,7 +275,7 @@ def test_alias_nonexistent_index(self):
{"add": {"index": "test1", "alias": "alias1"}}
]
}
- self.assertRaises(ElasticHttpNotFoundError,
+ assert_raises(ElasticHttpNotFoundError,
self.conn.update_aliases,
settings)
@@ -287,12 +288,12 @@ def test_list_aliases(self):
}
self.conn.update_aliases(settings)
result = self.conn.aliases('test-index')
- self.assertEqual(result, {u'test-index': {u'aliases': {u'test-alias': {}}}})
+ eq_(result, {u'test-index': {u'aliases': {u'test-alias': {}}}})
def test_empty_path_segments(self):
"""'' segments passed to ``_join_path`` should be omitted."""
# Call _join_path like get_mapping might if called with no params:
- self.assertEqual(self.conn._join_path(['', '', '_mapping']),
+ eq_(self.conn._join_path(['', '', '_mapping']),
'/_mapping')
def test_0_path_segments(self):
@@ -301,7 +302,7 @@ def test_0_path_segments(self):
This is so doc IDs that are 0 work.
"""
- self.assertEqual(self.conn._join_path([0, '_mapping']),
+ eq_(self.conn._join_path([0, '_mapping']),
'/0/_mapping')
@@ -368,7 +369,7 @@ def test_search_by_dsl(self):
},
}
result = self.conn.search(query, index=['test-index'], doc_type=['test-type'])
- self.assertTrue(result.get('hits').get('hits').__len__() > 0, str(result))
+ ok_(result.get('hits').get('hits').__len__() > 0, str(result))
def test_mlt(self):
self.conn.index('test-index', 'test-type', {'name': 'Joe Test'}, id=3)
@@ -428,7 +429,7 @@ def delete_index_no_args(self):
"""
``delete_index()`` should raise ValueError if no indexes are given.
"""
- self.assertRaises(ValueError, self.conn.delete_index, [])
+ assert_raises(ValueError, self.conn.delete_index, [])
def test_delete_all_indexes(self):
"""Make sure ``delete_all_indexes()`` sends the right request."""
@@ -441,7 +442,7 @@ def update_settings_no_args(self):
``update_settings()`` should refuse to update *all* indexes when none
are given.
"""
- self.assertRaises(ValueError, self.conn.update_settings, [], {'b': 4})
+ assert_raises(ValueError, self.conn.update_settings, [], {'b': 4})
def update_all_settings(self):
"""Make sure ``update_all_settings()`` sends the right request."""
@@ -481,15 +482,15 @@ def get_but_fail_the_first_time(url, **kwargs):
conn.get('test-index', 'test-type', 7)
# Assert that one server was tried and then the other.
- self.assertEqual(session_get.call_count, 2)
+ eq_(session_get.call_count, 2)
calls = session_get.call_args_list
down_server = calls[0][0]
- self.assertNotEqual(calls[1][0], down_server)
+ assert_not_equal(calls[1][0], down_server)
# Assert there's one item in the live pool and one in the dead.
# That oughta cover a fair amount.
- self.assertEqual(len(conn.servers.live), 1)
- self.assertEqual(len(conn.servers.dead), 1)
+ eq_(len(conn.servers.live), 1)
+ eq_(len(conn.servers.dead), 1)
def test_death_and_rebirth(self):
"""
@@ -515,8 +516,8 @@ def test_death_and_rebirth(self):
pass
# Make sure the pools are as we expect:
- self.assertEquals(len(conn.servers.dead), 2)
- self.assertEquals(len(conn.servers.live), 0)
+ eq_(len(conn.servers.dead), 2)
+ eq_(len(conn.servers.live), 0)
# And this should use a dead server, though the request will still
# time out:
@@ -534,8 +535,8 @@ def test_death_and_rebirth(self):
conn.get('test-index', 'test-type', 7)
# Then that server should have come back to life:
- self.assertEquals(len(conn.servers.dead), 1)
- self.assertEquals(len(conn.servers.live), 1)
+ eq_(len(conn.servers.dead), 1)
+ eq_(len(conn.servers.live), 1)
class KwargsForQueryTests(unittest.TestCase):
@@ -544,19 +545,19 @@ class KwargsForQueryTests(unittest.TestCase):
def test_to_query(self):
"""Test the thing that translates objects to query string text."""
to_query = ElasticSearch._to_query
- self.assertEqual(to_query(4), '4')
- self.assertEqual(to_query(4.5), '4.5')
- self.assertEqual(to_query(True), 'true')
- self.assertEqual(to_query(('4', 'hi', 'thomas')), '4,hi,thomas')
- self.assertEqual(to_query(datetime(2000, 1, 2, 12, 34, 56)),
+ eq_(to_query(4), '4')
+ eq_(to_query(4.5), '4.5')
+ eq_(to_query(True), 'true')
+ eq_(to_query(('4', 'hi', 'thomas')), '4,hi,thomas')
+ eq_(to_query(datetime(2000, 1, 2, 12, 34, 56)),
'2000-01-02T12:34:56')
- self.assertEqual(to_query(date(2000, 1, 2)),
+ eq_(to_query(date(2000, 1, 2)),
'2000-01-02T00:00:00')
- self.assertRaises(TypeError, to_query, object())
+ assert_raises(TypeError, to_query, object())
# do not use unittest.skipIf because of python 2.6
if not six.PY3:
- self.assertEqual(to_query(long(4)), '4')
+ eq_(to_query(long(4)), '4')
def test_es_kwargs(self):
@@ -573,9 +574,9 @@ def index(doc, query_params=None, other_kwarg=None):
"""
return doc, query_params, other_kwarg
- self.assertEqual(index(3, refresh=True, es_timeout=7, other_kwarg=1),
+ eq_(index(3, refresh=True, es_timeout=7, other_kwarg=1),
(3, {'refresh': True, 'timeout': 7}, 1))
- self.assertEqual(index.__name__, 'index')
+ eq_(index.__name__, 'index')
def test_index(self):
"""Integration-test ``index()`` with some decorator-handled arg."""
@@ -599,12 +600,12 @@ def valid_responder(*args, **kwargs):
# Make sure all the query string params got into the URL:
url = put.call_args[0][0]
- self.assertTrue(
+ ok_(
url.startswith('http://example.com:9200/some_index/some_type/3?'))
- self.assertTrue('routing=boogie' in url)
- self.assertTrue('snorkfest=true' in url)
- self.assertTrue('borkfest=gerbils%3Agreat' in url)
- self.assertTrue('es_' not in url) # We stripped the "es_" prefixes.
+ ok_('routing=boogie' in url)
+ ok_('snorkfest=true' in url)
+ ok_('borkfest=gerbils%3Agreat' in url)
+ ok_('es_' not in url) # We stripped the "es_" prefixes.
def test_arg_cross_refs_with_trailing(self):
"""
@@ -628,7 +629,7 @@ def some_method(foo, bar, query_params=None):
# Make sure it adds (only) the undocumented args and preserves anything
# that comes after the args block:
- self.assertEqual(
+ eq_(
some_method.__doc__,
"""
Do stuff.
@@ -656,7 +657,7 @@ def some_method(foo, bar, query_params=None):
if some_method.__doc__ is None:
raise SkipTest("This test doesn't work under python -OO.")
- self.assertEqual(
+ eq_(
some_method.__doc__,
"""
Do stuff.
@@ -674,40 +675,40 @@ def test_decimal_encoding(self):
up with quotes around them, which would suggest to ES to represent them
as strings if inferring a mapping."""
ones = '1.111111111111111111'
- self.assertEqual(self.conn._encode_json({'hi': Decimal(ones)}),
+ eq_(self.conn._encode_json({'hi': Decimal(ones)}),
'{"hi": %s}' % ones)
def test_set_encoding(self):
"""Make sure encountering a set doesn't raise a circular reference
error."""
- self.assertEqual(self.conn._encode_json({'hi': set([1])}),
+ eq_(self.conn._encode_json({'hi': set([1])}),
'{"hi": [1]}')
def test_tuple_encoding(self):
"""Make sure tuples encode as lists."""
- self.assertEqual(self.conn._encode_json({'hi': (1, 2, 3)}),
+ eq_(self.conn._encode_json({'hi': (1, 2, 3)}),
'{"hi": [1, 2, 3]}')
def test_unhandled_encoding(self):
"""Make sure we raise a TypeError when encoding an unsupported type."""
- self.assertRaises(TypeError, self.conn._encode_json, object())
+ assert_raises(TypeError, self.conn._encode_json, object())
def test_encoding(self):
"""Test encoding a zillion other types."""
- self.assertEqual(self.conn._encode_json('abc'), u'"abc"')
- self.assertEqual(self.conn._encode_json(u''), r'"\u2603"')
- self.assertEqual(self.conn._encode_json(123), '123')
- self.assertEqual(self.conn._encode_json(12.25), '12.25')
- self.assertEqual(self.conn._encode_json(True), 'true')
- self.assertEqual(self.conn._encode_json(False), 'false')
- self.assertEqual(self.conn._encode_json(
+ eq_(self.conn._encode_json('abc'), u'"abc"')
+ eq_(self.conn._encode_json(u''), r'"\u2603"')
+ eq_(self.conn._encode_json(123), '123')
+ eq_(self.conn._encode_json(12.25), '12.25')
+ eq_(self.conn._encode_json(True), 'true')
+ eq_(self.conn._encode_json(False), 'false')
+ eq_(self.conn._encode_json(
date(2011, 12, 30)),
'"2011-12-30T00:00:00"')
- self.assertEqual(self.conn._encode_json(
+ eq_(self.conn._encode_json(
datetime(2011, 12, 30, 11, 59, 32)),
'"2011-12-30T11:59:32"')
- self.assertEqual(self.conn._encode_json([1, 2, 3]), '[1, 2, 3]')
- self.assertEqual(self.conn._encode_json({'a': 1}), '{"a": 1}')
+ eq_(self.conn._encode_json([1, 2, 3]), '[1, 2, 3]')
+ eq_(self.conn._encode_json({'a': 1}), '{"a": 1}')
if __name__ == '__main__':
View
2  setup.py
@@ -64,6 +64,6 @@ def find_version(file_path):
'six'
],
tests_require=['mock', 'nose>=1.2.1'],
- test_suite='pyelasticsearch.tests',
+ test_suite='nose.collector',
url='http://github.com/rhec/pyelasticsearch'
)
Please sign in to comment.
Something went wrong with that request. Please try again.