Fuel UI
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_handlers.py 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2013 Mirantis, Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. import json
  16. import urllib
  17. import web
  18. from nailgun.api.v1.handlers.base import BaseHandler
  19. from nailgun.api.v1.handlers.base import CollectionHandler
  20. from nailgun.api.v1.handlers.base import handle_errors
  21. from nailgun.api.v1.handlers.base import Pagination
  22. from nailgun.api.v1.handlers.base import serialize
  23. from nailgun.objects import NodeCollection
  24. from nailgun.test.base import BaseIntegrationTest
  25. from nailgun.utils import reverse
  26. class TestHandlers(BaseIntegrationTest):
  27. def test_all_api_urls_404_or_405(self):
  28. urls = {
  29. 'ClusterHandler': {'obj_id': 1},
  30. 'NodeHandler': {'obj_id': 1},
  31. 'ReleaseHandler': {'obj_id': 1},
  32. }
  33. for handler in urls:
  34. test_url = reverse(handler, urls[handler])
  35. resp = self.app.get(test_url, expect_errors=True)
  36. self.assertIn(resp.status_code, [404, 405])
  37. resp = self.app.delete(test_url, expect_errors=True)
  38. self.assertIn(resp.status_code, [404, 405])
  39. resp = self.app.put(
  40. test_url,
  41. json.dumps({}),
  42. expect_errors=True
  43. )
  44. self.assertIn(resp.status_code, [404, 405])
  45. resp = self.app.post(
  46. test_url,
  47. json.dumps({}),
  48. expect_errors=True
  49. )
  50. self.assertIn(resp.status_code, [404, 405])
  51. def test_http_response(self):
  52. web.ctx.headers = []
  53. http_codes = (
  54. (200, 'ok'),
  55. (201, 'created'),
  56. (202, 'accepted'),
  57. (204, 'no content'),
  58. (400, 'bad request :('),
  59. (401, 'unauthorized'),
  60. (403, 'forbidden'),
  61. (404, 'not found, try again'),
  62. (405, 'no method'),
  63. (406, 'unacceptable'),
  64. (409, 'ooops, conflict'),
  65. (415, 'unsupported media type'),
  66. (500, 'internal problems'),
  67. )
  68. headers = {
  69. 'Content-Type': 'application/json',
  70. 'ETag': '737060cd8c284d8af7ad3082f209582d',
  71. }
  72. # test response status code and message
  73. for code, message in http_codes:
  74. with self.assertRaises(web.HTTPError) as cm:
  75. raise BaseHandler.http(
  76. status_code=code,
  77. msg=message,
  78. headers=headers
  79. )
  80. self.assertTrue(web.ctx.status.startswith(str(code)))
  81. self.assertTrue(cm.exception.data, message)
  82. for header, value in headers.items():
  83. self.assertIn((header, value), web.ctx.headers)
  84. def test_content_decorator(self):
  85. class FakeHandler(BaseHandler):
  86. @serialize
  87. def GET(self):
  88. return {}
  89. @serialize
  90. def POST(self):
  91. return {}
  92. web.ctx.headers = []
  93. web.ctx.env = {"HTTP_ACCEPT": "text/html"}
  94. fake_handler = FakeHandler()
  95. self.assertRaises(
  96. web.webapi.UnsupportedMediaType,
  97. fake_handler.GET
  98. )
  99. web.ctx.env = {"HTTP_ACCEPT": "*/*"}
  100. web.ctx.headers = []
  101. fake_handler.GET()
  102. self.assertIn(
  103. ('Content-Type', 'application/json'),
  104. web.ctx.headers
  105. )
  106. web.ctx.headers = []
  107. web.ctx.env = {"HTTP_ACCEPT": "application/json"}
  108. fake_handler.POST()
  109. self.assertIn(
  110. # we don't have plain/text serializer right now
  111. ('Content-Type', 'application/json'),
  112. web.ctx.headers
  113. )
  114. def test_invalid_handler_output(self):
  115. class FakeHandler(object):
  116. @handle_errors
  117. @serialize
  118. def GET(self):
  119. return {set([1, 2, 3])}
  120. fake_handler = FakeHandler()
  121. web.ctx.env = {"HTTP_ACCEPT": "*/*"}
  122. web.ctx.headers = []
  123. self.assertRaises(web.HTTPError, fake_handler.GET)
  124. def test_get_param_as_set(self):
  125. urls = ("/hello", "hello")
  126. class hello(object):
  127. def GET(self_inner):
  128. web.header('Content-Type', 'application/json')
  129. data = BaseHandler.get_param_as_set('test_param',
  130. delimiter=';')
  131. return json.dumps(list(data))
  132. app = web.application(urls, {'hello': hello})
  133. url = '/hello?test_param=' + urllib.quote('1;4 ; 777; 4;x ')
  134. resp = app.request(url)
  135. self.assertEqual(set(json.loads(resp.data)),
  136. set(['1', '4', '777', 'x']))
  137. def check_get_requested_mime(self, headers, expected_mime):
  138. urls = ("/hello", "hello")
  139. class hello(object):
  140. def GET(self_inner):
  141. web.header('Content-Type', 'text/plain')
  142. return BaseHandler.get_requested_mime()
  143. app = web.application(urls, {'hello': hello})
  144. resp = app.request('/hello', headers=headers)
  145. self.assertEqual(resp.data, expected_mime)
  146. def test_get_requested_mime1(self):
  147. self.check_get_requested_mime({'ACCEPT': 'text/html'}, 'text/html')
  148. def test_get_requested_mime2(self):
  149. self.check_get_requested_mime(
  150. {'ACCEPT': 'text/plain;q=0.7, text/html;level=1,'}, 'text/plain')
  151. def test_get_requested_default(self):
  152. self.check_get_requested_mime({}, 'application/json')
  153. def test_pagination_class(self):
  154. # test empty query
  155. web.ctx.env = {'REQUEST_METHOD': 'GET'}
  156. pagination = Pagination()
  157. self.assertEqual(pagination.limit, None)
  158. self.assertEqual(pagination.offset, None)
  159. self.assertEqual(pagination.order_by, None)
  160. # test value retrieval from web + order_by cleanup
  161. q = 'limit=1&offset=5&order_by=-id, timestamp , somefield '
  162. web.ctx.env['QUERY_STRING'] = q
  163. pagination = Pagination()
  164. self.assertEqual(pagination.limit, 1)
  165. self.assertEqual(pagination.offset, 5)
  166. self.assertEqual(set(pagination.order_by),
  167. set(['-id', 'timestamp', 'somefield']))
  168. # test incorrect values raise 400
  169. web.ctx.env['QUERY_STRING'] = 'limit=qwe'
  170. self.assertRaises(web.HTTPError, Pagination)
  171. web.ctx.env['QUERY_STRING'] = 'offset=asd'
  172. self.assertRaises(web.HTTPError, Pagination)
  173. web.ctx.env['QUERY_STRING'] = 'limit='
  174. self.assertRaises(web.HTTPError, Pagination)
  175. web.ctx.env['QUERY_STRING'] = 'offset=-2'
  176. self.assertRaises(web.HTTPError, Pagination)
  177. # test constructor, limit = 0 -> 0, offset '0' -> 0, bad order_by
  178. pagination = Pagination(0, '0', ', ,,, ,')
  179. self.assertEqual(pagination.limit, 0)
  180. self.assertEqual(pagination.offset, 0)
  181. self.assertEqual(pagination.order_by, None)
  182. def test_pagination_of_node_collection(self):
  183. def assert_pagination_and_cont_rng(q, cr, sz, first, last, ttl, valid):
  184. self.assertEqual(q.count(), sz)
  185. self.assertEqual(cr.first, first)
  186. self.assertEqual(cr.last, last)
  187. self.assertEqual(cr.total, ttl)
  188. self.assertEqual(cr.valid, valid)
  189. self.env.create_nodes(5)
  190. # test pagination limited to 2 first items
  191. pagination = Pagination(limit=2)
  192. q, cr = NodeCollection.scope(pagination)
  193. assert_pagination_and_cont_rng(q, cr, 2, 1, 2, 5, True)
  194. # test invalid pagination
  195. pagination = Pagination(offset=5)
  196. q, cr = NodeCollection.scope(pagination)
  197. assert_pagination_and_cont_rng(q, cr, 0, 0, 0, 5, False)
  198. # test limit=0, offset ignored
  199. pagination = Pagination(limit=0, offset=999)
  200. q, cr = NodeCollection.scope(pagination)
  201. assert_pagination_and_cont_rng(q, cr, 0, 0, 0, 5, True)
  202. # test limit+offset+order_by
  203. pagination = Pagination(limit=3, offset=1, order_by='-id')
  204. q, cr = NodeCollection.scope(pagination)
  205. assert_pagination_and_cont_rng(q, cr, 3, 2, 4, 5, True)
  206. ids = sorted([i.id for i in self.env.nodes])
  207. n = q.all()
  208. self.assertEqual(n[0].id, ids[3])
  209. self.assertEqual(n[1].id, ids[2])
  210. self.assertEqual(n[2].id, ids[1])
  211. def test_collection_handler(self):
  212. FakeHandler = CollectionHandler
  213. # setting a collection is mandatory, CollectionHandler is not ready
  214. # to use "as-is"
  215. FakeHandler.collection = NodeCollection
  216. urls = ("/collection_test", "collection_test")
  217. app = web.application(urls, {'collection_test': FakeHandler})
  218. resp = app.request(urls[0])
  219. self.assertEqual(resp.status, '200 OK')
  220. def test_content_range_header(self):
  221. self.env.create_nodes(5)
  222. FakeHandler = CollectionHandler
  223. FakeHandler.collection = NodeCollection
  224. urls = ("/collection_test", "collection_test")
  225. app = web.application(urls, {'collection_test': FakeHandler})
  226. # test paginated query
  227. resp = app.request("/collection_test?limit=3&offset=1")
  228. self.assertEqual(resp.status, '200 OK')
  229. self.assertIn('Content-Range', resp.headers)
  230. self.assertEqual(resp.headers['Content-Range'], 'objects 2-4/5')
  231. # test invalid range (offset = 6 >= number of nodes ---> no data)
  232. resp = app.request("/collection_test?limit=3&offset=5&order_by=id")
  233. self.assertEqual(resp.status, '416 Range Not Satisfiable')