PageRenderTime 40ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/telemetry/third_party/gsutilz/third_party/boto/tests/unit/cloudsearch2/test_search.py

https://gitlab.com/jonnialva90/iridium-browser
Python | 387 lines | 313 code | 63 blank | 11 comment | 1 complexity | 03237892dcfa8e41fbf6d93605f70ee0 MD5 | raw file
  1. #!/usr/bin env python
  2. from boto.cloudsearch2.domain import Domain
  3. from boto.cloudsearch2.layer1 import CloudSearchConnection
  4. from tests.compat import mock, unittest
  5. from httpretty import HTTPretty
  6. import json
  7. from boto.cloudsearch2.search import SearchConnection, SearchServiceException
  8. from boto.compat import six, map
  9. from tests.unit import AWSMockServiceTestCase
  10. from tests.unit.cloudsearch2 import DEMO_DOMAIN_DATA
  11. from tests.unit.cloudsearch2.test_connection import TestCloudSearchCreateDomain
  12. HOSTNAME = "search-demo-userdomain.us-east-1.cloudsearch.amazonaws.com"
  13. FULL_URL = 'http://%s/2013-01-01/search' % HOSTNAME
  14. class CloudSearchSearchBaseTest(unittest.TestCase):
  15. hits = [
  16. {
  17. 'id': '12341',
  18. 'fields': {
  19. 'title': 'Document 1',
  20. 'rank': 1
  21. }
  22. },
  23. {
  24. 'id': '12342',
  25. 'fields': {
  26. 'title': 'Document 2',
  27. 'rank': 2
  28. }
  29. },
  30. {
  31. 'id': '12343',
  32. 'fields': {
  33. 'title': 'Document 3',
  34. 'rank': 3
  35. }
  36. },
  37. {
  38. 'id': '12344',
  39. 'fields': {
  40. 'title': 'Document 4',
  41. 'rank': 4
  42. }
  43. },
  44. {
  45. 'id': '12345',
  46. 'fields': {
  47. 'title': 'Document 5',
  48. 'rank': 5
  49. }
  50. },
  51. {
  52. 'id': '12346',
  53. 'fields': {
  54. 'title': 'Document 6',
  55. 'rank': 6
  56. }
  57. },
  58. {
  59. 'id': '12347',
  60. 'fields': {
  61. 'title': 'Document 7',
  62. 'rank': 7
  63. }
  64. },
  65. ]
  66. content_type = "text/xml"
  67. response_status = 200
  68. def get_args(self, requestline):
  69. (_, request, _) = requestline.split(b" ")
  70. (_, request) = request.split(b"?", 1)
  71. args = six.moves.urllib.parse.parse_qs(request)
  72. return args
  73. def setUp(self):
  74. HTTPretty.enable()
  75. body = self.response
  76. if not isinstance(body, bytes):
  77. body = json.dumps(body).encode('utf-8')
  78. HTTPretty.register_uri(HTTPretty.GET, FULL_URL,
  79. body=body,
  80. content_type=self.content_type,
  81. status=self.response_status)
  82. def tearDown(self):
  83. HTTPretty.disable()
  84. class CloudSearchSearchTest(CloudSearchSearchBaseTest):
  85. response = {
  86. 'rank': '-text_relevance',
  87. 'match-expr': "Test",
  88. 'hits': {
  89. 'found': 30,
  90. 'start': 0,
  91. 'hit': CloudSearchSearchBaseTest.hits
  92. },
  93. 'status': {
  94. 'rid': 'b7c167f6c2da6d93531b9a7b314ad030b3a74803b4b7797edb905ba5a6a08',
  95. 'time-ms': 2,
  96. 'cpu-time-ms': 0
  97. }
  98. }
  99. def test_cloudsearch_qsearch(self):
  100. search = SearchConnection(endpoint=HOSTNAME)
  101. search.search(q='Test', options='TestOptions')
  102. args = self.get_args(HTTPretty.last_request.raw_requestline)
  103. self.assertEqual(args[b'q'], [b"Test"])
  104. self.assertEqual(args[b'q.options'], [b"TestOptions"])
  105. self.assertEqual(args[b'start'], [b"0"])
  106. self.assertEqual(args[b'size'], [b"10"])
  107. def test_cloudsearch_search_details(self):
  108. search = SearchConnection(endpoint=HOSTNAME)
  109. search.search(q='Test', size=50, start=20)
  110. args = self.get_args(HTTPretty.last_request.raw_requestline)
  111. self.assertEqual(args[b'q'], [b"Test"])
  112. self.assertEqual(args[b'size'], [b"50"])
  113. self.assertEqual(args[b'start'], [b"20"])
  114. def test_cloudsearch_facet_constraint_single(self):
  115. search = SearchConnection(endpoint=HOSTNAME)
  116. search.search(
  117. q='Test',
  118. facet={'author': "'John Smith','Mark Smith'"})
  119. args = self.get_args(HTTPretty.last_request.raw_requestline)
  120. self.assertEqual(args[b'facet.author'],
  121. [b"'John Smith','Mark Smith'"])
  122. def test_cloudsearch_facet_constraint_multiple(self):
  123. search = SearchConnection(endpoint=HOSTNAME)
  124. search.search(
  125. q='Test',
  126. facet={'author': "'John Smith','Mark Smith'",
  127. 'category': "'News','Reviews'"})
  128. args = self.get_args(HTTPretty.last_request.raw_requestline)
  129. self.assertEqual(args[b'facet.author'],
  130. [b"'John Smith','Mark Smith'"])
  131. self.assertEqual(args[b'facet.category'],
  132. [b"'News','Reviews'"])
  133. def test_cloudsearch_facet_sort_single(self):
  134. search = SearchConnection(endpoint=HOSTNAME)
  135. search.search(q='Test', facet={'author': {'sort': 'alpha'}})
  136. args = self.get_args(HTTPretty.last_request.raw_requestline)
  137. print(args)
  138. self.assertEqual(args[b'facet.author'], [b'{"sort": "alpha"}'])
  139. def test_cloudsearch_facet_sort_multiple(self):
  140. search = SearchConnection(endpoint=HOSTNAME)
  141. search.search(q='Test', facet={'author': {'sort': 'alpha'},
  142. 'cat': {'sort': 'count'}})
  143. args = self.get_args(HTTPretty.last_request.raw_requestline)
  144. self.assertEqual(args[b'facet.author'], [b'{"sort": "alpha"}'])
  145. self.assertEqual(args[b'facet.cat'], [b'{"sort": "count"}'])
  146. def test_cloudsearch_result_fields_single(self):
  147. search = SearchConnection(endpoint=HOSTNAME)
  148. search.search(q='Test', return_fields=['author'])
  149. args = self.get_args(HTTPretty.last_request.raw_requestline)
  150. self.assertEqual(args[b'return'], [b'author'])
  151. def test_cloudsearch_result_fields_multiple(self):
  152. search = SearchConnection(endpoint=HOSTNAME)
  153. search.search(q='Test', return_fields=['author', 'title'])
  154. args = self.get_args(HTTPretty.last_request.raw_requestline)
  155. self.assertEqual(args[b'return'], [b'author,title'])
  156. def test_cloudsearch_results_meta(self):
  157. """Check returned metadata is parsed correctly"""
  158. search = SearchConnection(endpoint=HOSTNAME)
  159. results = search.search(q='Test')
  160. # These rely on the default response which is fed into HTTPretty
  161. self.assertEqual(results.hits, 30)
  162. self.assertEqual(results.docs[0]['fields']['rank'], 1)
  163. def test_cloudsearch_results_info(self):
  164. """Check num_pages_needed is calculated correctly"""
  165. search = SearchConnection(endpoint=HOSTNAME)
  166. results = search.search(q='Test')
  167. # This relies on the default response which is fed into HTTPretty
  168. self.assertEqual(results.num_pages_needed, 3.0)
  169. def test_cloudsearch_results_matched(self):
  170. """
  171. Check that information objects are passed back through the API
  172. correctly.
  173. """
  174. search = SearchConnection(endpoint=HOSTNAME)
  175. query = search.build_query(q='Test')
  176. results = search(query)
  177. self.assertEqual(results.search_service, search)
  178. self.assertEqual(results.query, query)
  179. def test_cloudsearch_results_hits(self):
  180. """Check that documents are parsed properly from AWS"""
  181. search = SearchConnection(endpoint=HOSTNAME)
  182. results = search.search(q='Test')
  183. hits = list(map(lambda x: x['id'], results.docs))
  184. # This relies on the default response which is fed into HTTPretty
  185. self.assertEqual(
  186. hits, ["12341", "12342", "12343", "12344",
  187. "12345", "12346", "12347"])
  188. def test_cloudsearch_results_iterator(self):
  189. """Check the results iterator"""
  190. search = SearchConnection(endpoint=HOSTNAME)
  191. results = search.search(q='Test')
  192. results_correct = iter(["12341", "12342", "12343", "12344",
  193. "12345", "12346", "12347"])
  194. for x in results:
  195. self.assertEqual(x['id'], next(results_correct))
  196. def test_cloudsearch_results_internal_consistancy(self):
  197. """Check the documents length matches the iterator details"""
  198. search = SearchConnection(endpoint=HOSTNAME)
  199. results = search.search(q='Test')
  200. self.assertEqual(len(results), len(results.docs))
  201. def test_cloudsearch_search_nextpage(self):
  202. """Check next page query is correct"""
  203. search = SearchConnection(endpoint=HOSTNAME)
  204. query1 = search.build_query(q='Test')
  205. query2 = search.build_query(q='Test')
  206. results = search(query2)
  207. self.assertEqual(results.next_page().query.start,
  208. query1.start + query1.size)
  209. self.assertEqual(query1.q, query2.q)
  210. class CloudSearchSearchFacetTest(CloudSearchSearchBaseTest):
  211. response = {
  212. 'rank': '-text_relevance',
  213. 'match-expr': "Test",
  214. 'hits': {
  215. 'found': 30,
  216. 'start': 0,
  217. 'hit': CloudSearchSearchBaseTest.hits
  218. },
  219. 'status': {
  220. 'rid': 'b7c167f6c2da6d93531b9a7b314ad030b3a74803b4b7797edb905ba5a6a08',
  221. 'time-ms': 2,
  222. 'cpu-time-ms': 0
  223. },
  224. 'facets': {
  225. 'tags': {},
  226. 'animals': {'buckets': [{'count': '2', 'value': 'fish'}, {'count': '1', 'value': 'lions'}]},
  227. }
  228. }
  229. def test_cloudsearch_search_facets(self):
  230. #self.response['facets'] = {'tags': {}}
  231. search = SearchConnection(endpoint=HOSTNAME)
  232. results = search.search(q='Test', facet={'tags': {}})
  233. self.assertTrue('tags' not in results.facets)
  234. self.assertEqual(results.facets['animals'], {u'lions': u'1', u'fish': u'2'})
  235. class CloudSearchNonJsonTest(CloudSearchSearchBaseTest):
  236. response = b'<html><body><h1>500 Internal Server Error</h1></body></html>'
  237. response_status = 500
  238. content_type = 'text/xml'
  239. def test_response(self):
  240. search = SearchConnection(endpoint=HOSTNAME)
  241. with self.assertRaises(SearchServiceException):
  242. search.search(q='Test')
  243. class CloudSearchUnauthorizedTest(CloudSearchSearchBaseTest):
  244. response = b'<html><body><h1>403 Forbidden</h1>foo bar baz</body></html>'
  245. response_status = 403
  246. content_type = 'text/html'
  247. def test_response(self):
  248. search = SearchConnection(endpoint=HOSTNAME)
  249. with self.assertRaisesRegexp(SearchServiceException, 'foo bar baz'):
  250. search.search(q='Test')
  251. class FakeResponse(object):
  252. status_code = 405
  253. content = b''
  254. class CloudSearchConnectionTest(AWSMockServiceTestCase):
  255. cloudsearch = True
  256. connection_class = CloudSearchConnection
  257. def setUp(self):
  258. super(CloudSearchConnectionTest, self).setUp()
  259. self.conn = SearchConnection(
  260. endpoint='test-domain.cloudsearch.amazonaws.com'
  261. )
  262. def test_expose_additional_error_info(self):
  263. mpo = mock.patch.object
  264. fake = FakeResponse()
  265. fake.content = b'Nopenopenope'
  266. # First, in the case of a non-JSON, non-403 error.
  267. with mpo(self.conn.session, 'get', return_value=fake) as mock_request:
  268. with self.assertRaises(SearchServiceException) as cm:
  269. self.conn.search(q='not_gonna_happen')
  270. self.assertTrue('non-json response' in str(cm.exception))
  271. self.assertTrue('Nopenopenope' in str(cm.exception))
  272. # Then with JSON & an 'error' key within.
  273. fake.content = json.dumps({
  274. 'error': "Something went wrong. Oops."
  275. }).encode('utf-8')
  276. with mpo(self.conn.session, 'get', return_value=fake) as mock_request:
  277. with self.assertRaises(SearchServiceException) as cm:
  278. self.conn.search(q='no_luck_here')
  279. self.assertTrue('Unknown error' in str(cm.exception))
  280. self.assertTrue('went wrong. Oops' in str(cm.exception))
  281. def test_proxy(self):
  282. conn = self.service_connection
  283. conn.proxy = "127.0.0.1"
  284. conn.proxy_user = "john.doe"
  285. conn.proxy_pass="p4ssw0rd"
  286. conn.proxy_port="8180"
  287. conn.use_proxy = True
  288. domain = Domain(conn, DEMO_DOMAIN_DATA)
  289. search = SearchConnection(domain=domain)
  290. self.assertEqual(search.session.proxies, {'http': 'http://john.doe:p4ssw0rd@127.0.0.1:8180'})